Snap for 12357242 from 60f176dc2d2223b782a56ac25115846350c680c2 to studio-ladybug-feature-release
Change-Id: Id29d00f6f383171f7418928793e6500b323e5983
diff --git a/BUILD b/BUILD
index d9c4ce6..006f829 100644
--- a/BUILD
+++ b/BUILD
@@ -35,31 +35,31 @@
filegroup(
name = "linux-x86-bundle",
srcs = glob(
- include = ["lib/python3.10/**"],
+ include = ["lib/python3.11/**"],
exclude = [
- "lib/python3.10/**/*.pyc",
- "lib/python3.10/test/**",
- "lib/python3.10/unittest/**",
- "lib/python3.10/config/**",
- "lib/python3.10/distutils/**",
- "lib/python3.10/idlelib/**",
- "lib/python3.10/lib2to3/**",
- "lib/python3.10/plat-linux2/**",
- "lib/python3.10/bsddb/test/**",
- "lib/python3.10/ctypes/test/**",
- "lib/python3.10/email/test/**",
- "lib/python3.10/lib-tk/test/**",
- "lib/python3.10/sqlite3/test/**",
- "lib/python3.10/site-packages/setuptools/gui-64.exe",
- "lib/python3.10/site-packages/setuptools/gui.exe",
- "lib/python3.10/site-packages/setuptools/cli.exe",
- "lib/python3.10/site-packages/setuptools/cli-64.exe",
- "lib/python3.10/site-packages/setuptools/cli-32.exe",
- "lib/python3.10/site-packages/setuptools/gui-32.exe",
- "lib/python3.10/site-packages/pip/_vendor/distlib/w64.exe",
- "lib/python3.10/site-packages/pip/_vendor/distlib/t64.exe",
- "lib/python3.10/site-packages/pip/_vendor/distlib/t32.exe",
- "lib/python3.10/site-packages/pip/_vendor/distlib/w32.exe",
+ "lib/python3.11/**/*.pyc",
+ "lib/python3.11/test/**",
+ "lib/python3.11/unittest/**",
+ "lib/python3.11/config/**",
+ "lib/python3.11/distutils/**",
+ "lib/python3.11/idlelib/**",
+ "lib/python3.11/lib2to3/**",
+ "lib/python3.11/plat-linux2/**",
+ "lib/python3.11/bsddb/test/**",
+ "lib/python3.11/ctypes/test/**",
+ "lib/python3.11/email/test/**",
+ "lib/python3.11/lib-tk/test/**",
+ "lib/python3.11/sqlite3/test/**",
+ "lib/python3.11/site-packages/setuptools/gui-64.exe",
+ "lib/python3.11/site-packages/setuptools/gui.exe",
+ "lib/python3.11/site-packages/setuptools/cli.exe",
+ "lib/python3.11/site-packages/setuptools/cli-64.exe",
+ "lib/python3.11/site-packages/setuptools/cli-32.exe",
+ "lib/python3.11/site-packages/setuptools/gui-32.exe",
+ "lib/python3.11/site-packages/pip/_vendor/distlib/w64.exe",
+ "lib/python3.11/site-packages/pip/_vendor/distlib/t64.exe",
+ "lib/python3.11/site-packages/pip/_vendor/distlib/t32.exe",
+ "lib/python3.11/site-packages/pip/_vendor/distlib/w32.exe",
],
),
)
diff --git a/bin/2to3 b/bin/2to3
index 272887a..c5828ad 100644
--- a/bin/2to3
+++ b/bin/2to3
@@ -1,4 +1,4 @@
-#!/tmpfs/src/git/out/python3/install/bin/python3.10
+#!/tmpfs/src/git/out/python3/install/bin/python3.11
import sys
from lib2to3.main import main
diff --git a/bin/2to3-3.10 b/bin/2to3-3.10
deleted file mode 100644
index 272887a..0000000
--- a/bin/2to3-3.10
+++ /dev/null
@@ -1,5 +0,0 @@
-#!/tmpfs/src/git/out/python3/install/bin/python3.10
-import sys
-from lib2to3.main import main
-
-sys.exit(main("lib2to3.fixes"))
diff --git a/bin/2to3-3.11 b/bin/2to3-3.11
new file mode 100644
index 0000000..c5828ad
--- /dev/null
+++ b/bin/2to3-3.11
@@ -0,0 +1,5 @@
+#!/tmpfs/src/git/out/python3/install/bin/python3.11
+import sys
+from lib2to3.main import main
+
+sys.exit(main("lib2to3.fixes"))
diff --git a/bin/idle3 b/bin/idle3
index 656fabb..c2e02bc 100644
--- a/bin/idle3
+++ b/bin/idle3
@@ -1,4 +1,4 @@
-#!/tmpfs/src/git/out/python3/install/bin/python3.10
+#!/tmpfs/src/git/out/python3/install/bin/python3.11
from idlelib.pyshell import main
if __name__ == '__main__':
diff --git a/bin/idle3.10 b/bin/idle3.10
deleted file mode 100644
index 656fabb..0000000
--- a/bin/idle3.10
+++ /dev/null
@@ -1,5 +0,0 @@
-#!/tmpfs/src/git/out/python3/install/bin/python3.10
-
-from idlelib.pyshell import main
-if __name__ == '__main__':
- main()
diff --git a/bin/idle3.11 b/bin/idle3.11
new file mode 100644
index 0000000..c2e02bc
--- /dev/null
+++ b/bin/idle3.11
@@ -0,0 +1,5 @@
+#!/tmpfs/src/git/out/python3/install/bin/python3.11
+
+from idlelib.pyshell import main
+if __name__ == '__main__':
+ main()
diff --git a/bin/pip3 b/bin/pip3
index 2045a68..ab01fb9 100644
--- a/bin/pip3
+++ b/bin/pip3
@@ -1,4 +1,4 @@
-#!/tmpfs/src/git/out/python3/install/bin/python3.10
+#!/tmpfs/src/git/out/python3/install/bin/python3.11
# -*- coding: utf-8 -*-
import re
import sys
diff --git a/bin/pip3.10 b/bin/pip3.10
deleted file mode 100644
index 2045a68..0000000
--- a/bin/pip3.10
+++ /dev/null
@@ -1,8 +0,0 @@
-#!/tmpfs/src/git/out/python3/install/bin/python3.10
-# -*- coding: utf-8 -*-
-import re
-import sys
-from pip._internal.cli.main import main
-if __name__ == '__main__':
- sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
- sys.exit(main())
diff --git a/bin/pip3.11 b/bin/pip3.11
new file mode 100644
index 0000000..ab01fb9
--- /dev/null
+++ b/bin/pip3.11
@@ -0,0 +1,8 @@
+#!/tmpfs/src/git/out/python3/install/bin/python3.11
+# -*- coding: utf-8 -*-
+import re
+import sys
+from pip._internal.cli.main import main
+if __name__ == '__main__':
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
+ sys.exit(main())
diff --git a/bin/pydoc3 b/bin/pydoc3
index ec983a9..07e57fd 100644
--- a/bin/pydoc3
+++ b/bin/pydoc3
@@ -1,4 +1,4 @@
-#!/tmpfs/src/git/out/python3/install/bin/python3.10
+#!/tmpfs/src/git/out/python3/install/bin/python3.11
import pydoc
if __name__ == '__main__':
diff --git a/bin/pydoc3.10 b/bin/pydoc3.10
deleted file mode 100644
index ec983a9..0000000
--- a/bin/pydoc3.10
+++ /dev/null
@@ -1,5 +0,0 @@
-#!/tmpfs/src/git/out/python3/install/bin/python3.10
-
-import pydoc
-if __name__ == '__main__':
- pydoc.cli()
diff --git a/bin/pydoc3.11 b/bin/pydoc3.11
new file mode 100644
index 0000000..07e57fd
--- /dev/null
+++ b/bin/pydoc3.11
@@ -0,0 +1,5 @@
+#!/tmpfs/src/git/out/python3/install/bin/python3.11
+
+import pydoc
+if __name__ == '__main__':
+ pydoc.cli()
diff --git a/bin/python3 b/bin/python3
index e70b9ec..e4f6b3e 100755
--- a/bin/python3
+++ b/bin/python3
Binary files differ
diff --git a/bin/python3-config b/bin/python3-config
index 9d6979e..0989c46 100644
--- a/bin/python3-config
+++ b/bin/python3-config
@@ -36,21 +36,21 @@
includedir=$(echo "${prefix}/include" | sed "s#$prefix#$prefix_real#")
libdir=$(echo "${exec_prefix}/lib" | sed "s#$prefix#$prefix_real#")
CFLAGS=$(echo "-Wno-unused-command-line-argument" | sed "s#$prefix#$prefix_real#")
-VERSION="3.10"
+VERSION="3.11"
LIBM="-lm"
LIBC=""
SYSLIBS="$LIBM $LIBC"
ABIFLAGS=""
-LIBS=" -lcrypt -lpthread -ldl -lutil -lm $SYSLIBS"
-LIBS_EMBED="-lpython${VERSION}${ABIFLAGS} -lcrypt -lpthread -ldl -lutil -lm $SYSLIBS"
-BASECFLAGS=" -Wno-unused-result -Wsign-compare"
+LIBS=" -lpthread -ldl -lutil $SYSLIBS"
+LIBS_EMBED="-lpython${VERSION}${ABIFLAGS} -lpthread -ldl -lutil $SYSLIBS"
+BASECFLAGS=" -Wsign-compare"
LDLIBRARY="libpython${LDVERSION}.so"
-OPT="-DNDEBUG -g -fwrapv -O3 -Wall"
+OPT="-DNDEBUG -g -O3 -Wall"
PY_ENABLE_SHARED="1"
LDVERSION="${VERSION}${ABIFLAGS}"
LIBDEST=${prefix_real}/lib/python${VERSION}
-LIBPL=$(echo "${prefix}/lib/python3.10/config-${VERSION}${ABIFLAGS}-x86_64-linux-gnu" | sed "s#$prefix#$prefix_real#")
-SO=".cpython-310-x86_64-linux-gnu.so"
+LIBPL=$(echo "${prefix}/lib/python3.11/config-${VERSION}${ABIFLAGS}-x86_64-linux-gnu" | sed "s#$prefix#$prefix_real#")
+SO=".cpython-311-x86_64-linux-gnu.so"
PYTHONFRAMEWORK=""
INCDIR="-I$includedir/python${VERSION}${ABIFLAGS}"
PLATINCDIR="-I$includedir/python${VERSION}${ABIFLAGS}"
diff --git a/bin/python3.10 b/bin/python3.10
deleted file mode 100755
index e70b9ec..0000000
--- a/bin/python3.10
+++ /dev/null
Binary files differ
diff --git a/bin/python3.10-config b/bin/python3.10-config
deleted file mode 100644
index 9d6979e..0000000
--- a/bin/python3.10-config
+++ /dev/null
@@ -1,116 +0,0 @@
-#!/bin/sh
-
-# Keep this script in sync with python-config.in
-
-exit_with_usage ()
-{
- echo "Usage: $0 --prefix|--exec-prefix|--includes|--libs|--cflags|--ldflags|--extension-suffix|--help|--abiflags|--configdir|--embed"
- exit $1
-}
-
-if [ "$1" = "" ] ; then
- exit_with_usage 1
-fi
-
-# Returns the actual prefix where this script was installed to.
-installed_prefix ()
-{
- RESULT=$(dirname $(cd $(dirname "$1") && pwd -P))
- if which readlink >/dev/null 2>&1 ; then
- if readlink -f "$RESULT" >/dev/null 2>&1; then
- RESULT=$(readlink -f "$RESULT")
- fi
- fi
- echo $RESULT
-}
-
-prefix_real=$(installed_prefix "$0")
-
-# Use sed to fix paths from their built-to locations to their installed-to
-# locations. Keep prefix & exec_prefix using their original values in case
-# they are referenced in other configure variables, to prevent double
-# substitution, issue #22140.
-prefix="/tmpfs/src/git/out/python3/install"
-exec_prefix="${prefix}"
-exec_prefix_real=${prefix_real}
-includedir=$(echo "${prefix}/include" | sed "s#$prefix#$prefix_real#")
-libdir=$(echo "${exec_prefix}/lib" | sed "s#$prefix#$prefix_real#")
-CFLAGS=$(echo "-Wno-unused-command-line-argument" | sed "s#$prefix#$prefix_real#")
-VERSION="3.10"
-LIBM="-lm"
-LIBC=""
-SYSLIBS="$LIBM $LIBC"
-ABIFLAGS=""
-LIBS=" -lcrypt -lpthread -ldl -lutil -lm $SYSLIBS"
-LIBS_EMBED="-lpython${VERSION}${ABIFLAGS} -lcrypt -lpthread -ldl -lutil -lm $SYSLIBS"
-BASECFLAGS=" -Wno-unused-result -Wsign-compare"
-LDLIBRARY="libpython${LDVERSION}.so"
-OPT="-DNDEBUG -g -fwrapv -O3 -Wall"
-PY_ENABLE_SHARED="1"
-LDVERSION="${VERSION}${ABIFLAGS}"
-LIBDEST=${prefix_real}/lib/python${VERSION}
-LIBPL=$(echo "${prefix}/lib/python3.10/config-${VERSION}${ABIFLAGS}-x86_64-linux-gnu" | sed "s#$prefix#$prefix_real#")
-SO=".cpython-310-x86_64-linux-gnu.so"
-PYTHONFRAMEWORK=""
-INCDIR="-I$includedir/python${VERSION}${ABIFLAGS}"
-PLATINCDIR="-I$includedir/python${VERSION}${ABIFLAGS}"
-PY_EMBED=0
-
-# Scan for --help or unknown argument.
-for ARG in $*
-do
- case $ARG in
- --help)
- exit_with_usage 0
- ;;
- --embed)
- PY_EMBED=1
- ;;
- --prefix|--exec-prefix|--includes|--libs|--cflags|--ldflags|--extension-suffix|--abiflags|--configdir)
- ;;
- *)
- exit_with_usage 1
- ;;
- esac
-done
-
-if [ $PY_EMBED = 1 ] ; then
- LIBS="$LIBS_EMBED"
-fi
-
-for ARG in "$@"
-do
- case "$ARG" in
- --prefix)
- echo "$prefix_real"
- ;;
- --exec-prefix)
- echo "$exec_prefix_real"
- ;;
- --includes)
- echo "$INCDIR $PLATINCDIR"
- ;;
- --cflags)
- echo "$INCDIR $PLATINCDIR $BASECFLAGS $CFLAGS $OPT"
- ;;
- --libs)
- echo "$LIBS"
- ;;
- --ldflags)
- LIBPLUSED=
- if [ "$PY_ENABLE_SHARED" = "0" ] ; then
- LIBPLUSED="-L$LIBPL"
- fi
- echo "$LIBPLUSED -L$libdir $LIBS"
- ;;
- --extension-suffix)
- echo "$SO"
- ;;
- --abiflags)
- echo "$ABIFLAGS"
- ;;
- --configdir)
- echo "$LIBPL"
- ;;
-esac
-done
diff --git a/bin/python3.11 b/bin/python3.11
new file mode 100755
index 0000000..e4f6b3e
--- /dev/null
+++ b/bin/python3.11
Binary files differ
diff --git a/bin/python3.11-config b/bin/python3.11-config
new file mode 100644
index 0000000..0989c46
--- /dev/null
+++ b/bin/python3.11-config
@@ -0,0 +1,116 @@
+#!/bin/sh
+
+# Keep this script in sync with python-config.in
+
+exit_with_usage ()
+{
+ echo "Usage: $0 --prefix|--exec-prefix|--includes|--libs|--cflags|--ldflags|--extension-suffix|--help|--abiflags|--configdir|--embed"
+ exit $1
+}
+
+if [ "$1" = "" ] ; then
+ exit_with_usage 1
+fi
+
+# Returns the actual prefix where this script was installed to.
+installed_prefix ()
+{
+ RESULT=$(dirname $(cd $(dirname "$1") && pwd -P))
+ if which readlink >/dev/null 2>&1 ; then
+ if readlink -f "$RESULT" >/dev/null 2>&1; then
+ RESULT=$(readlink -f "$RESULT")
+ fi
+ fi
+ echo $RESULT
+}
+
+prefix_real=$(installed_prefix "$0")
+
+# Use sed to fix paths from their built-to locations to their installed-to
+# locations. Keep prefix & exec_prefix using their original values in case
+# they are referenced in other configure variables, to prevent double
+# substitution, issue #22140.
+prefix="/tmpfs/src/git/out/python3/install"
+exec_prefix="${prefix}"
+exec_prefix_real=${prefix_real}
+includedir=$(echo "${prefix}/include" | sed "s#$prefix#$prefix_real#")
+libdir=$(echo "${exec_prefix}/lib" | sed "s#$prefix#$prefix_real#")
+CFLAGS=$(echo "-Wno-unused-command-line-argument" | sed "s#$prefix#$prefix_real#")
+VERSION="3.11"
+LIBM="-lm"
+LIBC=""
+SYSLIBS="$LIBM $LIBC"
+ABIFLAGS=""
+LIBS=" -lpthread -ldl -lutil $SYSLIBS"
+LIBS_EMBED="-lpython${VERSION}${ABIFLAGS} -lpthread -ldl -lutil $SYSLIBS"
+BASECFLAGS=" -Wsign-compare"
+LDLIBRARY="libpython${LDVERSION}.so"
+OPT="-DNDEBUG -g -O3 -Wall"
+PY_ENABLE_SHARED="1"
+LDVERSION="${VERSION}${ABIFLAGS}"
+LIBDEST=${prefix_real}/lib/python${VERSION}
+LIBPL=$(echo "${prefix}/lib/python3.11/config-${VERSION}${ABIFLAGS}-x86_64-linux-gnu" | sed "s#$prefix#$prefix_real#")
+SO=".cpython-311-x86_64-linux-gnu.so"
+PYTHONFRAMEWORK=""
+INCDIR="-I$includedir/python${VERSION}${ABIFLAGS}"
+PLATINCDIR="-I$includedir/python${VERSION}${ABIFLAGS}"
+PY_EMBED=0
+
+# Scan for --help or unknown argument.
+for ARG in $*
+do
+ case $ARG in
+ --help)
+ exit_with_usage 0
+ ;;
+ --embed)
+ PY_EMBED=1
+ ;;
+ --prefix|--exec-prefix|--includes|--libs|--cflags|--ldflags|--extension-suffix|--abiflags|--configdir)
+ ;;
+ *)
+ exit_with_usage 1
+ ;;
+ esac
+done
+
+if [ $PY_EMBED = 1 ] ; then
+ LIBS="$LIBS_EMBED"
+fi
+
+for ARG in "$@"
+do
+ case "$ARG" in
+ --prefix)
+ echo "$prefix_real"
+ ;;
+ --exec-prefix)
+ echo "$exec_prefix_real"
+ ;;
+ --includes)
+ echo "$INCDIR $PLATINCDIR"
+ ;;
+ --cflags)
+ echo "$INCDIR $PLATINCDIR $BASECFLAGS $CFLAGS $OPT"
+ ;;
+ --libs)
+ echo "$LIBS"
+ ;;
+ --ldflags)
+ LIBPLUSED=
+ if [ "$PY_ENABLE_SHARED" = "0" ] ; then
+ LIBPLUSED="-L$LIBPL"
+ fi
+ echo "$LIBPLUSED -L$libdir $LIBS"
+ ;;
+ --extension-suffix)
+ echo "$SO"
+ ;;
+ --abiflags)
+ echo "$ABIFLAGS"
+ ;;
+ --configdir)
+ echo "$LIBPL"
+ ;;
+esac
+done
diff --git a/include/python3.10/Python.h b/include/python3.10/Python.h
deleted file mode 100644
index d3186c3..0000000
--- a/include/python3.10/Python.h
+++ /dev/null
@@ -1,148 +0,0 @@
-#ifndef Py_PYTHON_H
-#define Py_PYTHON_H
-/* Since this is a "meta-include" file, no #ifdef __cplusplus / extern "C" { */
-
-/* Include nearly all Python header files */
-
-#include "patchlevel.h"
-#include "pyconfig.h"
-#include "pymacconfig.h"
-
-#include <limits.h>
-
-#ifndef UCHAR_MAX
-#error "Something's broken. UCHAR_MAX should be defined in limits.h."
-#endif
-
-#if UCHAR_MAX != 255
-#error "Python's source code assumes C's unsigned char is an 8-bit type."
-#endif
-
-#if defined(__sgi) && !defined(_SGI_MP_SOURCE)
-#define _SGI_MP_SOURCE
-#endif
-
-#include <stdio.h>
-#ifndef NULL
-# error "Python.h requires that stdio.h define NULL."
-#endif
-
-#include <string.h>
-#ifdef HAVE_ERRNO_H
-#include <errno.h>
-#endif
-#include <stdlib.h>
-#ifndef MS_WINDOWS
-#include <unistd.h>
-#endif
-
-/* For size_t? */
-#ifdef HAVE_STDDEF_H
-#include <stddef.h>
-#endif
-
-/* CAUTION: Build setups should ensure that NDEBUG is defined on the
- * compiler command line when building Python in release mode; else
- * assert() calls won't be removed.
- */
-#include <assert.h>
-
-#include "pyport.h"
-#include "pymacro.h"
-
-/* A convenient way for code to know if sanitizers are enabled. */
-#if defined(__has_feature)
-# if __has_feature(memory_sanitizer)
-# if !defined(_Py_MEMORY_SANITIZER)
-# define _Py_MEMORY_SANITIZER
-# endif
-# endif
-# if __has_feature(address_sanitizer)
-# if !defined(_Py_ADDRESS_SANITIZER)
-# define _Py_ADDRESS_SANITIZER
-# endif
-# endif
-#elif defined(__GNUC__)
-# if defined(__SANITIZE_ADDRESS__)
-# define _Py_ADDRESS_SANITIZER
-# endif
-#endif
-
-#include "pymath.h"
-#include "pymem.h"
-
-#include "object.h"
-#include "objimpl.h"
-#include "typeslots.h"
-#include "pyhash.h"
-
-#include "cpython/pydebug.h"
-
-#include "bytearrayobject.h"
-#include "bytesobject.h"
-#include "unicodeobject.h"
-#include "longobject.h"
-#include "longintrepr.h"
-#include "boolobject.h"
-#include "floatobject.h"
-#include "complexobject.h"
-#include "rangeobject.h"
-#include "memoryobject.h"
-#include "tupleobject.h"
-#include "listobject.h"
-#include "dictobject.h"
-#include "cpython/odictobject.h"
-#include "enumobject.h"
-#include "setobject.h"
-#include "methodobject.h"
-#include "moduleobject.h"
-#include "funcobject.h"
-#include "classobject.h"
-#include "fileobject.h"
-#include "pycapsule.h"
-#include "code.h"
-#include "pyframe.h"
-#include "traceback.h"
-#include "sliceobject.h"
-#include "cellobject.h"
-#include "iterobject.h"
-#include "cpython/initconfig.h"
-#include "genobject.h"
-#include "descrobject.h"
-#include "genericaliasobject.h"
-#include "warnings.h"
-#include "weakrefobject.h"
-#include "structseq.h"
-#include "namespaceobject.h"
-#include "cpython/picklebufobject.h"
-#include "cpython/pytime.h"
-
-#include "codecs.h"
-#include "pyerrors.h"
-#include "pythread.h"
-#include "pystate.h"
-#include "context.h"
-
-#include "modsupport.h"
-#include "compile.h"
-#include "pythonrun.h"
-#include "pylifecycle.h"
-#include "ceval.h"
-#include "sysmodule.h"
-#include "osmodule.h"
-#include "intrcheck.h"
-#include "import.h"
-
-#include "abstract.h"
-#include "bltinmodule.h"
-
-#include "eval.h"
-
-#include "cpython/pyctype.h"
-#include "pystrtod.h"
-#include "pystrcmp.h"
-#include "fileutils.h"
-#include "cpython/pyfpe.h"
-#include "tracemalloc.h"
-
-#endif /* !Py_PYTHON_H */
diff --git a/include/python3.10/abstract.h b/include/python3.10/abstract.h
deleted file mode 100644
index 9eaab6b..0000000
--- a/include/python3.10/abstract.h
+++ /dev/null
@@ -1,873 +0,0 @@
-/* Abstract Object Interface (many thanks to Jim Fulton) */
-
-#ifndef Py_ABSTRACTOBJECT_H
-#define Py_ABSTRACTOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* === Object Protocol ================================================== */
-
-/* Implemented elsewhere:
-
- int PyObject_Print(PyObject *o, FILE *fp, int flags);
-
- Print an object 'o' on file 'fp'. Returns -1 on error. The flags argument
- is used to enable certain printing options. The only option currently
- supported is Py_Print_RAW.
-
- (What should be said about Py_Print_RAW?). */
-
-
-/* Implemented elsewhere:
-
- int PyObject_HasAttrString(PyObject *o, const char *attr_name);
-
- Returns 1 if object 'o' has the attribute attr_name, and 0 otherwise.
-
- This is equivalent to the Python expression: hasattr(o,attr_name).
-
- This function always succeeds. */
-
-
-/* Implemented elsewhere:
-
- PyObject* PyObject_GetAttrString(PyObject *o, const char *attr_name);
-
- Retrieve an attributed named attr_name form object o.
- Returns the attribute value on success, or NULL on failure.
-
- This is the equivalent of the Python expression: o.attr_name. */
-
-
-/* Implemented elsewhere:
-
- int PyObject_HasAttr(PyObject *o, PyObject *attr_name);
-
- Returns 1 if o has the attribute attr_name, and 0 otherwise.
-
- This is equivalent to the Python expression: hasattr(o,attr_name).
-
- This function always succeeds. */
-
-/* Implemented elsewhere:
-
- PyObject* PyObject_GetAttr(PyObject *o, PyObject *attr_name);
-
- Retrieve an attributed named 'attr_name' form object 'o'.
- Returns the attribute value on success, or NULL on failure.
-
- This is the equivalent of the Python expression: o.attr_name. */
-
-
-/* Implemented elsewhere:
-
- int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v);
-
- Set the value of the attribute named attr_name, for object 'o',
- to the value 'v'. Raise an exception and return -1 on failure; return 0 on
- success.
-
- This is the equivalent of the Python statement o.attr_name=v. */
-
-
-/* Implemented elsewhere:
-
- int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v);
-
- Set the value of the attribute named attr_name, for object 'o', to the value
- 'v'. an exception and return -1 on failure; return 0 on success.
-
- This is the equivalent of the Python statement o.attr_name=v. */
-
-/* Implemented as a macro:
-
- int PyObject_DelAttrString(PyObject *o, const char *attr_name);
-
- Delete attribute named attr_name, for object o. Returns
- -1 on failure.
-
- This is the equivalent of the Python statement: del o.attr_name. */
-#define PyObject_DelAttrString(O,A) PyObject_SetAttrString((O),(A), NULL)
-
-
-/* Implemented as a macro:
-
- int PyObject_DelAttr(PyObject *o, PyObject *attr_name);
-
- Delete attribute named attr_name, for object o. Returns -1
- on failure. This is the equivalent of the Python
- statement: del o.attr_name. */
-#define PyObject_DelAttr(O,A) PyObject_SetAttr((O),(A), NULL)
-
-
-/* Implemented elsewhere:
-
- PyObject *PyObject_Repr(PyObject *o);
-
- Compute the string representation of object 'o'. Returns the
- string representation on success, NULL on failure.
-
- This is the equivalent of the Python expression: repr(o).
-
- Called by the repr() built-in function. */
-
-
-/* Implemented elsewhere:
-
- PyObject *PyObject_Str(PyObject *o);
-
- Compute the string representation of object, o. Returns the
- string representation on success, NULL on failure.
-
- This is the equivalent of the Python expression: str(o).
-
- Called by the str() and print() built-in functions. */
-
-
-/* Declared elsewhere
-
- PyAPI_FUNC(int) PyCallable_Check(PyObject *o);
-
- Determine if the object, o, is callable. Return 1 if the object is callable
- and 0 otherwise.
-
- This function always succeeds. */
-
-
-#ifdef PY_SSIZE_T_CLEAN
-# define PyObject_CallFunction _PyObject_CallFunction_SizeT
-# define PyObject_CallMethod _PyObject_CallMethod_SizeT
-#endif
-
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03090000
-/* Call a callable Python object without any arguments */
-PyAPI_FUNC(PyObject *) PyObject_CallNoArgs(PyObject *func);
-#endif
-
-
-/* Call a callable Python object 'callable' with arguments given by the
- tuple 'args' and keywords arguments given by the dictionary 'kwargs'.
-
- 'args' must not be NULL, use an empty tuple if no arguments are
- needed. If no named arguments are needed, 'kwargs' can be NULL.
-
- This is the equivalent of the Python expression:
- callable(*args, **kwargs). */
-PyAPI_FUNC(PyObject *) PyObject_Call(PyObject *callable,
- PyObject *args, PyObject *kwargs);
-
-
-/* Call a callable Python object 'callable', with arguments given by the
- tuple 'args'. If no arguments are needed, then 'args' can be NULL.
-
- Returns the result of the call on success, or NULL on failure.
-
- This is the equivalent of the Python expression:
- callable(*args). */
-PyAPI_FUNC(PyObject *) PyObject_CallObject(PyObject *callable,
- PyObject *args);
-
-/* Call a callable Python object, callable, with a variable number of C
- arguments. The C arguments are described using a mkvalue-style format
- string.
-
- The format may be NULL, indicating that no arguments are provided.
-
- Returns the result of the call on success, or NULL on failure.
-
- This is the equivalent of the Python expression:
- callable(arg1, arg2, ...). */
-PyAPI_FUNC(PyObject *) PyObject_CallFunction(PyObject *callable,
- const char *format, ...);
-
-/* Call the method named 'name' of object 'obj' with a variable number of
- C arguments. The C arguments are described by a mkvalue format string.
-
- The format can be NULL, indicating that no arguments are provided.
-
- Returns the result of the call on success, or NULL on failure.
-
- This is the equivalent of the Python expression:
- obj.name(arg1, arg2, ...). */
-PyAPI_FUNC(PyObject *) PyObject_CallMethod(PyObject *obj,
- const char *name,
- const char *format, ...);
-
-PyAPI_FUNC(PyObject *) _PyObject_CallFunction_SizeT(PyObject *callable,
- const char *format,
- ...);
-
-PyAPI_FUNC(PyObject *) _PyObject_CallMethod_SizeT(PyObject *obj,
- const char *name,
- const char *format,
- ...);
-
-/* Call a callable Python object 'callable' with a variable number of C
- arguments. The C arguments are provided as PyObject* values, terminated
- by a NULL.
-
- Returns the result of the call on success, or NULL on failure.
-
- This is the equivalent of the Python expression:
- callable(arg1, arg2, ...). */
-PyAPI_FUNC(PyObject *) PyObject_CallFunctionObjArgs(PyObject *callable,
- ...);
-
-/* Call the method named 'name' of object 'obj' with a variable number of
- C arguments. The C arguments are provided as PyObject* values, terminated
- by NULL.
-
- Returns the result of the call on success, or NULL on failure.
-
- This is the equivalent of the Python expression: obj.name(*args). */
-
-PyAPI_FUNC(PyObject *) PyObject_CallMethodObjArgs(
- PyObject *obj,
- PyObject *name,
- ...);
-
-
-/* Implemented elsewhere:
-
- Py_hash_t PyObject_Hash(PyObject *o);
-
- Compute and return the hash, hash_value, of an object, o. On
- failure, return -1.
-
- This is the equivalent of the Python expression: hash(o). */
-
-
-/* Implemented elsewhere:
-
- int PyObject_IsTrue(PyObject *o);
-
- Returns 1 if the object, o, is considered to be true, 0 if o is
- considered to be false and -1 on failure.
-
- This is equivalent to the Python expression: not not o. */
-
-
-/* Implemented elsewhere:
-
- int PyObject_Not(PyObject *o);
-
- Returns 0 if the object, o, is considered to be true, 1 if o is
- considered to be false and -1 on failure.
-
- This is equivalent to the Python expression: not o. */
-
-
-/* Get the type of an object.
-
- On success, returns a type object corresponding to the object type of object
- 'o'. On failure, returns NULL.
-
- This is equivalent to the Python expression: type(o) */
-PyAPI_FUNC(PyObject *) PyObject_Type(PyObject *o);
-
-
-/* Return the size of object 'o'. If the object 'o' provides both sequence and
- mapping protocols, the sequence size is returned.
-
- On error, -1 is returned.
-
- This is the equivalent to the Python expression: len(o) */
-PyAPI_FUNC(Py_ssize_t) PyObject_Size(PyObject *o);
-
-
-/* For DLL compatibility */
-#undef PyObject_Length
-PyAPI_FUNC(Py_ssize_t) PyObject_Length(PyObject *o);
-#define PyObject_Length PyObject_Size
-
-/* Return element of 'o' corresponding to the object 'key'. Return NULL
- on failure.
-
- This is the equivalent of the Python expression: o[key] */
-PyAPI_FUNC(PyObject *) PyObject_GetItem(PyObject *o, PyObject *key);
-
-
-/* Map the object 'key' to the value 'v' into 'o'.
-
- Raise an exception and return -1 on failure; return 0 on success.
-
- This is the equivalent of the Python statement: o[key]=v. */
-PyAPI_FUNC(int) PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v);
-
-/* Remove the mapping for the string 'key' from the object 'o'.
- Returns -1 on failure.
-
- This is equivalent to the Python statement: del o[key]. */
-PyAPI_FUNC(int) PyObject_DelItemString(PyObject *o, const char *key);
-
-/* Delete the mapping for the object 'key' from the object 'o'.
- Returns -1 on failure.
-
- This is the equivalent of the Python statement: del o[key]. */
-PyAPI_FUNC(int) PyObject_DelItem(PyObject *o, PyObject *key);
-
-
-/* === Old Buffer API ============================================ */
-
-/* FIXME: usage of these should all be replaced in Python itself
- but for backwards compatibility we will implement them.
- Their usage without a corresponding "unlock" mechanism
- may create issues (but they would already be there). */
-
-/* Takes an arbitrary object which must support the (character, single segment)
- buffer interface and returns a pointer to a read-only memory location
- usable as character based input for subsequent processing.
-
- Return 0 on success. buffer and buffer_len are only set in case no error
- occurs. Otherwise, -1 is returned and an exception set. */
-Py_DEPRECATED(3.0)
-PyAPI_FUNC(int) PyObject_AsCharBuffer(PyObject *obj,
- const char **buffer,
- Py_ssize_t *buffer_len);
-
-/* Checks whether an arbitrary object supports the (character, single segment)
- buffer interface.
-
- Returns 1 on success, 0 on failure. */
-Py_DEPRECATED(3.0) PyAPI_FUNC(int) PyObject_CheckReadBuffer(PyObject *obj);
-
-/* Same as PyObject_AsCharBuffer() except that this API expects (readable,
- single segment) buffer interface and returns a pointer to a read-only memory
- location which can contain arbitrary data.
-
- 0 is returned on success. buffer and buffer_len are only set in case no
- error occurs. Otherwise, -1 is returned and an exception set. */
-Py_DEPRECATED(3.0)
-PyAPI_FUNC(int) PyObject_AsReadBuffer(PyObject *obj,
- const void **buffer,
- Py_ssize_t *buffer_len);
-
-/* Takes an arbitrary object which must support the (writable, single segment)
- buffer interface and returns a pointer to a writable memory location in
- buffer of size 'buffer_len'.
-
- Return 0 on success. buffer and buffer_len are only set in case no error
- occurs. Otherwise, -1 is returned and an exception set. */
-Py_DEPRECATED(3.0)
-PyAPI_FUNC(int) PyObject_AsWriteBuffer(PyObject *obj,
- void **buffer,
- Py_ssize_t *buffer_len);
-
-
-/* === New Buffer API ============================================ */
-
-/* Takes an arbitrary object and returns the result of calling
- obj.__format__(format_spec). */
-PyAPI_FUNC(PyObject *) PyObject_Format(PyObject *obj,
- PyObject *format_spec);
-
-
-/* ==== Iterators ================================================ */
-
-/* Takes an object and returns an iterator for it.
- This is typically a new iterator but if the argument is an iterator, this
- returns itself. */
-PyAPI_FUNC(PyObject *) PyObject_GetIter(PyObject *);
-
-/* Takes an AsyncIterable object and returns an AsyncIterator for it.
- This is typically a new iterator but if the argument is an AsyncIterator,
- this returns itself. */
-PyAPI_FUNC(PyObject *) PyObject_GetAIter(PyObject *);
-
-/* Returns non-zero if the object 'obj' provides iterator protocols, and 0 otherwise.
-
- This function always succeeds. */
-PyAPI_FUNC(int) PyIter_Check(PyObject *);
-
-/* Returns non-zero if the object 'obj' provides AsyncIterator protocols, and 0 otherwise.
-
- This function always succeeds. */
-PyAPI_FUNC(int) PyAIter_Check(PyObject *);
-
-/* Takes an iterator object and calls its tp_iternext slot,
- returning the next value.
-
- If the iterator is exhausted, this returns NULL without setting an
- exception.
-
- NULL with an exception means an error occurred. */
-PyAPI_FUNC(PyObject *) PyIter_Next(PyObject *);
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000
-
-/* Takes generator, coroutine or iterator object and sends the value into it.
- Returns:
- - PYGEN_RETURN (0) if generator has returned.
- 'result' parameter is filled with return value
- - PYGEN_ERROR (-1) if exception was raised.
- 'result' parameter is NULL
- - PYGEN_NEXT (1) if generator has yielded.
- 'result' parameter is filled with yielded value. */
-PyAPI_FUNC(PySendResult) PyIter_Send(PyObject *, PyObject *, PyObject **);
-#endif
-
-
-/* === Number Protocol ================================================== */
-
-/* Returns 1 if the object 'o' provides numeric protocols, and 0 otherwise.
-
- This function always succeeds. */
-PyAPI_FUNC(int) PyNumber_Check(PyObject *o);
-
-/* Returns the result of adding o1 and o2, or NULL on failure.
-
- This is the equivalent of the Python expression: o1 + o2. */
-PyAPI_FUNC(PyObject *) PyNumber_Add(PyObject *o1, PyObject *o2);
-
-/* Returns the result of subtracting o2 from o1, or NULL on failure.
-
- This is the equivalent of the Python expression: o1 - o2. */
-PyAPI_FUNC(PyObject *) PyNumber_Subtract(PyObject *o1, PyObject *o2);
-
-/* Returns the result of multiplying o1 and o2, or NULL on failure.
-
- This is the equivalent of the Python expression: o1 * o2. */
-PyAPI_FUNC(PyObject *) PyNumber_Multiply(PyObject *o1, PyObject *o2);
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
-/* This is the equivalent of the Python expression: o1 @ o2. */
-PyAPI_FUNC(PyObject *) PyNumber_MatrixMultiply(PyObject *o1, PyObject *o2);
-#endif
-
-/* Returns the result of dividing o1 by o2 giving an integral result,
- or NULL on failure.
-
- This is the equivalent of the Python expression: o1 // o2. */
-PyAPI_FUNC(PyObject *) PyNumber_FloorDivide(PyObject *o1, PyObject *o2);
-
-/* Returns the result of dividing o1 by o2 giving a float result, or NULL on
- failure.
-
- This is the equivalent of the Python expression: o1 / o2. */
-PyAPI_FUNC(PyObject *) PyNumber_TrueDivide(PyObject *o1, PyObject *o2);
-
-/* Returns the remainder of dividing o1 by o2, or NULL on failure.
-
- This is the equivalent of the Python expression: o1 % o2. */
-PyAPI_FUNC(PyObject *) PyNumber_Remainder(PyObject *o1, PyObject *o2);
-
-/* See the built-in function divmod.
-
- Returns NULL on failure.
-
- This is the equivalent of the Python expression: divmod(o1, o2). */
-PyAPI_FUNC(PyObject *) PyNumber_Divmod(PyObject *o1, PyObject *o2);
-
-/* See the built-in function pow. Returns NULL on failure.
-
- This is the equivalent of the Python expression: pow(o1, o2, o3),
- where o3 is optional. */
-PyAPI_FUNC(PyObject *) PyNumber_Power(PyObject *o1, PyObject *o2,
- PyObject *o3);
-
-/* Returns the negation of o on success, or NULL on failure.
-
- This is the equivalent of the Python expression: -o. */
-PyAPI_FUNC(PyObject *) PyNumber_Negative(PyObject *o);
-
-/* Returns the positive of o on success, or NULL on failure.
-
- This is the equivalent of the Python expression: +o. */
-PyAPI_FUNC(PyObject *) PyNumber_Positive(PyObject *o);
-
-/* Returns the absolute value of 'o', or NULL on failure.
-
- This is the equivalent of the Python expression: abs(o). */
-PyAPI_FUNC(PyObject *) PyNumber_Absolute(PyObject *o);
-
-/* Returns the bitwise negation of 'o' on success, or NULL on failure.
-
- This is the equivalent of the Python expression: ~o. */
-PyAPI_FUNC(PyObject *) PyNumber_Invert(PyObject *o);
-
-/* Returns the result of left shifting o1 by o2 on success, or NULL on failure.
-
- This is the equivalent of the Python expression: o1 << o2. */
-PyAPI_FUNC(PyObject *) PyNumber_Lshift(PyObject *o1, PyObject *o2);
-
-/* Returns the result of right shifting o1 by o2 on success, or NULL on
- failure.
-
- This is the equivalent of the Python expression: o1 >> o2. */
-PyAPI_FUNC(PyObject *) PyNumber_Rshift(PyObject *o1, PyObject *o2);
-
-/* Returns the result of bitwise and of o1 and o2 on success, or NULL on
- failure.
-
- This is the equivalent of the Python expression: o1 & o2. */
-PyAPI_FUNC(PyObject *) PyNumber_And(PyObject *o1, PyObject *o2);
-
-/* Returns the bitwise exclusive or of o1 by o2 on success, or NULL on failure.
-
- This is the equivalent of the Python expression: o1 ^ o2. */
-PyAPI_FUNC(PyObject *) PyNumber_Xor(PyObject *o1, PyObject *o2);
-
-/* Returns the result of bitwise or on o1 and o2 on success, or NULL on
- failure.
-
- This is the equivalent of the Python expression: o1 | o2. */
-PyAPI_FUNC(PyObject *) PyNumber_Or(PyObject *o1, PyObject *o2);
-
-/* Returns 1 if obj is an index integer (has the nb_index slot of the
- tp_as_number structure filled in), and 0 otherwise. */
-PyAPI_FUNC(int) PyIndex_Check(PyObject *);
-
-/* Returns the object 'o' converted to a Python int, or NULL with an exception
- raised on failure. */
-PyAPI_FUNC(PyObject *) PyNumber_Index(PyObject *o);
-
-/* Returns the object 'o' converted to Py_ssize_t by going through
- PyNumber_Index() first.
-
- If an overflow error occurs while converting the int to Py_ssize_t, then the
- second argument 'exc' is the error-type to return. If it is NULL, then the
- overflow error is cleared and the value is clipped. */
-PyAPI_FUNC(Py_ssize_t) PyNumber_AsSsize_t(PyObject *o, PyObject *exc);
-
-/* Returns the object 'o' converted to an integer object on success, or NULL
- on failure.
-
- This is the equivalent of the Python expression: int(o). */
-PyAPI_FUNC(PyObject *) PyNumber_Long(PyObject *o);
-
-/* Returns the object 'o' converted to a float object on success, or NULL
- on failure.
-
- This is the equivalent of the Python expression: float(o). */
-PyAPI_FUNC(PyObject *) PyNumber_Float(PyObject *o);
-
-
-/* --- In-place variants of (some of) the above number protocol functions -- */
-
-/* Returns the result of adding o2 to o1, possibly in-place, or NULL
- on failure.
-
- This is the equivalent of the Python expression: o1 += o2. */
-PyAPI_FUNC(PyObject *) PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2);
-
-/* Returns the result of subtracting o2 from o1, possibly in-place or
- NULL on failure.
-
- This is the equivalent of the Python expression: o1 -= o2. */
-PyAPI_FUNC(PyObject *) PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2);
-
-/* Returns the result of multiplying o1 by o2, possibly in-place, or NULL on
- failure.
-
- This is the equivalent of the Python expression: o1 *= o2. */
-PyAPI_FUNC(PyObject *) PyNumber_InPlaceMultiply(PyObject *o1, PyObject *o2);
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
-/* This is the equivalent of the Python expression: o1 @= o2. */
-PyAPI_FUNC(PyObject *) PyNumber_InPlaceMatrixMultiply(PyObject *o1, PyObject *o2);
-#endif
-
-/* Returns the result of dividing o1 by o2 giving an integral result, possibly
- in-place, or NULL on failure.
-
- This is the equivalent of the Python expression: o1 /= o2. */
-PyAPI_FUNC(PyObject *) PyNumber_InPlaceFloorDivide(PyObject *o1,
- PyObject *o2);
-
-/* Returns the result of dividing o1 by o2 giving a float result, possibly
- in-place, or null on failure.
-
- This is the equivalent of the Python expression: o1 /= o2. */
-PyAPI_FUNC(PyObject *) PyNumber_InPlaceTrueDivide(PyObject *o1,
- PyObject *o2);
-
-/* Returns the remainder of dividing o1 by o2, possibly in-place, or NULL on
- failure.
-
- This is the equivalent of the Python expression: o1 %= o2. */
-PyAPI_FUNC(PyObject *) PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2);
-
-/* Returns the result of raising o1 to the power of o2, possibly in-place,
- or NULL on failure.
-
- This is the equivalent of the Python expression: o1 **= o2,
- or o1 = pow(o1, o2, o3) if o3 is present. */
-PyAPI_FUNC(PyObject *) PyNumber_InPlacePower(PyObject *o1, PyObject *o2,
- PyObject *o3);
-
-/* Returns the result of left shifting o1 by o2, possibly in-place, or NULL
- on failure.
-
- This is the equivalent of the Python expression: o1 <<= o2. */
-PyAPI_FUNC(PyObject *) PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2);
-
-/* Returns the result of right shifting o1 by o2, possibly in-place or NULL
- on failure.
-
- This is the equivalent of the Python expression: o1 >>= o2. */
-PyAPI_FUNC(PyObject *) PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2);
-
-/* Returns the result of bitwise and of o1 and o2, possibly in-place, or NULL
- on failure.
-
- This is the equivalent of the Python expression: o1 &= o2. */
-PyAPI_FUNC(PyObject *) PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2);
-
-/* Returns the bitwise exclusive or of o1 by o2, possibly in-place, or NULL
- on failure.
-
- This is the equivalent of the Python expression: o1 ^= o2. */
-PyAPI_FUNC(PyObject *) PyNumber_InPlaceXor(PyObject *o1, PyObject *o2);
-
-/* Returns the result of bitwise or of o1 and o2, possibly in-place,
- or NULL on failure.
-
- This is the equivalent of the Python expression: o1 |= o2. */
-PyAPI_FUNC(PyObject *) PyNumber_InPlaceOr(PyObject *o1, PyObject *o2);
-
-/* Returns the integer n converted to a string with a base, with a base
- marker of 0b, 0o or 0x prefixed if applicable.
-
- If n is not an int object, it is converted with PyNumber_Index first. */
-PyAPI_FUNC(PyObject *) PyNumber_ToBase(PyObject *n, int base);
-
-
-/* === Sequence protocol ================================================ */
-
-/* Return 1 if the object provides sequence protocol, and zero
- otherwise.
-
- This function always succeeds. */
-PyAPI_FUNC(int) PySequence_Check(PyObject *o);
-
-/* Return the size of sequence object o, or -1 on failure. */
-PyAPI_FUNC(Py_ssize_t) PySequence_Size(PyObject *o);
-
-/* For DLL compatibility */
-#undef PySequence_Length
-PyAPI_FUNC(Py_ssize_t) PySequence_Length(PyObject *o);
-#define PySequence_Length PySequence_Size
-
-
-/* Return the concatenation of o1 and o2 on success, and NULL on failure.
-
- This is the equivalent of the Python expression: o1 + o2. */
-PyAPI_FUNC(PyObject *) PySequence_Concat(PyObject *o1, PyObject *o2);
-
-/* Return the result of repeating sequence object 'o' 'count' times,
- or NULL on failure.
-
- This is the equivalent of the Python expression: o * count. */
-PyAPI_FUNC(PyObject *) PySequence_Repeat(PyObject *o, Py_ssize_t count);
-
-/* Return the ith element of o, or NULL on failure.
-
- This is the equivalent of the Python expression: o[i]. */
-PyAPI_FUNC(PyObject *) PySequence_GetItem(PyObject *o, Py_ssize_t i);
-
-/* Return the slice of sequence object o between i1 and i2, or NULL on failure.
-
- This is the equivalent of the Python expression: o[i1:i2]. */
-PyAPI_FUNC(PyObject *) PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2);
-
-/* Assign object 'v' to the ith element of the sequence 'o'. Raise an exception
- and return -1 on failure; return 0 on success.
-
- This is the equivalent of the Python statement o[i] = v. */
-PyAPI_FUNC(int) PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v);
-
-/* Delete the 'i'-th element of the sequence 'v'. Returns -1 on failure.
-
- This is the equivalent of the Python statement: del o[i]. */
-PyAPI_FUNC(int) PySequence_DelItem(PyObject *o, Py_ssize_t i);
-
-/* Assign the sequence object 'v' to the slice in sequence object 'o',
- from 'i1' to 'i2'. Returns -1 on failure.
-
- This is the equivalent of the Python statement: o[i1:i2] = v. */
-PyAPI_FUNC(int) PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2,
- PyObject *v);
-
-/* Delete the slice in sequence object 'o' from 'i1' to 'i2'.
- Returns -1 on failure.
-
- This is the equivalent of the Python statement: del o[i1:i2]. */
-PyAPI_FUNC(int) PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2);
-
-/* Returns the sequence 'o' as a tuple on success, and NULL on failure.
-
- This is equivalent to the Python expression: tuple(o). */
-PyAPI_FUNC(PyObject *) PySequence_Tuple(PyObject *o);
-
-/* Returns the sequence 'o' as a list on success, and NULL on failure.
- This is equivalent to the Python expression: list(o) */
-PyAPI_FUNC(PyObject *) PySequence_List(PyObject *o);
-
-/* Return the sequence 'o' as a list, unless it's already a tuple or list.
-
- Use PySequence_Fast_GET_ITEM to access the members of this list, and
- PySequence_Fast_GET_SIZE to get its length.
-
- Returns NULL on failure. If the object does not support iteration, raises a
- TypeError exception with 'm' as the message text. */
-PyAPI_FUNC(PyObject *) PySequence_Fast(PyObject *o, const char* m);
-
-/* Return the size of the sequence 'o', assuming that 'o' was returned by
- PySequence_Fast and is not NULL. */
-#define PySequence_Fast_GET_SIZE(o) \
- (PyList_Check(o) ? PyList_GET_SIZE(o) : PyTuple_GET_SIZE(o))
-
-/* Return the 'i'-th element of the sequence 'o', assuming that o was returned
- by PySequence_Fast, and that i is within bounds. */
-#define PySequence_Fast_GET_ITEM(o, i)\
- (PyList_Check(o) ? PyList_GET_ITEM(o, i) : PyTuple_GET_ITEM(o, i))
-
-/* Return a pointer to the underlying item array for
- an object returned by PySequence_Fast */
-#define PySequence_Fast_ITEMS(sf) \
- (PyList_Check(sf) ? ((PyListObject *)(sf))->ob_item \
- : ((PyTupleObject *)(sf))->ob_item)
-
-/* Return the number of occurrences on value on 'o', that is, return
- the number of keys for which o[key] == value.
-
- On failure, return -1. This is equivalent to the Python expression:
- o.count(value). */
-PyAPI_FUNC(Py_ssize_t) PySequence_Count(PyObject *o, PyObject *value);
-
-/* Return 1 if 'ob' is in the sequence 'seq'; 0 if 'ob' is not in the sequence
- 'seq'; -1 on error.
-
- Use __contains__ if possible, else _PySequence_IterSearch(). */
-PyAPI_FUNC(int) PySequence_Contains(PyObject *seq, PyObject *ob);
-
-/* For DLL-level backwards compatibility */
-#undef PySequence_In
-/* Determine if the sequence 'o' contains 'value'. If an item in 'o' is equal
- to 'value', return 1, otherwise return 0. On error, return -1.
-
- This is equivalent to the Python expression: value in o. */
-PyAPI_FUNC(int) PySequence_In(PyObject *o, PyObject *value);
-
-/* For source-level backwards compatibility */
-#define PySequence_In PySequence_Contains
-
-
-/* Return the first index for which o[i] == value.
- On error, return -1.
-
- This is equivalent to the Python expression: o.index(value). */
-PyAPI_FUNC(Py_ssize_t) PySequence_Index(PyObject *o, PyObject *value);
-
-
-/* --- In-place versions of some of the above Sequence functions --- */
-
-/* Append sequence 'o2' to sequence 'o1', in-place when possible. Return the
- resulting object, which could be 'o1', or NULL on failure.
-
- This is the equivalent of the Python expression: o1 += o2. */
-PyAPI_FUNC(PyObject *) PySequence_InPlaceConcat(PyObject *o1, PyObject *o2);
-
-/* Repeat sequence 'o' by 'count', in-place when possible. Return the resulting
- object, which could be 'o', or NULL on failure.
-
- This is the equivalent of the Python expression: o1 *= count. */
-PyAPI_FUNC(PyObject *) PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count);
-
-
-/* === Mapping protocol ================================================= */
-
-/* Return 1 if the object provides mapping protocol, and 0 otherwise.
-
- This function always succeeds. */
-PyAPI_FUNC(int) PyMapping_Check(PyObject *o);
-
-/* Returns the number of keys in mapping object 'o' on success, and -1 on
- failure. This is equivalent to the Python expression: len(o). */
-PyAPI_FUNC(Py_ssize_t) PyMapping_Size(PyObject *o);
-
-/* For DLL compatibility */
-#undef PyMapping_Length
-PyAPI_FUNC(Py_ssize_t) PyMapping_Length(PyObject *o);
-#define PyMapping_Length PyMapping_Size
-
-
-/* Implemented as a macro:
-
- int PyMapping_DelItemString(PyObject *o, const char *key);
-
- Remove the mapping for the string 'key' from the mapping 'o'. Returns -1 on
- failure.
-
- This is equivalent to the Python statement: del o[key]. */
-#define PyMapping_DelItemString(O,K) PyObject_DelItemString((O),(K))
-
-/* Implemented as a macro:
-
- int PyMapping_DelItem(PyObject *o, PyObject *key);
-
- Remove the mapping for the object 'key' from the mapping object 'o'.
- Returns -1 on failure.
-
- This is equivalent to the Python statement: del o[key]. */
-#define PyMapping_DelItem(O,K) PyObject_DelItem((O),(K))
-
-/* On success, return 1 if the mapping object 'o' has the key 'key',
- and 0 otherwise.
-
- This is equivalent to the Python expression: key in o.
-
- This function always succeeds. */
-PyAPI_FUNC(int) PyMapping_HasKeyString(PyObject *o, const char *key);
-
-/* Return 1 if the mapping object has the key 'key', and 0 otherwise.
-
- This is equivalent to the Python expression: key in o.
-
- This function always succeeds. */
-PyAPI_FUNC(int) PyMapping_HasKey(PyObject *o, PyObject *key);
-
-/* On success, return a list or tuple of the keys in mapping object 'o'.
- On failure, return NULL. */
-PyAPI_FUNC(PyObject *) PyMapping_Keys(PyObject *o);
-
-/* On success, return a list or tuple of the values in mapping object 'o'.
- On failure, return NULL. */
-PyAPI_FUNC(PyObject *) PyMapping_Values(PyObject *o);
-
-/* On success, return a list or tuple of the items in mapping object 'o',
- where each item is a tuple containing a key-value pair. On failure, return
- NULL. */
-PyAPI_FUNC(PyObject *) PyMapping_Items(PyObject *o);
-
-/* Return element of 'o' corresponding to the string 'key' or NULL on failure.
-
- This is the equivalent of the Python expression: o[key]. */
-PyAPI_FUNC(PyObject *) PyMapping_GetItemString(PyObject *o,
- const char *key);
-
-/* Map the string 'key' to the value 'v' in the mapping 'o'.
- Returns -1 on failure.
-
- This is the equivalent of the Python statement: o[key]=v. */
-PyAPI_FUNC(int) PyMapping_SetItemString(PyObject *o, const char *key,
- PyObject *value);
-
-/* isinstance(object, typeorclass) */
-PyAPI_FUNC(int) PyObject_IsInstance(PyObject *object, PyObject *typeorclass);
-
-/* issubclass(object, typeorclass) */
-PyAPI_FUNC(int) PyObject_IsSubclass(PyObject *object, PyObject *typeorclass);
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_ABSTRACTOBJECT_H
-# include "cpython/abstract.h"
-# undef Py_CPYTHON_ABSTRACTOBJECT_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* Py_ABSTRACTOBJECT_H */
diff --git a/include/python3.10/boolobject.h b/include/python3.10/boolobject.h
deleted file mode 100644
index cda6f89..0000000
--- a/include/python3.10/boolobject.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/* Boolean object interface */
-
-#ifndef Py_BOOLOBJECT_H
-#define Py_BOOLOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-PyAPI_DATA(PyTypeObject) PyBool_Type;
-
-#define PyBool_Check(x) Py_IS_TYPE(x, &PyBool_Type)
-
-/* Py_False and Py_True are the only two bools in existence.
-Don't forget to apply Py_INCREF() when returning either!!! */
-
-/* Don't use these directly */
-PyAPI_DATA(struct _longobject) _Py_FalseStruct;
-PyAPI_DATA(struct _longobject) _Py_TrueStruct;
-
-/* Use these macros */
-#define Py_False ((PyObject *) &_Py_FalseStruct)
-#define Py_True ((PyObject *) &_Py_TrueStruct)
-
-// Test if an object is the True singleton, the same as "x is True" in Python.
-PyAPI_FUNC(int) Py_IsTrue(PyObject *x);
-#define Py_IsTrue(x) Py_Is((x), Py_True)
-
-// Test if an object is the False singleton, the same as "x is False" in Python.
-PyAPI_FUNC(int) Py_IsFalse(PyObject *x);
-#define Py_IsFalse(x) Py_Is((x), Py_False)
-
-/* Macros for returning Py_True or Py_False, respectively */
-#define Py_RETURN_TRUE return Py_NewRef(Py_True)
-#define Py_RETURN_FALSE return Py_NewRef(Py_False)
-
-/* Function to return a bool from a C long */
-PyAPI_FUNC(PyObject *) PyBool_FromLong(long);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_BOOLOBJECT_H */
diff --git a/include/python3.10/bytearrayobject.h b/include/python3.10/bytearrayobject.h
deleted file mode 100644
index 9e95433..0000000
--- a/include/python3.10/bytearrayobject.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/* ByteArray object interface */
-
-#ifndef Py_BYTEARRAYOBJECT_H
-#define Py_BYTEARRAYOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <stdarg.h>
-
-/* Type PyByteArrayObject represents a mutable array of bytes.
- * The Python API is that of a sequence;
- * the bytes are mapped to ints in [0, 256).
- * Bytes are not characters; they may be used to encode characters.
- * The only way to go between bytes and str/unicode is via encoding
- * and decoding.
- * For the convenience of C programmers, the bytes type is considered
- * to contain a char pointer, not an unsigned char pointer.
- */
-
-/* Type object */
-PyAPI_DATA(PyTypeObject) PyByteArray_Type;
-PyAPI_DATA(PyTypeObject) PyByteArrayIter_Type;
-
-/* Type check macros */
-#define PyByteArray_Check(self) PyObject_TypeCheck(self, &PyByteArray_Type)
-#define PyByteArray_CheckExact(self) Py_IS_TYPE(self, &PyByteArray_Type)
-
-/* Direct API functions */
-PyAPI_FUNC(PyObject *) PyByteArray_FromObject(PyObject *);
-PyAPI_FUNC(PyObject *) PyByteArray_Concat(PyObject *, PyObject *);
-PyAPI_FUNC(PyObject *) PyByteArray_FromStringAndSize(const char *, Py_ssize_t);
-PyAPI_FUNC(Py_ssize_t) PyByteArray_Size(PyObject *);
-PyAPI_FUNC(char *) PyByteArray_AsString(PyObject *);
-PyAPI_FUNC(int) PyByteArray_Resize(PyObject *, Py_ssize_t);
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_BYTEARRAYOBJECT_H
-# include "cpython/bytearrayobject.h"
-# undef Py_CPYTHON_BYTEARRAYOBJECT_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_BYTEARRAYOBJECT_H */
diff --git a/include/python3.10/bytesobject.h b/include/python3.10/bytesobject.h
deleted file mode 100644
index 39c241a..0000000
--- a/include/python3.10/bytesobject.h
+++ /dev/null
@@ -1,69 +0,0 @@
-
-/* Bytes object interface */
-
-#ifndef Py_BYTESOBJECT_H
-#define Py_BYTESOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <stdarg.h>
-
-/*
-Type PyBytesObject represents a byte string. An extra zero byte is
-reserved at the end to ensure it is zero-terminated, but a size is
-present so strings with null bytes in them can be represented. This
-is an immutable object type.
-
-There are functions to create new bytes objects, to test
-an object for bytes-ness, and to get the
-byte string value. The latter function returns a null pointer
-if the object is not of the proper type.
-There is a variant that takes an explicit size as well as a
-variant that assumes a zero-terminated string. Note that none of the
-functions should be applied to NULL pointer.
-*/
-
-PyAPI_DATA(PyTypeObject) PyBytes_Type;
-PyAPI_DATA(PyTypeObject) PyBytesIter_Type;
-
-#define PyBytes_Check(op) \
- PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_BYTES_SUBCLASS)
-#define PyBytes_CheckExact(op) Py_IS_TYPE(op, &PyBytes_Type)
-
-PyAPI_FUNC(PyObject *) PyBytes_FromStringAndSize(const char *, Py_ssize_t);
-PyAPI_FUNC(PyObject *) PyBytes_FromString(const char *);
-PyAPI_FUNC(PyObject *) PyBytes_FromObject(PyObject *);
-PyAPI_FUNC(PyObject *) PyBytes_FromFormatV(const char*, va_list)
- Py_GCC_ATTRIBUTE((format(printf, 1, 0)));
-PyAPI_FUNC(PyObject *) PyBytes_FromFormat(const char*, ...)
- Py_GCC_ATTRIBUTE((format(printf, 1, 2)));
-PyAPI_FUNC(Py_ssize_t) PyBytes_Size(PyObject *);
-PyAPI_FUNC(char *) PyBytes_AsString(PyObject *);
-PyAPI_FUNC(PyObject *) PyBytes_Repr(PyObject *, int);
-PyAPI_FUNC(void) PyBytes_Concat(PyObject **, PyObject *);
-PyAPI_FUNC(void) PyBytes_ConcatAndDel(PyObject **, PyObject *);
-PyAPI_FUNC(PyObject *) PyBytes_DecodeEscape(const char *, Py_ssize_t,
- const char *, Py_ssize_t,
- const char *);
-
-/* Provides access to the internal data buffer and size of a bytes object.
- Passing NULL as len parameter will force the string buffer to be
- 0-terminated (passing a string with embedded NUL characters will
- cause an exception). */
-PyAPI_FUNC(int) PyBytes_AsStringAndSize(
- PyObject *obj, /* bytes object */
- char **s, /* pointer to buffer variable */
- Py_ssize_t *len /* pointer to length variable or NULL */
- );
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_BYTESOBJECT_H
-# include "cpython/bytesobject.h"
-# undef Py_CPYTHON_BYTESOBJECT_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_BYTESOBJECT_H */
diff --git a/include/python3.10/cellobject.h b/include/python3.10/cellobject.h
deleted file mode 100644
index 81bc784..0000000
--- a/include/python3.10/cellobject.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/* Cell object interface */
-#ifndef Py_LIMITED_API
-#ifndef Py_CELLOBJECT_H
-#define Py_CELLOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef struct {
- PyObject_HEAD
- PyObject *ob_ref; /* Content of the cell or NULL when empty */
-} PyCellObject;
-
-PyAPI_DATA(PyTypeObject) PyCell_Type;
-
-#define PyCell_Check(op) Py_IS_TYPE(op, &PyCell_Type)
-
-PyAPI_FUNC(PyObject *) PyCell_New(PyObject *);
-PyAPI_FUNC(PyObject *) PyCell_Get(PyObject *);
-PyAPI_FUNC(int) PyCell_Set(PyObject *, PyObject *);
-
-#define PyCell_GET(op) (((PyCellObject *)(op))->ob_ref)
-#define PyCell_SET(op, v) ((void)(((PyCellObject *)(op))->ob_ref = v))
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_TUPLEOBJECT_H */
-#endif /* Py_LIMITED_API */
diff --git a/include/python3.10/ceval.h b/include/python3.10/ceval.h
deleted file mode 100644
index 0f68766..0000000
--- a/include/python3.10/ceval.h
+++ /dev/null
@@ -1,158 +0,0 @@
-#ifndef Py_CEVAL_H
-#define Py_CEVAL_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-/* Interface to random parts in ceval.c */
-
-/* PyEval_CallObjectWithKeywords(), PyEval_CallObject(), PyEval_CallFunction
- * and PyEval_CallMethod are deprecated. Since they are officially part of the
- * stable ABI (PEP 384), they must be kept for backward compatibility.
- * PyObject_Call(), PyObject_CallFunction() and PyObject_CallMethod() are
- * recommended to call a callable object.
- */
-
-Py_DEPRECATED(3.9) PyAPI_FUNC(PyObject *) PyEval_CallObjectWithKeywords(
- PyObject *callable,
- PyObject *args,
- PyObject *kwargs);
-
-/* Deprecated since PyEval_CallObjectWithKeywords is deprecated */
-#define PyEval_CallObject(callable, arg) \
- PyEval_CallObjectWithKeywords(callable, arg, (PyObject *)NULL)
-
-Py_DEPRECATED(3.9) PyAPI_FUNC(PyObject *) PyEval_CallFunction(
- PyObject *callable, const char *format, ...);
-Py_DEPRECATED(3.9) PyAPI_FUNC(PyObject *) PyEval_CallMethod(
- PyObject *obj, const char *name, const char *format, ...);
-
-PyAPI_FUNC(PyObject *) PyEval_GetBuiltins(void);
-PyAPI_FUNC(PyObject *) PyEval_GetGlobals(void);
-PyAPI_FUNC(PyObject *) PyEval_GetLocals(void);
-PyAPI_FUNC(PyFrameObject *) PyEval_GetFrame(void);
-
-PyAPI_FUNC(int) Py_AddPendingCall(int (*func)(void *), void *arg);
-PyAPI_FUNC(int) Py_MakePendingCalls(void);
-
-/* Protection against deeply nested recursive calls
-
- In Python 3.0, this protection has two levels:
- * normal anti-recursion protection is triggered when the recursion level
- exceeds the current recursion limit. It raises a RecursionError, and sets
- the "overflowed" flag in the thread state structure. This flag
- temporarily *disables* the normal protection; this allows cleanup code
- to potentially outgrow the recursion limit while processing the
- RecursionError.
- * "last chance" anti-recursion protection is triggered when the recursion
- level exceeds "current recursion limit + 50". By construction, this
- protection can only be triggered when the "overflowed" flag is set. It
- means the cleanup code has itself gone into an infinite loop, or the
- RecursionError has been mistakingly ignored. When this protection is
- triggered, the interpreter aborts with a Fatal Error.
-
- In addition, the "overflowed" flag is automatically reset when the
- recursion level drops below "current recursion limit - 50". This heuristic
- is meant to ensure that the normal anti-recursion protection doesn't get
- disabled too long.
-
- Please note: this scheme has its own limitations. See:
- http://mail.python.org/pipermail/python-dev/2008-August/082106.html
- for some observations.
-*/
-PyAPI_FUNC(void) Py_SetRecursionLimit(int);
-PyAPI_FUNC(int) Py_GetRecursionLimit(void);
-
-PyAPI_FUNC(int) Py_EnterRecursiveCall(const char *where);
-PyAPI_FUNC(void) Py_LeaveRecursiveCall(void);
-
-PyAPI_FUNC(const char *) PyEval_GetFuncName(PyObject *);
-PyAPI_FUNC(const char *) PyEval_GetFuncDesc(PyObject *);
-
-PyAPI_FUNC(PyObject *) PyEval_EvalFrame(PyFrameObject *);
-PyAPI_FUNC(PyObject *) PyEval_EvalFrameEx(PyFrameObject *f, int exc);
-
-/* Interface for threads.
-
- A module that plans to do a blocking system call (or something else
- that lasts a long time and doesn't touch Python data) can allow other
- threads to run as follows:
-
- ...preparations here...
- Py_BEGIN_ALLOW_THREADS
- ...blocking system call here...
- Py_END_ALLOW_THREADS
- ...interpret result here...
-
- The Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS pair expands to a
- {}-surrounded block.
- To leave the block in the middle (e.g., with return), you must insert
- a line containing Py_BLOCK_THREADS before the return, e.g.
-
- if (...premature_exit...) {
- Py_BLOCK_THREADS
- PyErr_SetFromErrno(PyExc_OSError);
- return NULL;
- }
-
- An alternative is:
-
- Py_BLOCK_THREADS
- if (...premature_exit...) {
- PyErr_SetFromErrno(PyExc_OSError);
- return NULL;
- }
- Py_UNBLOCK_THREADS
-
- For convenience, that the value of 'errno' is restored across
- Py_END_ALLOW_THREADS and Py_BLOCK_THREADS.
-
- WARNING: NEVER NEST CALLS TO Py_BEGIN_ALLOW_THREADS AND
- Py_END_ALLOW_THREADS!!!
-
- Note that not yet all candidates have been converted to use this
- mechanism!
-*/
-
-PyAPI_FUNC(PyThreadState *) PyEval_SaveThread(void);
-PyAPI_FUNC(void) PyEval_RestoreThread(PyThreadState *);
-
-Py_DEPRECATED(3.9) PyAPI_FUNC(int) PyEval_ThreadsInitialized(void);
-Py_DEPRECATED(3.9) PyAPI_FUNC(void) PyEval_InitThreads(void);
-/* PyEval_AcquireLock() and PyEval_ReleaseLock() are part of stable ABI.
- * They will be removed from this header file in the future version.
- * But they will be remained in ABI until Python 4.0.
- */
-Py_DEPRECATED(3.2) PyAPI_FUNC(void) PyEval_AcquireLock(void);
-Py_DEPRECATED(3.2) PyAPI_FUNC(void) PyEval_ReleaseLock(void);
-PyAPI_FUNC(void) PyEval_AcquireThread(PyThreadState *tstate);
-PyAPI_FUNC(void) PyEval_ReleaseThread(PyThreadState *tstate);
-
-#define Py_BEGIN_ALLOW_THREADS { \
- PyThreadState *_save; \
- _save = PyEval_SaveThread();
-#define Py_BLOCK_THREADS PyEval_RestoreThread(_save);
-#define Py_UNBLOCK_THREADS _save = PyEval_SaveThread();
-#define Py_END_ALLOW_THREADS PyEval_RestoreThread(_save); \
- }
-
-/* Masks and values used by FORMAT_VALUE opcode. */
-#define FVC_MASK 0x3
-#define FVC_NONE 0x0
-#define FVC_STR 0x1
-#define FVC_REPR 0x2
-#define FVC_ASCII 0x3
-#define FVS_MASK 0x4
-#define FVS_HAVE_SPEC 0x4
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_CEVAL_H
-# include "cpython/ceval.h"
-# undef Py_CPYTHON_CEVAL_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_CEVAL_H */
diff --git a/include/python3.10/classobject.h b/include/python3.10/classobject.h
deleted file mode 100644
index 1952f67..0000000
--- a/include/python3.10/classobject.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/* Former class object interface -- now only bound methods are here */
-
-/* Revealing some structures (not for general use) */
-
-#ifndef Py_LIMITED_API
-#ifndef Py_CLASSOBJECT_H
-#define Py_CLASSOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef struct {
- PyObject_HEAD
- PyObject *im_func; /* The callable object implementing the method */
- PyObject *im_self; /* The instance it is bound to */
- PyObject *im_weakreflist; /* List of weak references */
- vectorcallfunc vectorcall;
-} PyMethodObject;
-
-PyAPI_DATA(PyTypeObject) PyMethod_Type;
-
-#define PyMethod_Check(op) Py_IS_TYPE(op, &PyMethod_Type)
-
-PyAPI_FUNC(PyObject *) PyMethod_New(PyObject *, PyObject *);
-
-PyAPI_FUNC(PyObject *) PyMethod_Function(PyObject *);
-PyAPI_FUNC(PyObject *) PyMethod_Self(PyObject *);
-
-/* Macros for direct access to these values. Type checks are *not*
- done, so use with care. */
-#define PyMethod_GET_FUNCTION(meth) \
- (((PyMethodObject *)meth) -> im_func)
-#define PyMethod_GET_SELF(meth) \
- (((PyMethodObject *)meth) -> im_self)
-
-typedef struct {
- PyObject_HEAD
- PyObject *func;
-} PyInstanceMethodObject;
-
-PyAPI_DATA(PyTypeObject) PyInstanceMethod_Type;
-
-#define PyInstanceMethod_Check(op) Py_IS_TYPE(op, &PyInstanceMethod_Type)
-
-PyAPI_FUNC(PyObject *) PyInstanceMethod_New(PyObject *);
-PyAPI_FUNC(PyObject *) PyInstanceMethod_Function(PyObject *);
-
-/* Macros for direct access to these values. Type checks are *not*
- done, so use with care. */
-#define PyInstanceMethod_GET_FUNCTION(meth) \
- (((PyInstanceMethodObject *)meth) -> func)
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_CLASSOBJECT_H */
-#endif /* Py_LIMITED_API */
diff --git a/include/python3.10/code.h b/include/python3.10/code.h
deleted file mode 100644
index b9e23eb..0000000
--- a/include/python3.10/code.h
+++ /dev/null
@@ -1,20 +0,0 @@
-/* Definitions for bytecode */
-
-#ifndef Py_CODE_H
-#define Py_CODE_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef struct PyCodeObject PyCodeObject;
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_CODE_H
-# include "cpython/code.h"
-# undef Py_CPYTHON_CODE_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_CODE_H */
diff --git a/include/python3.10/complexobject.h b/include/python3.10/complexobject.h
deleted file mode 100644
index 9221f9c..0000000
--- a/include/python3.10/complexobject.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/* Complex number structure */
-
-#ifndef Py_COMPLEXOBJECT_H
-#define Py_COMPLEXOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_LIMITED_API
-typedef struct {
- double real;
- double imag;
-} Py_complex;
-
-/* Operations on complex numbers from complexmodule.c */
-
-PyAPI_FUNC(Py_complex) _Py_c_sum(Py_complex, Py_complex);
-PyAPI_FUNC(Py_complex) _Py_c_diff(Py_complex, Py_complex);
-PyAPI_FUNC(Py_complex) _Py_c_neg(Py_complex);
-PyAPI_FUNC(Py_complex) _Py_c_prod(Py_complex, Py_complex);
-PyAPI_FUNC(Py_complex) _Py_c_quot(Py_complex, Py_complex);
-PyAPI_FUNC(Py_complex) _Py_c_pow(Py_complex, Py_complex);
-PyAPI_FUNC(double) _Py_c_abs(Py_complex);
-#endif
-
-/* Complex object interface */
-
-/*
-PyComplexObject represents a complex number with double-precision
-real and imaginary parts.
-*/
-#ifndef Py_LIMITED_API
-typedef struct {
- PyObject_HEAD
- Py_complex cval;
-} PyComplexObject;
-#endif
-
-PyAPI_DATA(PyTypeObject) PyComplex_Type;
-
-#define PyComplex_Check(op) PyObject_TypeCheck(op, &PyComplex_Type)
-#define PyComplex_CheckExact(op) Py_IS_TYPE(op, &PyComplex_Type)
-
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(PyObject *) PyComplex_FromCComplex(Py_complex);
-#endif
-PyAPI_FUNC(PyObject *) PyComplex_FromDoubles(double real, double imag);
-
-PyAPI_FUNC(double) PyComplex_RealAsDouble(PyObject *op);
-PyAPI_FUNC(double) PyComplex_ImagAsDouble(PyObject *op);
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(Py_complex) PyComplex_AsCComplex(PyObject *op);
-#endif
-
-/* Format the object based on the format_spec, as defined in PEP 3101
- (Advanced String Formatting). */
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(int) _PyComplex_FormatAdvancedWriter(
- _PyUnicodeWriter *writer,
- PyObject *obj,
- PyObject *format_spec,
- Py_ssize_t start,
- Py_ssize_t end);
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_COMPLEXOBJECT_H */
diff --git a/include/python3.10/context.h b/include/python3.10/context.h
deleted file mode 100644
index 4e50070..0000000
--- a/include/python3.10/context.h
+++ /dev/null
@@ -1,81 +0,0 @@
-#ifndef Py_CONTEXT_H
-#define Py_CONTEXT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_LIMITED_API
-
-
-PyAPI_DATA(PyTypeObject) PyContext_Type;
-typedef struct _pycontextobject PyContext;
-
-PyAPI_DATA(PyTypeObject) PyContextVar_Type;
-typedef struct _pycontextvarobject PyContextVar;
-
-PyAPI_DATA(PyTypeObject) PyContextToken_Type;
-typedef struct _pycontexttokenobject PyContextToken;
-
-
-#define PyContext_CheckExact(o) Py_IS_TYPE(o, &PyContext_Type)
-#define PyContextVar_CheckExact(o) Py_IS_TYPE(o, &PyContextVar_Type)
-#define PyContextToken_CheckExact(o) Py_IS_TYPE(o, &PyContextToken_Type)
-
-
-PyAPI_FUNC(PyObject *) PyContext_New(void);
-PyAPI_FUNC(PyObject *) PyContext_Copy(PyObject *);
-PyAPI_FUNC(PyObject *) PyContext_CopyCurrent(void);
-
-PyAPI_FUNC(int) PyContext_Enter(PyObject *);
-PyAPI_FUNC(int) PyContext_Exit(PyObject *);
-
-
-/* Create a new context variable.
-
- default_value can be NULL.
-*/
-PyAPI_FUNC(PyObject *) PyContextVar_New(
- const char *name, PyObject *default_value);
-
-
-/* Get a value for the variable.
-
- Returns -1 if an error occurred during lookup.
-
- Returns 0 if value either was or was not found.
-
- If value was found, *value will point to it.
- If not, it will point to:
-
- - default_value, if not NULL;
- - the default value of "var", if not NULL;
- - NULL.
-
- '*value' will be a new ref, if not NULL.
-*/
-PyAPI_FUNC(int) PyContextVar_Get(
- PyObject *var, PyObject *default_value, PyObject **value);
-
-
-/* Set a new value for the variable.
- Returns NULL if an error occurs.
-*/
-PyAPI_FUNC(PyObject *) PyContextVar_Set(PyObject *var, PyObject *value);
-
-
-/* Reset a variable to its previous value.
- Returns 0 on success, -1 on error.
-*/
-PyAPI_FUNC(int) PyContextVar_Reset(PyObject *var, PyObject *token);
-
-
-/* This method is exposed only for CPython tests. Don not use it. */
-PyAPI_FUNC(PyObject *) _PyContext_NewHamtForTests(void);
-
-
-#endif /* !Py_LIMITED_API */
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_CONTEXT_H */
diff --git a/include/python3.10/cpython/abstract.h b/include/python3.10/cpython/abstract.h
deleted file mode 100644
index db85021..0000000
--- a/include/python3.10/cpython/abstract.h
+++ /dev/null
@@ -1,373 +0,0 @@
-#ifndef Py_CPYTHON_ABSTRACTOBJECT_H
-# error "this header file must not be included directly"
-#endif
-
-/* === Object Protocol ================================================== */
-
-#ifdef PY_SSIZE_T_CLEAN
-# define _PyObject_CallMethodId _PyObject_CallMethodId_SizeT
-#endif
-
-/* Convert keyword arguments from the FASTCALL (stack: C array, kwnames: tuple)
- format to a Python dictionary ("kwargs" dict).
-
- The type of kwnames keys is not checked. The final function getting
- arguments is responsible to check if all keys are strings, for example using
- PyArg_ParseTupleAndKeywords() or PyArg_ValidateKeywordArguments().
-
- Duplicate keys are merged using the last value. If duplicate keys must raise
- an exception, the caller is responsible to implement an explicit keys on
- kwnames. */
-PyAPI_FUNC(PyObject *) _PyStack_AsDict(
- PyObject *const *values,
- PyObject *kwnames);
-
-/* Suggested size (number of positional arguments) for arrays of PyObject*
- allocated on a C stack to avoid allocating memory on the heap memory. Such
- array is used to pass positional arguments to call functions of the
- PyObject_Vectorcall() family.
-
- The size is chosen to not abuse the C stack and so limit the risk of stack
- overflow. The size is also chosen to allow using the small stack for most
- function calls of the Python standard library. On 64-bit CPU, it allocates
- 40 bytes on the stack. */
-#define _PY_FASTCALL_SMALL_STACK 5
-
-PyAPI_FUNC(PyObject *) _Py_CheckFunctionResult(
- PyThreadState *tstate,
- PyObject *callable,
- PyObject *result,
- const char *where);
-
-/* === Vectorcall protocol (PEP 590) ============================= */
-
-/* Call callable using tp_call. Arguments are like PyObject_Vectorcall()
- or PyObject_FastCallDict() (both forms are supported),
- except that nargs is plainly the number of arguments without flags. */
-PyAPI_FUNC(PyObject *) _PyObject_MakeTpCall(
- PyThreadState *tstate,
- PyObject *callable,
- PyObject *const *args, Py_ssize_t nargs,
- PyObject *keywords);
-
-#define PY_VECTORCALL_ARGUMENTS_OFFSET ((size_t)1 << (8 * sizeof(size_t) - 1))
-
-static inline Py_ssize_t
-PyVectorcall_NARGS(size_t n)
-{
- return n & ~PY_VECTORCALL_ARGUMENTS_OFFSET;
-}
-
-static inline vectorcallfunc
-PyVectorcall_Function(PyObject *callable)
-{
- PyTypeObject *tp;
- Py_ssize_t offset;
- vectorcallfunc ptr;
-
- assert(callable != NULL);
- tp = Py_TYPE(callable);
- if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_VECTORCALL)) {
- return NULL;
- }
- assert(PyCallable_Check(callable));
- offset = tp->tp_vectorcall_offset;
- assert(offset > 0);
- memcpy(&ptr, (char *) callable + offset, sizeof(ptr));
- return ptr;
-}
-
-/* Call the callable object 'callable' with the "vectorcall" calling
- convention.
-
- args is a C array for positional arguments.
-
- nargsf is the number of positional arguments plus optionally the flag
- PY_VECTORCALL_ARGUMENTS_OFFSET which means that the caller is allowed to
- modify args[-1].
-
- kwnames is a tuple of keyword names. The values of the keyword arguments
- are stored in "args" after the positional arguments (note that the number
- of keyword arguments does not change nargsf). kwnames can also be NULL if
- there are no keyword arguments.
-
- keywords must only contain strings and all keys must be unique.
-
- Return the result on success. Raise an exception and return NULL on
- error. */
-static inline PyObject *
-_PyObject_VectorcallTstate(PyThreadState *tstate, PyObject *callable,
- PyObject *const *args, size_t nargsf,
- PyObject *kwnames)
-{
- vectorcallfunc func;
- PyObject *res;
-
- assert(kwnames == NULL || PyTuple_Check(kwnames));
- assert(args != NULL || PyVectorcall_NARGS(nargsf) == 0);
-
- func = PyVectorcall_Function(callable);
- if (func == NULL) {
- Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
- return _PyObject_MakeTpCall(tstate, callable, args, nargs, kwnames);
- }
- res = func(callable, args, nargsf, kwnames);
- return _Py_CheckFunctionResult(tstate, callable, res, NULL);
-}
-
-static inline PyObject *
-PyObject_Vectorcall(PyObject *callable, PyObject *const *args,
- size_t nargsf, PyObject *kwnames)
-{
- PyThreadState *tstate = PyThreadState_Get();
- return _PyObject_VectorcallTstate(tstate, callable,
- args, nargsf, kwnames);
-}
-
-// Backwards compatibility aliases for API that was provisional in Python 3.8
-#define _PyObject_Vectorcall PyObject_Vectorcall
-#define _PyObject_VectorcallMethod PyObject_VectorcallMethod
-#define _PyObject_FastCallDict PyObject_VectorcallDict
-#define _PyVectorcall_Function PyVectorcall_Function
-#define _PyObject_CallOneArg PyObject_CallOneArg
-#define _PyObject_CallMethodNoArgs PyObject_CallMethodNoArgs
-#define _PyObject_CallMethodOneArg PyObject_CallMethodOneArg
-
-/* Same as PyObject_Vectorcall except that keyword arguments are passed as
- dict, which may be NULL if there are no keyword arguments. */
-PyAPI_FUNC(PyObject *) PyObject_VectorcallDict(
- PyObject *callable,
- PyObject *const *args,
- size_t nargsf,
- PyObject *kwargs);
-
-/* Call "callable" (which must support vectorcall) with positional arguments
- "tuple" and keyword arguments "dict". "dict" may also be NULL */
-PyAPI_FUNC(PyObject *) PyVectorcall_Call(PyObject *callable, PyObject *tuple, PyObject *dict);
-
-static inline PyObject *
-_PyObject_FastCallTstate(PyThreadState *tstate, PyObject *func, PyObject *const *args, Py_ssize_t nargs)
-{
- return _PyObject_VectorcallTstate(tstate, func, args, (size_t)nargs, NULL);
-}
-
-/* Same as PyObject_Vectorcall except without keyword arguments */
-static inline PyObject *
-_PyObject_FastCall(PyObject *func, PyObject *const *args, Py_ssize_t nargs)
-{
- PyThreadState *tstate = PyThreadState_Get();
- return _PyObject_FastCallTstate(tstate, func, args, nargs);
-}
-
-/* Call a callable without any arguments
- Private static inline function variant of public function
- PyObject_CallNoArgs(). */
-static inline PyObject *
-_PyObject_CallNoArg(PyObject *func) {
- PyThreadState *tstate = PyThreadState_Get();
- return _PyObject_VectorcallTstate(tstate, func, NULL, 0, NULL);
-}
-
-static inline PyObject *
-PyObject_CallOneArg(PyObject *func, PyObject *arg)
-{
- PyObject *_args[2];
- PyObject **args;
- PyThreadState *tstate;
- size_t nargsf;
-
- assert(arg != NULL);
- args = _args + 1; // For PY_VECTORCALL_ARGUMENTS_OFFSET
- args[0] = arg;
- tstate = PyThreadState_Get();
- nargsf = 1 | PY_VECTORCALL_ARGUMENTS_OFFSET;
- return _PyObject_VectorcallTstate(tstate, func, args, nargsf, NULL);
-}
-
-PyAPI_FUNC(PyObject *) PyObject_VectorcallMethod(
- PyObject *name, PyObject *const *args,
- size_t nargsf, PyObject *kwnames);
-
-static inline PyObject *
-PyObject_CallMethodNoArgs(PyObject *self, PyObject *name)
-{
- return PyObject_VectorcallMethod(name, &self,
- 1 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL);
-}
-
-static inline PyObject *
-PyObject_CallMethodOneArg(PyObject *self, PyObject *name, PyObject *arg)
-{
- PyObject *args[2] = {self, arg};
-
- assert(arg != NULL);
- return PyObject_VectorcallMethod(name, args,
- 2 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL);
-}
-
-/* Like PyObject_CallMethod(), but expect a _Py_Identifier*
- as the method name. */
-PyAPI_FUNC(PyObject *) _PyObject_CallMethodId(PyObject *obj,
- _Py_Identifier *name,
- const char *format, ...);
-
-PyAPI_FUNC(PyObject *) _PyObject_CallMethodId_SizeT(PyObject *obj,
- _Py_Identifier *name,
- const char *format,
- ...);
-
-PyAPI_FUNC(PyObject *) _PyObject_CallMethodIdObjArgs(
- PyObject *obj,
- struct _Py_Identifier *name,
- ...);
-
-static inline PyObject *
-_PyObject_VectorcallMethodId(
- _Py_Identifier *name, PyObject *const *args,
- size_t nargsf, PyObject *kwnames)
-{
- PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
- if (!oname) {
- return NULL;
- }
- return PyObject_VectorcallMethod(oname, args, nargsf, kwnames);
-}
-
-static inline PyObject *
-_PyObject_CallMethodIdNoArgs(PyObject *self, _Py_Identifier *name)
-{
- return _PyObject_VectorcallMethodId(name, &self,
- 1 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL);
-}
-
-static inline PyObject *
-_PyObject_CallMethodIdOneArg(PyObject *self, _Py_Identifier *name, PyObject *arg)
-{
- PyObject *args[2] = {self, arg};
-
- assert(arg != NULL);
- return _PyObject_VectorcallMethodId(name, args,
- 2 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL);
-}
-
-PyAPI_FUNC(int) _PyObject_HasLen(PyObject *o);
-
-/* Guess the size of object 'o' using len(o) or o.__length_hint__().
- If neither of those return a non-negative value, then return the default
- value. If one of the calls fails, this function returns -1. */
-PyAPI_FUNC(Py_ssize_t) PyObject_LengthHint(PyObject *o, Py_ssize_t);
-
-/* === New Buffer API ============================================ */
-
-/* Return 1 if the getbuffer function is available, otherwise return 0. */
-PyAPI_FUNC(int) PyObject_CheckBuffer(PyObject *obj);
-
-/* This is a C-API version of the getbuffer function call. It checks
- to make sure object has the required function pointer and issues the
- call.
-
- Returns -1 and raises an error on failure and returns 0 on success. */
-PyAPI_FUNC(int) PyObject_GetBuffer(PyObject *obj, Py_buffer *view,
- int flags);
-
-/* Get the memory area pointed to by the indices for the buffer given.
- Note that view->ndim is the assumed size of indices. */
-PyAPI_FUNC(void *) PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices);
-
-/* Return the implied itemsize of the data-format area from a
- struct-style description. */
-PyAPI_FUNC(Py_ssize_t) PyBuffer_SizeFromFormat(const char *format);
-
-/* Implementation in memoryobject.c */
-PyAPI_FUNC(int) PyBuffer_ToContiguous(void *buf, Py_buffer *view,
- Py_ssize_t len, char order);
-
-PyAPI_FUNC(int) PyBuffer_FromContiguous(Py_buffer *view, void *buf,
- Py_ssize_t len, char order);
-
-/* Copy len bytes of data from the contiguous chunk of memory
- pointed to by buf into the buffer exported by obj. Return
- 0 on success and return -1 and raise a PyBuffer_Error on
- error (i.e. the object does not have a buffer interface or
- it is not working).
-
- If fort is 'F', then if the object is multi-dimensional,
- then the data will be copied into the array in
- Fortran-style (first dimension varies the fastest). If
- fort is 'C', then the data will be copied into the array
- in C-style (last dimension varies the fastest). If fort
- is 'A', then it does not matter and the copy will be made
- in whatever way is more efficient. */
-PyAPI_FUNC(int) PyObject_CopyData(PyObject *dest, PyObject *src);
-
-/* Copy the data from the src buffer to the buffer of destination. */
-PyAPI_FUNC(int) PyBuffer_IsContiguous(const Py_buffer *view, char fort);
-
-/*Fill the strides array with byte-strides of a contiguous
- (Fortran-style if fort is 'F' or C-style otherwise)
- array of the given shape with the given number of bytes
- per element. */
-PyAPI_FUNC(void) PyBuffer_FillContiguousStrides(int ndims,
- Py_ssize_t *shape,
- Py_ssize_t *strides,
- int itemsize,
- char fort);
-
-/* Fills in a buffer-info structure correctly for an exporter
- that can only share a contiguous chunk of memory of
- "unsigned bytes" of the given length.
-
- Returns 0 on success and -1 (with raising an error) on error. */
-PyAPI_FUNC(int) PyBuffer_FillInfo(Py_buffer *view, PyObject *o, void *buf,
- Py_ssize_t len, int readonly,
- int flags);
-
-/* Releases a Py_buffer obtained from getbuffer ParseTuple's "s*". */
-PyAPI_FUNC(void) PyBuffer_Release(Py_buffer *view);
-
-/* === Sequence protocol ================================================ */
-
-/* Assume tp_as_sequence and sq_item exist and that 'i' does not
- need to be corrected for a negative index. */
-#define PySequence_ITEM(o, i)\
- ( Py_TYPE(o)->tp_as_sequence->sq_item(o, i) )
-
-#define PY_ITERSEARCH_COUNT 1
-#define PY_ITERSEARCH_INDEX 2
-#define PY_ITERSEARCH_CONTAINS 3
-
-/* Iterate over seq.
-
- Result depends on the operation:
-
- PY_ITERSEARCH_COUNT: return # of times obj appears in seq; -1 if
- error.
- PY_ITERSEARCH_INDEX: return 0-based index of first occurrence of
- obj in seq; set ValueError and return -1 if none found;
- also return -1 on error.
- PY_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on
- error. */
-PyAPI_FUNC(Py_ssize_t) _PySequence_IterSearch(PyObject *seq,
- PyObject *obj, int operation);
-
-/* === Mapping protocol ================================================= */
-
-PyAPI_FUNC(int) _PyObject_RealIsInstance(PyObject *inst, PyObject *cls);
-
-PyAPI_FUNC(int) _PyObject_RealIsSubclass(PyObject *derived, PyObject *cls);
-
-PyAPI_FUNC(char *const *) _PySequence_BytesToCharpArray(PyObject* self);
-
-PyAPI_FUNC(void) _Py_FreeCharPArray(char *const array[]);
-
-/* For internal use by buffer API functions */
-PyAPI_FUNC(void) _Py_add_one_to_index_F(int nd, Py_ssize_t *index,
- const Py_ssize_t *shape);
-PyAPI_FUNC(void) _Py_add_one_to_index_C(int nd, Py_ssize_t *index,
- const Py_ssize_t *shape);
-
-/* Convert Python int to Py_ssize_t. Do nothing if the argument is None. */
-PyAPI_FUNC(int) _Py_convert_optional_to_ssize_t(PyObject *, void *);
-
-/* Same as PyNumber_Index but can return an instance of a subclass of int. */
-PyAPI_FUNC(PyObject *) _PyNumber_Index(PyObject *o);
diff --git a/include/python3.10/cpython/bytearrayobject.h b/include/python3.10/cpython/bytearrayobject.h
deleted file mode 100644
index 569b0cd..0000000
--- a/include/python3.10/cpython/bytearrayobject.h
+++ /dev/null
@@ -1,20 +0,0 @@
-#ifndef Py_CPYTHON_BYTEARRAYOBJECT_H
-# error "this header file must not be included directly"
-#endif
-
-/* Object layout */
-typedef struct {
- PyObject_VAR_HEAD
- Py_ssize_t ob_alloc; /* How many bytes allocated in ob_bytes */
- char *ob_bytes; /* Physical backing buffer */
- char *ob_start; /* Logical start inside ob_bytes */
- Py_ssize_t ob_exports; /* How many buffer exports */
-} PyByteArrayObject;
-
-/* Macros, trading safety for speed */
-#define PyByteArray_AS_STRING(self) \
- (assert(PyByteArray_Check(self)), \
- Py_SIZE(self) ? ((PyByteArrayObject *)(self))->ob_start : _PyByteArray_empty_string)
-#define PyByteArray_GET_SIZE(self) (assert(PyByteArray_Check(self)), Py_SIZE(self))
-
-PyAPI_DATA(char) _PyByteArray_empty_string[];
diff --git a/include/python3.10/cpython/bytesobject.h b/include/python3.10/cpython/bytesobject.h
deleted file mode 100644
index 6b3f552..0000000
--- a/include/python3.10/cpython/bytesobject.h
+++ /dev/null
@@ -1,118 +0,0 @@
-#ifndef Py_CPYTHON_BYTESOBJECT_H
-# error "this header file must not be included directly"
-#endif
-
-typedef struct {
- PyObject_VAR_HEAD
- Py_hash_t ob_shash;
- char ob_sval[1];
-
- /* Invariants:
- * ob_sval contains space for 'ob_size+1' elements.
- * ob_sval[ob_size] == 0.
- * ob_shash is the hash of the byte string or -1 if not computed yet.
- */
-} PyBytesObject;
-
-PyAPI_FUNC(int) _PyBytes_Resize(PyObject **, Py_ssize_t);
-PyAPI_FUNC(PyObject*) _PyBytes_FormatEx(
- const char *format,
- Py_ssize_t format_len,
- PyObject *args,
- int use_bytearray);
-PyAPI_FUNC(PyObject*) _PyBytes_FromHex(
- PyObject *string,
- int use_bytearray);
-
-/* Helper for PyBytes_DecodeEscape that detects invalid escape chars. */
-PyAPI_FUNC(PyObject *) _PyBytes_DecodeEscape(const char *, Py_ssize_t,
- const char *, const char **);
-
-/* Macro, trading safety for speed */
-#define PyBytes_AS_STRING(op) (assert(PyBytes_Check(op)), \
- (((PyBytesObject *)(op))->ob_sval))
-#define PyBytes_GET_SIZE(op) (assert(PyBytes_Check(op)),Py_SIZE(op))
-
-/* _PyBytes_Join(sep, x) is like sep.join(x). sep must be PyBytesObject*,
- x must be an iterable object. */
-PyAPI_FUNC(PyObject *) _PyBytes_Join(PyObject *sep, PyObject *x);
-
-
-/* The _PyBytesWriter structure is big: it contains an embedded "stack buffer".
- A _PyBytesWriter variable must be declared at the end of variables in a
- function to optimize the memory allocation on the stack. */
-typedef struct {
- /* bytes, bytearray or NULL (when the small buffer is used) */
- PyObject *buffer;
-
- /* Number of allocated size. */
- Py_ssize_t allocated;
-
- /* Minimum number of allocated bytes,
- incremented by _PyBytesWriter_Prepare() */
- Py_ssize_t min_size;
-
- /* If non-zero, use a bytearray instead of a bytes object for buffer. */
- int use_bytearray;
-
- /* If non-zero, overallocate the buffer (default: 0).
- This flag must be zero if use_bytearray is non-zero. */
- int overallocate;
-
- /* Stack buffer */
- int use_small_buffer;
- char small_buffer[512];
-} _PyBytesWriter;
-
-/* Initialize a bytes writer
-
- By default, the overallocation is disabled. Set the overallocate attribute
- to control the allocation of the buffer. */
-PyAPI_FUNC(void) _PyBytesWriter_Init(_PyBytesWriter *writer);
-
-/* Get the buffer content and reset the writer.
- Return a bytes object, or a bytearray object if use_bytearray is non-zero.
- Raise an exception and return NULL on error. */
-PyAPI_FUNC(PyObject *) _PyBytesWriter_Finish(_PyBytesWriter *writer,
- void *str);
-
-/* Deallocate memory of a writer (clear its internal buffer). */
-PyAPI_FUNC(void) _PyBytesWriter_Dealloc(_PyBytesWriter *writer);
-
-/* Allocate the buffer to write size bytes.
- Return the pointer to the beginning of buffer data.
- Raise an exception and return NULL on error. */
-PyAPI_FUNC(void*) _PyBytesWriter_Alloc(_PyBytesWriter *writer,
- Py_ssize_t size);
-
-/* Ensure that the buffer is large enough to write *size* bytes.
- Add size to the writer minimum size (min_size attribute).
-
- str is the current pointer inside the buffer.
- Return the updated current pointer inside the buffer.
- Raise an exception and return NULL on error. */
-PyAPI_FUNC(void*) _PyBytesWriter_Prepare(_PyBytesWriter *writer,
- void *str,
- Py_ssize_t size);
-
-/* Resize the buffer to make it larger.
- The new buffer may be larger than size bytes because of overallocation.
- Return the updated current pointer inside the buffer.
- Raise an exception and return NULL on error.
-
- Note: size must be greater than the number of allocated bytes in the writer.
-
- This function doesn't use the writer minimum size (min_size attribute).
-
- See also _PyBytesWriter_Prepare().
- */
-PyAPI_FUNC(void*) _PyBytesWriter_Resize(_PyBytesWriter *writer,
- void *str,
- Py_ssize_t size);
-
-/* Write bytes.
- Raise an exception and return NULL on error. */
-PyAPI_FUNC(void*) _PyBytesWriter_WriteBytes(_PyBytesWriter *writer,
- void *str,
- const void *bytes,
- Py_ssize_t size);
diff --git a/include/python3.10/cpython/ceval.h b/include/python3.10/cpython/ceval.h
deleted file mode 100644
index 0633892..0000000
--- a/include/python3.10/cpython/ceval.h
+++ /dev/null
@@ -1,30 +0,0 @@
-#ifndef Py_CPYTHON_CEVAL_H
-# error "this header file must not be included directly"
-#endif
-
-PyAPI_FUNC(void) PyEval_SetProfile(Py_tracefunc, PyObject *);
-PyAPI_DATA(int) _PyEval_SetProfile(PyThreadState *tstate, Py_tracefunc func, PyObject *arg);
-PyAPI_FUNC(void) PyEval_SetTrace(Py_tracefunc, PyObject *);
-PyAPI_FUNC(int) _PyEval_SetTrace(PyThreadState *tstate, Py_tracefunc func, PyObject *arg);
-PyAPI_FUNC(int) _PyEval_GetCoroutineOriginTrackingDepth(void);
-PyAPI_FUNC(int) _PyEval_SetAsyncGenFirstiter(PyObject *);
-PyAPI_FUNC(PyObject *) _PyEval_GetAsyncGenFirstiter(void);
-PyAPI_FUNC(int) _PyEval_SetAsyncGenFinalizer(PyObject *);
-PyAPI_FUNC(PyObject *) _PyEval_GetAsyncGenFinalizer(void);
-
-/* Helper to look up a builtin object */
-PyAPI_FUNC(PyObject *) _PyEval_GetBuiltinId(_Py_Identifier *);
-/* Look at the current frame's (if any) code's co_flags, and turn on
- the corresponding compiler flags in cf->cf_flags. Return 1 if any
- flag was set, else return 0. */
-PyAPI_FUNC(int) PyEval_MergeCompilerFlags(PyCompilerFlags *cf);
-
-PyAPI_FUNC(PyObject *) _PyEval_EvalFrameDefault(PyThreadState *tstate, PyFrameObject *f, int exc);
-
-PyAPI_FUNC(void) _PyEval_SetSwitchInterval(unsigned long microseconds);
-PyAPI_FUNC(unsigned long) _PyEval_GetSwitchInterval(void);
-
-PyAPI_FUNC(Py_ssize_t) _PyEval_RequestCodeExtraIndex(freefunc);
-
-PyAPI_FUNC(int) _PyEval_SliceIndex(PyObject *, Py_ssize_t *);
-PyAPI_FUNC(int) _PyEval_SliceIndexNotNone(PyObject *, Py_ssize_t *);
diff --git a/include/python3.10/cpython/code.h b/include/python3.10/cpython/code.h
deleted file mode 100644
index fa64085..0000000
--- a/include/python3.10/cpython/code.h
+++ /dev/null
@@ -1,184 +0,0 @@
-#ifndef Py_CPYTHON_CODE_H
-# error "this header file must not be included directly"
-#endif
-
-typedef uint16_t _Py_CODEUNIT;
-
-#ifdef WORDS_BIGENDIAN
-# define _Py_OPCODE(word) ((word) >> 8)
-# define _Py_OPARG(word) ((word) & 255)
-#else
-# define _Py_OPCODE(word) ((word) & 255)
-# define _Py_OPARG(word) ((word) >> 8)
-#endif
-
-typedef struct _PyOpcache _PyOpcache;
-
-/* Bytecode object */
-struct PyCodeObject {
- PyObject_HEAD
- int co_argcount; /* #arguments, except *args */
- int co_posonlyargcount; /* #positional only arguments */
- int co_kwonlyargcount; /* #keyword only arguments */
- int co_nlocals; /* #local variables */
- int co_stacksize; /* #entries needed for evaluation stack */
- int co_flags; /* CO_..., see below */
- int co_firstlineno; /* first source line number */
- PyObject *co_code; /* instruction opcodes */
- PyObject *co_consts; /* list (constants used) */
- PyObject *co_names; /* list of strings (names used) */
- PyObject *co_varnames; /* tuple of strings (local variable names) */
- PyObject *co_freevars; /* tuple of strings (free variable names) */
- PyObject *co_cellvars; /* tuple of strings (cell variable names) */
- /* The rest aren't used in either hash or comparisons, except for co_name,
- used in both. This is done to preserve the name and line number
- for tracebacks and debuggers; otherwise, constant de-duplication
- would collapse identical functions/lambdas defined on different lines.
- */
- Py_ssize_t *co_cell2arg; /* Maps cell vars which are arguments. */
- PyObject *co_filename; /* unicode (where it was loaded from) */
- PyObject *co_name; /* unicode (name, for reference) */
- PyObject *co_linetable; /* string (encoding addr<->lineno mapping) See
- Objects/lnotab_notes.txt for details. */
- void *co_zombieframe; /* for optimization only (see frameobject.c) */
- PyObject *co_weakreflist; /* to support weakrefs to code objects */
- /* Scratch space for extra data relating to the code object.
- Type is a void* to keep the format private in codeobject.c to force
- people to go through the proper APIs. */
- void *co_extra;
-
- /* Per opcodes just-in-time cache
- *
- * To reduce cache size, we use indirect mapping from opcode index to
- * cache object:
- * cache = co_opcache[co_opcache_map[next_instr - first_instr] - 1]
- */
-
- // co_opcache_map is indexed by (next_instr - first_instr).
- // * 0 means there is no cache for this opcode.
- // * n > 0 means there is cache in co_opcache[n-1].
- unsigned char *co_opcache_map;
- _PyOpcache *co_opcache;
- int co_opcache_flag; // used to determine when create a cache.
- unsigned char co_opcache_size; // length of co_opcache.
-};
-
-/* Masks for co_flags above */
-#define CO_OPTIMIZED 0x0001
-#define CO_NEWLOCALS 0x0002
-#define CO_VARARGS 0x0004
-#define CO_VARKEYWORDS 0x0008
-#define CO_NESTED 0x0010
-#define CO_GENERATOR 0x0020
-/* The CO_NOFREE flag is set if there are no free or cell variables.
- This information is redundant, but it allows a single flag test
- to determine whether there is any extra work to be done when the
- call frame it setup.
-*/
-#define CO_NOFREE 0x0040
-
-/* The CO_COROUTINE flag is set for coroutine functions (defined with
- ``async def`` keywords) */
-#define CO_COROUTINE 0x0080
-#define CO_ITERABLE_COROUTINE 0x0100
-#define CO_ASYNC_GENERATOR 0x0200
-
-/* bpo-39562: These constant values are changed in Python 3.9
- to prevent collision with compiler flags. CO_FUTURE_ and PyCF_
- constants must be kept unique. PyCF_ constants can use bits from
- 0x0100 to 0x10000. CO_FUTURE_ constants use bits starting at 0x20000. */
-#define CO_FUTURE_DIVISION 0x20000
-#define CO_FUTURE_ABSOLUTE_IMPORT 0x40000 /* do absolute imports by default */
-#define CO_FUTURE_WITH_STATEMENT 0x80000
-#define CO_FUTURE_PRINT_FUNCTION 0x100000
-#define CO_FUTURE_UNICODE_LITERALS 0x200000
-
-#define CO_FUTURE_BARRY_AS_BDFL 0x400000
-#define CO_FUTURE_GENERATOR_STOP 0x800000
-#define CO_FUTURE_ANNOTATIONS 0x1000000
-
-/* This value is found in the co_cell2arg array when the associated cell
- variable does not correspond to an argument. */
-#define CO_CELL_NOT_AN_ARG (-1)
-
-/* This should be defined if a future statement modifies the syntax.
- For example, when a keyword is added.
-*/
-#define PY_PARSER_REQUIRES_FUTURE_KEYWORD
-
-#define CO_MAXBLOCKS 20 /* Max static block nesting within a function */
-
-PyAPI_DATA(PyTypeObject) PyCode_Type;
-
-#define PyCode_Check(op) Py_IS_TYPE(op, &PyCode_Type)
-#define PyCode_GetNumFree(op) (PyTuple_GET_SIZE((op)->co_freevars))
-
-/* Public interface */
-PyAPI_FUNC(PyCodeObject *) PyCode_New(
- int, int, int, int, int, PyObject *, PyObject *,
- PyObject *, PyObject *, PyObject *, PyObject *,
- PyObject *, PyObject *, int, PyObject *);
-
-PyAPI_FUNC(PyCodeObject *) PyCode_NewWithPosOnlyArgs(
- int, int, int, int, int, int, PyObject *, PyObject *,
- PyObject *, PyObject *, PyObject *, PyObject *,
- PyObject *, PyObject *, int, PyObject *);
- /* same as struct above */
-
-/* Creates a new empty code object with the specified source location. */
-PyAPI_FUNC(PyCodeObject *)
-PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno);
-
-/* Return the line number associated with the specified bytecode index
- in this code object. If you just need the line number of a frame,
- use PyFrame_GetLineNumber() instead. */
-PyAPI_FUNC(int) PyCode_Addr2Line(PyCodeObject *, int);
-
-/* for internal use only */
-struct _opaque {
- int computed_line;
- const char *lo_next;
- const char *limit;
-};
-
-typedef struct _line_offsets {
- int ar_start;
- int ar_end;
- int ar_line;
- struct _opaque opaque;
-} PyCodeAddressRange;
-
-/* Update *bounds to describe the first and one-past-the-last instructions in the
- same line as lasti. Return the number of that line.
-*/
-PyAPI_FUNC(int) _PyCode_CheckLineNumber(int lasti, PyCodeAddressRange *bounds);
-
-/* Create a comparable key used to compare constants taking in account the
- * object type. It is used to make sure types are not coerced (e.g., float and
- * complex) _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms
- *
- * Return (type(obj), obj, ...): a tuple with variable size (at least 2 items)
- * depending on the type and the value. The type is the first item to not
- * compare bytes and str which can raise a BytesWarning exception. */
-PyAPI_FUNC(PyObject*) _PyCode_ConstantKey(PyObject *obj);
-
-PyAPI_FUNC(PyObject*) PyCode_Optimize(PyObject *code, PyObject* consts,
- PyObject *names, PyObject *lnotab);
-
-
-PyAPI_FUNC(int) _PyCode_GetExtra(PyObject *code, Py_ssize_t index,
- void **extra);
-PyAPI_FUNC(int) _PyCode_SetExtra(PyObject *code, Py_ssize_t index,
- void *extra);
-
-/** API for initializing the line number table. */
-int _PyCode_InitAddressRange(PyCodeObject* co, PyCodeAddressRange *bounds);
-
-/** Out of process API for initializing the line number table. */
-void PyLineTable_InitAddressRange(const char *linetable, Py_ssize_t length, int firstlineno, PyCodeAddressRange *range);
-
-/** API for traversing the line number table. */
-int PyLineTable_NextAddressRange(PyCodeAddressRange *range);
-int PyLineTable_PreviousAddressRange(PyCodeAddressRange *range);
-
-
diff --git a/include/python3.10/cpython/dictobject.h b/include/python3.10/cpython/dictobject.h
deleted file mode 100644
index 641d7bd..0000000
--- a/include/python3.10/cpython/dictobject.h
+++ /dev/null
@@ -1,84 +0,0 @@
-#ifndef Py_CPYTHON_DICTOBJECT_H
-# error "this header file must not be included directly"
-#endif
-
-typedef struct _dictkeysobject PyDictKeysObject;
-
-/* The ma_values pointer is NULL for a combined table
- * or points to an array of PyObject* for a split table
- */
-typedef struct {
- PyObject_HEAD
-
- /* Number of items in the dictionary */
- Py_ssize_t ma_used;
-
- /* Dictionary version: globally unique, value change each time
- the dictionary is modified */
- uint64_t ma_version_tag;
-
- PyDictKeysObject *ma_keys;
-
- /* If ma_values is NULL, the table is "combined": keys and values
- are stored in ma_keys.
-
- If ma_values is not NULL, the table is split:
- keys are stored in ma_keys and values are stored in ma_values */
- PyObject **ma_values;
-} PyDictObject;
-
-PyAPI_FUNC(PyObject *) _PyDict_GetItem_KnownHash(PyObject *mp, PyObject *key,
- Py_hash_t hash);
-PyAPI_FUNC(PyObject *) _PyDict_GetItemIdWithError(PyObject *dp,
- struct _Py_Identifier *key);
-PyAPI_FUNC(PyObject *) _PyDict_GetItemStringWithError(PyObject *, const char *);
-PyAPI_FUNC(PyObject *) PyDict_SetDefault(
- PyObject *mp, PyObject *key, PyObject *defaultobj);
-PyAPI_FUNC(int) _PyDict_SetItem_KnownHash(PyObject *mp, PyObject *key,
- PyObject *item, Py_hash_t hash);
-PyAPI_FUNC(int) _PyDict_DelItem_KnownHash(PyObject *mp, PyObject *key,
- Py_hash_t hash);
-PyAPI_FUNC(int) _PyDict_DelItemIf(PyObject *mp, PyObject *key,
- int (*predicate)(PyObject *value));
-PyDictKeysObject *_PyDict_NewKeysForClass(void);
-PyAPI_FUNC(int) _PyDict_Next(
- PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, Py_hash_t *hash);
-
-/* Get the number of items of a dictionary. */
-#define PyDict_GET_SIZE(mp) (assert(PyDict_Check(mp)),((PyDictObject *)mp)->ma_used)
-PyAPI_FUNC(int) _PyDict_Contains_KnownHash(PyObject *, PyObject *, Py_hash_t);
-PyAPI_FUNC(int) _PyDict_ContainsId(PyObject *, struct _Py_Identifier *);
-PyAPI_FUNC(PyObject *) _PyDict_NewPresized(Py_ssize_t minused);
-PyAPI_FUNC(void) _PyDict_MaybeUntrack(PyObject *mp);
-PyAPI_FUNC(int) _PyDict_HasOnlyStringKeys(PyObject *mp);
-Py_ssize_t _PyDict_KeysSize(PyDictKeysObject *keys);
-PyAPI_FUNC(Py_ssize_t) _PyDict_SizeOf(PyDictObject *);
-PyAPI_FUNC(PyObject *) _PyDict_Pop(PyObject *, PyObject *, PyObject *);
-PyObject *_PyDict_Pop_KnownHash(PyObject *, PyObject *, Py_hash_t, PyObject *);
-PyObject *_PyDict_FromKeys(PyObject *, PyObject *, PyObject *);
-#define _PyDict_HasSplitTable(d) ((d)->ma_values != NULL)
-
-/* Like PyDict_Merge, but override can be 0, 1 or 2. If override is 0,
- the first occurrence of a key wins, if override is 1, the last occurrence
- of a key wins, if override is 2, a KeyError with conflicting key as
- argument is raised.
-*/
-PyAPI_FUNC(int) _PyDict_MergeEx(PyObject *mp, PyObject *other, int override);
-PyAPI_FUNC(int) _PyDict_SetItemId(PyObject *dp, struct _Py_Identifier *key, PyObject *item);
-
-PyAPI_FUNC(int) _PyDict_DelItemId(PyObject *mp, struct _Py_Identifier *key);
-PyAPI_FUNC(void) _PyDict_DebugMallocStats(FILE *out);
-
-int _PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr, PyObject *name, PyObject *value);
-PyObject *_PyDict_LoadGlobal(PyDictObject *, PyDictObject *, PyObject *);
-Py_ssize_t _PyDict_GetItemHint(PyDictObject *, PyObject *, Py_ssize_t, PyObject **);
-
-/* _PyDictView */
-
-typedef struct {
- PyObject_HEAD
- PyDictObject *dv_dict;
-} _PyDictViewObject;
-
-PyAPI_FUNC(PyObject *) _PyDictView_New(PyObject *, PyTypeObject *);
-PyAPI_FUNC(PyObject *) _PyDictView_Intersect(PyObject* self, PyObject *other);
diff --git a/include/python3.10/cpython/fileobject.h b/include/python3.10/cpython/fileobject.h
deleted file mode 100644
index cff2243..0000000
--- a/include/python3.10/cpython/fileobject.h
+++ /dev/null
@@ -1,18 +0,0 @@
-#ifndef Py_CPYTHON_FILEOBJECT_H
-# error "this header file must not be included directly"
-#endif
-
-PyAPI_FUNC(char *) Py_UniversalNewlineFgets(char *, int, FILE*, PyObject *);
-
-/* The std printer acts as a preliminary sys.stderr until the new io
- infrastructure is in place. */
-PyAPI_FUNC(PyObject *) PyFile_NewStdPrinter(int);
-PyAPI_DATA(PyTypeObject) PyStdPrinter_Type;
-
-typedef PyObject * (*Py_OpenCodeHookFunction)(PyObject *, void *);
-
-PyAPI_FUNC(PyObject *) PyFile_OpenCode(const char *utf8path);
-PyAPI_FUNC(PyObject *) PyFile_OpenCodeObject(PyObject *path);
-PyAPI_FUNC(int) PyFile_SetOpenCodeHook(Py_OpenCodeHookFunction hook, void *userData);
-
-PyAPI_FUNC(int) _PyLong_FileDescriptor_Converter(PyObject *, void *);
diff --git a/include/python3.10/cpython/fileutils.h b/include/python3.10/cpython/fileutils.h
deleted file mode 100644
index ccf37e9..0000000
--- a/include/python3.10/cpython/fileutils.h
+++ /dev/null
@@ -1,172 +0,0 @@
-#ifndef Py_CPYTHON_FILEUTILS_H
-# error "this header file must not be included directly"
-#endif
-
-typedef enum {
- _Py_ERROR_UNKNOWN=0,
- _Py_ERROR_STRICT,
- _Py_ERROR_SURROGATEESCAPE,
- _Py_ERROR_REPLACE,
- _Py_ERROR_IGNORE,
- _Py_ERROR_BACKSLASHREPLACE,
- _Py_ERROR_SURROGATEPASS,
- _Py_ERROR_XMLCHARREFREPLACE,
- _Py_ERROR_OTHER
-} _Py_error_handler;
-
-PyAPI_FUNC(_Py_error_handler) _Py_GetErrorHandler(const char *errors);
-
-PyAPI_FUNC(int) _Py_DecodeLocaleEx(
- const char *arg,
- wchar_t **wstr,
- size_t *wlen,
- const char **reason,
- int current_locale,
- _Py_error_handler errors);
-
-PyAPI_FUNC(int) _Py_EncodeLocaleEx(
- const wchar_t *text,
- char **str,
- size_t *error_pos,
- const char **reason,
- int current_locale,
- _Py_error_handler errors);
-
-PyAPI_FUNC(char*) _Py_EncodeLocaleRaw(
- const wchar_t *text,
- size_t *error_pos);
-
-PyAPI_FUNC(PyObject *) _Py_device_encoding(int);
-
-#if defined(MS_WINDOWS) || defined(__APPLE__)
- /* On Windows, the count parameter of read() is an int (bpo-9015, bpo-9611).
- On macOS 10.13, read() and write() with more than INT_MAX bytes
- fail with EINVAL (bpo-24658). */
-# define _PY_READ_MAX INT_MAX
-# define _PY_WRITE_MAX INT_MAX
-#else
- /* write() should truncate the input to PY_SSIZE_T_MAX bytes,
- but it's safer to do it ourself to have a portable behaviour */
-# define _PY_READ_MAX PY_SSIZE_T_MAX
-# define _PY_WRITE_MAX PY_SSIZE_T_MAX
-#endif
-
-#ifdef MS_WINDOWS
-struct _Py_stat_struct {
- unsigned long st_dev;
- uint64_t st_ino;
- unsigned short st_mode;
- int st_nlink;
- int st_uid;
- int st_gid;
- unsigned long st_rdev;
- __int64 st_size;
- time_t st_atime;
- int st_atime_nsec;
- time_t st_mtime;
- int st_mtime_nsec;
- time_t st_ctime;
- int st_ctime_nsec;
- unsigned long st_file_attributes;
- unsigned long st_reparse_tag;
-};
-#else
-# define _Py_stat_struct stat
-#endif
-
-PyAPI_FUNC(int) _Py_fstat(
- int fd,
- struct _Py_stat_struct *status);
-
-PyAPI_FUNC(int) _Py_fstat_noraise(
- int fd,
- struct _Py_stat_struct *status);
-
-PyAPI_FUNC(int) _Py_stat(
- PyObject *path,
- struct stat *status);
-
-PyAPI_FUNC(int) _Py_open(
- const char *pathname,
- int flags);
-
-PyAPI_FUNC(int) _Py_open_noraise(
- const char *pathname,
- int flags);
-
-PyAPI_FUNC(FILE *) _Py_wfopen(
- const wchar_t *path,
- const wchar_t *mode);
-
-PyAPI_FUNC(FILE*) _Py_fopen_obj(
- PyObject *path,
- const char *mode);
-
-PyAPI_FUNC(Py_ssize_t) _Py_read(
- int fd,
- void *buf,
- size_t count);
-
-PyAPI_FUNC(Py_ssize_t) _Py_write(
- int fd,
- const void *buf,
- size_t count);
-
-PyAPI_FUNC(Py_ssize_t) _Py_write_noraise(
- int fd,
- const void *buf,
- size_t count);
-
-#ifdef HAVE_READLINK
-PyAPI_FUNC(int) _Py_wreadlink(
- const wchar_t *path,
- wchar_t *buf,
- /* Number of characters of 'buf' buffer
- including the trailing NUL character */
- size_t buflen);
-#endif
-
-#ifdef HAVE_REALPATH
-PyAPI_FUNC(wchar_t*) _Py_wrealpath(
- const wchar_t *path,
- wchar_t *resolved_path,
- /* Number of characters of 'resolved_path' buffer
- including the trailing NUL character */
- size_t resolved_path_len);
-#endif
-
-#ifndef MS_WINDOWS
-PyAPI_FUNC(int) _Py_isabs(const wchar_t *path);
-#endif
-
-PyAPI_FUNC(int) _Py_abspath(const wchar_t *path, wchar_t **abspath_p);
-
-PyAPI_FUNC(wchar_t*) _Py_wgetcwd(
- wchar_t *buf,
- /* Number of characters of 'buf' buffer
- including the trailing NUL character */
- size_t buflen);
-
-PyAPI_FUNC(int) _Py_get_inheritable(int fd);
-
-PyAPI_FUNC(int) _Py_set_inheritable(int fd, int inheritable,
- int *atomic_flag_works);
-
-PyAPI_FUNC(int) _Py_set_inheritable_async_safe(int fd, int inheritable,
- int *atomic_flag_works);
-
-PyAPI_FUNC(int) _Py_dup(int fd);
-
-#ifndef MS_WINDOWS
-PyAPI_FUNC(int) _Py_get_blocking(int fd);
-
-PyAPI_FUNC(int) _Py_set_blocking(int fd, int blocking);
-#else /* MS_WINDOWS */
-PyAPI_FUNC(void*) _Py_get_osfhandle_noraise(int fd);
-
-PyAPI_FUNC(void*) _Py_get_osfhandle(int fd);
-
-PyAPI_FUNC(int) _Py_open_osfhandle_noraise(void *handle, int flags);
-
-PyAPI_FUNC(int) _Py_open_osfhandle(void *handle, int flags);
-#endif /* MS_WINDOWS */
diff --git a/include/python3.10/cpython/frameobject.h b/include/python3.10/cpython/frameobject.h
deleted file mode 100644
index 5122ec4..0000000
--- a/include/python3.10/cpython/frameobject.h
+++ /dev/null
@@ -1,94 +0,0 @@
-/* Frame object interface */
-
-#ifndef Py_CPYTHON_FRAMEOBJECT_H
-# error "this header file must not be included directly"
-#endif
-
-/* These values are chosen so that the inline functions below all
- * compare f_state to zero.
- */
-enum _framestate {
- FRAME_CREATED = -2,
- FRAME_SUSPENDED = -1,
- FRAME_EXECUTING = 0,
- FRAME_RETURNED = 1,
- FRAME_UNWINDING = 2,
- FRAME_RAISED = 3,
- FRAME_CLEARED = 4
-};
-
-typedef signed char PyFrameState;
-
-typedef struct {
- int b_type; /* what kind of block this is */
- int b_handler; /* where to jump to find handler */
- int b_level; /* value stack level to pop to */
-} PyTryBlock;
-
-struct _frame {
- PyObject_VAR_HEAD
- struct _frame *f_back; /* previous frame, or NULL */
- PyCodeObject *f_code; /* code segment */
- PyObject *f_builtins; /* builtin symbol table (PyDictObject) */
- PyObject *f_globals; /* global symbol table (PyDictObject) */
- PyObject *f_locals; /* local symbol table (any mapping) */
- PyObject **f_valuestack; /* points after the last local */
- PyObject *f_trace; /* Trace function */
- int f_stackdepth; /* Depth of value stack */
- char f_trace_lines; /* Emit per-line trace events? */
- char f_trace_opcodes; /* Emit per-opcode trace events? */
-
- /* Borrowed reference to a generator, or NULL */
- PyObject *f_gen;
-
- int f_lasti; /* Last instruction if called */
- int f_lineno; /* Current line number. Only valid if non-zero */
- int f_iblock; /* index in f_blockstack */
- PyFrameState f_state; /* What state the frame is in */
- PyTryBlock f_blockstack[CO_MAXBLOCKS]; /* for try and loop blocks */
- PyObject *f_localsplus[1]; /* locals+stack, dynamically sized */
-};
-
-static inline int _PyFrame_IsRunnable(struct _frame *f) {
- return f->f_state < FRAME_EXECUTING;
-}
-
-static inline int _PyFrame_IsExecuting(struct _frame *f) {
- return f->f_state == FRAME_EXECUTING;
-}
-
-static inline int _PyFrameHasCompleted(struct _frame *f) {
- return f->f_state > FRAME_EXECUTING;
-}
-
-/* Standard object interface */
-
-PyAPI_DATA(PyTypeObject) PyFrame_Type;
-
-#define PyFrame_Check(op) Py_IS_TYPE(op, &PyFrame_Type)
-
-PyAPI_FUNC(PyFrameObject *) PyFrame_New(PyThreadState *, PyCodeObject *,
- PyObject *, PyObject *);
-
-/* only internal use */
-PyFrameObject*
-_PyFrame_New_NoTrack(PyThreadState *, PyFrameConstructor *, PyObject *);
-
-
-/* The rest of the interface is specific for frame objects */
-
-/* Block management functions */
-
-PyAPI_FUNC(void) PyFrame_BlockSetup(PyFrameObject *, int, int, int);
-PyAPI_FUNC(PyTryBlock *) PyFrame_BlockPop(PyFrameObject *);
-
-/* Conversions between "fast locals" and locals in dictionary */
-
-PyAPI_FUNC(void) PyFrame_LocalsToFast(PyFrameObject *, int);
-
-PyAPI_FUNC(int) PyFrame_FastToLocalsWithError(PyFrameObject *f);
-PyAPI_FUNC(void) PyFrame_FastToLocals(PyFrameObject *);
-
-PyAPI_FUNC(void) _PyFrame_DebugMallocStats(FILE *out);
-
-PyAPI_FUNC(PyFrameObject *) PyFrame_GetBack(PyFrameObject *frame);
diff --git a/include/python3.10/cpython/import.h b/include/python3.10/cpython/import.h
deleted file mode 100644
index dd5bbdb..0000000
--- a/include/python3.10/cpython/import.h
+++ /dev/null
@@ -1,43 +0,0 @@
-#ifndef Py_CPYTHON_IMPORT_H
-# error "this header file must not be included directly"
-#endif
-
-PyMODINIT_FUNC PyInit__imp(void);
-
-PyAPI_FUNC(int) _PyImport_IsInitialized(PyInterpreterState *);
-
-PyAPI_FUNC(PyObject *) _PyImport_GetModuleId(struct _Py_Identifier *name);
-PyAPI_FUNC(int) _PyImport_SetModule(PyObject *name, PyObject *module);
-PyAPI_FUNC(int) _PyImport_SetModuleString(const char *name, PyObject* module);
-
-PyAPI_FUNC(void) _PyImport_AcquireLock(void);
-PyAPI_FUNC(int) _PyImport_ReleaseLock(void);
-
-/* Obsolete since 3.5, will be removed in 3.11. */
-Py_DEPRECATED(3.10) PyAPI_FUNC(PyObject *) _PyImport_FindExtensionObject(PyObject *, PyObject *);
-
-PyAPI_FUNC(int) _PyImport_FixupBuiltin(
- PyObject *mod,
- const char *name, /* UTF-8 encoded string */
- PyObject *modules
- );
-PyAPI_FUNC(int) _PyImport_FixupExtensionObject(PyObject*, PyObject *,
- PyObject *, PyObject *);
-
-struct _inittab {
- const char *name; /* ASCII encoded string */
- PyObject* (*initfunc)(void);
-};
-PyAPI_DATA(struct _inittab *) PyImport_Inittab;
-PyAPI_FUNC(int) PyImport_ExtendInittab(struct _inittab *newtab);
-
-struct _frozen {
- const char *name; /* ASCII encoded string */
- const unsigned char *code;
- int size;
-};
-
-/* Embedding apps may change this pointer to point to their favorite
- collection of frozen modules: */
-
-PyAPI_DATA(const struct _frozen *) PyImport_FrozenModules;
diff --git a/include/python3.10/cpython/initconfig.h b/include/python3.10/cpython/initconfig.h
deleted file mode 100644
index 583165b..0000000
--- a/include/python3.10/cpython/initconfig.h
+++ /dev/null
@@ -1,249 +0,0 @@
-#ifndef Py_PYCORECONFIG_H
-#define Py_PYCORECONFIG_H
-#ifndef Py_LIMITED_API
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* --- PyStatus ----------------------------------------------- */
-
-typedef struct {
- enum {
- _PyStatus_TYPE_OK=0,
- _PyStatus_TYPE_ERROR=1,
- _PyStatus_TYPE_EXIT=2
- } _type;
- const char *func;
- const char *err_msg;
- int exitcode;
-} PyStatus;
-
-PyAPI_FUNC(PyStatus) PyStatus_Ok(void);
-PyAPI_FUNC(PyStatus) PyStatus_Error(const char *err_msg);
-PyAPI_FUNC(PyStatus) PyStatus_NoMemory(void);
-PyAPI_FUNC(PyStatus) PyStatus_Exit(int exitcode);
-PyAPI_FUNC(int) PyStatus_IsError(PyStatus err);
-PyAPI_FUNC(int) PyStatus_IsExit(PyStatus err);
-PyAPI_FUNC(int) PyStatus_Exception(PyStatus err);
-
-/* --- PyWideStringList ------------------------------------------------ */
-
-typedef struct {
- /* If length is greater than zero, items must be non-NULL
- and all items strings must be non-NULL */
- Py_ssize_t length;
- wchar_t **items;
-} PyWideStringList;
-
-PyAPI_FUNC(PyStatus) PyWideStringList_Append(PyWideStringList *list,
- const wchar_t *item);
-PyAPI_FUNC(PyStatus) PyWideStringList_Insert(PyWideStringList *list,
- Py_ssize_t index,
- const wchar_t *item);
-
-
-/* --- PyPreConfig ----------------------------------------------- */
-
-typedef struct PyPreConfig {
- int _config_init; /* _PyConfigInitEnum value */
-
- /* Parse Py_PreInitializeFromBytesArgs() arguments?
- See PyConfig.parse_argv */
- int parse_argv;
-
- /* If greater than 0, enable isolated mode: sys.path contains
- neither the script's directory nor the user's site-packages directory.
-
- Set to 1 by the -I command line option. If set to -1 (default), inherit
- Py_IsolatedFlag value. */
- int isolated;
-
- /* If greater than 0: use environment variables.
- Set to 0 by -E command line option. If set to -1 (default), it is
- set to !Py_IgnoreEnvironmentFlag. */
- int use_environment;
-
- /* Set the LC_CTYPE locale to the user preferred locale? If equals to 0,
- set coerce_c_locale and coerce_c_locale_warn to 0. */
- int configure_locale;
-
- /* Coerce the LC_CTYPE locale if it's equal to "C"? (PEP 538)
-
- Set to 0 by PYTHONCOERCECLOCALE=0. Set to 1 by PYTHONCOERCECLOCALE=1.
- Set to 2 if the user preferred LC_CTYPE locale is "C".
-
- If it is equal to 1, LC_CTYPE locale is read to decide if it should be
- coerced or not (ex: PYTHONCOERCECLOCALE=1). Internally, it is set to 2
- if the LC_CTYPE locale must be coerced.
-
- Disable by default (set to 0). Set it to -1 to let Python decide if it
- should be enabled or not. */
- int coerce_c_locale;
-
- /* Emit a warning if the LC_CTYPE locale is coerced?
-
- Set to 1 by PYTHONCOERCECLOCALE=warn.
-
- Disable by default (set to 0). Set it to -1 to let Python decide if it
- should be enabled or not. */
- int coerce_c_locale_warn;
-
-#ifdef MS_WINDOWS
- /* If greater than 1, use the "mbcs" encoding instead of the UTF-8
- encoding for the filesystem encoding.
-
- Set to 1 if the PYTHONLEGACYWINDOWSFSENCODING environment variable is
- set to a non-empty string. If set to -1 (default), inherit
- Py_LegacyWindowsFSEncodingFlag value.
-
- See PEP 529 for more details. */
- int legacy_windows_fs_encoding;
-#endif
-
- /* Enable UTF-8 mode? (PEP 540)
-
- Disabled by default (equals to 0).
-
- Set to 1 by "-X utf8" and "-X utf8=1" command line options.
- Set to 1 by PYTHONUTF8=1 environment variable.
-
- Set to 0 by "-X utf8=0" and PYTHONUTF8=0.
-
- If equals to -1, it is set to 1 if the LC_CTYPE locale is "C" or
- "POSIX", otherwise it is set to 0. Inherit Py_UTF8Mode value value. */
- int utf8_mode;
-
- /* If non-zero, enable the Python Development Mode.
-
- Set to 1 by the -X dev command line option. Set by the PYTHONDEVMODE
- environment variable. */
- int dev_mode;
-
- /* Memory allocator: PYTHONMALLOC env var.
- See PyMemAllocatorName for valid values. */
- int allocator;
-} PyPreConfig;
-
-PyAPI_FUNC(void) PyPreConfig_InitPythonConfig(PyPreConfig *config);
-PyAPI_FUNC(void) PyPreConfig_InitIsolatedConfig(PyPreConfig *config);
-
-
-/* --- PyConfig ---------------------------------------------- */
-
-/* This structure is best documented in the Doc/c-api/init_config.rst file. */
-typedef struct PyConfig {
- int _config_init; /* _PyConfigInitEnum value */
-
- int isolated;
- int use_environment;
- int dev_mode;
- int install_signal_handlers;
- int use_hash_seed;
- unsigned long hash_seed;
- int faulthandler;
- int tracemalloc;
- int import_time;
- int show_ref_count;
- int dump_refs;
- int malloc_stats;
- wchar_t *filesystem_encoding;
- wchar_t *filesystem_errors;
- wchar_t *pycache_prefix;
- int parse_argv;
- PyWideStringList orig_argv;
- PyWideStringList argv;
- PyWideStringList xoptions;
- PyWideStringList warnoptions;
- int site_import;
- int bytes_warning;
- int warn_default_encoding;
- int inspect;
- int interactive;
- int optimization_level;
- int parser_debug;
- int write_bytecode;
- int verbose;
- int quiet;
- int user_site_directory;
- int configure_c_stdio;
- int buffered_stdio;
- wchar_t *stdio_encoding;
- wchar_t *stdio_errors;
-#ifdef MS_WINDOWS
- int legacy_windows_stdio;
-#endif
- wchar_t *check_hash_pycs_mode;
-
- /* --- Path configuration inputs ------------ */
- int pathconfig_warnings;
- wchar_t *program_name;
- wchar_t *pythonpath_env;
- wchar_t *home;
- wchar_t *platlibdir;
-
- /* --- Path configuration outputs ----------- */
- int module_search_paths_set;
- PyWideStringList module_search_paths;
- wchar_t *executable;
- wchar_t *base_executable;
- wchar_t *prefix;
- wchar_t *base_prefix;
- wchar_t *exec_prefix;
- wchar_t *base_exec_prefix;
-
- /* --- Parameter only used by Py_Main() ---------- */
- int skip_source_first_line;
- wchar_t *run_command;
- wchar_t *run_module;
- wchar_t *run_filename;
-
- /* --- Private fields ---------------------------- */
-
- // Install importlib? If equals to 0, importlib is not initialized at all.
- // Needed by freeze_importlib.
- int _install_importlib;
-
- // If equal to 0, stop Python initialization before the "main" phase.
- int _init_main;
-
- // If non-zero, disallow threads, subprocesses, and fork.
- // Default: 0.
- int _isolated_interpreter;
-} PyConfig;
-
-PyAPI_FUNC(void) PyConfig_InitPythonConfig(PyConfig *config);
-PyAPI_FUNC(void) PyConfig_InitIsolatedConfig(PyConfig *config);
-PyAPI_FUNC(void) PyConfig_Clear(PyConfig *);
-PyAPI_FUNC(PyStatus) PyConfig_SetString(
- PyConfig *config,
- wchar_t **config_str,
- const wchar_t *str);
-PyAPI_FUNC(PyStatus) PyConfig_SetBytesString(
- PyConfig *config,
- wchar_t **config_str,
- const char *str);
-PyAPI_FUNC(PyStatus) PyConfig_Read(PyConfig *config);
-PyAPI_FUNC(PyStatus) PyConfig_SetBytesArgv(
- PyConfig *config,
- Py_ssize_t argc,
- char * const *argv);
-PyAPI_FUNC(PyStatus) PyConfig_SetArgv(PyConfig *config,
- Py_ssize_t argc,
- wchar_t * const *argv);
-PyAPI_FUNC(PyStatus) PyConfig_SetWideStringList(PyConfig *config,
- PyWideStringList *list,
- Py_ssize_t length, wchar_t **items);
-
-
-/* --- Helper functions --------------------------------------- */
-
-/* Get the original command line arguments, before Python modified them.
-
- See also PyConfig.orig_argv. */
-PyAPI_FUNC(void) Py_GetArgcArgv(int *argc, wchar_t ***argv);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_LIMITED_API */
-#endif /* !Py_PYCORECONFIG_H */
diff --git a/include/python3.10/cpython/interpreteridobject.h b/include/python3.10/cpython/interpreteridobject.h
deleted file mode 100644
index 5076584..0000000
--- a/include/python3.10/cpython/interpreteridobject.h
+++ /dev/null
@@ -1,11 +0,0 @@
-#ifndef Py_CPYTHON_INTERPRETERIDOBJECT_H
-# error "this header file must not be included directly"
-#endif
-
-/* Interpreter ID Object */
-
-PyAPI_DATA(PyTypeObject) _PyInterpreterID_Type;
-
-PyAPI_FUNC(PyObject *) _PyInterpreterID_New(int64_t);
-PyAPI_FUNC(PyObject *) _PyInterpreterState_GetIDObject(PyInterpreterState *);
-PyAPI_FUNC(PyInterpreterState *) _PyInterpreterID_LookUp(PyObject *);
diff --git a/include/python3.10/cpython/listobject.h b/include/python3.10/cpython/listobject.h
deleted file mode 100644
index e323915..0000000
--- a/include/python3.10/cpython/listobject.h
+++ /dev/null
@@ -1,34 +0,0 @@
-#ifndef Py_CPYTHON_LISTOBJECT_H
-# error "this header file must not be included directly"
-#endif
-
-typedef struct {
- PyObject_VAR_HEAD
- /* Vector of pointers to list elements. list[0] is ob_item[0], etc. */
- PyObject **ob_item;
-
- /* ob_item contains space for 'allocated' elements. The number
- * currently in use is ob_size.
- * Invariants:
- * 0 <= ob_size <= allocated
- * len(list) == ob_size
- * ob_item == NULL implies ob_size == allocated == 0
- * list.sort() temporarily sets allocated to -1 to detect mutations.
- *
- * Items must normally not be NULL, except during construction when
- * the list is not yet visible outside the function that builds it.
- */
- Py_ssize_t allocated;
-} PyListObject;
-
-PyAPI_FUNC(PyObject *) _PyList_Extend(PyListObject *, PyObject *);
-PyAPI_FUNC(void) _PyList_DebugMallocStats(FILE *out);
-
-/* Macro, trading safety for speed */
-
-/* Cast argument to PyListObject* type. */
-#define _PyList_CAST(op) (assert(PyList_Check(op)), (PyListObject *)(op))
-
-#define PyList_GET_ITEM(op, i) (_PyList_CAST(op)->ob_item[i])
-#define PyList_SET_ITEM(op, i, v) ((void)(_PyList_CAST(op)->ob_item[i] = (v)))
-#define PyList_GET_SIZE(op) Py_SIZE(_PyList_CAST(op))
diff --git a/include/python3.10/cpython/methodobject.h b/include/python3.10/cpython/methodobject.h
deleted file mode 100644
index 7ecbfe3..0000000
--- a/include/python3.10/cpython/methodobject.h
+++ /dev/null
@@ -1,35 +0,0 @@
-#ifndef Py_CPYTHON_METHODOBJECT_H
-# error "this header file must not be included directly"
-#endif
-
-PyAPI_DATA(PyTypeObject) PyCMethod_Type;
-
-#define PyCMethod_CheckExact(op) Py_IS_TYPE(op, &PyCMethod_Type)
-#define PyCMethod_Check(op) PyObject_TypeCheck(op, &PyCMethod_Type)
-
-/* Macros for direct access to these values. Type checks are *not*
- done, so use with care. */
-#define PyCFunction_GET_FUNCTION(func) \
- (((PyCFunctionObject *)func) -> m_ml -> ml_meth)
-#define PyCFunction_GET_SELF(func) \
- (((PyCFunctionObject *)func) -> m_ml -> ml_flags & METH_STATIC ? \
- NULL : ((PyCFunctionObject *)func) -> m_self)
-#define PyCFunction_GET_FLAGS(func) \
- (((PyCFunctionObject *)func) -> m_ml -> ml_flags)
-#define PyCFunction_GET_CLASS(func) \
- (((PyCFunctionObject *)func) -> m_ml -> ml_flags & METH_METHOD ? \
- ((PyCMethodObject *)func) -> mm_class : NULL)
-
-typedef struct {
- PyObject_HEAD
- PyMethodDef *m_ml; /* Description of the C function to call */
- PyObject *m_self; /* Passed as 'self' arg to the C func, can be NULL */
- PyObject *m_module; /* The __module__ attribute, can be anything */
- PyObject *m_weakreflist; /* List of weak references */
- vectorcallfunc vectorcall;
-} PyCFunctionObject;
-
-typedef struct {
- PyCFunctionObject func;
- PyTypeObject *mm_class; /* Class that defines this method */
-} PyCMethodObject;
diff --git a/include/python3.10/cpython/object.h b/include/python3.10/cpython/object.h
deleted file mode 100644
index 84c60e5..0000000
--- a/include/python3.10/cpython/object.h
+++ /dev/null
@@ -1,552 +0,0 @@
-#ifndef Py_CPYTHON_OBJECT_H
-# error "this header file must not be included directly"
-#endif
-
-PyAPI_FUNC(void) _Py_NewReference(PyObject *op);
-
-#ifdef Py_TRACE_REFS
-/* Py_TRACE_REFS is such major surgery that we call external routines. */
-PyAPI_FUNC(void) _Py_ForgetReference(PyObject *);
-#endif
-
-#ifdef Py_REF_DEBUG
-PyAPI_FUNC(Py_ssize_t) _Py_GetRefTotal(void);
-#endif
-
-
-/********************* String Literals ****************************************/
-/* This structure helps managing static strings. The basic usage goes like this:
- Instead of doing
-
- r = PyObject_CallMethod(o, "foo", "args", ...);
-
- do
-
- _Py_IDENTIFIER(foo);
- ...
- r = _PyObject_CallMethodId(o, &PyId_foo, "args", ...);
-
- PyId_foo is a static variable, either on block level or file level. On first
- usage, the string "foo" is interned, and the structures are linked. On interpreter
- shutdown, all strings are released.
-
- Alternatively, _Py_static_string allows choosing the variable name.
- _PyUnicode_FromId returns a borrowed reference to the interned string.
- _PyObject_{Get,Set,Has}AttrId are __getattr__ versions using _Py_Identifier*.
-*/
-typedef struct _Py_Identifier {
- const char* string;
- // Index in PyInterpreterState.unicode.ids.array. It is process-wide
- // unique and must be initialized to -1.
- Py_ssize_t index;
-} _Py_Identifier;
-
-#define _Py_static_string_init(value) { .string = value, .index = -1 }
-#define _Py_static_string(varname, value) static _Py_Identifier varname = _Py_static_string_init(value)
-#define _Py_IDENTIFIER(varname) _Py_static_string(PyId_##varname, #varname)
-
-/* buffer interface */
-typedef struct bufferinfo {
- void *buf;
- PyObject *obj; /* owned reference */
- Py_ssize_t len;
- Py_ssize_t itemsize; /* This is Py_ssize_t so it can be
- pointed to by strides in simple case.*/
- int readonly;
- int ndim;
- char *format;
- Py_ssize_t *shape;
- Py_ssize_t *strides;
- Py_ssize_t *suboffsets;
- void *internal;
-} Py_buffer;
-
-typedef int (*getbufferproc)(PyObject *, Py_buffer *, int);
-typedef void (*releasebufferproc)(PyObject *, Py_buffer *);
-
-typedef PyObject *(*vectorcallfunc)(PyObject *callable, PyObject *const *args,
- size_t nargsf, PyObject *kwnames);
-
-/* Maximum number of dimensions */
-#define PyBUF_MAX_NDIM 64
-
-/* Flags for getting buffers */
-#define PyBUF_SIMPLE 0
-#define PyBUF_WRITABLE 0x0001
-/* we used to include an E, backwards compatible alias */
-#define PyBUF_WRITEABLE PyBUF_WRITABLE
-#define PyBUF_FORMAT 0x0004
-#define PyBUF_ND 0x0008
-#define PyBUF_STRIDES (0x0010 | PyBUF_ND)
-#define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES)
-#define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES)
-#define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES)
-#define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES)
-
-#define PyBUF_CONTIG (PyBUF_ND | PyBUF_WRITABLE)
-#define PyBUF_CONTIG_RO (PyBUF_ND)
-
-#define PyBUF_STRIDED (PyBUF_STRIDES | PyBUF_WRITABLE)
-#define PyBUF_STRIDED_RO (PyBUF_STRIDES)
-
-#define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_WRITABLE | PyBUF_FORMAT)
-#define PyBUF_RECORDS_RO (PyBUF_STRIDES | PyBUF_FORMAT)
-
-#define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_WRITABLE | PyBUF_FORMAT)
-#define PyBUF_FULL_RO (PyBUF_INDIRECT | PyBUF_FORMAT)
-
-
-#define PyBUF_READ 0x100
-#define PyBUF_WRITE 0x200
-/* End buffer interface */
-
-
-typedef struct {
- /* Number implementations must check *both*
- arguments for proper type and implement the necessary conversions
- in the slot functions themselves. */
-
- binaryfunc nb_add;
- binaryfunc nb_subtract;
- binaryfunc nb_multiply;
- binaryfunc nb_remainder;
- binaryfunc nb_divmod;
- ternaryfunc nb_power;
- unaryfunc nb_negative;
- unaryfunc nb_positive;
- unaryfunc nb_absolute;
- inquiry nb_bool;
- unaryfunc nb_invert;
- binaryfunc nb_lshift;
- binaryfunc nb_rshift;
- binaryfunc nb_and;
- binaryfunc nb_xor;
- binaryfunc nb_or;
- unaryfunc nb_int;
- void *nb_reserved; /* the slot formerly known as nb_long */
- unaryfunc nb_float;
-
- binaryfunc nb_inplace_add;
- binaryfunc nb_inplace_subtract;
- binaryfunc nb_inplace_multiply;
- binaryfunc nb_inplace_remainder;
- ternaryfunc nb_inplace_power;
- binaryfunc nb_inplace_lshift;
- binaryfunc nb_inplace_rshift;
- binaryfunc nb_inplace_and;
- binaryfunc nb_inplace_xor;
- binaryfunc nb_inplace_or;
-
- binaryfunc nb_floor_divide;
- binaryfunc nb_true_divide;
- binaryfunc nb_inplace_floor_divide;
- binaryfunc nb_inplace_true_divide;
-
- unaryfunc nb_index;
-
- binaryfunc nb_matrix_multiply;
- binaryfunc nb_inplace_matrix_multiply;
-} PyNumberMethods;
-
-typedef struct {
- lenfunc sq_length;
- binaryfunc sq_concat;
- ssizeargfunc sq_repeat;
- ssizeargfunc sq_item;
- void *was_sq_slice;
- ssizeobjargproc sq_ass_item;
- void *was_sq_ass_slice;
- objobjproc sq_contains;
-
- binaryfunc sq_inplace_concat;
- ssizeargfunc sq_inplace_repeat;
-} PySequenceMethods;
-
-typedef struct {
- lenfunc mp_length;
- binaryfunc mp_subscript;
- objobjargproc mp_ass_subscript;
-} PyMappingMethods;
-
-typedef PySendResult (*sendfunc)(PyObject *iter, PyObject *value, PyObject **result);
-
-typedef struct {
- unaryfunc am_await;
- unaryfunc am_aiter;
- unaryfunc am_anext;
- sendfunc am_send;
-} PyAsyncMethods;
-
-typedef struct {
- getbufferproc bf_getbuffer;
- releasebufferproc bf_releasebuffer;
-} PyBufferProcs;
-
-/* Allow printfunc in the tp_vectorcall_offset slot for
- * backwards-compatibility */
-typedef Py_ssize_t printfunc;
-
-// If this structure is modified, Doc/includes/typestruct.h should be updated
-// as well.
-struct _typeobject {
- PyObject_VAR_HEAD
- const char *tp_name; /* For printing, in format "<module>.<name>" */
- Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */
-
- /* Methods to implement standard operations */
-
- destructor tp_dealloc;
- Py_ssize_t tp_vectorcall_offset;
- getattrfunc tp_getattr;
- setattrfunc tp_setattr;
- PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
- or tp_reserved (Python 3) */
- reprfunc tp_repr;
-
- /* Method suites for standard classes */
-
- PyNumberMethods *tp_as_number;
- PySequenceMethods *tp_as_sequence;
- PyMappingMethods *tp_as_mapping;
-
- /* More standard operations (here for binary compatibility) */
-
- hashfunc tp_hash;
- ternaryfunc tp_call;
- reprfunc tp_str;
- getattrofunc tp_getattro;
- setattrofunc tp_setattro;
-
- /* Functions to access object as input/output buffer */
- PyBufferProcs *tp_as_buffer;
-
- /* Flags to define presence of optional/expanded features */
- unsigned long tp_flags;
-
- const char *tp_doc; /* Documentation string */
-
- /* Assigned meaning in release 2.0 */
- /* call function for all accessible objects */
- traverseproc tp_traverse;
-
- /* delete references to contained objects */
- inquiry tp_clear;
-
- /* Assigned meaning in release 2.1 */
- /* rich comparisons */
- richcmpfunc tp_richcompare;
-
- /* weak reference enabler */
- Py_ssize_t tp_weaklistoffset;
-
- /* Iterators */
- getiterfunc tp_iter;
- iternextfunc tp_iternext;
-
- /* Attribute descriptor and subclassing stuff */
- struct PyMethodDef *tp_methods;
- struct PyMemberDef *tp_members;
- struct PyGetSetDef *tp_getset;
- // Strong reference on a heap type, borrowed reference on a static type
- struct _typeobject *tp_base;
- PyObject *tp_dict;
- descrgetfunc tp_descr_get;
- descrsetfunc tp_descr_set;
- Py_ssize_t tp_dictoffset;
- initproc tp_init;
- allocfunc tp_alloc;
- newfunc tp_new;
- freefunc tp_free; /* Low-level free-memory routine */
- inquiry tp_is_gc; /* For PyObject_IS_GC */
- PyObject *tp_bases;
- PyObject *tp_mro; /* method resolution order */
- PyObject *tp_cache;
- PyObject *tp_subclasses;
- PyObject *tp_weaklist;
- destructor tp_del;
-
- /* Type attribute cache version tag. Added in version 2.6 */
- unsigned int tp_version_tag;
-
- destructor tp_finalize;
- vectorcallfunc tp_vectorcall;
-};
-
-/* The *real* layout of a type object when allocated on the heap */
-typedef struct _heaptypeobject {
- /* Note: there's a dependency on the order of these members
- in slotptr() in typeobject.c . */
- PyTypeObject ht_type;
- PyAsyncMethods as_async;
- PyNumberMethods as_number;
- PyMappingMethods as_mapping;
- PySequenceMethods as_sequence; /* as_sequence comes after as_mapping,
- so that the mapping wins when both
- the mapping and the sequence define
- a given operator (e.g. __getitem__).
- see add_operators() in typeobject.c . */
- PyBufferProcs as_buffer;
- PyObject *ht_name, *ht_slots, *ht_qualname;
- struct _dictkeysobject *ht_cached_keys;
- PyObject *ht_module;
- /* here are optional user slots, followed by the members. */
-} PyHeapTypeObject;
-
-/* access macro to the members which are floating "behind" the object */
-#define PyHeapType_GET_MEMBERS(etype) \
- ((PyMemberDef *)(((char *)etype) + Py_TYPE(etype)->tp_basicsize))
-
-PyAPI_FUNC(const char *) _PyType_Name(PyTypeObject *);
-PyAPI_FUNC(PyObject *) _PyType_Lookup(PyTypeObject *, PyObject *);
-PyAPI_FUNC(PyObject *) _PyType_LookupId(PyTypeObject *, _Py_Identifier *);
-PyAPI_FUNC(PyObject *) _PyObject_LookupSpecial(PyObject *, _Py_Identifier *);
-PyAPI_FUNC(PyTypeObject *) _PyType_CalculateMetaclass(PyTypeObject *, PyObject *);
-PyAPI_FUNC(PyObject *) _PyType_GetDocFromInternalDoc(const char *, const char *);
-PyAPI_FUNC(PyObject *) _PyType_GetTextSignatureFromInternalDoc(const char *, const char *);
-struct PyModuleDef;
-PyAPI_FUNC(PyObject *) _PyType_GetModuleByDef(PyTypeObject *, struct PyModuleDef *);
-
-struct _Py_Identifier;
-PyAPI_FUNC(int) PyObject_Print(PyObject *, FILE *, int);
-PyAPI_FUNC(void) _Py_BreakPoint(void);
-PyAPI_FUNC(void) _PyObject_Dump(PyObject *);
-PyAPI_FUNC(int) _PyObject_IsFreed(PyObject *);
-
-PyAPI_FUNC(int) _PyObject_IsAbstract(PyObject *);
-PyAPI_FUNC(PyObject *) _PyObject_GetAttrId(PyObject *, struct _Py_Identifier *);
-PyAPI_FUNC(int) _PyObject_SetAttrId(PyObject *, struct _Py_Identifier *, PyObject *);
-/* Replacements of PyObject_GetAttr() and _PyObject_GetAttrId() which
- don't raise AttributeError.
-
- Return 1 and set *result != NULL if an attribute is found.
- Return 0 and set *result == NULL if an attribute is not found;
- an AttributeError is silenced.
- Return -1 and set *result == NULL if an error other than AttributeError
- is raised.
-*/
-PyAPI_FUNC(int) _PyObject_LookupAttr(PyObject *, PyObject *, PyObject **);
-PyAPI_FUNC(int) _PyObject_LookupAttrId(PyObject *, struct _Py_Identifier *, PyObject **);
-
-PyAPI_FUNC(int) _PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method);
-
-PyAPI_FUNC(PyObject **) _PyObject_GetDictPtr(PyObject *);
-PyAPI_FUNC(PyObject *) _PyObject_NextNotImplemented(PyObject *);
-PyAPI_FUNC(void) PyObject_CallFinalizer(PyObject *);
-PyAPI_FUNC(int) PyObject_CallFinalizerFromDealloc(PyObject *);
-
-/* Same as PyObject_Generic{Get,Set}Attr, but passing the attributes
- dict as the last parameter. */
-PyAPI_FUNC(PyObject *)
-_PyObject_GenericGetAttrWithDict(PyObject *, PyObject *, PyObject *, int);
-PyAPI_FUNC(int)
-_PyObject_GenericSetAttrWithDict(PyObject *, PyObject *,
- PyObject *, PyObject *);
-
-PyAPI_FUNC(PyObject *) _PyObject_FunctionStr(PyObject *);
-
-/* Safely decref `op` and set `op` to `op2`.
- *
- * As in case of Py_CLEAR "the obvious" code can be deadly:
- *
- * Py_DECREF(op);
- * op = op2;
- *
- * The safe way is:
- *
- * Py_SETREF(op, op2);
- *
- * That arranges to set `op` to `op2` _before_ decref'ing, so that any code
- * triggered as a side-effect of `op` getting torn down no longer believes
- * `op` points to a valid object.
- *
- * Py_XSETREF is a variant of Py_SETREF that uses Py_XDECREF instead of
- * Py_DECREF.
- */
-
-#define Py_SETREF(op, op2) \
- do { \
- PyObject *_py_tmp = _PyObject_CAST(op); \
- (op) = (op2); \
- Py_DECREF(_py_tmp); \
- } while (0)
-
-#define Py_XSETREF(op, op2) \
- do { \
- PyObject *_py_tmp = _PyObject_CAST(op); \
- (op) = (op2); \
- Py_XDECREF(_py_tmp); \
- } while (0)
-
-
-PyAPI_DATA(PyTypeObject) _PyNone_Type;
-PyAPI_DATA(PyTypeObject) _PyNotImplemented_Type;
-
-/* Maps Py_LT to Py_GT, ..., Py_GE to Py_LE.
- * Defined in object.c.
- */
-PyAPI_DATA(int) _Py_SwappedOp[];
-
-PyAPI_FUNC(void)
-_PyDebugAllocatorStats(FILE *out, const char *block_name, int num_blocks,
- size_t sizeof_block);
-PyAPI_FUNC(void)
-_PyObject_DebugTypeStats(FILE *out);
-
-/* Define a pair of assertion macros:
- _PyObject_ASSERT_FROM(), _PyObject_ASSERT_WITH_MSG() and _PyObject_ASSERT().
-
- These work like the regular C assert(), in that they will abort the
- process with a message on stderr if the given condition fails to hold,
- but compile away to nothing if NDEBUG is defined.
-
- However, before aborting, Python will also try to call _PyObject_Dump() on
- the given object. This may be of use when investigating bugs in which a
- particular object is corrupt (e.g. buggy a tp_visit method in an extension
- module breaking the garbage collector), to help locate the broken objects.
-
- The WITH_MSG variant allows you to supply an additional message that Python
- will attempt to print to stderr, after the object dump. */
-#ifdef NDEBUG
- /* No debugging: compile away the assertions: */
-# define _PyObject_ASSERT_FROM(obj, expr, msg, filename, lineno, func) \
- ((void)0)
-#else
- /* With debugging: generate checks: */
-# define _PyObject_ASSERT_FROM(obj, expr, msg, filename, lineno, func) \
- ((expr) \
- ? (void)(0) \
- : _PyObject_AssertFailed((obj), Py_STRINGIFY(expr), \
- (msg), (filename), (lineno), (func)))
-#endif
-
-#define _PyObject_ASSERT_WITH_MSG(obj, expr, msg) \
- _PyObject_ASSERT_FROM(obj, expr, msg, __FILE__, __LINE__, __func__)
-#define _PyObject_ASSERT(obj, expr) \
- _PyObject_ASSERT_WITH_MSG(obj, expr, NULL)
-
-#define _PyObject_ASSERT_FAILED_MSG(obj, msg) \
- _PyObject_AssertFailed((obj), NULL, (msg), __FILE__, __LINE__, __func__)
-
-/* Declare and define _PyObject_AssertFailed() even when NDEBUG is defined,
- to avoid causing compiler/linker errors when building extensions without
- NDEBUG against a Python built with NDEBUG defined.
-
- msg, expr and function can be NULL. */
-PyAPI_FUNC(void) _Py_NO_RETURN _PyObject_AssertFailed(
- PyObject *obj,
- const char *expr,
- const char *msg,
- const char *file,
- int line,
- const char *function);
-
-/* Check if an object is consistent. For example, ensure that the reference
- counter is greater than or equal to 1, and ensure that ob_type is not NULL.
-
- Call _PyObject_AssertFailed() if the object is inconsistent.
-
- If check_content is zero, only check header fields: reduce the overhead.
-
- The function always return 1. The return value is just here to be able to
- write:
-
- assert(_PyObject_CheckConsistency(obj, 1)); */
-PyAPI_FUNC(int) _PyObject_CheckConsistency(
- PyObject *op,
- int check_content);
-
-
-/* Trashcan mechanism, thanks to Christian Tismer.
-
-When deallocating a container object, it's possible to trigger an unbounded
-chain of deallocations, as each Py_DECREF in turn drops the refcount on "the
-next" object in the chain to 0. This can easily lead to stack overflows,
-especially in threads (which typically have less stack space to work with).
-
-A container object can avoid this by bracketing the body of its tp_dealloc
-function with a pair of macros:
-
-static void
-mytype_dealloc(mytype *p)
-{
- ... declarations go here ...
-
- PyObject_GC_UnTrack(p); // must untrack first
- Py_TRASHCAN_BEGIN(p, mytype_dealloc)
- ... The body of the deallocator goes here, including all calls ...
- ... to Py_DECREF on contained objects. ...
- Py_TRASHCAN_END // there should be no code after this
-}
-
-CAUTION: Never return from the middle of the body! If the body needs to
-"get out early", put a label immediately before the Py_TRASHCAN_END
-call, and goto it. Else the call-depth counter (see below) will stay
-above 0 forever, and the trashcan will never get emptied.
-
-How it works: The BEGIN macro increments a call-depth counter. So long
-as this counter is small, the body of the deallocator is run directly without
-further ado. But if the counter gets large, it instead adds p to a list of
-objects to be deallocated later, skips the body of the deallocator, and
-resumes execution after the END macro. The tp_dealloc routine then returns
-without deallocating anything (and so unbounded call-stack depth is avoided).
-
-When the call stack finishes unwinding again, code generated by the END macro
-notices this, and calls another routine to deallocate all the objects that
-may have been added to the list of deferred deallocations. In effect, a
-chain of N deallocations is broken into (N-1)/(PyTrash_UNWIND_LEVEL-1) pieces,
-with the call stack never exceeding a depth of PyTrash_UNWIND_LEVEL.
-
-Since the tp_dealloc of a subclass typically calls the tp_dealloc of the base
-class, we need to ensure that the trashcan is only triggered on the tp_dealloc
-of the actual class being deallocated. Otherwise we might end up with a
-partially-deallocated object. To check this, the tp_dealloc function must be
-passed as second argument to Py_TRASHCAN_BEGIN().
-*/
-
-/* This is the old private API, invoked by the macros before 3.2.4.
- Kept for binary compatibility of extensions using the stable ABI. */
-PyAPI_FUNC(void) _PyTrash_deposit_object(PyObject*);
-PyAPI_FUNC(void) _PyTrash_destroy_chain(void);
-
-/* This is the old private API, invoked by the macros before 3.9.
- Kept for binary compatibility of extensions using the stable ABI. */
-PyAPI_FUNC(void) _PyTrash_thread_deposit_object(PyObject*);
-PyAPI_FUNC(void) _PyTrash_thread_destroy_chain(void);
-
-/* Forward declarations for PyThreadState */
-struct _ts;
-
-/* Python 3.9 private API, invoked by the macros below. */
-PyAPI_FUNC(int) _PyTrash_begin(struct _ts *tstate, PyObject *op);
-PyAPI_FUNC(void) _PyTrash_end(struct _ts *tstate);
-/* Python 3.10 private API, invoked by the Py_TRASHCAN_BEGIN(). */
-PyAPI_FUNC(int) _PyTrash_cond(PyObject *op, destructor dealloc);
-
-#define PyTrash_UNWIND_LEVEL 50
-
-#define Py_TRASHCAN_BEGIN_CONDITION(op, cond) \
- do { \
- PyThreadState *_tstate = NULL; \
- /* If "cond" is false, then _tstate remains NULL and the deallocator \
- * is run normally without involving the trashcan */ \
- if (cond) { \
- _tstate = PyThreadState_Get(); \
- if (_PyTrash_begin(_tstate, _PyObject_CAST(op))) { \
- break; \
- } \
- }
- /* The body of the deallocator is here. */
-#define Py_TRASHCAN_END \
- if (_tstate) { \
- _PyTrash_end(_tstate); \
- } \
- } while (0);
-
-#define Py_TRASHCAN_BEGIN(op, dealloc) \
- Py_TRASHCAN_BEGIN_CONDITION(op, \
- _PyTrash_cond(_PyObject_CAST(op), (destructor)dealloc))
-
-/* For backwards compatibility, these macros enable the trashcan
- * unconditionally */
-#define Py_TRASHCAN_SAFE_BEGIN(op) Py_TRASHCAN_BEGIN_CONDITION(op, 1)
-#define Py_TRASHCAN_SAFE_END(op) Py_TRASHCAN_END
diff --git a/include/python3.10/cpython/objimpl.h b/include/python3.10/cpython/objimpl.h
deleted file mode 100644
index d83700e..0000000
--- a/include/python3.10/cpython/objimpl.h
+++ /dev/null
@@ -1,100 +0,0 @@
-#ifndef Py_CPYTHON_OBJIMPL_H
-# error "this header file must not be included directly"
-#endif
-
-#define _PyObject_SIZE(typeobj) ( (typeobj)->tp_basicsize )
-
-/* _PyObject_VAR_SIZE returns the number of bytes (as size_t) allocated for a
- vrbl-size object with nitems items, exclusive of gc overhead (if any). The
- value is rounded up to the closest multiple of sizeof(void *), in order to
- ensure that pointer fields at the end of the object are correctly aligned
- for the platform (this is of special importance for subclasses of, e.g.,
- str or int, so that pointers can be stored after the embedded data).
-
- Note that there's no memory wastage in doing this, as malloc has to
- return (at worst) pointer-aligned memory anyway.
-*/
-#if ((SIZEOF_VOID_P - 1) & SIZEOF_VOID_P) != 0
-# error "_PyObject_VAR_SIZE requires SIZEOF_VOID_P be a power of 2"
-#endif
-
-#define _PyObject_VAR_SIZE(typeobj, nitems) \
- _Py_SIZE_ROUND_UP((typeobj)->tp_basicsize + \
- (nitems)*(typeobj)->tp_itemsize, \
- SIZEOF_VOID_P)
-
-
-/* This example code implements an object constructor with a custom
- allocator, where PyObject_New is inlined, and shows the important
- distinction between two steps (at least):
- 1) the actual allocation of the object storage;
- 2) the initialization of the Python specific fields
- in this storage with PyObject_{Init, InitVar}.
-
- PyObject *
- YourObject_New(...)
- {
- PyObject *op;
-
- op = (PyObject *) Your_Allocator(_PyObject_SIZE(YourTypeStruct));
- if (op == NULL) {
- return PyErr_NoMemory();
- }
-
- PyObject_Init(op, &YourTypeStruct);
-
- op->ob_field = value;
- ...
- return op;
- }
-
- Note that in C++, the use of the new operator usually implies that
- the 1st step is performed automatically for you, so in a C++ class
- constructor you would start directly with PyObject_Init/InitVar. */
-
-/* This function returns the number of allocated memory blocks, regardless of size */
-PyAPI_FUNC(Py_ssize_t) _Py_GetAllocatedBlocks(void);
-
-/* Macros */
-#ifdef WITH_PYMALLOC
-PyAPI_FUNC(int) _PyObject_DebugMallocStats(FILE *out);
-#endif
-
-
-typedef struct {
- /* user context passed as the first argument to the 2 functions */
- void *ctx;
-
- /* allocate an arena of size bytes */
- void* (*alloc) (void *ctx, size_t size);
-
- /* free an arena */
- void (*free) (void *ctx, void *ptr, size_t size);
-} PyObjectArenaAllocator;
-
-/* Get the arena allocator. */
-PyAPI_FUNC(void) PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator);
-
-/* Set the arena allocator. */
-PyAPI_FUNC(void) PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator);
-
-
-/* Test if an object implements the garbage collector protocol */
-PyAPI_FUNC(int) PyObject_IS_GC(PyObject *obj);
-
-
-/* Code built with Py_BUILD_CORE must include pycore_gc.h instead which
- defines a different _PyGC_FINALIZED() macro. */
-#ifndef Py_BUILD_CORE
- // Kept for backward compatibility with Python 3.8
-# define _PyGC_FINALIZED(o) PyObject_GC_IsFinalized(o)
-#endif
-
-PyAPI_FUNC(PyObject *) _PyObject_GC_Malloc(size_t size);
-PyAPI_FUNC(PyObject *) _PyObject_GC_Calloc(size_t size);
-
-
-/* Test if a type supports weak references */
-#define PyType_SUPPORTS_WEAKREFS(t) ((t)->tp_weaklistoffset > 0)
-
-PyAPI_FUNC(PyObject **) PyObject_GET_WEAKREFS_LISTPTR(PyObject *op);
diff --git a/include/python3.10/cpython/pydebug.h b/include/python3.10/cpython/pydebug.h
deleted file mode 100644
index 78bcb11..0000000
--- a/include/python3.10/cpython/pydebug.h
+++ /dev/null
@@ -1,38 +0,0 @@
-#ifndef Py_LIMITED_API
-#ifndef Py_PYDEBUG_H
-#define Py_PYDEBUG_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-PyAPI_DATA(int) Py_DebugFlag;
-PyAPI_DATA(int) Py_VerboseFlag;
-PyAPI_DATA(int) Py_QuietFlag;
-PyAPI_DATA(int) Py_InteractiveFlag;
-PyAPI_DATA(int) Py_InspectFlag;
-PyAPI_DATA(int) Py_OptimizeFlag;
-PyAPI_DATA(int) Py_NoSiteFlag;
-PyAPI_DATA(int) Py_BytesWarningFlag;
-PyAPI_DATA(int) Py_FrozenFlag;
-PyAPI_DATA(int) Py_IgnoreEnvironmentFlag;
-PyAPI_DATA(int) Py_DontWriteBytecodeFlag;
-PyAPI_DATA(int) Py_NoUserSiteDirectory;
-PyAPI_DATA(int) Py_UnbufferedStdioFlag;
-PyAPI_DATA(int) Py_HashRandomizationFlag;
-PyAPI_DATA(int) Py_IsolatedFlag;
-
-#ifdef MS_WINDOWS
-PyAPI_DATA(int) Py_LegacyWindowsFSEncodingFlag;
-PyAPI_DATA(int) Py_LegacyWindowsStdioFlag;
-#endif
-
-/* this is a wrapper around getenv() that pays attention to
- Py_IgnoreEnvironmentFlag. It should be used for getting variables like
- PYTHONPATH and PYTHONHOME from the environment */
-#define Py_GETENV(s) (Py_IgnoreEnvironmentFlag ? NULL : getenv(s))
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_PYDEBUG_H */
-#endif /* Py_LIMITED_API */
diff --git a/include/python3.10/cpython/pyerrors.h b/include/python3.10/cpython/pyerrors.h
deleted file mode 100644
index 3f95245..0000000
--- a/include/python3.10/cpython/pyerrors.h
+++ /dev/null
@@ -1,214 +0,0 @@
-#ifndef Py_CPYTHON_ERRORS_H
-# error "this header file must not be included directly"
-#endif
-
-/* Error objects */
-
-/* PyException_HEAD defines the initial segment of every exception class. */
-#define PyException_HEAD PyObject_HEAD PyObject *dict;\
- PyObject *args; PyObject *traceback;\
- PyObject *context; PyObject *cause;\
- char suppress_context;
-
-typedef struct {
- PyException_HEAD
-} PyBaseExceptionObject;
-
-typedef struct {
- PyException_HEAD
- PyObject *msg;
- PyObject *filename;
- PyObject *lineno;
- PyObject *offset;
- PyObject *end_lineno;
- PyObject *end_offset;
- PyObject *text;
- PyObject *print_file_and_line;
-} PySyntaxErrorObject;
-
-typedef struct {
- PyException_HEAD
- PyObject *msg;
- PyObject *name;
- PyObject *path;
-} PyImportErrorObject;
-
-typedef struct {
- PyException_HEAD
- PyObject *encoding;
- PyObject *object;
- Py_ssize_t start;
- Py_ssize_t end;
- PyObject *reason;
-} PyUnicodeErrorObject;
-
-typedef struct {
- PyException_HEAD
- PyObject *code;
-} PySystemExitObject;
-
-typedef struct {
- PyException_HEAD
- PyObject *myerrno;
- PyObject *strerror;
- PyObject *filename;
- PyObject *filename2;
-#ifdef MS_WINDOWS
- PyObject *winerror;
-#endif
- Py_ssize_t written; /* only for BlockingIOError, -1 otherwise */
-} PyOSErrorObject;
-
-typedef struct {
- PyException_HEAD
- PyObject *value;
-} PyStopIterationObject;
-
-typedef struct {
- PyException_HEAD
- PyObject *name;
-} PyNameErrorObject;
-
-typedef struct {
- PyException_HEAD
- PyObject *obj;
- PyObject *name;
-} PyAttributeErrorObject;
-
-/* Compatibility typedefs */
-typedef PyOSErrorObject PyEnvironmentErrorObject;
-#ifdef MS_WINDOWS
-typedef PyOSErrorObject PyWindowsErrorObject;
-#endif
-
-/* Error handling definitions */
-
-PyAPI_FUNC(void) _PyErr_SetKeyError(PyObject *);
-PyAPI_FUNC(_PyErr_StackItem*) _PyErr_GetTopmostException(PyThreadState *tstate);
-PyAPI_FUNC(void) _PyErr_GetExcInfo(PyThreadState *, PyObject **, PyObject **, PyObject **);
-
-/* Context manipulation (PEP 3134) */
-
-PyAPI_FUNC(void) _PyErr_ChainExceptions(PyObject *, PyObject *, PyObject *);
-
-/* Convenience functions */
-
-#ifdef MS_WINDOWS
-Py_DEPRECATED(3.3)
-PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithUnicodeFilename(
- PyObject *, const Py_UNICODE *);
-#endif /* MS_WINDOWS */
-
-/* Like PyErr_Format(), but saves current exception as __context__ and
- __cause__.
- */
-PyAPI_FUNC(PyObject *) _PyErr_FormatFromCause(
- PyObject *exception,
- const char *format, /* ASCII-encoded string */
- ...
- );
-
-#ifdef MS_WINDOWS
-/* XXX redeclare to use WSTRING */
-Py_DEPRECATED(3.3)
-PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithUnicodeFilename(
- int, const Py_UNICODE *);
-Py_DEPRECATED(3.3)
-PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithUnicodeFilename(
- PyObject *,int, const Py_UNICODE *);
-#endif
-
-/* In exceptions.c */
-
-/* Helper that attempts to replace the current exception with one of the
- * same type but with a prefix added to the exception text. The resulting
- * exception description looks like:
- *
- * prefix (exc_type: original_exc_str)
- *
- * Only some exceptions can be safely replaced. If the function determines
- * it isn't safe to perform the replacement, it will leave the original
- * unmodified exception in place.
- *
- * Returns a borrowed reference to the new exception (if any), NULL if the
- * existing exception was left in place.
- */
-PyAPI_FUNC(PyObject *) _PyErr_TrySetFromCause(
- const char *prefix_format, /* ASCII-encoded string */
- ...
- );
-
-/* In signalmodule.c */
-
-int PySignal_SetWakeupFd(int fd);
-PyAPI_FUNC(int) _PyErr_CheckSignals(void);
-
-/* Support for adding program text to SyntaxErrors */
-
-PyAPI_FUNC(void) PyErr_SyntaxLocationObject(
- PyObject *filename,
- int lineno,
- int col_offset);
-
-PyAPI_FUNC(void) PyErr_RangedSyntaxLocationObject(
- PyObject *filename,
- int lineno,
- int col_offset,
- int end_lineno,
- int end_col_offset);
-
-PyAPI_FUNC(PyObject *) PyErr_ProgramTextObject(
- PyObject *filename,
- int lineno);
-
-/* Create a UnicodeEncodeError object.
- *
- * TODO: This API will be removed in Python 3.11.
- */
-Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_Create(
- const char *encoding, /* UTF-8 encoded string */
- const Py_UNICODE *object,
- Py_ssize_t length,
- Py_ssize_t start,
- Py_ssize_t end,
- const char *reason /* UTF-8 encoded string */
- );
-
-/* Create a UnicodeTranslateError object.
- *
- * TODO: This API will be removed in Python 3.11.
- */
-Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject *) PyUnicodeTranslateError_Create(
- const Py_UNICODE *object,
- Py_ssize_t length,
- Py_ssize_t start,
- Py_ssize_t end,
- const char *reason /* UTF-8 encoded string */
- );
-
-PyAPI_FUNC(PyObject *) _PyErr_ProgramDecodedTextObject(
- PyObject *filename,
- int lineno,
- const char* encoding);
-
-PyAPI_FUNC(PyObject *) _PyUnicodeTranslateError_Create(
- PyObject *object,
- Py_ssize_t start,
- Py_ssize_t end,
- const char *reason /* UTF-8 encoded string */
- );
-
-PyAPI_FUNC(void) _PyErr_WriteUnraisableMsg(
- const char *err_msg,
- PyObject *obj);
-
-PyAPI_FUNC(void) _Py_NO_RETURN _Py_FatalErrorFunc(
- const char *func,
- const char *message);
-
-PyAPI_FUNC(void) _Py_NO_RETURN _Py_FatalErrorFormat(
- const char *func,
- const char *format,
- ...);
-
-#define Py_FatalError(message) _Py_FatalErrorFunc(__func__, message)
diff --git a/include/python3.10/cpython/pylifecycle.h b/include/python3.10/cpython/pylifecycle.h
deleted file mode 100644
index 5faeb35..0000000
--- a/include/python3.10/cpython/pylifecycle.h
+++ /dev/null
@@ -1,64 +0,0 @@
-#ifndef Py_CPYTHON_PYLIFECYCLE_H
-# error "this header file must not be included directly"
-#endif
-
-/* Py_FrozenMain is kept out of the Limited API until documented and present
- in all builds of Python */
-PyAPI_FUNC(int) Py_FrozenMain(int argc, char **argv);
-
-/* Only used by applications that embed the interpreter and need to
- * override the standard encoding determination mechanism
- */
-PyAPI_FUNC(int) Py_SetStandardStreamEncoding(const char *encoding,
- const char *errors);
-
-/* PEP 432 Multi-phase initialization API (Private while provisional!) */
-
-PyAPI_FUNC(PyStatus) Py_PreInitialize(
- const PyPreConfig *src_config);
-PyAPI_FUNC(PyStatus) Py_PreInitializeFromBytesArgs(
- const PyPreConfig *src_config,
- Py_ssize_t argc,
- char **argv);
-PyAPI_FUNC(PyStatus) Py_PreInitializeFromArgs(
- const PyPreConfig *src_config,
- Py_ssize_t argc,
- wchar_t **argv);
-
-PyAPI_FUNC(int) _Py_IsCoreInitialized(void);
-
-
-/* Initialization and finalization */
-
-PyAPI_FUNC(PyStatus) Py_InitializeFromConfig(
- const PyConfig *config);
-PyAPI_FUNC(PyStatus) _Py_InitializeMain(void);
-
-PyAPI_FUNC(int) Py_RunMain(void);
-
-
-PyAPI_FUNC(void) _Py_NO_RETURN Py_ExitStatusException(PyStatus err);
-
-/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL. */
-PyAPI_FUNC(void) _Py_RestoreSignals(void);
-
-PyAPI_FUNC(int) Py_FdIsInteractive(FILE *, const char *);
-PyAPI_FUNC(int) _Py_FdIsInteractive(FILE *fp, PyObject *filename);
-
-PyAPI_FUNC(void) _Py_SetProgramFullPath(const wchar_t *);
-
-PyAPI_FUNC(const char *) _Py_gitidentifier(void);
-PyAPI_FUNC(const char *) _Py_gitversion(void);
-
-PyAPI_FUNC(int) _Py_IsFinalizing(void);
-
-/* Random */
-PyAPI_FUNC(int) _PyOS_URandom(void *buffer, Py_ssize_t size);
-PyAPI_FUNC(int) _PyOS_URandomNonblock(void *buffer, Py_ssize_t size);
-
-/* Legacy locale support */
-PyAPI_FUNC(int) _Py_CoerceLegacyLocale(int warn);
-PyAPI_FUNC(int) _Py_LegacyLocaleDetected(int warn);
-PyAPI_FUNC(char *) _Py_SetLocaleFromEnv(int category);
-
-PyAPI_FUNC(PyThreadState *) _Py_NewInterpreter(int isolated_subinterpreter);
diff --git a/include/python3.10/cpython/pystate.h b/include/python3.10/cpython/pystate.h
deleted file mode 100644
index 7c995b9..0000000
--- a/include/python3.10/cpython/pystate.h
+++ /dev/null
@@ -1,305 +0,0 @@
-#ifndef Py_CPYTHON_PYSTATE_H
-# error "this header file must not be included directly"
-#endif
-
-PyAPI_FUNC(int) _PyInterpreterState_RequiresIDRef(PyInterpreterState *);
-PyAPI_FUNC(void) _PyInterpreterState_RequireIDRef(PyInterpreterState *, int);
-
-PyAPI_FUNC(PyObject *) _PyInterpreterState_GetMainModule(PyInterpreterState *);
-
-/* State unique per thread */
-
-/* Py_tracefunc return -1 when raising an exception, or 0 for success. */
-typedef int (*Py_tracefunc)(PyObject *, PyFrameObject *, int, PyObject *);
-
-/* The following values are used for 'what' for tracefunc functions
- *
- * To add a new kind of trace event, also update "trace_init" in
- * Python/sysmodule.c to define the Python level event name
- */
-#define PyTrace_CALL 0
-#define PyTrace_EXCEPTION 1
-#define PyTrace_LINE 2
-#define PyTrace_RETURN 3
-#define PyTrace_C_CALL 4
-#define PyTrace_C_EXCEPTION 5
-#define PyTrace_C_RETURN 6
-#define PyTrace_OPCODE 7
-
-
-typedef struct _cframe {
- /* This struct will be threaded through the C stack
- * allowing fast access to per-thread state that needs
- * to be accessed quickly by the interpreter, but can
- * be modified outside of the interpreter.
- *
- * WARNING: This makes data on the C stack accessible from
- * heap objects. Care must be taken to maintain stack
- * discipline and make sure that instances of this struct cannot
- * accessed outside of their lifetime.
- */
- int use_tracing;
- struct _cframe *previous;
-} CFrame;
-
-typedef struct _err_stackitem {
- /* This struct represents an entry on the exception stack, which is a
- * per-coroutine state. (Coroutine in the computer science sense,
- * including the thread and generators).
- * This ensures that the exception state is not impacted by "yields"
- * from an except handler.
- */
- PyObject *exc_type, *exc_value, *exc_traceback;
-
- struct _err_stackitem *previous_item;
-
-} _PyErr_StackItem;
-
-
-// The PyThreadState typedef is in Include/pystate.h.
-struct _ts {
- /* See Python/ceval.c for comments explaining most fields */
-
- struct _ts *prev;
- struct _ts *next;
- PyInterpreterState *interp;
-
- /* Borrowed reference to the current frame (it can be NULL) */
- PyFrameObject *frame;
- int recursion_depth;
- int recursion_headroom; /* Allow 50 more calls to handle any errors. */
- int stackcheck_counter;
-
- /* 'tracing' keeps track of the execution depth when tracing/profiling.
- This is to prevent the actual trace/profile code from being recorded in
- the trace/profile. */
- int tracing;
-
- /* Pointer to current CFrame in the C stack frame of the currently,
- * or most recently, executing _PyEval_EvalFrameDefault. */
- CFrame *cframe;
-
- Py_tracefunc c_profilefunc;
- Py_tracefunc c_tracefunc;
- PyObject *c_profileobj;
- PyObject *c_traceobj;
-
- /* The exception currently being raised */
- PyObject *curexc_type;
- PyObject *curexc_value;
- PyObject *curexc_traceback;
-
- /* The exception currently being handled, if no coroutines/generators
- * are present. Always last element on the stack referred to be exc_info.
- */
- _PyErr_StackItem exc_state;
-
- /* Pointer to the top of the stack of the exceptions currently
- * being handled */
- _PyErr_StackItem *exc_info;
-
- PyObject *dict; /* Stores per-thread state */
-
- int gilstate_counter;
-
- PyObject *async_exc; /* Asynchronous exception to raise */
- unsigned long thread_id; /* Thread id where this tstate was created */
-
- int trash_delete_nesting;
- PyObject *trash_delete_later;
-
- /* Called when a thread state is deleted normally, but not when it
- * is destroyed after fork().
- * Pain: to prevent rare but fatal shutdown errors (issue 18808),
- * Thread.join() must wait for the join'ed thread's tstate to be unlinked
- * from the tstate chain. That happens at the end of a thread's life,
- * in pystate.c.
- * The obvious way doesn't quite work: create a lock which the tstate
- * unlinking code releases, and have Thread.join() wait to acquire that
- * lock. The problem is that we _are_ at the end of the thread's life:
- * if the thread holds the last reference to the lock, decref'ing the
- * lock will delete the lock, and that may trigger arbitrary Python code
- * if there's a weakref, with a callback, to the lock. But by this time
- * _PyRuntime.gilstate.tstate_current is already NULL, so only the simplest
- * of C code can be allowed to run (in particular it must not be possible to
- * release the GIL).
- * So instead of holding the lock directly, the tstate holds a weakref to
- * the lock: that's the value of on_delete_data below. Decref'ing a
- * weakref is harmless.
- * on_delete points to _threadmodule.c's static release_sentinel() function.
- * After the tstate is unlinked, release_sentinel is called with the
- * weakref-to-lock (on_delete_data) argument, and release_sentinel releases
- * the indirectly held lock.
- */
- void (*on_delete)(void *);
- void *on_delete_data;
-
- int coroutine_origin_tracking_depth;
-
- PyObject *async_gen_firstiter;
- PyObject *async_gen_finalizer;
-
- PyObject *context;
- uint64_t context_ver;
-
- /* Unique thread state id. */
- uint64_t id;
-
- CFrame root_cframe;
-
- /* XXX signal handlers should also be here */
-
-};
-
-// Alias for backward compatibility with Python 3.8
-#define _PyInterpreterState_Get PyInterpreterState_Get
-
-PyAPI_FUNC(PyThreadState *) _PyThreadState_Prealloc(PyInterpreterState *);
-
-/* Similar to PyThreadState_Get(), but don't issue a fatal error
- * if it is NULL. */
-PyAPI_FUNC(PyThreadState *) _PyThreadState_UncheckedGet(void);
-
-PyAPI_FUNC(PyObject *) _PyThreadState_GetDict(PyThreadState *tstate);
-
-/* PyGILState */
-
-/* Helper/diagnostic function - return 1 if the current thread
- currently holds the GIL, 0 otherwise.
-
- The function returns 1 if _PyGILState_check_enabled is non-zero. */
-PyAPI_FUNC(int) PyGILState_Check(void);
-
-/* Get the single PyInterpreterState used by this process' GILState
- implementation.
-
- This function doesn't check for error. Return NULL before _PyGILState_Init()
- is called and after _PyGILState_Fini() is called.
-
- See also _PyInterpreterState_Get() and _PyInterpreterState_GET(). */
-PyAPI_FUNC(PyInterpreterState *) _PyGILState_GetInterpreterStateUnsafe(void);
-
-/* The implementation of sys._current_frames() Returns a dict mapping
- thread id to that thread's current frame.
-*/
-PyAPI_FUNC(PyObject *) _PyThread_CurrentFrames(void);
-
-/* The implementation of sys._current_exceptions() Returns a dict mapping
- thread id to that thread's current exception.
-*/
-PyAPI_FUNC(PyObject *) _PyThread_CurrentExceptions(void);
-
-/* Routines for advanced debuggers, requested by David Beazley.
- Don't use unless you know what you are doing! */
-PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Main(void);
-PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Head(void);
-PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Next(PyInterpreterState *);
-PyAPI_FUNC(PyThreadState *) PyInterpreterState_ThreadHead(PyInterpreterState *);
-PyAPI_FUNC(PyThreadState *) PyThreadState_Next(PyThreadState *);
-PyAPI_FUNC(void) PyThreadState_DeleteCurrent(void);
-
-/* Frame evaluation API */
-
-typedef PyObject* (*_PyFrameEvalFunction)(PyThreadState *tstate, PyFrameObject *, int);
-
-PyAPI_FUNC(_PyFrameEvalFunction) _PyInterpreterState_GetEvalFrameFunc(
- PyInterpreterState *interp);
-PyAPI_FUNC(void) _PyInterpreterState_SetEvalFrameFunc(
- PyInterpreterState *interp,
- _PyFrameEvalFunction eval_frame);
-
-PyAPI_FUNC(const PyConfig*) _PyInterpreterState_GetConfig(PyInterpreterState *interp);
-
-/* Get a copy of the current interpreter configuration.
-
- Return 0 on success. Raise an exception and return -1 on error.
-
- The caller must initialize 'config', using PyConfig_InitPythonConfig()
- for example.
-
- Python must be preinitialized to call this method.
- The caller must hold the GIL. */
-PyAPI_FUNC(int) _PyInterpreterState_GetConfigCopy(
- struct PyConfig *config);
-
-/* Set the configuration of the current interpreter.
-
- This function should be called during or just after the Python
- initialization.
-
- Update the sys module with the new configuration. If the sys module was
- modified directly after the Python initialization, these changes are lost.
-
- Some configuration like faulthandler or warnoptions can be updated in the
- configuration, but don't reconfigure Python (don't enable/disable
- faulthandler and don't reconfigure warnings filters).
-
- Return 0 on success. Raise an exception and return -1 on error.
-
- The configuration should come from _PyInterpreterState_GetConfigCopy(). */
-PyAPI_FUNC(int) _PyInterpreterState_SetConfig(
- const struct PyConfig *config);
-
-// Get the configuration of the current interpreter.
-// The caller must hold the GIL.
-PyAPI_FUNC(const PyConfig*) _Py_GetConfig(void);
-
-
-/* cross-interpreter data */
-
-struct _xid;
-
-// _PyCrossInterpreterData is similar to Py_buffer as an effectively
-// opaque struct that holds data outside the object machinery. This
-// is necessary to pass safely between interpreters in the same process.
-typedef struct _xid {
- // data is the cross-interpreter-safe derivation of a Python object
- // (see _PyObject_GetCrossInterpreterData). It will be NULL if the
- // new_object func (below) encodes the data.
- void *data;
- // obj is the Python object from which the data was derived. This
- // is non-NULL only if the data remains bound to the object in some
- // way, such that the object must be "released" (via a decref) when
- // the data is released. In that case the code that sets the field,
- // likely a registered "crossinterpdatafunc", is responsible for
- // ensuring it owns the reference (i.e. incref).
- PyObject *obj;
- // interp is the ID of the owning interpreter of the original
- // object. It corresponds to the active interpreter when
- // _PyObject_GetCrossInterpreterData() was called. This should only
- // be set by the cross-interpreter machinery.
- //
- // We use the ID rather than the PyInterpreterState to avoid issues
- // with deleted interpreters. Note that IDs are never re-used, so
- // each one will always correspond to a specific interpreter
- // (whether still alive or not).
- int64_t interp;
- // new_object is a function that returns a new object in the current
- // interpreter given the data. The resulting object (a new
- // reference) will be equivalent to the original object. This field
- // is required.
- PyObject *(*new_object)(struct _xid *);
- // free is called when the data is released. If it is NULL then
- // nothing will be done to free the data. For some types this is
- // okay (e.g. bytes) and for those types this field should be set
- // to NULL. However, for most the data was allocated just for
- // cross-interpreter use, so it must be freed when
- // _PyCrossInterpreterData_Release is called or the memory will
- // leak. In that case, at the very least this field should be set
- // to PyMem_RawFree (the default if not explicitly set to NULL).
- // The call will happen with the original interpreter activated.
- void (*free)(void *);
-} _PyCrossInterpreterData;
-
-PyAPI_FUNC(int) _PyObject_GetCrossInterpreterData(PyObject *, _PyCrossInterpreterData *);
-PyAPI_FUNC(PyObject *) _PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *);
-PyAPI_FUNC(void) _PyCrossInterpreterData_Release(_PyCrossInterpreterData *);
-
-PyAPI_FUNC(int) _PyObject_CheckCrossInterpreterData(PyObject *);
-
-/* cross-interpreter data registry */
-
-typedef int (*crossinterpdatafunc)(PyObject *, struct _xid *);
-
-PyAPI_FUNC(int) _PyCrossInterpreterData_RegisterClass(PyTypeObject *, crossinterpdatafunc);
-PyAPI_FUNC(crossinterpdatafunc) _PyCrossInterpreterData_Lookup(PyObject *);
diff --git a/include/python3.10/cpython/pytime.h b/include/python3.10/cpython/pytime.h
deleted file mode 100644
index 754c7f4..0000000
--- a/include/python3.10/cpython/pytime.h
+++ /dev/null
@@ -1,247 +0,0 @@
-#ifndef Py_LIMITED_API
-#ifndef Py_PYTIME_H
-#define Py_PYTIME_H
-
-/**************************************************************************
-Symbols and macros to supply platform-independent interfaces to time related
-functions and constants
-**************************************************************************/
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* _PyTime_t: Python timestamp with subsecond precision. It can be used to
- store a duration, and so indirectly a date (related to another date, like
- UNIX epoch). */
-typedef int64_t _PyTime_t;
-#define _PyTime_MIN INT64_MIN
-#define _PyTime_MAX INT64_MAX
-
-typedef enum {
- /* Round towards minus infinity (-inf).
- For example, used to read a clock. */
- _PyTime_ROUND_FLOOR=0,
- /* Round towards infinity (+inf).
- For example, used for timeout to wait "at least" N seconds. */
- _PyTime_ROUND_CEILING=1,
- /* Round to nearest with ties going to nearest even integer.
- For example, used to round from a Python float. */
- _PyTime_ROUND_HALF_EVEN=2,
- /* Round away from zero
- For example, used for timeout. _PyTime_ROUND_CEILING rounds
- -1e-9 to 0 milliseconds which causes bpo-31786 issue.
- _PyTime_ROUND_UP rounds -1e-9 to -1 millisecond which keeps
- the timeout sign as expected. select.poll(timeout) must block
- for negative values." */
- _PyTime_ROUND_UP=3,
- /* _PyTime_ROUND_TIMEOUT (an alias for _PyTime_ROUND_UP) should be
- used for timeouts. */
- _PyTime_ROUND_TIMEOUT = _PyTime_ROUND_UP
-} _PyTime_round_t;
-
-
-/* Convert a time_t to a PyLong. */
-PyAPI_FUNC(PyObject *) _PyLong_FromTime_t(
- time_t sec);
-
-/* Convert a PyLong to a time_t. */
-PyAPI_FUNC(time_t) _PyLong_AsTime_t(
- PyObject *obj);
-
-/* Convert a number of seconds, int or float, to time_t. */
-PyAPI_FUNC(int) _PyTime_ObjectToTime_t(
- PyObject *obj,
- time_t *sec,
- _PyTime_round_t);
-
-/* Convert a number of seconds, int or float, to a timeval structure.
- usec is in the range [0; 999999] and rounded towards zero.
- For example, -1.2 is converted to (-2, 800000). */
-PyAPI_FUNC(int) _PyTime_ObjectToTimeval(
- PyObject *obj,
- time_t *sec,
- long *usec,
- _PyTime_round_t);
-
-/* Convert a number of seconds, int or float, to a timespec structure.
- nsec is in the range [0; 999999999] and rounded towards zero.
- For example, -1.2 is converted to (-2, 800000000). */
-PyAPI_FUNC(int) _PyTime_ObjectToTimespec(
- PyObject *obj,
- time_t *sec,
- long *nsec,
- _PyTime_round_t);
-
-
-/* Create a timestamp from a number of seconds. */
-PyAPI_FUNC(_PyTime_t) _PyTime_FromSeconds(int seconds);
-
-/* Macro to create a timestamp from a number of seconds, no integer overflow.
- Only use the macro for small values, prefer _PyTime_FromSeconds(). */
-#define _PYTIME_FROMSECONDS(seconds) \
- ((_PyTime_t)(seconds) * (1000 * 1000 * 1000))
-
-/* Create a timestamp from a number of nanoseconds. */
-PyAPI_FUNC(_PyTime_t) _PyTime_FromNanoseconds(_PyTime_t ns);
-
-/* Create a timestamp from nanoseconds (Python int). */
-PyAPI_FUNC(int) _PyTime_FromNanosecondsObject(_PyTime_t *t,
- PyObject *obj);
-
-/* Convert a number of seconds (Python float or int) to a timestamp.
- Raise an exception and return -1 on error, return 0 on success. */
-PyAPI_FUNC(int) _PyTime_FromSecondsObject(_PyTime_t *t,
- PyObject *obj,
- _PyTime_round_t round);
-
-/* Convert a number of milliseconds (Python float or int, 10^-3) to a timestamp.
- Raise an exception and return -1 on error, return 0 on success. */
-PyAPI_FUNC(int) _PyTime_FromMillisecondsObject(_PyTime_t *t,
- PyObject *obj,
- _PyTime_round_t round);
-
-/* Convert a timestamp to a number of seconds as a C double. */
-PyAPI_FUNC(double) _PyTime_AsSecondsDouble(_PyTime_t t);
-
-/* Convert timestamp to a number of milliseconds (10^-3 seconds). */
-PyAPI_FUNC(_PyTime_t) _PyTime_AsMilliseconds(_PyTime_t t,
- _PyTime_round_t round);
-
-/* Convert timestamp to a number of microseconds (10^-6 seconds). */
-PyAPI_FUNC(_PyTime_t) _PyTime_AsMicroseconds(_PyTime_t t,
- _PyTime_round_t round);
-
-/* Convert timestamp to a number of nanoseconds (10^-9 seconds) as a Python int
- object. */
-PyAPI_FUNC(PyObject *) _PyTime_AsNanosecondsObject(_PyTime_t t);
-
-/* Create a timestamp from a timeval structure.
- Raise an exception and return -1 on overflow, return 0 on success. */
-PyAPI_FUNC(int) _PyTime_FromTimeval(_PyTime_t *tp, struct timeval *tv);
-
-/* Convert a timestamp to a timeval structure (microsecond resolution).
- tv_usec is always positive.
- Raise an exception and return -1 if the conversion overflowed,
- return 0 on success. */
-PyAPI_FUNC(int) _PyTime_AsTimeval(_PyTime_t t,
- struct timeval *tv,
- _PyTime_round_t round);
-
-/* Similar to _PyTime_AsTimeval(), but don't raise an exception on error. */
-PyAPI_FUNC(int) _PyTime_AsTimeval_noraise(_PyTime_t t,
- struct timeval *tv,
- _PyTime_round_t round);
-
-/* Convert a timestamp to a number of seconds (secs) and microseconds (us).
- us is always positive. This function is similar to _PyTime_AsTimeval()
- except that secs is always a time_t type, whereas the timeval structure
- uses a C long for tv_sec on Windows.
- Raise an exception and return -1 if the conversion overflowed,
- return 0 on success. */
-PyAPI_FUNC(int) _PyTime_AsTimevalTime_t(
- _PyTime_t t,
- time_t *secs,
- int *us,
- _PyTime_round_t round);
-
-#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_KQUEUE)
-/* Create a timestamp from a timespec structure.
- Raise an exception and return -1 on overflow, return 0 on success. */
-PyAPI_FUNC(int) _PyTime_FromTimespec(_PyTime_t *tp, struct timespec *ts);
-
-/* Convert a timestamp to a timespec structure (nanosecond resolution).
- tv_nsec is always positive.
- Raise an exception and return -1 on error, return 0 on success. */
-PyAPI_FUNC(int) _PyTime_AsTimespec(_PyTime_t t, struct timespec *ts);
-#endif
-
-/* Compute ticks * mul / div.
- The caller must ensure that ((div - 1) * mul) cannot overflow. */
-PyAPI_FUNC(_PyTime_t) _PyTime_MulDiv(_PyTime_t ticks,
- _PyTime_t mul,
- _PyTime_t div);
-
-/* Structure used by time.get_clock_info() */
-typedef struct {
- const char *implementation;
- int monotonic;
- int adjustable;
- double resolution;
-} _Py_clock_info_t;
-
-/* Get the current time from the system clock.
-
- If the internal clock fails, silently ignore the error and return 0.
- On integer overflow, silently ignore the overflow and truncated the clock to
- _PyTime_MIN or _PyTime_MAX.
-
- Use _PyTime_GetSystemClockWithInfo() to check for failure. */
-PyAPI_FUNC(_PyTime_t) _PyTime_GetSystemClock(void);
-
-/* Get the current time from the system clock.
- * On success, set *t and *info (if not NULL), and return 0.
- * On error, raise an exception and return -1.
- */
-PyAPI_FUNC(int) _PyTime_GetSystemClockWithInfo(
- _PyTime_t *t,
- _Py_clock_info_t *info);
-
-/* Get the time of a monotonic clock, i.e. a clock that cannot go backwards.
- The clock is not affected by system clock updates. The reference point of
- the returned value is undefined, so that only the difference between the
- results of consecutive calls is valid.
-
- If the internal clock fails, silently ignore the error and return 0.
- On integer overflow, silently ignore the overflow and truncated the clock to
- _PyTime_MIN or _PyTime_MAX.
-
- Use _PyTime_GetMonotonicClockWithInfo() to check for failure. */
-PyAPI_FUNC(_PyTime_t) _PyTime_GetMonotonicClock(void);
-
-/* Get the time of a monotonic clock, i.e. a clock that cannot go backwards.
- The clock is not affected by system clock updates. The reference point of
- the returned value is undefined, so that only the difference between the
- results of consecutive calls is valid.
-
- Fill info (if set) with information of the function used to get the time.
-
- Return 0 on success, raise an exception and return -1 on error. */
-PyAPI_FUNC(int) _PyTime_GetMonotonicClockWithInfo(
- _PyTime_t *t,
- _Py_clock_info_t *info);
-
-
-/* Converts a timestamp to the Gregorian time, using the local time zone.
- Return 0 on success, raise an exception and return -1 on error. */
-PyAPI_FUNC(int) _PyTime_localtime(time_t t, struct tm *tm);
-
-/* Converts a timestamp to the Gregorian time, assuming UTC.
- Return 0 on success, raise an exception and return -1 on error. */
-PyAPI_FUNC(int) _PyTime_gmtime(time_t t, struct tm *tm);
-
-/* Get the performance counter: clock with the highest available resolution to
- measure a short duration.
-
- If the internal clock fails, silently ignore the error and return 0.
- On integer overflow, silently ignore the overflow and truncated the clock to
- _PyTime_MIN or _PyTime_MAX.
-
- Use _PyTime_GetPerfCounterWithInfo() to check for failure. */
-PyAPI_FUNC(_PyTime_t) _PyTime_GetPerfCounter(void);
-
-/* Get the performance counter: clock with the highest available resolution to
- measure a short duration.
-
- Fill info (if set) with information of the function used to get the time.
-
- Return 0 on success, raise an exception and return -1 on error. */
-PyAPI_FUNC(int) _PyTime_GetPerfCounterWithInfo(
- _PyTime_t *t,
- _Py_clock_info_t *info);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* Py_PYTIME_H */
-#endif /* Py_LIMITED_API */
diff --git a/include/python3.10/cpython/sysmodule.h b/include/python3.10/cpython/sysmodule.h
deleted file mode 100644
index fc4c899..0000000
--- a/include/python3.10/cpython/sysmodule.h
+++ /dev/null
@@ -1,16 +0,0 @@
-#ifndef Py_CPYTHON_SYSMODULE_H
-# error "this header file must not be included directly"
-#endif
-
-PyAPI_FUNC(PyObject *) _PySys_GetObjectId(_Py_Identifier *key);
-PyAPI_FUNC(int) _PySys_SetObjectId(_Py_Identifier *key, PyObject *);
-
-PyAPI_FUNC(size_t) _PySys_GetSizeOf(PyObject *);
-
-typedef int(*Py_AuditHookFunction)(const char *, PyObject *, void *);
-
-PyAPI_FUNC(int) PySys_Audit(
- const char *event,
- const char *argFormat,
- ...);
-PyAPI_FUNC(int) PySys_AddAuditHook(Py_AuditHookFunction, void*);
diff --git a/include/python3.10/cpython/traceback.h b/include/python3.10/cpython/traceback.h
deleted file mode 100644
index aac5b42..0000000
--- a/include/python3.10/cpython/traceback.h
+++ /dev/null
@@ -1,14 +0,0 @@
-#ifndef Py_CPYTHON_TRACEBACK_H
-# error "this header file must not be included directly"
-#endif
-
-typedef struct _traceback {
- PyObject_HEAD
- struct _traceback *tb_next;
- PyFrameObject *tb_frame;
- int tb_lasti;
- int tb_lineno;
-} PyTracebackObject;
-
-PyAPI_FUNC(int) _Py_DisplaySourceLine(PyObject *, PyObject *, int, int);
-PyAPI_FUNC(void) _PyTraceback_Add(const char *, const char *, int);
diff --git a/include/python3.10/cpython/tupleobject.h b/include/python3.10/cpython/tupleobject.h
deleted file mode 100644
index 7cada88..0000000
--- a/include/python3.10/cpython/tupleobject.h
+++ /dev/null
@@ -1,28 +0,0 @@
-#ifndef Py_CPYTHON_TUPLEOBJECT_H
-# error "this header file must not be included directly"
-#endif
-
-typedef struct {
- PyObject_VAR_HEAD
- /* ob_item contains space for 'ob_size' elements.
- Items must normally not be NULL, except during construction when
- the tuple is not yet visible outside the function that builds it. */
- PyObject *ob_item[1];
-} PyTupleObject;
-
-PyAPI_FUNC(int) _PyTuple_Resize(PyObject **, Py_ssize_t);
-PyAPI_FUNC(void) _PyTuple_MaybeUntrack(PyObject *);
-
-/* Macros trading safety for speed */
-
-/* Cast argument to PyTupleObject* type. */
-#define _PyTuple_CAST(op) (assert(PyTuple_Check(op)), (PyTupleObject *)(op))
-
-#define PyTuple_GET_SIZE(op) Py_SIZE(_PyTuple_CAST(op))
-
-#define PyTuple_GET_ITEM(op, i) (_PyTuple_CAST(op)->ob_item[i])
-
-/* Macro, *only* to be used to fill in brand new tuples */
-#define PyTuple_SET_ITEM(op, i, v) ((void)(_PyTuple_CAST(op)->ob_item[i] = v))
-
-PyAPI_FUNC(void) _PyTuple_DebugMallocStats(FILE *out);
diff --git a/include/python3.10/cpython/unicodeobject.h b/include/python3.10/cpython/unicodeobject.h
deleted file mode 100644
index 0761f01..0000000
--- a/include/python3.10/cpython/unicodeobject.h
+++ /dev/null
@@ -1,1169 +0,0 @@
-#ifndef Py_CPYTHON_UNICODEOBJECT_H
-# error "this header file must not be included directly"
-#endif
-
-/* Py_UNICODE was the native Unicode storage format (code unit) used by
- Python and represents a single Unicode element in the Unicode type.
- With PEP 393, Py_UNICODE is deprecated and replaced with a
- typedef to wchar_t. */
-#define PY_UNICODE_TYPE wchar_t
-/* Py_DEPRECATED(3.3) */ typedef wchar_t Py_UNICODE;
-
-/* --- Internal Unicode Operations ---------------------------------------- */
-
-#ifndef USE_UNICODE_WCHAR_CACHE
-# define USE_UNICODE_WCHAR_CACHE 1
-#endif /* USE_UNICODE_WCHAR_CACHE */
-
-/* Since splitting on whitespace is an important use case, and
- whitespace in most situations is solely ASCII whitespace, we
- optimize for the common case by using a quick look-up table
- _Py_ascii_whitespace (see below) with an inlined check.
-
- */
-#define Py_UNICODE_ISSPACE(ch) \
- ((Py_UCS4)(ch) < 128U ? _Py_ascii_whitespace[(ch)] : _PyUnicode_IsWhitespace(ch))
-
-#define Py_UNICODE_ISLOWER(ch) _PyUnicode_IsLowercase(ch)
-#define Py_UNICODE_ISUPPER(ch) _PyUnicode_IsUppercase(ch)
-#define Py_UNICODE_ISTITLE(ch) _PyUnicode_IsTitlecase(ch)
-#define Py_UNICODE_ISLINEBREAK(ch) _PyUnicode_IsLinebreak(ch)
-
-#define Py_UNICODE_TOLOWER(ch) _PyUnicode_ToLowercase(ch)
-#define Py_UNICODE_TOUPPER(ch) _PyUnicode_ToUppercase(ch)
-#define Py_UNICODE_TOTITLE(ch) _PyUnicode_ToTitlecase(ch)
-
-#define Py_UNICODE_ISDECIMAL(ch) _PyUnicode_IsDecimalDigit(ch)
-#define Py_UNICODE_ISDIGIT(ch) _PyUnicode_IsDigit(ch)
-#define Py_UNICODE_ISNUMERIC(ch) _PyUnicode_IsNumeric(ch)
-#define Py_UNICODE_ISPRINTABLE(ch) _PyUnicode_IsPrintable(ch)
-
-#define Py_UNICODE_TODECIMAL(ch) _PyUnicode_ToDecimalDigit(ch)
-#define Py_UNICODE_TODIGIT(ch) _PyUnicode_ToDigit(ch)
-#define Py_UNICODE_TONUMERIC(ch) _PyUnicode_ToNumeric(ch)
-
-#define Py_UNICODE_ISALPHA(ch) _PyUnicode_IsAlpha(ch)
-
-#define Py_UNICODE_ISALNUM(ch) \
- (Py_UNICODE_ISALPHA(ch) || \
- Py_UNICODE_ISDECIMAL(ch) || \
- Py_UNICODE_ISDIGIT(ch) || \
- Py_UNICODE_ISNUMERIC(ch))
-
-Py_DEPRECATED(3.3) static inline void
-Py_UNICODE_COPY(Py_UNICODE *target, const Py_UNICODE *source, Py_ssize_t length) {
- memcpy(target, source, (size_t)(length) * sizeof(Py_UNICODE));
-}
-
-Py_DEPRECATED(3.3) static inline void
-Py_UNICODE_FILL(Py_UNICODE *target, Py_UNICODE value, Py_ssize_t length) {
- Py_ssize_t i;
- for (i = 0; i < length; i++) {
- target[i] = value;
- }
-}
-
-/* macros to work with surrogates */
-#define Py_UNICODE_IS_SURROGATE(ch) (0xD800 <= (ch) && (ch) <= 0xDFFF)
-#define Py_UNICODE_IS_HIGH_SURROGATE(ch) (0xD800 <= (ch) && (ch) <= 0xDBFF)
-#define Py_UNICODE_IS_LOW_SURROGATE(ch) (0xDC00 <= (ch) && (ch) <= 0xDFFF)
-/* Join two surrogate characters and return a single Py_UCS4 value. */
-#define Py_UNICODE_JOIN_SURROGATES(high, low) \
- (((((Py_UCS4)(high) & 0x03FF) << 10) | \
- ((Py_UCS4)(low) & 0x03FF)) + 0x10000)
-/* high surrogate = top 10 bits added to D800 */
-#define Py_UNICODE_HIGH_SURROGATE(ch) (0xD800 - (0x10000 >> 10) + ((ch) >> 10))
-/* low surrogate = bottom 10 bits added to DC00 */
-#define Py_UNICODE_LOW_SURROGATE(ch) (0xDC00 + ((ch) & 0x3FF))
-
-/* --- Unicode Type ------------------------------------------------------- */
-
-/* ASCII-only strings created through PyUnicode_New use the PyASCIIObject
- structure. state.ascii and state.compact are set, and the data
- immediately follow the structure. utf8_length and wstr_length can be found
- in the length field; the utf8 pointer is equal to the data pointer. */
-typedef struct {
- /* There are 4 forms of Unicode strings:
-
- - compact ascii:
-
- * structure = PyASCIIObject
- * test: PyUnicode_IS_COMPACT_ASCII(op)
- * kind = PyUnicode_1BYTE_KIND
- * compact = 1
- * ascii = 1
- * ready = 1
- * (length is the length of the utf8 and wstr strings)
- * (data starts just after the structure)
- * (since ASCII is decoded from UTF-8, the utf8 string are the data)
-
- - compact:
-
- * structure = PyCompactUnicodeObject
- * test: PyUnicode_IS_COMPACT(op) && !PyUnicode_IS_ASCII(op)
- * kind = PyUnicode_1BYTE_KIND, PyUnicode_2BYTE_KIND or
- PyUnicode_4BYTE_KIND
- * compact = 1
- * ready = 1
- * ascii = 0
- * utf8 is not shared with data
- * utf8_length = 0 if utf8 is NULL
- * wstr is shared with data and wstr_length=length
- if kind=PyUnicode_2BYTE_KIND and sizeof(wchar_t)=2
- or if kind=PyUnicode_4BYTE_KIND and sizeof(wchar_t)=4
- * wstr_length = 0 if wstr is NULL
- * (data starts just after the structure)
-
- - legacy string, not ready:
-
- * structure = PyUnicodeObject
- * test: kind == PyUnicode_WCHAR_KIND
- * length = 0 (use wstr_length)
- * hash = -1
- * kind = PyUnicode_WCHAR_KIND
- * compact = 0
- * ascii = 0
- * ready = 0
- * interned = SSTATE_NOT_INTERNED
- * wstr is not NULL
- * data.any is NULL
- * utf8 is NULL
- * utf8_length = 0
-
- - legacy string, ready:
-
- * structure = PyUnicodeObject structure
- * test: !PyUnicode_IS_COMPACT(op) && kind != PyUnicode_WCHAR_KIND
- * kind = PyUnicode_1BYTE_KIND, PyUnicode_2BYTE_KIND or
- PyUnicode_4BYTE_KIND
- * compact = 0
- * ready = 1
- * data.any is not NULL
- * utf8 is shared and utf8_length = length with data.any if ascii = 1
- * utf8_length = 0 if utf8 is NULL
- * wstr is shared with data.any and wstr_length = length
- if kind=PyUnicode_2BYTE_KIND and sizeof(wchar_t)=2
- or if kind=PyUnicode_4BYTE_KIND and sizeof(wchar_4)=4
- * wstr_length = 0 if wstr is NULL
-
- Compact strings use only one memory block (structure + characters),
- whereas legacy strings use one block for the structure and one block
- for characters.
-
- Legacy strings are created by PyUnicode_FromUnicode() and
- PyUnicode_FromStringAndSize(NULL, size) functions. They become ready
- when PyUnicode_READY() is called.
-
- See also _PyUnicode_CheckConsistency().
- */
- PyObject_HEAD
- Py_ssize_t length; /* Number of code points in the string */
- Py_hash_t hash; /* Hash value; -1 if not set */
- struct {
- /*
- SSTATE_NOT_INTERNED (0)
- SSTATE_INTERNED_MORTAL (1)
- SSTATE_INTERNED_IMMORTAL (2)
-
- If interned != SSTATE_NOT_INTERNED, the two references from the
- dictionary to this object are *not* counted in ob_refcnt.
- */
- unsigned int interned:2;
- /* Character size:
-
- - PyUnicode_WCHAR_KIND (0):
-
- * character type = wchar_t (16 or 32 bits, depending on the
- platform)
-
- - PyUnicode_1BYTE_KIND (1):
-
- * character type = Py_UCS1 (8 bits, unsigned)
- * all characters are in the range U+0000-U+00FF (latin1)
- * if ascii is set, all characters are in the range U+0000-U+007F
- (ASCII), otherwise at least one character is in the range
- U+0080-U+00FF
-
- - PyUnicode_2BYTE_KIND (2):
-
- * character type = Py_UCS2 (16 bits, unsigned)
- * all characters are in the range U+0000-U+FFFF (BMP)
- * at least one character is in the range U+0100-U+FFFF
-
- - PyUnicode_4BYTE_KIND (4):
-
- * character type = Py_UCS4 (32 bits, unsigned)
- * all characters are in the range U+0000-U+10FFFF
- * at least one character is in the range U+10000-U+10FFFF
- */
- unsigned int kind:3;
- /* Compact is with respect to the allocation scheme. Compact unicode
- objects only require one memory block while non-compact objects use
- one block for the PyUnicodeObject struct and another for its data
- buffer. */
- unsigned int compact:1;
- /* The string only contains characters in the range U+0000-U+007F (ASCII)
- and the kind is PyUnicode_1BYTE_KIND. If ascii is set and compact is
- set, use the PyASCIIObject structure. */
- unsigned int ascii:1;
- /* The ready flag indicates whether the object layout is initialized
- completely. This means that this is either a compact object, or
- the data pointer is filled out. The bit is redundant, and helps
- to minimize the test in PyUnicode_IS_READY(). */
- unsigned int ready:1;
- /* Padding to ensure that PyUnicode_DATA() is always aligned to
- 4 bytes (see issue #19537 on m68k). */
- unsigned int :24;
- } state;
- wchar_t *wstr; /* wchar_t representation (null-terminated) */
-} PyASCIIObject;
-
-/* Non-ASCII strings allocated through PyUnicode_New use the
- PyCompactUnicodeObject structure. state.compact is set, and the data
- immediately follow the structure. */
-typedef struct {
- PyASCIIObject _base;
- Py_ssize_t utf8_length; /* Number of bytes in utf8, excluding the
- * terminating \0. */
- char *utf8; /* UTF-8 representation (null-terminated) */
- Py_ssize_t wstr_length; /* Number of code points in wstr, possible
- * surrogates count as two code points. */
-} PyCompactUnicodeObject;
-
-/* Strings allocated through PyUnicode_FromUnicode(NULL, len) use the
- PyUnicodeObject structure. The actual string data is initially in the wstr
- block, and copied into the data block using _PyUnicode_Ready. */
-typedef struct {
- PyCompactUnicodeObject _base;
- union {
- void *any;
- Py_UCS1 *latin1;
- Py_UCS2 *ucs2;
- Py_UCS4 *ucs4;
- } data; /* Canonical, smallest-form Unicode buffer */
-} PyUnicodeObject;
-
-PyAPI_FUNC(int) _PyUnicode_CheckConsistency(
- PyObject *op,
- int check_content);
-
-/* Fast access macros */
-
-/* Returns the deprecated Py_UNICODE representation's size in code units
- (this includes surrogate pairs as 2 units).
- If the Py_UNICODE representation is not available, it will be computed
- on request. Use PyUnicode_GET_LENGTH() for the length in code points. */
-
-/* Py_DEPRECATED(3.3) */
-#define PyUnicode_GET_SIZE(op) \
- (assert(PyUnicode_Check(op)), \
- (((PyASCIIObject *)(op))->wstr) ? \
- PyUnicode_WSTR_LENGTH(op) : \
- ((void)PyUnicode_AsUnicode(_PyObject_CAST(op)),\
- assert(((PyASCIIObject *)(op))->wstr), \
- PyUnicode_WSTR_LENGTH(op)))
-
-/* Py_DEPRECATED(3.3) */
-#define PyUnicode_GET_DATA_SIZE(op) \
- (PyUnicode_GET_SIZE(op) * Py_UNICODE_SIZE)
-
-/* Alias for PyUnicode_AsUnicode(). This will create a wchar_t/Py_UNICODE
- representation on demand. Using this macro is very inefficient now,
- try to port your code to use the new PyUnicode_*BYTE_DATA() macros or
- use PyUnicode_WRITE() and PyUnicode_READ(). */
-
-/* Py_DEPRECATED(3.3) */
-#define PyUnicode_AS_UNICODE(op) \
- (assert(PyUnicode_Check(op)), \
- (((PyASCIIObject *)(op))->wstr) ? (((PyASCIIObject *)(op))->wstr) : \
- PyUnicode_AsUnicode(_PyObject_CAST(op)))
-
-/* Py_DEPRECATED(3.3) */
-#define PyUnicode_AS_DATA(op) \
- ((const char *)(PyUnicode_AS_UNICODE(op)))
-
-
-/* --- Flexible String Representation Helper Macros (PEP 393) -------------- */
-
-/* Values for PyASCIIObject.state: */
-
-/* Interning state. */
-#define SSTATE_NOT_INTERNED 0
-#define SSTATE_INTERNED_MORTAL 1
-#define SSTATE_INTERNED_IMMORTAL 2
-
-/* Return true if the string contains only ASCII characters, or 0 if not. The
- string may be compact (PyUnicode_IS_COMPACT_ASCII) or not, but must be
- ready. */
-#define PyUnicode_IS_ASCII(op) \
- (assert(PyUnicode_Check(op)), \
- assert(PyUnicode_IS_READY(op)), \
- ((PyASCIIObject*)op)->state.ascii)
-
-/* Return true if the string is compact or 0 if not.
- No type checks or Ready calls are performed. */
-#define PyUnicode_IS_COMPACT(op) \
- (((PyASCIIObject*)(op))->state.compact)
-
-/* Return true if the string is a compact ASCII string (use PyASCIIObject
- structure), or 0 if not. No type checks or Ready calls are performed. */
-#define PyUnicode_IS_COMPACT_ASCII(op) \
- (((PyASCIIObject*)op)->state.ascii && PyUnicode_IS_COMPACT(op))
-
-enum PyUnicode_Kind {
-/* String contains only wstr byte characters. This is only possible
- when the string was created with a legacy API and _PyUnicode_Ready()
- has not been called yet. */
- PyUnicode_WCHAR_KIND = 0,
-/* Return values of the PyUnicode_KIND() macro: */
- PyUnicode_1BYTE_KIND = 1,
- PyUnicode_2BYTE_KIND = 2,
- PyUnicode_4BYTE_KIND = 4
-};
-
-/* Return pointers to the canonical representation cast to unsigned char,
- Py_UCS2, or Py_UCS4 for direct character access.
- No checks are performed, use PyUnicode_KIND() before to ensure
- these will work correctly. */
-
-#define PyUnicode_1BYTE_DATA(op) ((Py_UCS1*)PyUnicode_DATA(op))
-#define PyUnicode_2BYTE_DATA(op) ((Py_UCS2*)PyUnicode_DATA(op))
-#define PyUnicode_4BYTE_DATA(op) ((Py_UCS4*)PyUnicode_DATA(op))
-
-/* Return one of the PyUnicode_*_KIND values defined above. */
-#define PyUnicode_KIND(op) \
- (assert(PyUnicode_Check(op)), \
- assert(PyUnicode_IS_READY(op)), \
- ((PyASCIIObject *)(op))->state.kind)
-
-/* Return a void pointer to the raw unicode buffer. */
-#define _PyUnicode_COMPACT_DATA(op) \
- (PyUnicode_IS_ASCII(op) ? \
- ((void*)((PyASCIIObject*)(op) + 1)) : \
- ((void*)((PyCompactUnicodeObject*)(op) + 1)))
-
-#define _PyUnicode_NONCOMPACT_DATA(op) \
- (assert(((PyUnicodeObject*)(op))->data.any), \
- ((((PyUnicodeObject *)(op))->data.any)))
-
-#define PyUnicode_DATA(op) \
- (assert(PyUnicode_Check(op)), \
- PyUnicode_IS_COMPACT(op) ? _PyUnicode_COMPACT_DATA(op) : \
- _PyUnicode_NONCOMPACT_DATA(op))
-
-/* In the access macros below, "kind" may be evaluated more than once.
- All other macro parameters are evaluated exactly once, so it is safe
- to put side effects into them (such as increasing the index). */
-
-/* Write into the canonical representation, this macro does not do any sanity
- checks and is intended for usage in loops. The caller should cache the
- kind and data pointers obtained from other macro calls.
- index is the index in the string (starts at 0) and value is the new
- code point value which should be written to that location. */
-#define PyUnicode_WRITE(kind, data, index, value) \
- do { \
- switch ((kind)) { \
- case PyUnicode_1BYTE_KIND: { \
- ((Py_UCS1 *)(data))[(index)] = (Py_UCS1)(value); \
- break; \
- } \
- case PyUnicode_2BYTE_KIND: { \
- ((Py_UCS2 *)(data))[(index)] = (Py_UCS2)(value); \
- break; \
- } \
- default: { \
- assert((kind) == PyUnicode_4BYTE_KIND); \
- ((Py_UCS4 *)(data))[(index)] = (Py_UCS4)(value); \
- } \
- } \
- } while (0)
-
-/* Read a code point from the string's canonical representation. No checks
- or ready calls are performed. */
-#define PyUnicode_READ(kind, data, index) \
- ((Py_UCS4) \
- ((kind) == PyUnicode_1BYTE_KIND ? \
- ((const Py_UCS1 *)(data))[(index)] : \
- ((kind) == PyUnicode_2BYTE_KIND ? \
- ((const Py_UCS2 *)(data))[(index)] : \
- ((const Py_UCS4 *)(data))[(index)] \
- ) \
- ))
-
-/* PyUnicode_READ_CHAR() is less efficient than PyUnicode_READ() because it
- calls PyUnicode_KIND() and might call it twice. For single reads, use
- PyUnicode_READ_CHAR, for multiple consecutive reads callers should
- cache kind and use PyUnicode_READ instead. */
-#define PyUnicode_READ_CHAR(unicode, index) \
- (assert(PyUnicode_Check(unicode)), \
- assert(PyUnicode_IS_READY(unicode)), \
- (Py_UCS4) \
- (PyUnicode_KIND((unicode)) == PyUnicode_1BYTE_KIND ? \
- ((const Py_UCS1 *)(PyUnicode_DATA((unicode))))[(index)] : \
- (PyUnicode_KIND((unicode)) == PyUnicode_2BYTE_KIND ? \
- ((const Py_UCS2 *)(PyUnicode_DATA((unicode))))[(index)] : \
- ((const Py_UCS4 *)(PyUnicode_DATA((unicode))))[(index)] \
- ) \
- ))
-
-/* Returns the length of the unicode string. The caller has to make sure that
- the string has it's canonical representation set before calling
- this macro. Call PyUnicode_(FAST_)Ready to ensure that. */
-#define PyUnicode_GET_LENGTH(op) \
- (assert(PyUnicode_Check(op)), \
- assert(PyUnicode_IS_READY(op)), \
- ((PyASCIIObject *)(op))->length)
-
-
-/* Fast check to determine whether an object is ready. Equivalent to
- PyUnicode_IS_COMPACT(op) || ((PyUnicodeObject*)(op))->data.any */
-
-#define PyUnicode_IS_READY(op) (((PyASCIIObject*)op)->state.ready)
-
-/* PyUnicode_READY() does less work than _PyUnicode_Ready() in the best
- case. If the canonical representation is not yet set, it will still call
- _PyUnicode_Ready().
- Returns 0 on success and -1 on errors. */
-#define PyUnicode_READY(op) \
- (assert(PyUnicode_Check(op)), \
- (PyUnicode_IS_READY(op) ? \
- 0 : _PyUnicode_Ready(_PyObject_CAST(op))))
-
-/* Return a maximum character value which is suitable for creating another
- string based on op. This is always an approximation but more efficient
- than iterating over the string. */
-#define PyUnicode_MAX_CHAR_VALUE(op) \
- (assert(PyUnicode_IS_READY(op)), \
- (PyUnicode_IS_ASCII(op) ? \
- (0x7f) : \
- (PyUnicode_KIND(op) == PyUnicode_1BYTE_KIND ? \
- (0xffU) : \
- (PyUnicode_KIND(op) == PyUnicode_2BYTE_KIND ? \
- (0xffffU) : \
- (0x10ffffU)))))
-
-Py_DEPRECATED(3.3)
-static inline Py_ssize_t _PyUnicode_get_wstr_length(PyObject *op) {
- return PyUnicode_IS_COMPACT_ASCII(op) ?
- ((PyASCIIObject*)op)->length :
- ((PyCompactUnicodeObject*)op)->wstr_length;
-}
-#define PyUnicode_WSTR_LENGTH(op) _PyUnicode_get_wstr_length((PyObject*)op)
-
-/* === Public API ========================================================= */
-
-/* --- Plain Py_UNICODE --------------------------------------------------- */
-
-/* With PEP 393, this is the recommended way to allocate a new unicode object.
- This function will allocate the object and its buffer in a single memory
- block. Objects created using this function are not resizable. */
-PyAPI_FUNC(PyObject*) PyUnicode_New(
- Py_ssize_t size, /* Number of code points in the new string */
- Py_UCS4 maxchar /* maximum code point value in the string */
- );
-
-/* Initializes the canonical string representation from the deprecated
- wstr/Py_UNICODE representation. This function is used to convert Unicode
- objects which were created using the old API to the new flexible format
- introduced with PEP 393.
-
- Don't call this function directly, use the public PyUnicode_READY() macro
- instead. */
-PyAPI_FUNC(int) _PyUnicode_Ready(
- PyObject *unicode /* Unicode object */
- );
-
-/* Get a copy of a Unicode string. */
-PyAPI_FUNC(PyObject*) _PyUnicode_Copy(
- PyObject *unicode
- );
-
-/* Copy character from one unicode object into another, this function performs
- character conversion when necessary and falls back to memcpy() if possible.
-
- Fail if to is too small (smaller than *how_many* or smaller than
- len(from)-from_start), or if kind(from[from_start:from_start+how_many]) >
- kind(to), or if *to* has more than 1 reference.
-
- Return the number of written character, or return -1 and raise an exception
- on error.
-
- Pseudo-code:
-
- how_many = min(how_many, len(from) - from_start)
- to[to_start:to_start+how_many] = from[from_start:from_start+how_many]
- return how_many
-
- Note: The function doesn't write a terminating null character.
- */
-PyAPI_FUNC(Py_ssize_t) PyUnicode_CopyCharacters(
- PyObject *to,
- Py_ssize_t to_start,
- PyObject *from,
- Py_ssize_t from_start,
- Py_ssize_t how_many
- );
-
-/* Unsafe version of PyUnicode_CopyCharacters(): don't check arguments and so
- may crash if parameters are invalid (e.g. if the output string
- is too short). */
-PyAPI_FUNC(void) _PyUnicode_FastCopyCharacters(
- PyObject *to,
- Py_ssize_t to_start,
- PyObject *from,
- Py_ssize_t from_start,
- Py_ssize_t how_many
- );
-
-/* Fill a string with a character: write fill_char into
- unicode[start:start+length].
-
- Fail if fill_char is bigger than the string maximum character, or if the
- string has more than 1 reference.
-
- Return the number of written character, or return -1 and raise an exception
- on error. */
-PyAPI_FUNC(Py_ssize_t) PyUnicode_Fill(
- PyObject *unicode,
- Py_ssize_t start,
- Py_ssize_t length,
- Py_UCS4 fill_char
- );
-
-/* Unsafe version of PyUnicode_Fill(): don't check arguments and so may crash
- if parameters are invalid (e.g. if length is longer than the string). */
-PyAPI_FUNC(void) _PyUnicode_FastFill(
- PyObject *unicode,
- Py_ssize_t start,
- Py_ssize_t length,
- Py_UCS4 fill_char
- );
-
-/* Create a Unicode Object from the Py_UNICODE buffer u of the given
- size.
-
- u may be NULL which causes the contents to be undefined. It is the
- user's responsibility to fill in the needed data afterwards. Note
- that modifying the Unicode object contents after construction is
- only allowed if u was set to NULL.
-
- The buffer is copied into the new object. */
-Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_FromUnicode(
- const Py_UNICODE *u, /* Unicode buffer */
- Py_ssize_t size /* size of buffer */
- );
-
-/* Create a new string from a buffer of Py_UCS1, Py_UCS2 or Py_UCS4 characters.
- Scan the string to find the maximum character. */
-PyAPI_FUNC(PyObject*) PyUnicode_FromKindAndData(
- int kind,
- const void *buffer,
- Py_ssize_t size);
-
-/* Create a new string from a buffer of ASCII characters.
- WARNING: Don't check if the string contains any non-ASCII character. */
-PyAPI_FUNC(PyObject*) _PyUnicode_FromASCII(
- const char *buffer,
- Py_ssize_t size);
-
-/* Compute the maximum character of the substring unicode[start:end].
- Return 127 for an empty string. */
-PyAPI_FUNC(Py_UCS4) _PyUnicode_FindMaxChar (
- PyObject *unicode,
- Py_ssize_t start,
- Py_ssize_t end);
-
-/* Return a read-only pointer to the Unicode object's internal
- Py_UNICODE buffer.
- If the wchar_t/Py_UNICODE representation is not yet available, this
- function will calculate it. */
-Py_DEPRECATED(3.3) PyAPI_FUNC(Py_UNICODE *) PyUnicode_AsUnicode(
- PyObject *unicode /* Unicode object */
- );
-
-/* Similar to PyUnicode_AsUnicode(), but raises a ValueError if the string
- contains null characters. */
-PyAPI_FUNC(const Py_UNICODE *) _PyUnicode_AsUnicode(
- PyObject *unicode /* Unicode object */
- );
-
-/* Return a read-only pointer to the Unicode object's internal
- Py_UNICODE buffer and save the length at size.
- If the wchar_t/Py_UNICODE representation is not yet available, this
- function will calculate it. */
-
-Py_DEPRECATED(3.3) PyAPI_FUNC(Py_UNICODE *) PyUnicode_AsUnicodeAndSize(
- PyObject *unicode, /* Unicode object */
- Py_ssize_t *size /* location where to save the length */
- );
-
-
-/* --- _PyUnicodeWriter API ----------------------------------------------- */
-
-typedef struct {
- PyObject *buffer;
- void *data;
- enum PyUnicode_Kind kind;
- Py_UCS4 maxchar;
- Py_ssize_t size;
- Py_ssize_t pos;
-
- /* minimum number of allocated characters (default: 0) */
- Py_ssize_t min_length;
-
- /* minimum character (default: 127, ASCII) */
- Py_UCS4 min_char;
-
- /* If non-zero, overallocate the buffer (default: 0). */
- unsigned char overallocate;
-
- /* If readonly is 1, buffer is a shared string (cannot be modified)
- and size is set to 0. */
- unsigned char readonly;
-} _PyUnicodeWriter ;
-
-/* Initialize a Unicode writer.
- *
- * By default, the minimum buffer size is 0 character and overallocation is
- * disabled. Set min_length, min_char and overallocate attributes to control
- * the allocation of the buffer. */
-PyAPI_FUNC(void)
-_PyUnicodeWriter_Init(_PyUnicodeWriter *writer);
-
-/* Prepare the buffer to write 'length' characters
- with the specified maximum character.
-
- Return 0 on success, raise an exception and return -1 on error. */
-#define _PyUnicodeWriter_Prepare(WRITER, LENGTH, MAXCHAR) \
- (((MAXCHAR) <= (WRITER)->maxchar \
- && (LENGTH) <= (WRITER)->size - (WRITER)->pos) \
- ? 0 \
- : (((LENGTH) == 0) \
- ? 0 \
- : _PyUnicodeWriter_PrepareInternal((WRITER), (LENGTH), (MAXCHAR))))
-
-/* Don't call this function directly, use the _PyUnicodeWriter_Prepare() macro
- instead. */
-PyAPI_FUNC(int)
-_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
- Py_ssize_t length, Py_UCS4 maxchar);
-
-/* Prepare the buffer to have at least the kind KIND.
- For example, kind=PyUnicode_2BYTE_KIND ensures that the writer will
- support characters in range U+000-U+FFFF.
-
- Return 0 on success, raise an exception and return -1 on error. */
-#define _PyUnicodeWriter_PrepareKind(WRITER, KIND) \
- (assert((KIND) != PyUnicode_WCHAR_KIND), \
- (KIND) <= (WRITER)->kind \
- ? 0 \
- : _PyUnicodeWriter_PrepareKindInternal((WRITER), (KIND)))
-
-/* Don't call this function directly, use the _PyUnicodeWriter_PrepareKind()
- macro instead. */
-PyAPI_FUNC(int)
-_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
- enum PyUnicode_Kind kind);
-
-/* Append a Unicode character.
- Return 0 on success, raise an exception and return -1 on error. */
-PyAPI_FUNC(int)
-_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer,
- Py_UCS4 ch
- );
-
-/* Append a Unicode string.
- Return 0 on success, raise an exception and return -1 on error. */
-PyAPI_FUNC(int)
-_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer,
- PyObject *str /* Unicode string */
- );
-
-/* Append a substring of a Unicode string.
- Return 0 on success, raise an exception and return -1 on error. */
-PyAPI_FUNC(int)
-_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer,
- PyObject *str, /* Unicode string */
- Py_ssize_t start,
- Py_ssize_t end
- );
-
-/* Append an ASCII-encoded byte string.
- Return 0 on success, raise an exception and return -1 on error. */
-PyAPI_FUNC(int)
-_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
- const char *str, /* ASCII-encoded byte string */
- Py_ssize_t len /* number of bytes, or -1 if unknown */
- );
-
-/* Append a latin1-encoded byte string.
- Return 0 on success, raise an exception and return -1 on error. */
-PyAPI_FUNC(int)
-_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
- const char *str, /* latin1-encoded byte string */
- Py_ssize_t len /* length in bytes */
- );
-
-/* Get the value of the writer as a Unicode string. Clear the
- buffer of the writer. Raise an exception and return NULL
- on error. */
-PyAPI_FUNC(PyObject *)
-_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer);
-
-/* Deallocate memory of a writer (clear its internal buffer). */
-PyAPI_FUNC(void)
-_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer);
-
-
-/* Format the object based on the format_spec, as defined in PEP 3101
- (Advanced String Formatting). */
-PyAPI_FUNC(int) _PyUnicode_FormatAdvancedWriter(
- _PyUnicodeWriter *writer,
- PyObject *obj,
- PyObject *format_spec,
- Py_ssize_t start,
- Py_ssize_t end);
-
-/* --- Manage the default encoding ---------------------------------------- */
-
-/* Returns a pointer to the default encoding (UTF-8) of the
- Unicode object unicode.
-
- Like PyUnicode_AsUTF8AndSize(), this also caches the UTF-8 representation
- in the unicodeobject.
-
- _PyUnicode_AsString is a #define for PyUnicode_AsUTF8 to
- support the previous internal function with the same behaviour.
-
- Use of this API is DEPRECATED since no size information can be
- extracted from the returned data.
-*/
-
-PyAPI_FUNC(const char *) PyUnicode_AsUTF8(PyObject *unicode);
-
-#define _PyUnicode_AsString PyUnicode_AsUTF8
-
-/* --- Generic Codecs ----------------------------------------------------- */
-
-/* Encodes a Py_UNICODE buffer of the given size and returns a
- Python string object. */
-Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_Encode(
- const Py_UNICODE *s, /* Unicode char buffer */
- Py_ssize_t size, /* number of Py_UNICODE chars to encode */
- const char *encoding, /* encoding */
- const char *errors /* error handling */
- );
-
-/* --- UTF-7 Codecs ------------------------------------------------------- */
-
-Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF7(
- const Py_UNICODE *data, /* Unicode char buffer */
- Py_ssize_t length, /* number of Py_UNICODE chars to encode */
- int base64SetO, /* Encode RFC2152 Set O characters in base64 */
- int base64WhiteSpace, /* Encode whitespace (sp, ht, nl, cr) in base64 */
- const char *errors /* error handling */
- );
-
-PyAPI_FUNC(PyObject*) _PyUnicode_EncodeUTF7(
- PyObject *unicode, /* Unicode object */
- int base64SetO, /* Encode RFC2152 Set O characters in base64 */
- int base64WhiteSpace, /* Encode whitespace (sp, ht, nl, cr) in base64 */
- const char *errors /* error handling */
- );
-
-/* --- UTF-8 Codecs ------------------------------------------------------- */
-
-PyAPI_FUNC(PyObject*) _PyUnicode_AsUTF8String(
- PyObject *unicode,
- const char *errors);
-
-Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF8(
- const Py_UNICODE *data, /* Unicode char buffer */
- Py_ssize_t length, /* number of Py_UNICODE chars to encode */
- const char *errors /* error handling */
- );
-
-/* --- UTF-32 Codecs ------------------------------------------------------ */
-
-Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF32(
- const Py_UNICODE *data, /* Unicode char buffer */
- Py_ssize_t length, /* number of Py_UNICODE chars to encode */
- const char *errors, /* error handling */
- int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */
- );
-
-PyAPI_FUNC(PyObject*) _PyUnicode_EncodeUTF32(
- PyObject *object, /* Unicode object */
- const char *errors, /* error handling */
- int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */
- );
-
-/* --- UTF-16 Codecs ------------------------------------------------------ */
-
-/* Returns a Python string object holding the UTF-16 encoded value of
- the Unicode data.
-
- If byteorder is not 0, output is written according to the following
- byte order:
-
- byteorder == -1: little endian
- byteorder == 0: native byte order (writes a BOM mark)
- byteorder == 1: big endian
-
- If byteorder is 0, the output string will always start with the
- Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is
- prepended.
-
- Note that Py_UNICODE data is being interpreted as UTF-16 reduced to
- UCS-2. This trick makes it possible to add full UTF-16 capabilities
- at a later point without compromising the APIs.
-
-*/
-Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF16(
- const Py_UNICODE *data, /* Unicode char buffer */
- Py_ssize_t length, /* number of Py_UNICODE chars to encode */
- const char *errors, /* error handling */
- int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */
- );
-
-PyAPI_FUNC(PyObject*) _PyUnicode_EncodeUTF16(
- PyObject* unicode, /* Unicode object */
- const char *errors, /* error handling */
- int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */
- );
-
-/* --- Unicode-Escape Codecs ---------------------------------------------- */
-
-/* Variant of PyUnicode_DecodeUnicodeEscape that supports partial decoding. */
-PyAPI_FUNC(PyObject*) _PyUnicode_DecodeUnicodeEscapeStateful(
- const char *string, /* Unicode-Escape encoded string */
- Py_ssize_t length, /* size of string */
- const char *errors, /* error handling */
- Py_ssize_t *consumed /* bytes consumed */
-);
-
-/* Helper for PyUnicode_DecodeUnicodeEscape that detects invalid escape
- chars. */
-PyAPI_FUNC(PyObject*) _PyUnicode_DecodeUnicodeEscapeInternal(
- const char *string, /* Unicode-Escape encoded string */
- Py_ssize_t length, /* size of string */
- const char *errors, /* error handling */
- Py_ssize_t *consumed, /* bytes consumed */
- const char **first_invalid_escape /* on return, points to first
- invalid escaped char in
- string. */
-);
-
-Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_EncodeUnicodeEscape(
- const Py_UNICODE *data, /* Unicode char buffer */
- Py_ssize_t length /* Number of Py_UNICODE chars to encode */
- );
-
-/* --- Raw-Unicode-Escape Codecs ------------------------------------------ */
-
-Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_EncodeRawUnicodeEscape(
- const Py_UNICODE *data, /* Unicode char buffer */
- Py_ssize_t length /* Number of Py_UNICODE chars to encode */
- );
-
-/* Variant of PyUnicode_DecodeRawUnicodeEscape that supports partial decoding. */
-PyAPI_FUNC(PyObject*) _PyUnicode_DecodeRawUnicodeEscapeStateful(
- const char *string, /* Unicode-Escape encoded string */
- Py_ssize_t length, /* size of string */
- const char *errors, /* error handling */
- Py_ssize_t *consumed /* bytes consumed */
-);
-
-/* --- Latin-1 Codecs ----------------------------------------------------- */
-
-PyAPI_FUNC(PyObject*) _PyUnicode_AsLatin1String(
- PyObject* unicode,
- const char* errors);
-
-Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_EncodeLatin1(
- const Py_UNICODE *data, /* Unicode char buffer */
- Py_ssize_t length, /* Number of Py_UNICODE chars to encode */
- const char *errors /* error handling */
- );
-
-/* --- ASCII Codecs ------------------------------------------------------- */
-
-PyAPI_FUNC(PyObject*) _PyUnicode_AsASCIIString(
- PyObject* unicode,
- const char* errors);
-
-Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_EncodeASCII(
- const Py_UNICODE *data, /* Unicode char buffer */
- Py_ssize_t length, /* Number of Py_UNICODE chars to encode */
- const char *errors /* error handling */
- );
-
-/* --- Character Map Codecs ----------------------------------------------- */
-
-Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_EncodeCharmap(
- const Py_UNICODE *data, /* Unicode char buffer */
- Py_ssize_t length, /* Number of Py_UNICODE chars to encode */
- PyObject *mapping, /* encoding mapping */
- const char *errors /* error handling */
- );
-
-PyAPI_FUNC(PyObject*) _PyUnicode_EncodeCharmap(
- PyObject *unicode, /* Unicode object */
- PyObject *mapping, /* encoding mapping */
- const char *errors /* error handling */
- );
-
-/* Translate a Py_UNICODE buffer of the given length by applying a
- character mapping table to it and return the resulting Unicode
- object.
-
- The mapping table must map Unicode ordinal integers to Unicode strings,
- Unicode ordinal integers or None (causing deletion of the character).
-
- Mapping tables may be dictionaries or sequences. Unmapped character
- ordinals (ones which cause a LookupError) are left untouched and
- are copied as-is.
-
-*/
-Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject *) PyUnicode_TranslateCharmap(
- const Py_UNICODE *data, /* Unicode char buffer */
- Py_ssize_t length, /* Number of Py_UNICODE chars to encode */
- PyObject *table, /* Translate table */
- const char *errors /* error handling */
- );
-
-/* --- MBCS codecs for Windows -------------------------------------------- */
-
-#ifdef MS_WINDOWS
-Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_EncodeMBCS(
- const Py_UNICODE *data, /* Unicode char buffer */
- Py_ssize_t length, /* number of Py_UNICODE chars to encode */
- const char *errors /* error handling */
- );
-#endif
-
-/* --- Decimal Encoder ---------------------------------------------------- */
-
-/* Takes a Unicode string holding a decimal value and writes it into
- an output buffer using standard ASCII digit codes.
-
- The output buffer has to provide at least length+1 bytes of storage
- area. The output string is 0-terminated.
-
- The encoder converts whitespace to ' ', decimal characters to their
- corresponding ASCII digit and all other Latin-1 characters except
- \0 as-is. Characters outside this range (Unicode ordinals 1-256)
- are treated as errors. This includes embedded NULL bytes.
-
- Error handling is defined by the errors argument:
-
- NULL or "strict": raise a ValueError
- "ignore": ignore the wrong characters (these are not copied to the
- output buffer)
- "replace": replaces illegal characters with '?'
-
- Returns 0 on success, -1 on failure.
-
-*/
-
-Py_DEPRECATED(3.3) PyAPI_FUNC(int) PyUnicode_EncodeDecimal(
- Py_UNICODE *s, /* Unicode buffer */
- Py_ssize_t length, /* Number of Py_UNICODE chars to encode */
- char *output, /* Output buffer; must have size >= length */
- const char *errors /* error handling */
- );
-
-/* Transforms code points that have decimal digit property to the
- corresponding ASCII digit code points.
-
- Returns a new Unicode string on success, NULL on failure.
-*/
-
-Py_DEPRECATED(3.3)
-PyAPI_FUNC(PyObject*) PyUnicode_TransformDecimalToASCII(
- Py_UNICODE *s, /* Unicode buffer */
- Py_ssize_t length /* Number of Py_UNICODE chars to transform */
- );
-
-/* Coverts a Unicode object holding a decimal value to an ASCII string
- for using in int, float and complex parsers.
- Transforms code points that have decimal digit property to the
- corresponding ASCII digit code points. Transforms spaces to ASCII.
- Transforms code points starting from the first non-ASCII code point that
- is neither a decimal digit nor a space to the end into '?'. */
-
-PyAPI_FUNC(PyObject*) _PyUnicode_TransformDecimalAndSpaceToASCII(
- PyObject *unicode /* Unicode object */
- );
-
-/* --- Methods & Slots ---------------------------------------------------- */
-
-PyAPI_FUNC(PyObject *) _PyUnicode_JoinArray(
- PyObject *separator,
- PyObject *const *items,
- Py_ssize_t seqlen
- );
-
-/* Test whether a unicode is equal to ASCII identifier. Return 1 if true,
- 0 otherwise. The right argument must be ASCII identifier.
- Any error occurs inside will be cleared before return. */
-PyAPI_FUNC(int) _PyUnicode_EqualToASCIIId(
- PyObject *left, /* Left string */
- _Py_Identifier *right /* Right identifier */
- );
-
-/* Test whether a unicode is equal to ASCII string. Return 1 if true,
- 0 otherwise. The right argument must be ASCII-encoded string.
- Any error occurs inside will be cleared before return. */
-PyAPI_FUNC(int) _PyUnicode_EqualToASCIIString(
- PyObject *left,
- const char *right /* ASCII-encoded string */
- );
-
-/* Externally visible for str.strip(unicode) */
-PyAPI_FUNC(PyObject *) _PyUnicode_XStrip(
- PyObject *self,
- int striptype,
- PyObject *sepobj
- );
-
-/* Using explicit passed-in values, insert the thousands grouping
- into the string pointed to by buffer. For the argument descriptions,
- see Objects/stringlib/localeutil.h */
-PyAPI_FUNC(Py_ssize_t) _PyUnicode_InsertThousandsGrouping(
- _PyUnicodeWriter *writer,
- Py_ssize_t n_buffer,
- PyObject *digits,
- Py_ssize_t d_pos,
- Py_ssize_t n_digits,
- Py_ssize_t min_width,
- const char *grouping,
- PyObject *thousands_sep,
- Py_UCS4 *maxchar);
-
-/* === Characters Type APIs =============================================== */
-
-/* Helper array used by Py_UNICODE_ISSPACE(). */
-
-PyAPI_DATA(const unsigned char) _Py_ascii_whitespace[];
-
-/* These should not be used directly. Use the Py_UNICODE_IS* and
- Py_UNICODE_TO* macros instead.
-
- These APIs are implemented in Objects/unicodectype.c.
-
-*/
-
-PyAPI_FUNC(int) _PyUnicode_IsLowercase(
- Py_UCS4 ch /* Unicode character */
- );
-
-PyAPI_FUNC(int) _PyUnicode_IsUppercase(
- Py_UCS4 ch /* Unicode character */
- );
-
-PyAPI_FUNC(int) _PyUnicode_IsTitlecase(
- Py_UCS4 ch /* Unicode character */
- );
-
-PyAPI_FUNC(int) _PyUnicode_IsXidStart(
- Py_UCS4 ch /* Unicode character */
- );
-
-PyAPI_FUNC(int) _PyUnicode_IsXidContinue(
- Py_UCS4 ch /* Unicode character */
- );
-
-PyAPI_FUNC(int) _PyUnicode_IsWhitespace(
- const Py_UCS4 ch /* Unicode character */
- );
-
-PyAPI_FUNC(int) _PyUnicode_IsLinebreak(
- const Py_UCS4 ch /* Unicode character */
- );
-
-/* Py_DEPRECATED(3.3) */ PyAPI_FUNC(Py_UCS4) _PyUnicode_ToLowercase(
- Py_UCS4 ch /* Unicode character */
- );
-
-/* Py_DEPRECATED(3.3) */ PyAPI_FUNC(Py_UCS4) _PyUnicode_ToUppercase(
- Py_UCS4 ch /* Unicode character */
- );
-
-Py_DEPRECATED(3.3) PyAPI_FUNC(Py_UCS4) _PyUnicode_ToTitlecase(
- Py_UCS4 ch /* Unicode character */
- );
-
-PyAPI_FUNC(int) _PyUnicode_ToLowerFull(
- Py_UCS4 ch, /* Unicode character */
- Py_UCS4 *res
- );
-
-PyAPI_FUNC(int) _PyUnicode_ToTitleFull(
- Py_UCS4 ch, /* Unicode character */
- Py_UCS4 *res
- );
-
-PyAPI_FUNC(int) _PyUnicode_ToUpperFull(
- Py_UCS4 ch, /* Unicode character */
- Py_UCS4 *res
- );
-
-PyAPI_FUNC(int) _PyUnicode_ToFoldedFull(
- Py_UCS4 ch, /* Unicode character */
- Py_UCS4 *res
- );
-
-PyAPI_FUNC(int) _PyUnicode_IsCaseIgnorable(
- Py_UCS4 ch /* Unicode character */
- );
-
-PyAPI_FUNC(int) _PyUnicode_IsCased(
- Py_UCS4 ch /* Unicode character */
- );
-
-PyAPI_FUNC(int) _PyUnicode_ToDecimalDigit(
- Py_UCS4 ch /* Unicode character */
- );
-
-PyAPI_FUNC(int) _PyUnicode_ToDigit(
- Py_UCS4 ch /* Unicode character */
- );
-
-PyAPI_FUNC(double) _PyUnicode_ToNumeric(
- Py_UCS4 ch /* Unicode character */
- );
-
-PyAPI_FUNC(int) _PyUnicode_IsDecimalDigit(
- Py_UCS4 ch /* Unicode character */
- );
-
-PyAPI_FUNC(int) _PyUnicode_IsDigit(
- Py_UCS4 ch /* Unicode character */
- );
-
-PyAPI_FUNC(int) _PyUnicode_IsNumeric(
- Py_UCS4 ch /* Unicode character */
- );
-
-PyAPI_FUNC(int) _PyUnicode_IsPrintable(
- Py_UCS4 ch /* Unicode character */
- );
-
-PyAPI_FUNC(int) _PyUnicode_IsAlpha(
- Py_UCS4 ch /* Unicode character */
- );
-
-PyAPI_FUNC(PyObject*) _PyUnicode_FormatLong(PyObject *, int, int, int);
-
-/* Return an interned Unicode object for an Identifier; may fail if there is no memory.*/
-PyAPI_FUNC(PyObject*) _PyUnicode_FromId(_Py_Identifier*);
-
-/* Fast equality check when the inputs are known to be exact unicode types
- and where the hash values are equal (i.e. a very probable match) */
-PyAPI_FUNC(int) _PyUnicode_EQ(PyObject *, PyObject *);
-
-PyAPI_FUNC(int) _PyUnicode_WideCharString_Converter(PyObject *, void *);
-PyAPI_FUNC(int) _PyUnicode_WideCharString_Opt_Converter(PyObject *, void *);
-
-PyAPI_FUNC(Py_ssize_t) _PyUnicode_ScanIdentifier(PyObject *);
diff --git a/include/python3.10/descrobject.h b/include/python3.10/descrobject.h
deleted file mode 100644
index 703bc8f..0000000
--- a/include/python3.10/descrobject.h
+++ /dev/null
@@ -1,108 +0,0 @@
-/* Descriptors */
-#ifndef Py_DESCROBJECT_H
-#define Py_DESCROBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef PyObject *(*getter)(PyObject *, void *);
-typedef int (*setter)(PyObject *, PyObject *, void *);
-
-typedef struct PyGetSetDef {
- const char *name;
- getter get;
- setter set;
- const char *doc;
- void *closure;
-} PyGetSetDef;
-
-#ifndef Py_LIMITED_API
-typedef PyObject *(*wrapperfunc)(PyObject *self, PyObject *args,
- void *wrapped);
-
-typedef PyObject *(*wrapperfunc_kwds)(PyObject *self, PyObject *args,
- void *wrapped, PyObject *kwds);
-
-struct wrapperbase {
- const char *name;
- int offset;
- void *function;
- wrapperfunc wrapper;
- const char *doc;
- int flags;
- PyObject *name_strobj;
-};
-
-/* Flags for above struct */
-#define PyWrapperFlag_KEYWORDS 1 /* wrapper function takes keyword args */
-
-/* Various kinds of descriptor objects */
-
-typedef struct {
- PyObject_HEAD
- PyTypeObject *d_type;
- PyObject *d_name;
- PyObject *d_qualname;
-} PyDescrObject;
-
-#define PyDescr_COMMON PyDescrObject d_common
-
-#define PyDescr_TYPE(x) (((PyDescrObject *)(x))->d_type)
-#define PyDescr_NAME(x) (((PyDescrObject *)(x))->d_name)
-
-typedef struct {
- PyDescr_COMMON;
- PyMethodDef *d_method;
- vectorcallfunc vectorcall;
-} PyMethodDescrObject;
-
-typedef struct {
- PyDescr_COMMON;
- struct PyMemberDef *d_member;
-} PyMemberDescrObject;
-
-typedef struct {
- PyDescr_COMMON;
- PyGetSetDef *d_getset;
-} PyGetSetDescrObject;
-
-typedef struct {
- PyDescr_COMMON;
- struct wrapperbase *d_base;
- void *d_wrapped; /* This can be any function pointer */
-} PyWrapperDescrObject;
-#endif /* Py_LIMITED_API */
-
-PyAPI_DATA(PyTypeObject) PyClassMethodDescr_Type;
-PyAPI_DATA(PyTypeObject) PyGetSetDescr_Type;
-PyAPI_DATA(PyTypeObject) PyMemberDescr_Type;
-PyAPI_DATA(PyTypeObject) PyMethodDescr_Type;
-PyAPI_DATA(PyTypeObject) PyWrapperDescr_Type;
-PyAPI_DATA(PyTypeObject) PyDictProxy_Type;
-#ifndef Py_LIMITED_API
-PyAPI_DATA(PyTypeObject) _PyMethodWrapper_Type;
-#endif /* Py_LIMITED_API */
-
-PyAPI_FUNC(PyObject *) PyDescr_NewMethod(PyTypeObject *, PyMethodDef *);
-PyAPI_FUNC(PyObject *) PyDescr_NewClassMethod(PyTypeObject *, PyMethodDef *);
-struct PyMemberDef; /* forward declaration for following prototype */
-PyAPI_FUNC(PyObject *) PyDescr_NewMember(PyTypeObject *,
- struct PyMemberDef *);
-PyAPI_FUNC(PyObject *) PyDescr_NewGetSet(PyTypeObject *,
- struct PyGetSetDef *);
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(PyObject *) PyDescr_NewWrapper(PyTypeObject *,
- struct wrapperbase *, void *);
-PyAPI_FUNC(int) PyDescr_IsData(PyObject *);
-#endif
-
-PyAPI_FUNC(PyObject *) PyDictProxy_New(PyObject *);
-PyAPI_FUNC(PyObject *) PyWrapper_New(PyObject *, PyObject *);
-
-
-PyAPI_DATA(PyTypeObject) PyProperty_Type;
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_DESCROBJECT_H */
-
diff --git a/include/python3.10/dictobject.h b/include/python3.10/dictobject.h
deleted file mode 100644
index da5a36b..0000000
--- a/include/python3.10/dictobject.h
+++ /dev/null
@@ -1,97 +0,0 @@
-#ifndef Py_DICTOBJECT_H
-#define Py_DICTOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Dictionary object type -- mapping from hashable object to object */
-
-/* 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.
-*/
-
-PyAPI_DATA(PyTypeObject) PyDict_Type;
-
-#define PyDict_Check(op) \
- PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_DICT_SUBCLASS)
-#define PyDict_CheckExact(op) Py_IS_TYPE(op, &PyDict_Type)
-
-PyAPI_FUNC(PyObject *) PyDict_New(void);
-PyAPI_FUNC(PyObject *) PyDict_GetItem(PyObject *mp, PyObject *key);
-PyAPI_FUNC(PyObject *) PyDict_GetItemWithError(PyObject *mp, PyObject *key);
-PyAPI_FUNC(int) PyDict_SetItem(PyObject *mp, PyObject *key, PyObject *item);
-PyAPI_FUNC(int) PyDict_DelItem(PyObject *mp, PyObject *key);
-PyAPI_FUNC(void) PyDict_Clear(PyObject *mp);
-PyAPI_FUNC(int) PyDict_Next(
- PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value);
-PyAPI_FUNC(PyObject *) PyDict_Keys(PyObject *mp);
-PyAPI_FUNC(PyObject *) PyDict_Values(PyObject *mp);
-PyAPI_FUNC(PyObject *) PyDict_Items(PyObject *mp);
-PyAPI_FUNC(Py_ssize_t) PyDict_Size(PyObject *mp);
-PyAPI_FUNC(PyObject *) PyDict_Copy(PyObject *mp);
-PyAPI_FUNC(int) PyDict_Contains(PyObject *mp, PyObject *key);
-
-/* PyDict_Update(mp, other) is equivalent to PyDict_Merge(mp, other, 1). */
-PyAPI_FUNC(int) PyDict_Update(PyObject *mp, PyObject *other);
-
-/* PyDict_Merge updates/merges from a mapping object (an object that
- supports PyMapping_Keys() and PyObject_GetItem()). If override is true,
- the last occurrence of a key wins, else the first. The Python
- dict.update(other) is equivalent to PyDict_Merge(dict, other, 1).
-*/
-PyAPI_FUNC(int) PyDict_Merge(PyObject *mp,
- PyObject *other,
- int override);
-
-/* PyDict_MergeFromSeq2 updates/merges from an iterable object producing
- iterable objects of length 2. If override is true, the last occurrence
- of a key wins, else the first. The Python dict constructor dict(seq2)
- is equivalent to dict={}; PyDict_MergeFromSeq(dict, seq2, 1).
-*/
-PyAPI_FUNC(int) PyDict_MergeFromSeq2(PyObject *d,
- PyObject *seq2,
- int override);
-
-PyAPI_FUNC(PyObject *) PyDict_GetItemString(PyObject *dp, const char *key);
-PyAPI_FUNC(int) PyDict_SetItemString(PyObject *dp, const char *key, PyObject *item);
-PyAPI_FUNC(int) PyDict_DelItemString(PyObject *dp, const char *key);
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000
-PyAPI_FUNC(PyObject *) PyObject_GenericGetDict(PyObject *, void *);
-#endif
-
-/* Dictionary (keys, values, items) views */
-
-PyAPI_DATA(PyTypeObject) PyDictKeys_Type;
-PyAPI_DATA(PyTypeObject) PyDictValues_Type;
-PyAPI_DATA(PyTypeObject) PyDictItems_Type;
-
-#define PyDictKeys_Check(op) PyObject_TypeCheck(op, &PyDictKeys_Type)
-#define PyDictValues_Check(op) PyObject_TypeCheck(op, &PyDictValues_Type)
-#define PyDictItems_Check(op) PyObject_TypeCheck(op, &PyDictItems_Type)
-/* This excludes Values, since they are not sets. */
-# define PyDictViewSet_Check(op) \
- (PyDictKeys_Check(op) || PyDictItems_Check(op))
-
-/* Dictionary (key, value, items) iterators */
-
-PyAPI_DATA(PyTypeObject) PyDictIterKey_Type;
-PyAPI_DATA(PyTypeObject) PyDictIterValue_Type;
-PyAPI_DATA(PyTypeObject) PyDictIterItem_Type;
-
-PyAPI_DATA(PyTypeObject) PyDictRevIterKey_Type;
-PyAPI_DATA(PyTypeObject) PyDictRevIterItem_Type;
-PyAPI_DATA(PyTypeObject) PyDictRevIterValue_Type;
-
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_DICTOBJECT_H
-# include "cpython/dictobject.h"
-# undef Py_CPYTHON_DICTOBJECT_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_DICTOBJECT_H */
diff --git a/include/python3.10/dynamic_annotations.h b/include/python3.10/dynamic_annotations.h
deleted file mode 100644
index 0bd1a83..0000000
--- a/include/python3.10/dynamic_annotations.h
+++ /dev/null
@@ -1,499 +0,0 @@
-/* Copyright (c) 2008-2009, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * ---
- * Author: Kostya Serebryany
- * Copied to CPython by Jeffrey Yasskin, with all macros renamed to
- * start with _Py_ to avoid colliding with users embedding Python, and
- * with deprecated macros removed.
- */
-
-/* This file defines dynamic annotations for use with dynamic analysis
- tool such as valgrind, PIN, etc.
-
- Dynamic annotation is a source code annotation that affects
- the generated code (that is, the annotation is not a comment).
- Each such annotation is attached to a particular
- instruction and/or to a particular object (address) in the program.
-
- The annotations that should be used by users are macros in all upper-case
- (e.g., _Py_ANNOTATE_NEW_MEMORY).
-
- Actual implementation of these macros may differ depending on the
- dynamic analysis tool being used.
-
- See http://code.google.com/p/data-race-test/ for more information.
-
- This file supports the following dynamic analysis tools:
- - None (DYNAMIC_ANNOTATIONS_ENABLED is not defined or zero).
- Macros are defined empty.
- - ThreadSanitizer, Helgrind, DRD (DYNAMIC_ANNOTATIONS_ENABLED is 1).
- Macros are defined as calls to non-inlinable empty functions
- that are intercepted by Valgrind. */
-
-#ifndef __DYNAMIC_ANNOTATIONS_H__
-#define __DYNAMIC_ANNOTATIONS_H__
-
-#ifndef DYNAMIC_ANNOTATIONS_ENABLED
-# define DYNAMIC_ANNOTATIONS_ENABLED 0
-#endif
-
-#if DYNAMIC_ANNOTATIONS_ENABLED != 0
-
- /* -------------------------------------------------------------
- Annotations useful when implementing condition variables such as CondVar,
- using conditional critical sections (Await/LockWhen) and when constructing
- user-defined synchronization mechanisms.
-
- The annotations _Py_ANNOTATE_HAPPENS_BEFORE() and
- _Py_ANNOTATE_HAPPENS_AFTER() can be used to define happens-before arcs in
- user-defined synchronization mechanisms: the race detector will infer an
- arc from the former to the latter when they share the same argument
- pointer.
-
- Example 1 (reference counting):
-
- void Unref() {
- _Py_ANNOTATE_HAPPENS_BEFORE(&refcount_);
- if (AtomicDecrementByOne(&refcount_) == 0) {
- _Py_ANNOTATE_HAPPENS_AFTER(&refcount_);
- delete this;
- }
- }
-
- Example 2 (message queue):
-
- void MyQueue::Put(Type *e) {
- MutexLock lock(&mu_);
- _Py_ANNOTATE_HAPPENS_BEFORE(e);
- PutElementIntoMyQueue(e);
- }
-
- Type *MyQueue::Get() {
- MutexLock lock(&mu_);
- Type *e = GetElementFromMyQueue();
- _Py_ANNOTATE_HAPPENS_AFTER(e);
- return e;
- }
-
- Note: when possible, please use the existing reference counting and message
- queue implementations instead of inventing new ones. */
-
- /* Report that wait on the condition variable at address "cv" has succeeded
- and the lock at address "lock" is held. */
-#define _Py_ANNOTATE_CONDVAR_LOCK_WAIT(cv, lock) \
- AnnotateCondVarWait(__FILE__, __LINE__, cv, lock)
-
- /* Report that wait on the condition variable at "cv" has succeeded. Variant
- w/o lock. */
-#define _Py_ANNOTATE_CONDVAR_WAIT(cv) \
- AnnotateCondVarWait(__FILE__, __LINE__, cv, NULL)
-
- /* Report that we are about to signal on the condition variable at address
- "cv". */
-#define _Py_ANNOTATE_CONDVAR_SIGNAL(cv) \
- AnnotateCondVarSignal(__FILE__, __LINE__, cv)
-
- /* Report that we are about to signal_all on the condition variable at "cv". */
-#define _Py_ANNOTATE_CONDVAR_SIGNAL_ALL(cv) \
- AnnotateCondVarSignalAll(__FILE__, __LINE__, cv)
-
- /* Annotations for user-defined synchronization mechanisms. */
-#define _Py_ANNOTATE_HAPPENS_BEFORE(obj) _Py_ANNOTATE_CONDVAR_SIGNAL(obj)
-#define _Py_ANNOTATE_HAPPENS_AFTER(obj) _Py_ANNOTATE_CONDVAR_WAIT(obj)
-
- /* Report that the bytes in the range [pointer, pointer+size) are about
- to be published safely. The race checker will create a happens-before
- arc from the call _Py_ANNOTATE_PUBLISH_MEMORY_RANGE(pointer, size) to
- subsequent accesses to this memory.
- Note: this annotation may not work properly if the race detector uses
- sampling, i.e. does not observe all memory accesses.
- */
-#define _Py_ANNOTATE_PUBLISH_MEMORY_RANGE(pointer, size) \
- AnnotatePublishMemoryRange(__FILE__, __LINE__, pointer, size)
-
- /* Instruct the tool to create a happens-before arc between mu->Unlock() and
- mu->Lock(). This annotation may slow down the race detector and hide real
- races. Normally it is used only when it would be difficult to annotate each
- of the mutex's critical sections individually using the annotations above.
- This annotation makes sense only for hybrid race detectors. For pure
- happens-before detectors this is a no-op. For more details see
- http://code.google.com/p/data-race-test/wiki/PureHappensBeforeVsHybrid . */
-#define _Py_ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(mu) \
- AnnotateMutexIsUsedAsCondVar(__FILE__, __LINE__, mu)
-
- /* -------------------------------------------------------------
- Annotations useful when defining memory allocators, or when memory that
- was protected in one way starts to be protected in another. */
-
- /* Report that a new memory at "address" of size "size" has been allocated.
- This might be used when the memory has been retrieved from a free list and
- is about to be reused, or when the locking discipline for a variable
- changes. */
-#define _Py_ANNOTATE_NEW_MEMORY(address, size) \
- AnnotateNewMemory(__FILE__, __LINE__, address, size)
-
- /* -------------------------------------------------------------
- Annotations useful when defining FIFO queues that transfer data between
- threads. */
-
- /* Report that the producer-consumer queue (such as ProducerConsumerQueue) at
- address "pcq" has been created. The _Py_ANNOTATE_PCQ_* annotations should
- be used only for FIFO queues. For non-FIFO queues use
- _Py_ANNOTATE_HAPPENS_BEFORE (for put) and _Py_ANNOTATE_HAPPENS_AFTER (for
- get). */
-#define _Py_ANNOTATE_PCQ_CREATE(pcq) \
- AnnotatePCQCreate(__FILE__, __LINE__, pcq)
-
- /* Report that the queue at address "pcq" is about to be destroyed. */
-#define _Py_ANNOTATE_PCQ_DESTROY(pcq) \
- AnnotatePCQDestroy(__FILE__, __LINE__, pcq)
-
- /* Report that we are about to put an element into a FIFO queue at address
- "pcq". */
-#define _Py_ANNOTATE_PCQ_PUT(pcq) \
- AnnotatePCQPut(__FILE__, __LINE__, pcq)
-
- /* Report that we've just got an element from a FIFO queue at address "pcq". */
-#define _Py_ANNOTATE_PCQ_GET(pcq) \
- AnnotatePCQGet(__FILE__, __LINE__, pcq)
-
- /* -------------------------------------------------------------
- Annotations that suppress errors. It is usually better to express the
- program's synchronization using the other annotations, but these can
- be used when all else fails. */
-
- /* Report that we may have a benign race at "pointer", with size
- "sizeof(*(pointer))". "pointer" must be a non-void* pointer. Insert at the
- point where "pointer" has been allocated, preferably close to the point
- where the race happens. See also _Py_ANNOTATE_BENIGN_RACE_STATIC. */
-#define _Py_ANNOTATE_BENIGN_RACE(pointer, description) \
- AnnotateBenignRaceSized(__FILE__, __LINE__, pointer, \
- sizeof(*(pointer)), description)
-
- /* Same as _Py_ANNOTATE_BENIGN_RACE(address, description), but applies to
- the memory range [address, address+size). */
-#define _Py_ANNOTATE_BENIGN_RACE_SIZED(address, size, description) \
- AnnotateBenignRaceSized(__FILE__, __LINE__, address, size, description)
-
- /* Request the analysis tool to ignore all reads in the current thread
- until _Py_ANNOTATE_IGNORE_READS_END is called.
- Useful to ignore intentional racey reads, while still checking
- other reads and all writes.
- See also _Py_ANNOTATE_UNPROTECTED_READ. */
-#define _Py_ANNOTATE_IGNORE_READS_BEGIN() \
- AnnotateIgnoreReadsBegin(__FILE__, __LINE__)
-
- /* Stop ignoring reads. */
-#define _Py_ANNOTATE_IGNORE_READS_END() \
- AnnotateIgnoreReadsEnd(__FILE__, __LINE__)
-
- /* Similar to _Py_ANNOTATE_IGNORE_READS_BEGIN, but ignore writes. */
-#define _Py_ANNOTATE_IGNORE_WRITES_BEGIN() \
- AnnotateIgnoreWritesBegin(__FILE__, __LINE__)
-
- /* Stop ignoring writes. */
-#define _Py_ANNOTATE_IGNORE_WRITES_END() \
- AnnotateIgnoreWritesEnd(__FILE__, __LINE__)
-
- /* Start ignoring all memory accesses (reads and writes). */
-#define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() \
- do {\
- _Py_ANNOTATE_IGNORE_READS_BEGIN();\
- _Py_ANNOTATE_IGNORE_WRITES_BEGIN();\
- }while(0)\
-
- /* Stop ignoring all memory accesses. */
-#define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_END() \
- do {\
- _Py_ANNOTATE_IGNORE_WRITES_END();\
- _Py_ANNOTATE_IGNORE_READS_END();\
- }while(0)\
-
- /* Similar to _Py_ANNOTATE_IGNORE_READS_BEGIN, but ignore synchronization events:
- RWLOCK* and CONDVAR*. */
-#define _Py_ANNOTATE_IGNORE_SYNC_BEGIN() \
- AnnotateIgnoreSyncBegin(__FILE__, __LINE__)
-
- /* Stop ignoring sync events. */
-#define _Py_ANNOTATE_IGNORE_SYNC_END() \
- AnnotateIgnoreSyncEnd(__FILE__, __LINE__)
-
-
- /* Enable (enable!=0) or disable (enable==0) race detection for all threads.
- This annotation could be useful if you want to skip expensive race analysis
- during some period of program execution, e.g. during initialization. */
-#define _Py_ANNOTATE_ENABLE_RACE_DETECTION(enable) \
- AnnotateEnableRaceDetection(__FILE__, __LINE__, enable)
-
- /* -------------------------------------------------------------
- Annotations useful for debugging. */
-
- /* Request to trace every access to "address". */
-#define _Py_ANNOTATE_TRACE_MEMORY(address) \
- AnnotateTraceMemory(__FILE__, __LINE__, address)
-
- /* Report the current thread name to a race detector. */
-#define _Py_ANNOTATE_THREAD_NAME(name) \
- AnnotateThreadName(__FILE__, __LINE__, name)
-
- /* -------------------------------------------------------------
- Annotations useful when implementing locks. They are not
- normally needed by modules that merely use locks.
- The "lock" argument is a pointer to the lock object. */
-
- /* Report that a lock has been created at address "lock". */
-#define _Py_ANNOTATE_RWLOCK_CREATE(lock) \
- AnnotateRWLockCreate(__FILE__, __LINE__, lock)
-
- /* Report that the lock at address "lock" is about to be destroyed. */
-#define _Py_ANNOTATE_RWLOCK_DESTROY(lock) \
- AnnotateRWLockDestroy(__FILE__, __LINE__, lock)
-
- /* Report that the lock at address "lock" has been acquired.
- is_w=1 for writer lock, is_w=0 for reader lock. */
-#define _Py_ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) \
- AnnotateRWLockAcquired(__FILE__, __LINE__, lock, is_w)
-
- /* Report that the lock at address "lock" is about to be released. */
-#define _Py_ANNOTATE_RWLOCK_RELEASED(lock, is_w) \
- AnnotateRWLockReleased(__FILE__, __LINE__, lock, is_w)
-
- /* -------------------------------------------------------------
- Annotations useful when implementing barriers. They are not
- normally needed by modules that merely use barriers.
- The "barrier" argument is a pointer to the barrier object. */
-
- /* Report that the "barrier" has been initialized with initial "count".
- If 'reinitialization_allowed' is true, initialization is allowed to happen
- multiple times w/o calling barrier_destroy() */
-#define _Py_ANNOTATE_BARRIER_INIT(barrier, count, reinitialization_allowed) \
- AnnotateBarrierInit(__FILE__, __LINE__, barrier, count, \
- reinitialization_allowed)
-
- /* Report that we are about to enter barrier_wait("barrier"). */
-#define _Py_ANNOTATE_BARRIER_WAIT_BEFORE(barrier) \
- AnnotateBarrierWaitBefore(__FILE__, __LINE__, barrier)
-
- /* Report that we just exited barrier_wait("barrier"). */
-#define _Py_ANNOTATE_BARRIER_WAIT_AFTER(barrier) \
- AnnotateBarrierWaitAfter(__FILE__, __LINE__, barrier)
-
- /* Report that the "barrier" has been destroyed. */
-#define _Py_ANNOTATE_BARRIER_DESTROY(barrier) \
- AnnotateBarrierDestroy(__FILE__, __LINE__, barrier)
-
- /* -------------------------------------------------------------
- Annotations useful for testing race detectors. */
-
- /* Report that we expect a race on the variable at "address".
- Use only in unit tests for a race detector. */
-#define _Py_ANNOTATE_EXPECT_RACE(address, description) \
- AnnotateExpectRace(__FILE__, __LINE__, address, description)
-
- /* A no-op. Insert where you like to test the interceptors. */
-#define _Py_ANNOTATE_NO_OP(arg) \
- AnnotateNoOp(__FILE__, __LINE__, arg)
-
- /* Force the race detector to flush its state. The actual effect depends on
- * the implementation of the detector. */
-#define _Py_ANNOTATE_FLUSH_STATE() \
- AnnotateFlushState(__FILE__, __LINE__)
-
-
-#else /* DYNAMIC_ANNOTATIONS_ENABLED == 0 */
-
-#define _Py_ANNOTATE_RWLOCK_CREATE(lock) /* empty */
-#define _Py_ANNOTATE_RWLOCK_DESTROY(lock) /* empty */
-#define _Py_ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) /* empty */
-#define _Py_ANNOTATE_RWLOCK_RELEASED(lock, is_w) /* empty */
-#define _Py_ANNOTATE_BARRIER_INIT(barrier, count, reinitialization_allowed) /* */
-#define _Py_ANNOTATE_BARRIER_WAIT_BEFORE(barrier) /* empty */
-#define _Py_ANNOTATE_BARRIER_WAIT_AFTER(barrier) /* empty */
-#define _Py_ANNOTATE_BARRIER_DESTROY(barrier) /* empty */
-#define _Py_ANNOTATE_CONDVAR_LOCK_WAIT(cv, lock) /* empty */
-#define _Py_ANNOTATE_CONDVAR_WAIT(cv) /* empty */
-#define _Py_ANNOTATE_CONDVAR_SIGNAL(cv) /* empty */
-#define _Py_ANNOTATE_CONDVAR_SIGNAL_ALL(cv) /* empty */
-#define _Py_ANNOTATE_HAPPENS_BEFORE(obj) /* empty */
-#define _Py_ANNOTATE_HAPPENS_AFTER(obj) /* empty */
-#define _Py_ANNOTATE_PUBLISH_MEMORY_RANGE(address, size) /* empty */
-#define _Py_ANNOTATE_UNPUBLISH_MEMORY_RANGE(address, size) /* empty */
-#define _Py_ANNOTATE_SWAP_MEMORY_RANGE(address, size) /* empty */
-#define _Py_ANNOTATE_PCQ_CREATE(pcq) /* empty */
-#define _Py_ANNOTATE_PCQ_DESTROY(pcq) /* empty */
-#define _Py_ANNOTATE_PCQ_PUT(pcq) /* empty */
-#define _Py_ANNOTATE_PCQ_GET(pcq) /* empty */
-#define _Py_ANNOTATE_NEW_MEMORY(address, size) /* empty */
-#define _Py_ANNOTATE_EXPECT_RACE(address, description) /* empty */
-#define _Py_ANNOTATE_BENIGN_RACE(address, description) /* empty */
-#define _Py_ANNOTATE_BENIGN_RACE_SIZED(address, size, description) /* empty */
-#define _Py_ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(mu) /* empty */
-#define _Py_ANNOTATE_MUTEX_IS_USED_AS_CONDVAR(mu) /* empty */
-#define _Py_ANNOTATE_TRACE_MEMORY(arg) /* empty */
-#define _Py_ANNOTATE_THREAD_NAME(name) /* empty */
-#define _Py_ANNOTATE_IGNORE_READS_BEGIN() /* empty */
-#define _Py_ANNOTATE_IGNORE_READS_END() /* empty */
-#define _Py_ANNOTATE_IGNORE_WRITES_BEGIN() /* empty */
-#define _Py_ANNOTATE_IGNORE_WRITES_END() /* empty */
-#define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() /* empty */
-#define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_END() /* empty */
-#define _Py_ANNOTATE_IGNORE_SYNC_BEGIN() /* empty */
-#define _Py_ANNOTATE_IGNORE_SYNC_END() /* empty */
-#define _Py_ANNOTATE_ENABLE_RACE_DETECTION(enable) /* empty */
-#define _Py_ANNOTATE_NO_OP(arg) /* empty */
-#define _Py_ANNOTATE_FLUSH_STATE() /* empty */
-
-#endif /* DYNAMIC_ANNOTATIONS_ENABLED */
-
-/* Use the macros above rather than using these functions directly. */
-#ifdef __cplusplus
-extern "C" {
-#endif
-void AnnotateRWLockCreate(const char *file, int line,
- const volatile void *lock);
-void AnnotateRWLockDestroy(const char *file, int line,
- const volatile void *lock);
-void AnnotateRWLockAcquired(const char *file, int line,
- const volatile void *lock, long is_w);
-void AnnotateRWLockReleased(const char *file, int line,
- const volatile void *lock, long is_w);
-void AnnotateBarrierInit(const char *file, int line,
- const volatile void *barrier, long count,
- long reinitialization_allowed);
-void AnnotateBarrierWaitBefore(const char *file, int line,
- const volatile void *barrier);
-void AnnotateBarrierWaitAfter(const char *file, int line,
- const volatile void *barrier);
-void AnnotateBarrierDestroy(const char *file, int line,
- const volatile void *barrier);
-void AnnotateCondVarWait(const char *file, int line,
- const volatile void *cv,
- const volatile void *lock);
-void AnnotateCondVarSignal(const char *file, int line,
- const volatile void *cv);
-void AnnotateCondVarSignalAll(const char *file, int line,
- const volatile void *cv);
-void AnnotatePublishMemoryRange(const char *file, int line,
- const volatile void *address,
- long size);
-void AnnotateUnpublishMemoryRange(const char *file, int line,
- const volatile void *address,
- long size);
-void AnnotatePCQCreate(const char *file, int line,
- const volatile void *pcq);
-void AnnotatePCQDestroy(const char *file, int line,
- const volatile void *pcq);
-void AnnotatePCQPut(const char *file, int line,
- const volatile void *pcq);
-void AnnotatePCQGet(const char *file, int line,
- const volatile void *pcq);
-void AnnotateNewMemory(const char *file, int line,
- const volatile void *address,
- long size);
-void AnnotateExpectRace(const char *file, int line,
- const volatile void *address,
- const char *description);
-void AnnotateBenignRace(const char *file, int line,
- const volatile void *address,
- const char *description);
-void AnnotateBenignRaceSized(const char *file, int line,
- const volatile void *address,
- long size,
- const char *description);
-void AnnotateMutexIsUsedAsCondVar(const char *file, int line,
- const volatile void *mu);
-void AnnotateTraceMemory(const char *file, int line,
- const volatile void *arg);
-void AnnotateThreadName(const char *file, int line,
- const char *name);
-void AnnotateIgnoreReadsBegin(const char *file, int line);
-void AnnotateIgnoreReadsEnd(const char *file, int line);
-void AnnotateIgnoreWritesBegin(const char *file, int line);
-void AnnotateIgnoreWritesEnd(const char *file, int line);
-void AnnotateEnableRaceDetection(const char *file, int line, int enable);
-void AnnotateNoOp(const char *file, int line,
- const volatile void *arg);
-void AnnotateFlushState(const char *file, int line);
-
-/* Return non-zero value if running under valgrind.
-
- If "valgrind.h" is included into dynamic_annotations.c,
- the regular valgrind mechanism will be used.
- See http://valgrind.org/docs/manual/manual-core-adv.html about
- RUNNING_ON_VALGRIND and other valgrind "client requests".
- The file "valgrind.h" may be obtained by doing
- svn co svn://svn.valgrind.org/valgrind/trunk/include
-
- If for some reason you can't use "valgrind.h" or want to fake valgrind,
- there are two ways to make this function return non-zero:
- - Use environment variable: export RUNNING_ON_VALGRIND=1
- - Make your tool intercept the function RunningOnValgrind() and
- change its return value.
- */
-int RunningOnValgrind(void);
-
-#ifdef __cplusplus
-}
-#endif
-
-#if DYNAMIC_ANNOTATIONS_ENABLED != 0 && defined(__cplusplus)
-
- /* _Py_ANNOTATE_UNPROTECTED_READ is the preferred way to annotate racey reads.
-
- Instead of doing
- _Py_ANNOTATE_IGNORE_READS_BEGIN();
- ... = x;
- _Py_ANNOTATE_IGNORE_READS_END();
- one can use
- ... = _Py_ANNOTATE_UNPROTECTED_READ(x); */
- template <class T>
- inline T _Py_ANNOTATE_UNPROTECTED_READ(const volatile T &x) {
- _Py_ANNOTATE_IGNORE_READS_BEGIN();
- T res = x;
- _Py_ANNOTATE_IGNORE_READS_END();
- return res;
- }
- /* Apply _Py_ANNOTATE_BENIGN_RACE_SIZED to a static variable. */
-#define _Py_ANNOTATE_BENIGN_RACE_STATIC(static_var, description) \
- namespace { \
- class static_var ## _annotator { \
- public: \
- static_var ## _annotator() { \
- _Py_ANNOTATE_BENIGN_RACE_SIZED(&static_var, \
- sizeof(static_var), \
- # static_var ": " description); \
- } \
- }; \
- static static_var ## _annotator the ## static_var ## _annotator;\
- }
-#else /* DYNAMIC_ANNOTATIONS_ENABLED == 0 */
-
-#define _Py_ANNOTATE_UNPROTECTED_READ(x) (x)
-#define _Py_ANNOTATE_BENIGN_RACE_STATIC(static_var, description) /* empty */
-
-#endif /* DYNAMIC_ANNOTATIONS_ENABLED */
-
-#endif /* __DYNAMIC_ANNOTATIONS_H__ */
diff --git a/include/python3.10/eval.h b/include/python3.10/eval.h
deleted file mode 100644
index eda28df..0000000
--- a/include/python3.10/eval.h
+++ /dev/null
@@ -1,27 +0,0 @@
-
-/* Interface to execute compiled code */
-
-#ifndef Py_EVAL_H
-#define Py_EVAL_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-PyAPI_FUNC(PyObject *) PyEval_EvalCode(PyObject *, PyObject *, PyObject *);
-
-PyAPI_FUNC(PyObject *) PyEval_EvalCodeEx(PyObject *co,
- PyObject *globals,
- PyObject *locals,
- PyObject *const *args, int argc,
- PyObject *const *kwds, int kwdc,
- PyObject *const *defs, int defc,
- PyObject *kwdefs, PyObject *closure);
-
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(PyObject *) _PyEval_CallTracing(PyObject *func, PyObject *args);
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_EVAL_H */
diff --git a/include/python3.10/fileobject.h b/include/python3.10/fileobject.h
deleted file mode 100644
index 6ec2994..0000000
--- a/include/python3.10/fileobject.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/* File object interface (what's left of it -- see io.py) */
-
-#ifndef Py_FILEOBJECT_H
-#define Py_FILEOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define PY_STDIOTEXTMODE "b"
-
-PyAPI_FUNC(PyObject *) PyFile_FromFd(int, const char *, const char *, int,
- const char *, const char *,
- const char *, int);
-PyAPI_FUNC(PyObject *) PyFile_GetLine(PyObject *, int);
-PyAPI_FUNC(int) PyFile_WriteObject(PyObject *, PyObject *, int);
-PyAPI_FUNC(int) PyFile_WriteString(const char *, PyObject *);
-PyAPI_FUNC(int) PyObject_AsFileDescriptor(PyObject *);
-
-/* The default encoding used by the platform file system APIs
- If non-NULL, this is different than the default encoding for strings
-*/
-PyAPI_DATA(const char *) Py_FileSystemDefaultEncoding;
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000
-PyAPI_DATA(const char *) Py_FileSystemDefaultEncodeErrors;
-#endif
-PyAPI_DATA(int) Py_HasFileSystemDefaultEncoding;
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03070000
-PyAPI_DATA(int) Py_UTF8Mode;
-#endif
-
-/* A routine to check if a file descriptor can be select()-ed. */
-#ifdef _MSC_VER
- /* On Windows, any socket fd can be select()-ed, no matter how high */
- #define _PyIsSelectable_fd(FD) (1)
-#else
- #define _PyIsSelectable_fd(FD) ((unsigned int)(FD) < (unsigned int)FD_SETSIZE)
-#endif
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_FILEOBJECT_H
-# include "cpython/fileobject.h"
-# undef Py_CPYTHON_FILEOBJECT_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_FILEOBJECT_H */
diff --git a/include/python3.10/fileutils.h b/include/python3.10/fileutils.h
deleted file mode 100644
index 16f3b63..0000000
--- a/include/python3.10/fileutils.h
+++ /dev/null
@@ -1,26 +0,0 @@
-#ifndef Py_FILEUTILS_H
-#define Py_FILEUTILS_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
-PyAPI_FUNC(wchar_t *) Py_DecodeLocale(
- const char *arg,
- size_t *size);
-
-PyAPI_FUNC(char*) Py_EncodeLocale(
- const wchar_t *text,
- size_t *error_pos);
-#endif
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_FILEUTILS_H
-# include "cpython/fileutils.h"
-# undef Py_CPYTHON_FILEUTILS_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_FILEUTILS_H */
diff --git a/include/python3.10/floatobject.h b/include/python3.10/floatobject.h
deleted file mode 100644
index e994aa8..0000000
--- a/include/python3.10/floatobject.h
+++ /dev/null
@@ -1,118 +0,0 @@
-
-/* Float object interface */
-
-/*
-PyFloatObject represents a (double precision) floating point number.
-*/
-
-#ifndef Py_FLOATOBJECT_H
-#define Py_FLOATOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_LIMITED_API
-typedef struct {
- PyObject_HEAD
- double ob_fval;
-} PyFloatObject;
-#endif
-
-PyAPI_DATA(PyTypeObject) PyFloat_Type;
-
-#define PyFloat_Check(op) PyObject_TypeCheck(op, &PyFloat_Type)
-#define PyFloat_CheckExact(op) Py_IS_TYPE(op, &PyFloat_Type)
-
-#ifdef Py_NAN
-#define Py_RETURN_NAN return PyFloat_FromDouble(Py_NAN)
-#endif
-
-#define Py_RETURN_INF(sign) do \
- if (copysign(1., sign) == 1.) { \
- return PyFloat_FromDouble(Py_HUGE_VAL); \
- } else { \
- return PyFloat_FromDouble(-Py_HUGE_VAL); \
- } while(0)
-
-PyAPI_FUNC(double) PyFloat_GetMax(void);
-PyAPI_FUNC(double) PyFloat_GetMin(void);
-PyAPI_FUNC(PyObject *) PyFloat_GetInfo(void);
-
-/* Return Python float from string PyObject. */
-PyAPI_FUNC(PyObject *) PyFloat_FromString(PyObject*);
-
-/* Return Python float from C double. */
-PyAPI_FUNC(PyObject *) PyFloat_FromDouble(double);
-
-/* Extract C double from Python float. The macro version trades safety for
- speed. */
-PyAPI_FUNC(double) PyFloat_AsDouble(PyObject *);
-#ifndef Py_LIMITED_API
-#define PyFloat_AS_DOUBLE(op) (((PyFloatObject *)(op))->ob_fval)
-#endif
-
-#ifndef Py_LIMITED_API
-/* _PyFloat_{Pack,Unpack}{4,8}
- *
- * The struct and pickle (at least) modules need an efficient platform-
- * independent way to store floating-point values as byte strings.
- * The Pack routines produce a string from a C double, and the Unpack
- * routines produce a C double from such a string. The suffix (4 or 8)
- * specifies the number of bytes in the string.
- *
- * On platforms that appear to use (see _PyFloat_Init()) IEEE-754 formats
- * these functions work by copying bits. On other platforms, the formats the
- * 4- byte format is identical to the IEEE-754 single precision format, and
- * the 8-byte format to the IEEE-754 double precision format, although the
- * packing of INFs and NaNs (if such things exist on the platform) isn't
- * handled correctly, and attempting to unpack a string containing an IEEE
- * INF or NaN will raise an exception.
- *
- * On non-IEEE platforms with more precision, or larger dynamic range, than
- * 754 supports, not all values can be packed; on non-IEEE platforms with less
- * precision, or smaller dynamic range, not all values can be unpacked. What
- * happens in such cases is partly accidental (alas).
- */
-
-/* The pack routines write 2, 4 or 8 bytes, starting at p. le is a bool
- * argument, true if you want the string in little-endian format (exponent
- * last, at p+1, p+3 or p+7), false if you want big-endian format (exponent
- * first, at p).
- * Return value: 0 if all is OK, -1 if error (and an exception is
- * set, most likely OverflowError).
- * There are two problems on non-IEEE platforms:
- * 1): What this does is undefined if x is a NaN or infinity.
- * 2): -0.0 and +0.0 produce the same string.
- */
-PyAPI_FUNC(int) _PyFloat_Pack2(double x, unsigned char *p, int le);
-PyAPI_FUNC(int) _PyFloat_Pack4(double x, unsigned char *p, int le);
-PyAPI_FUNC(int) _PyFloat_Pack8(double x, unsigned char *p, int le);
-
-/* The unpack routines read 2, 4 or 8 bytes, starting at p. le is a bool
- * argument, true if the string is in little-endian format (exponent
- * last, at p+1, p+3 or p+7), false if big-endian (exponent first, at p).
- * Return value: The unpacked double. On error, this is -1.0 and
- * PyErr_Occurred() is true (and an exception is set, most likely
- * OverflowError). Note that on a non-IEEE platform this will refuse
- * to unpack a string that represents a NaN or infinity.
- */
-PyAPI_FUNC(double) _PyFloat_Unpack2(const unsigned char *p, int le);
-PyAPI_FUNC(double) _PyFloat_Unpack4(const unsigned char *p, int le);
-PyAPI_FUNC(double) _PyFloat_Unpack8(const unsigned char *p, int le);
-
-PyAPI_FUNC(void) _PyFloat_DebugMallocStats(FILE* out);
-
-/* Format the object based on the format_spec, as defined in PEP 3101
- (Advanced String Formatting). */
-PyAPI_FUNC(int) _PyFloat_FormatAdvancedWriter(
- _PyUnicodeWriter *writer,
- PyObject *obj,
- PyObject *format_spec,
- Py_ssize_t start,
- Py_ssize_t end);
-#endif /* Py_LIMITED_API */
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_FLOATOBJECT_H */
diff --git a/include/python3.10/frameobject.h b/include/python3.10/frameobject.h
deleted file mode 100644
index c118af1..0000000
--- a/include/python3.10/frameobject.h
+++ /dev/null
@@ -1,20 +0,0 @@
-/* Frame object interface */
-
-#ifndef Py_FRAMEOBJECT_H
-#define Py_FRAMEOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "pyframe.h"
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_FRAMEOBJECT_H
-# include "cpython/frameobject.h"
-# undef Py_CPYTHON_FRAMEOBJECT_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_FRAMEOBJECT_H */
diff --git a/include/python3.10/funcobject.h b/include/python3.10/funcobject.h
deleted file mode 100644
index d7acd18..0000000
--- a/include/python3.10/funcobject.h
+++ /dev/null
@@ -1,110 +0,0 @@
-
-/* Function object interface */
-#ifndef Py_LIMITED_API
-#ifndef Py_FUNCOBJECT_H
-#define Py_FUNCOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-#define COMMON_FIELDS(PREFIX) \
- PyObject *PREFIX ## globals; \
- PyObject *PREFIX ## builtins; \
- PyObject *PREFIX ## name; \
- PyObject *PREFIX ## qualname; \
- PyObject *PREFIX ## code; /* A code object, the __code__ attribute */ \
- PyObject *PREFIX ## defaults; /* NULL or a tuple */ \
- PyObject *PREFIX ## kwdefaults; /* NULL or a dict */ \
- PyObject *PREFIX ## closure; /* NULL or a tuple of cell objects */
-
-typedef struct {
- COMMON_FIELDS(fc_)
-} PyFrameConstructor;
-
-/* Function objects and code objects should not be confused with each other:
- *
- * Function objects are created by the execution of the 'def' statement.
- * They reference a code object in their __code__ attribute, which is a
- * purely syntactic object, i.e. nothing more than a compiled version of some
- * source code lines. There is one code object per source code "fragment",
- * but each code object can be referenced by zero or many function objects
- * depending only on how many times the 'def' statement in the source was
- * executed so far.
- */
-
-typedef struct {
- PyObject_HEAD
- COMMON_FIELDS(func_)
- PyObject *func_doc; /* The __doc__ attribute, can be anything */
- PyObject *func_dict; /* The __dict__ attribute, a dict or NULL */
- PyObject *func_weakreflist; /* List of weak references */
- PyObject *func_module; /* The __module__ attribute, can be anything */
- PyObject *func_annotations; /* Annotations, a dict or NULL */
- vectorcallfunc vectorcall;
-
- /* Invariant:
- * func_closure contains the bindings for func_code->co_freevars, so
- * PyTuple_Size(func_closure) == PyCode_GetNumFree(func_code)
- * (func_closure may be NULL if PyCode_GetNumFree(func_code) == 0).
- */
-} PyFunctionObject;
-
-PyAPI_DATA(PyTypeObject) PyFunction_Type;
-
-#define PyFunction_Check(op) Py_IS_TYPE(op, &PyFunction_Type)
-
-PyAPI_FUNC(PyObject *) PyFunction_New(PyObject *, PyObject *);
-PyAPI_FUNC(PyObject *) PyFunction_NewWithQualName(PyObject *, PyObject *, PyObject *);
-PyAPI_FUNC(PyObject *) PyFunction_GetCode(PyObject *);
-PyAPI_FUNC(PyObject *) PyFunction_GetGlobals(PyObject *);
-PyAPI_FUNC(PyObject *) PyFunction_GetModule(PyObject *);
-PyAPI_FUNC(PyObject *) PyFunction_GetDefaults(PyObject *);
-PyAPI_FUNC(int) PyFunction_SetDefaults(PyObject *, PyObject *);
-PyAPI_FUNC(PyObject *) PyFunction_GetKwDefaults(PyObject *);
-PyAPI_FUNC(int) PyFunction_SetKwDefaults(PyObject *, PyObject *);
-PyAPI_FUNC(PyObject *) PyFunction_GetClosure(PyObject *);
-PyAPI_FUNC(int) PyFunction_SetClosure(PyObject *, PyObject *);
-PyAPI_FUNC(PyObject *) PyFunction_GetAnnotations(PyObject *);
-PyAPI_FUNC(int) PyFunction_SetAnnotations(PyObject *, PyObject *);
-
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(PyObject *) _PyFunction_Vectorcall(
- PyObject *func,
- PyObject *const *stack,
- size_t nargsf,
- PyObject *kwnames);
-#endif
-
-/* Macros for direct access to these values. Type checks are *not*
- done, so use with care. */
-#define PyFunction_GET_CODE(func) \
- (((PyFunctionObject *)func) -> func_code)
-#define PyFunction_GET_GLOBALS(func) \
- (((PyFunctionObject *)func) -> func_globals)
-#define PyFunction_GET_MODULE(func) \
- (((PyFunctionObject *)func) -> func_module)
-#define PyFunction_GET_DEFAULTS(func) \
- (((PyFunctionObject *)func) -> func_defaults)
-#define PyFunction_GET_KW_DEFAULTS(func) \
- (((PyFunctionObject *)func) -> func_kwdefaults)
-#define PyFunction_GET_CLOSURE(func) \
- (((PyFunctionObject *)func) -> func_closure)
-#define PyFunction_GET_ANNOTATIONS(func) \
- (((PyFunctionObject *)func) -> func_annotations)
-
-#define PyFunction_AS_FRAME_CONSTRUCTOR(func) \
- ((PyFrameConstructor *)&((PyFunctionObject *)(func))->func_globals)
-
-/* The classmethod and staticmethod types lives here, too */
-PyAPI_DATA(PyTypeObject) PyClassMethod_Type;
-PyAPI_DATA(PyTypeObject) PyStaticMethod_Type;
-
-PyAPI_FUNC(PyObject *) PyClassMethod_New(PyObject *);
-PyAPI_FUNC(PyObject *) PyStaticMethod_New(PyObject *);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_FUNCOBJECT_H */
-#endif /* Py_LIMITED_API */
diff --git a/include/python3.10/genobject.h b/include/python3.10/genobject.h
deleted file mode 100644
index e965334..0000000
--- a/include/python3.10/genobject.h
+++ /dev/null
@@ -1,100 +0,0 @@
-
-/* Generator object interface */
-
-#ifndef Py_LIMITED_API
-#ifndef Py_GENOBJECT_H
-#define Py_GENOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "pystate.h" /* _PyErr_StackItem */
-#include "abstract.h" /* PySendResult */
-
-/* _PyGenObject_HEAD defines the initial segment of generator
- and coroutine objects. */
-#define _PyGenObject_HEAD(prefix) \
- PyObject_HEAD \
- /* Note: gi_frame can be NULL if the generator is "finished" */ \
- PyFrameObject *prefix##_frame; \
- /* The code object backing the generator */ \
- PyObject *prefix##_code; \
- /* List of weak reference. */ \
- PyObject *prefix##_weakreflist; \
- /* Name of the generator. */ \
- PyObject *prefix##_name; \
- /* Qualified name of the generator. */ \
- PyObject *prefix##_qualname; \
- _PyErr_StackItem prefix##_exc_state;
-
-typedef struct {
- /* The gi_ prefix is intended to remind of generator-iterator. */
- _PyGenObject_HEAD(gi)
-} PyGenObject;
-
-PyAPI_DATA(PyTypeObject) PyGen_Type;
-
-#define PyGen_Check(op) PyObject_TypeCheck(op, &PyGen_Type)
-#define PyGen_CheckExact(op) Py_IS_TYPE(op, &PyGen_Type)
-
-PyAPI_FUNC(PyObject *) PyGen_New(PyFrameObject *);
-PyAPI_FUNC(PyObject *) PyGen_NewWithQualName(PyFrameObject *,
- PyObject *name, PyObject *qualname);
-PyAPI_FUNC(int) _PyGen_SetStopIterationValue(PyObject *);
-PyAPI_FUNC(int) _PyGen_FetchStopIterationValue(PyObject **);
-PyObject *_PyGen_yf(PyGenObject *);
-PyAPI_FUNC(void) _PyGen_Finalize(PyObject *self);
-
-#ifndef Py_LIMITED_API
-typedef struct {
- _PyGenObject_HEAD(cr)
- PyObject *cr_origin;
-} PyCoroObject;
-
-PyAPI_DATA(PyTypeObject) PyCoro_Type;
-PyAPI_DATA(PyTypeObject) _PyCoroWrapper_Type;
-
-#define PyCoro_CheckExact(op) Py_IS_TYPE(op, &PyCoro_Type)
-PyObject *_PyCoro_GetAwaitableIter(PyObject *o);
-PyAPI_FUNC(PyObject *) PyCoro_New(PyFrameObject *,
- PyObject *name, PyObject *qualname);
-
-/* Asynchronous Generators */
-
-typedef struct {
- _PyGenObject_HEAD(ag)
- PyObject *ag_finalizer;
-
- /* Flag is set to 1 when hooks set up by sys.set_asyncgen_hooks
- were called on the generator, to avoid calling them more
- than once. */
- int ag_hooks_inited;
-
- /* Flag is set to 1 when aclose() is called for the first time, or
- when a StopAsyncIteration exception is raised. */
- int ag_closed;
-
- int ag_running_async;
-} PyAsyncGenObject;
-
-PyAPI_DATA(PyTypeObject) PyAsyncGen_Type;
-PyAPI_DATA(PyTypeObject) _PyAsyncGenASend_Type;
-PyAPI_DATA(PyTypeObject) _PyAsyncGenWrappedValue_Type;
-PyAPI_DATA(PyTypeObject) _PyAsyncGenAThrow_Type;
-
-PyAPI_FUNC(PyObject *) PyAsyncGen_New(PyFrameObject *,
- PyObject *name, PyObject *qualname);
-
-#define PyAsyncGen_CheckExact(op) Py_IS_TYPE(op, &PyAsyncGen_Type)
-
-PyObject *_PyAsyncGenValueWrapperNew(PyObject *);
-
-#endif
-
-#undef _PyGenObject_HEAD
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_GENOBJECT_H */
-#endif /* Py_LIMITED_API */
diff --git a/include/python3.10/import.h b/include/python3.10/import.h
deleted file mode 100644
index aeef3ef..0000000
--- a/include/python3.10/import.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/* Module definition and import interface */
-
-#ifndef Py_IMPORT_H
-#define Py_IMPORT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-PyAPI_FUNC(long) PyImport_GetMagicNumber(void);
-PyAPI_FUNC(const char *) PyImport_GetMagicTag(void);
-PyAPI_FUNC(PyObject *) PyImport_ExecCodeModule(
- const char *name, /* UTF-8 encoded string */
- PyObject *co
- );
-PyAPI_FUNC(PyObject *) PyImport_ExecCodeModuleEx(
- const char *name, /* UTF-8 encoded string */
- PyObject *co,
- const char *pathname /* decoded from the filesystem encoding */
- );
-PyAPI_FUNC(PyObject *) PyImport_ExecCodeModuleWithPathnames(
- const char *name, /* UTF-8 encoded string */
- PyObject *co,
- const char *pathname, /* decoded from the filesystem encoding */
- const char *cpathname /* decoded from the filesystem encoding */
- );
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-PyAPI_FUNC(PyObject *) PyImport_ExecCodeModuleObject(
- PyObject *name,
- PyObject *co,
- PyObject *pathname,
- PyObject *cpathname
- );
-#endif
-PyAPI_FUNC(PyObject *) PyImport_GetModuleDict(void);
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03070000
-PyAPI_FUNC(PyObject *) PyImport_GetModule(PyObject *name);
-#endif
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-PyAPI_FUNC(PyObject *) PyImport_AddModuleObject(
- PyObject *name
- );
-#endif
-PyAPI_FUNC(PyObject *) PyImport_AddModule(
- const char *name /* UTF-8 encoded string */
- );
-PyAPI_FUNC(PyObject *) PyImport_ImportModule(
- const char *name /* UTF-8 encoded string */
- );
-PyAPI_FUNC(PyObject *) PyImport_ImportModuleNoBlock(
- const char *name /* UTF-8 encoded string */
- );
-PyAPI_FUNC(PyObject *) PyImport_ImportModuleLevel(
- const char *name, /* UTF-8 encoded string */
- PyObject *globals,
- PyObject *locals,
- PyObject *fromlist,
- int level
- );
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
-PyAPI_FUNC(PyObject *) PyImport_ImportModuleLevelObject(
- PyObject *name,
- PyObject *globals,
- PyObject *locals,
- PyObject *fromlist,
- int level
- );
-#endif
-
-#define PyImport_ImportModuleEx(n, g, l, f) \
- PyImport_ImportModuleLevel(n, g, l, f, 0)
-
-PyAPI_FUNC(PyObject *) PyImport_GetImporter(PyObject *path);
-PyAPI_FUNC(PyObject *) PyImport_Import(PyObject *name);
-PyAPI_FUNC(PyObject *) PyImport_ReloadModule(PyObject *m);
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-PyAPI_FUNC(int) PyImport_ImportFrozenModuleObject(
- PyObject *name
- );
-#endif
-PyAPI_FUNC(int) PyImport_ImportFrozenModule(
- const char *name /* UTF-8 encoded string */
- );
-
-PyAPI_FUNC(int) PyImport_AppendInittab(
- const char *name, /* ASCII encoded string */
- PyObject* (*initfunc)(void)
- );
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_IMPORT_H
-# include "cpython/import.h"
-# undef Py_CPYTHON_IMPORT_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_IMPORT_H */
diff --git a/include/python3.10/internal/pycore_abstract.h b/include/python3.10/internal/pycore_abstract.h
deleted file mode 100644
index b791bf2..0000000
--- a/include/python3.10/internal/pycore_abstract.h
+++ /dev/null
@@ -1,22 +0,0 @@
-#ifndef Py_INTERNAL_ABSTRACT_H
-#define Py_INTERNAL_ABSTRACT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-// Fast inlined version of PyIndex_Check()
-static inline int
-_PyIndex_Check(PyObject *obj)
-{
- PyNumberMethods *tp_as_number = Py_TYPE(obj)->tp_as_number;
- return (tp_as_number != NULL && tp_as_number->nb_index != NULL);
-}
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_ABSTRACT_H */
diff --git a/include/python3.10/internal/pycore_asdl.h b/include/python3.10/internal/pycore_asdl.h
deleted file mode 100644
index c0b07c3..0000000
--- a/include/python3.10/internal/pycore_asdl.h
+++ /dev/null
@@ -1,112 +0,0 @@
-#ifndef Py_INTERNAL_ASDL_H
-#define Py_INTERNAL_ASDL_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-#include "pycore_pyarena.h" // _PyArena_Malloc()
-
-typedef PyObject * identifier;
-typedef PyObject * string;
-typedef PyObject * object;
-typedef PyObject * constant;
-
-/* It would be nice if the code generated by asdl_c.py was completely
- independent of Python, but it is a goal the requires too much work
- at this stage. So, for example, I'll represent identifiers as
- interned Python strings.
-*/
-
-#define _ASDL_SEQ_HEAD \
- Py_ssize_t size; \
- void **elements;
-
-typedef struct {
- _ASDL_SEQ_HEAD
-} asdl_seq;
-
-typedef struct {
- _ASDL_SEQ_HEAD
- void *typed_elements[1];
-} asdl_generic_seq;
-
-typedef struct {
- _ASDL_SEQ_HEAD
- PyObject *typed_elements[1];
-} asdl_identifier_seq;
-
-typedef struct {
- _ASDL_SEQ_HEAD
- int typed_elements[1];
-} asdl_int_seq;
-
-asdl_generic_seq *_Py_asdl_generic_seq_new(Py_ssize_t size, PyArena *arena);
-asdl_identifier_seq *_Py_asdl_identifier_seq_new(Py_ssize_t size, PyArena *arena);
-asdl_int_seq *_Py_asdl_int_seq_new(Py_ssize_t size, PyArena *arena);
-
-
-#define GENERATE_ASDL_SEQ_CONSTRUCTOR(NAME, TYPE) \
-asdl_ ## NAME ## _seq *_Py_asdl_ ## NAME ## _seq_new(Py_ssize_t size, PyArena *arena) \
-{ \
- asdl_ ## NAME ## _seq *seq = NULL; \
- size_t n; \
- /* check size is sane */ \
- if (size < 0 || \
- (size && (((size_t)size - 1) > (SIZE_MAX / sizeof(void *))))) { \
- PyErr_NoMemory(); \
- return NULL; \
- } \
- n = (size ? (sizeof(TYPE *) * (size - 1)) : 0); \
- /* check if size can be added safely */ \
- if (n > SIZE_MAX - sizeof(asdl_ ## NAME ## _seq)) { \
- PyErr_NoMemory(); \
- return NULL; \
- } \
- n += sizeof(asdl_ ## NAME ## _seq); \
- seq = (asdl_ ## NAME ## _seq *)_PyArena_Malloc(arena, n); \
- if (!seq) { \
- PyErr_NoMemory(); \
- return NULL; \
- } \
- memset(seq, 0, n); \
- seq->size = size; \
- seq->elements = (void**)seq->typed_elements; \
- return seq; \
-}
-
-#define asdl_seq_GET_UNTYPED(S, I) (S)->elements[(I)]
-#define asdl_seq_GET(S, I) (S)->typed_elements[(I)]
-#define asdl_seq_LEN(S) ((S) == NULL ? 0 : (S)->size)
-
-#ifdef Py_DEBUG
-# define asdl_seq_SET(S, I, V) \
- do { \
- Py_ssize_t _asdl_i = (I); \
- assert((S) != NULL); \
- assert(0 <= _asdl_i && _asdl_i < (S)->size); \
- (S)->typed_elements[_asdl_i] = (V); \
- } while (0)
-#else
-# define asdl_seq_SET(S, I, V) (S)->typed_elements[I] = (V)
-#endif
-
-#ifdef Py_DEBUG
-# define asdl_seq_SET_UNTYPED(S, I, V) \
- do { \
- Py_ssize_t _asdl_i = (I); \
- assert((S) != NULL); \
- assert(0 <= _asdl_i && _asdl_i < (S)->size); \
- (S)->elements[_asdl_i] = (V); \
- } while (0)
-#else
-# define asdl_seq_SET_UNTYPED(S, I, V) (S)->elements[I] = (V)
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_ASDL_H */
diff --git a/include/python3.10/internal/pycore_ast.h b/include/python3.10/internal/pycore_ast.h
deleted file mode 100644
index ebb6a90..0000000
--- a/include/python3.10/internal/pycore_ast.h
+++ /dev/null
@@ -1,855 +0,0 @@
-// File automatically generated by Parser/asdl_c.py.
-
-#ifndef Py_INTERNAL_AST_H
-#define Py_INTERNAL_AST_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-#include "pycore_asdl.h"
-
-typedef struct _mod *mod_ty;
-
-typedef struct _stmt *stmt_ty;
-
-typedef struct _expr *expr_ty;
-
-typedef enum _expr_context { Load=1, Store=2, Del=3 } expr_context_ty;
-
-typedef enum _boolop { And=1, Or=2 } boolop_ty;
-
-typedef enum _operator { Add=1, Sub=2, Mult=3, MatMult=4, Div=5, Mod=6, Pow=7,
- LShift=8, RShift=9, BitOr=10, BitXor=11, BitAnd=12,
- FloorDiv=13 } operator_ty;
-
-typedef enum _unaryop { Invert=1, Not=2, UAdd=3, USub=4 } unaryop_ty;
-
-typedef enum _cmpop { Eq=1, NotEq=2, Lt=3, LtE=4, Gt=5, GtE=6, Is=7, IsNot=8,
- In=9, NotIn=10 } cmpop_ty;
-
-typedef struct _comprehension *comprehension_ty;
-
-typedef struct _excepthandler *excepthandler_ty;
-
-typedef struct _arguments *arguments_ty;
-
-typedef struct _arg *arg_ty;
-
-typedef struct _keyword *keyword_ty;
-
-typedef struct _alias *alias_ty;
-
-typedef struct _withitem *withitem_ty;
-
-typedef struct _match_case *match_case_ty;
-
-typedef struct _pattern *pattern_ty;
-
-typedef struct _type_ignore *type_ignore_ty;
-
-
-typedef struct {
- _ASDL_SEQ_HEAD
- mod_ty typed_elements[1];
-} asdl_mod_seq;
-
-asdl_mod_seq *_Py_asdl_mod_seq_new(Py_ssize_t size, PyArena *arena);
-
-typedef struct {
- _ASDL_SEQ_HEAD
- stmt_ty typed_elements[1];
-} asdl_stmt_seq;
-
-asdl_stmt_seq *_Py_asdl_stmt_seq_new(Py_ssize_t size, PyArena *arena);
-
-typedef struct {
- _ASDL_SEQ_HEAD
- expr_ty typed_elements[1];
-} asdl_expr_seq;
-
-asdl_expr_seq *_Py_asdl_expr_seq_new(Py_ssize_t size, PyArena *arena);
-
-typedef struct {
- _ASDL_SEQ_HEAD
- comprehension_ty typed_elements[1];
-} asdl_comprehension_seq;
-
-asdl_comprehension_seq *_Py_asdl_comprehension_seq_new(Py_ssize_t size, PyArena
- *arena);
-
-typedef struct {
- _ASDL_SEQ_HEAD
- excepthandler_ty typed_elements[1];
-} asdl_excepthandler_seq;
-
-asdl_excepthandler_seq *_Py_asdl_excepthandler_seq_new(Py_ssize_t size, PyArena
- *arena);
-
-typedef struct {
- _ASDL_SEQ_HEAD
- arguments_ty typed_elements[1];
-} asdl_arguments_seq;
-
-asdl_arguments_seq *_Py_asdl_arguments_seq_new(Py_ssize_t size, PyArena *arena);
-
-typedef struct {
- _ASDL_SEQ_HEAD
- arg_ty typed_elements[1];
-} asdl_arg_seq;
-
-asdl_arg_seq *_Py_asdl_arg_seq_new(Py_ssize_t size, PyArena *arena);
-
-typedef struct {
- _ASDL_SEQ_HEAD
- keyword_ty typed_elements[1];
-} asdl_keyword_seq;
-
-asdl_keyword_seq *_Py_asdl_keyword_seq_new(Py_ssize_t size, PyArena *arena);
-
-typedef struct {
- _ASDL_SEQ_HEAD
- alias_ty typed_elements[1];
-} asdl_alias_seq;
-
-asdl_alias_seq *_Py_asdl_alias_seq_new(Py_ssize_t size, PyArena *arena);
-
-typedef struct {
- _ASDL_SEQ_HEAD
- withitem_ty typed_elements[1];
-} asdl_withitem_seq;
-
-asdl_withitem_seq *_Py_asdl_withitem_seq_new(Py_ssize_t size, PyArena *arena);
-
-typedef struct {
- _ASDL_SEQ_HEAD
- match_case_ty typed_elements[1];
-} asdl_match_case_seq;
-
-asdl_match_case_seq *_Py_asdl_match_case_seq_new(Py_ssize_t size, PyArena
- *arena);
-
-typedef struct {
- _ASDL_SEQ_HEAD
- pattern_ty typed_elements[1];
-} asdl_pattern_seq;
-
-asdl_pattern_seq *_Py_asdl_pattern_seq_new(Py_ssize_t size, PyArena *arena);
-
-typedef struct {
- _ASDL_SEQ_HEAD
- type_ignore_ty typed_elements[1];
-} asdl_type_ignore_seq;
-
-asdl_type_ignore_seq *_Py_asdl_type_ignore_seq_new(Py_ssize_t size, PyArena
- *arena);
-
-
-enum _mod_kind {Module_kind=1, Interactive_kind=2, Expression_kind=3,
- FunctionType_kind=4};
-struct _mod {
- enum _mod_kind kind;
- union {
- struct {
- asdl_stmt_seq *body;
- asdl_type_ignore_seq *type_ignores;
- } Module;
-
- struct {
- asdl_stmt_seq *body;
- } Interactive;
-
- struct {
- expr_ty body;
- } Expression;
-
- struct {
- asdl_expr_seq *argtypes;
- expr_ty returns;
- } FunctionType;
-
- } v;
-};
-
-enum _stmt_kind {FunctionDef_kind=1, AsyncFunctionDef_kind=2, ClassDef_kind=3,
- Return_kind=4, Delete_kind=5, Assign_kind=6,
- AugAssign_kind=7, AnnAssign_kind=8, For_kind=9,
- AsyncFor_kind=10, While_kind=11, If_kind=12, With_kind=13,
- AsyncWith_kind=14, Match_kind=15, Raise_kind=16, Try_kind=17,
- Assert_kind=18, Import_kind=19, ImportFrom_kind=20,
- Global_kind=21, Nonlocal_kind=22, Expr_kind=23, Pass_kind=24,
- Break_kind=25, Continue_kind=26};
-struct _stmt {
- enum _stmt_kind kind;
- union {
- struct {
- identifier name;
- arguments_ty args;
- asdl_stmt_seq *body;
- asdl_expr_seq *decorator_list;
- expr_ty returns;
- string type_comment;
- } FunctionDef;
-
- struct {
- identifier name;
- arguments_ty args;
- asdl_stmt_seq *body;
- asdl_expr_seq *decorator_list;
- expr_ty returns;
- string type_comment;
- } AsyncFunctionDef;
-
- struct {
- identifier name;
- asdl_expr_seq *bases;
- asdl_keyword_seq *keywords;
- asdl_stmt_seq *body;
- asdl_expr_seq *decorator_list;
- } ClassDef;
-
- struct {
- expr_ty value;
- } Return;
-
- struct {
- asdl_expr_seq *targets;
- } Delete;
-
- struct {
- asdl_expr_seq *targets;
- expr_ty value;
- string type_comment;
- } Assign;
-
- struct {
- expr_ty target;
- operator_ty op;
- expr_ty value;
- } AugAssign;
-
- struct {
- expr_ty target;
- expr_ty annotation;
- expr_ty value;
- int simple;
- } AnnAssign;
-
- struct {
- expr_ty target;
- expr_ty iter;
- asdl_stmt_seq *body;
- asdl_stmt_seq *orelse;
- string type_comment;
- } For;
-
- struct {
- expr_ty target;
- expr_ty iter;
- asdl_stmt_seq *body;
- asdl_stmt_seq *orelse;
- string type_comment;
- } AsyncFor;
-
- struct {
- expr_ty test;
- asdl_stmt_seq *body;
- asdl_stmt_seq *orelse;
- } While;
-
- struct {
- expr_ty test;
- asdl_stmt_seq *body;
- asdl_stmt_seq *orelse;
- } If;
-
- struct {
- asdl_withitem_seq *items;
- asdl_stmt_seq *body;
- string type_comment;
- } With;
-
- struct {
- asdl_withitem_seq *items;
- asdl_stmt_seq *body;
- string type_comment;
- } AsyncWith;
-
- struct {
- expr_ty subject;
- asdl_match_case_seq *cases;
- } Match;
-
- struct {
- expr_ty exc;
- expr_ty cause;
- } Raise;
-
- struct {
- asdl_stmt_seq *body;
- asdl_excepthandler_seq *handlers;
- asdl_stmt_seq *orelse;
- asdl_stmt_seq *finalbody;
- } Try;
-
- struct {
- expr_ty test;
- expr_ty msg;
- } Assert;
-
- struct {
- asdl_alias_seq *names;
- } Import;
-
- struct {
- identifier module;
- asdl_alias_seq *names;
- int level;
- } ImportFrom;
-
- struct {
- asdl_identifier_seq *names;
- } Global;
-
- struct {
- asdl_identifier_seq *names;
- } Nonlocal;
-
- struct {
- expr_ty value;
- } Expr;
-
- } v;
- int lineno;
- int col_offset;
- int end_lineno;
- int end_col_offset;
-};
-
-enum _expr_kind {BoolOp_kind=1, NamedExpr_kind=2, BinOp_kind=3, UnaryOp_kind=4,
- Lambda_kind=5, IfExp_kind=6, Dict_kind=7, Set_kind=8,
- ListComp_kind=9, SetComp_kind=10, DictComp_kind=11,
- GeneratorExp_kind=12, Await_kind=13, Yield_kind=14,
- YieldFrom_kind=15, Compare_kind=16, Call_kind=17,
- FormattedValue_kind=18, JoinedStr_kind=19, Constant_kind=20,
- Attribute_kind=21, Subscript_kind=22, Starred_kind=23,
- Name_kind=24, List_kind=25, Tuple_kind=26, Slice_kind=27};
-struct _expr {
- enum _expr_kind kind;
- union {
- struct {
- boolop_ty op;
- asdl_expr_seq *values;
- } BoolOp;
-
- struct {
- expr_ty target;
- expr_ty value;
- } NamedExpr;
-
- struct {
- expr_ty left;
- operator_ty op;
- expr_ty right;
- } BinOp;
-
- struct {
- unaryop_ty op;
- expr_ty operand;
- } UnaryOp;
-
- struct {
- arguments_ty args;
- expr_ty body;
- } Lambda;
-
- struct {
- expr_ty test;
- expr_ty body;
- expr_ty orelse;
- } IfExp;
-
- struct {
- asdl_expr_seq *keys;
- asdl_expr_seq *values;
- } Dict;
-
- struct {
- asdl_expr_seq *elts;
- } Set;
-
- struct {
- expr_ty elt;
- asdl_comprehension_seq *generators;
- } ListComp;
-
- struct {
- expr_ty elt;
- asdl_comprehension_seq *generators;
- } SetComp;
-
- struct {
- expr_ty key;
- expr_ty value;
- asdl_comprehension_seq *generators;
- } DictComp;
-
- struct {
- expr_ty elt;
- asdl_comprehension_seq *generators;
- } GeneratorExp;
-
- struct {
- expr_ty value;
- } Await;
-
- struct {
- expr_ty value;
- } Yield;
-
- struct {
- expr_ty value;
- } YieldFrom;
-
- struct {
- expr_ty left;
- asdl_int_seq *ops;
- asdl_expr_seq *comparators;
- } Compare;
-
- struct {
- expr_ty func;
- asdl_expr_seq *args;
- asdl_keyword_seq *keywords;
- } Call;
-
- struct {
- expr_ty value;
- int conversion;
- expr_ty format_spec;
- } FormattedValue;
-
- struct {
- asdl_expr_seq *values;
- } JoinedStr;
-
- struct {
- constant value;
- string kind;
- } Constant;
-
- struct {
- expr_ty value;
- identifier attr;
- expr_context_ty ctx;
- } Attribute;
-
- struct {
- expr_ty value;
- expr_ty slice;
- expr_context_ty ctx;
- } Subscript;
-
- struct {
- expr_ty value;
- expr_context_ty ctx;
- } Starred;
-
- struct {
- identifier id;
- expr_context_ty ctx;
- } Name;
-
- struct {
- asdl_expr_seq *elts;
- expr_context_ty ctx;
- } List;
-
- struct {
- asdl_expr_seq *elts;
- expr_context_ty ctx;
- } Tuple;
-
- struct {
- expr_ty lower;
- expr_ty upper;
- expr_ty step;
- } Slice;
-
- } v;
- int lineno;
- int col_offset;
- int end_lineno;
- int end_col_offset;
-};
-
-struct _comprehension {
- expr_ty target;
- expr_ty iter;
- asdl_expr_seq *ifs;
- int is_async;
-};
-
-enum _excepthandler_kind {ExceptHandler_kind=1};
-struct _excepthandler {
- enum _excepthandler_kind kind;
- union {
- struct {
- expr_ty type;
- identifier name;
- asdl_stmt_seq *body;
- } ExceptHandler;
-
- } v;
- int lineno;
- int col_offset;
- int end_lineno;
- int end_col_offset;
-};
-
-struct _arguments {
- asdl_arg_seq *posonlyargs;
- asdl_arg_seq *args;
- arg_ty vararg;
- asdl_arg_seq *kwonlyargs;
- asdl_expr_seq *kw_defaults;
- arg_ty kwarg;
- asdl_expr_seq *defaults;
-};
-
-struct _arg {
- identifier arg;
- expr_ty annotation;
- string type_comment;
- int lineno;
- int col_offset;
- int end_lineno;
- int end_col_offset;
-};
-
-struct _keyword {
- identifier arg;
- expr_ty value;
- int lineno;
- int col_offset;
- int end_lineno;
- int end_col_offset;
-};
-
-struct _alias {
- identifier name;
- identifier asname;
- int lineno;
- int col_offset;
- int end_lineno;
- int end_col_offset;
-};
-
-struct _withitem {
- expr_ty context_expr;
- expr_ty optional_vars;
-};
-
-struct _match_case {
- pattern_ty pattern;
- expr_ty guard;
- asdl_stmt_seq *body;
-};
-
-enum _pattern_kind {MatchValue_kind=1, MatchSingleton_kind=2,
- MatchSequence_kind=3, MatchMapping_kind=4,
- MatchClass_kind=5, MatchStar_kind=6, MatchAs_kind=7,
- MatchOr_kind=8};
-struct _pattern {
- enum _pattern_kind kind;
- union {
- struct {
- expr_ty value;
- } MatchValue;
-
- struct {
- constant value;
- } MatchSingleton;
-
- struct {
- asdl_pattern_seq *patterns;
- } MatchSequence;
-
- struct {
- asdl_expr_seq *keys;
- asdl_pattern_seq *patterns;
- identifier rest;
- } MatchMapping;
-
- struct {
- expr_ty cls;
- asdl_pattern_seq *patterns;
- asdl_identifier_seq *kwd_attrs;
- asdl_pattern_seq *kwd_patterns;
- } MatchClass;
-
- struct {
- identifier name;
- } MatchStar;
-
- struct {
- pattern_ty pattern;
- identifier name;
- } MatchAs;
-
- struct {
- asdl_pattern_seq *patterns;
- } MatchOr;
-
- } v;
- int lineno;
- int col_offset;
- int end_lineno;
- int end_col_offset;
-};
-
-enum _type_ignore_kind {TypeIgnore_kind=1};
-struct _type_ignore {
- enum _type_ignore_kind kind;
- union {
- struct {
- int lineno;
- string tag;
- } TypeIgnore;
-
- } v;
-};
-
-
-// Note: these macros affect function definitions, not only call sites.
-mod_ty _PyAST_Module(asdl_stmt_seq * body, asdl_type_ignore_seq * type_ignores,
- PyArena *arena);
-mod_ty _PyAST_Interactive(asdl_stmt_seq * body, PyArena *arena);
-mod_ty _PyAST_Expression(expr_ty body, PyArena *arena);
-mod_ty _PyAST_FunctionType(asdl_expr_seq * argtypes, expr_ty returns, PyArena
- *arena);
-stmt_ty _PyAST_FunctionDef(identifier name, arguments_ty args, asdl_stmt_seq *
- body, asdl_expr_seq * decorator_list, expr_ty
- returns, string type_comment, int lineno, int
- col_offset, int end_lineno, int end_col_offset,
- PyArena *arena);
-stmt_ty _PyAST_AsyncFunctionDef(identifier name, arguments_ty args,
- asdl_stmt_seq * body, asdl_expr_seq *
- decorator_list, expr_ty returns, string
- type_comment, int lineno, int col_offset, int
- end_lineno, int end_col_offset, PyArena *arena);
-stmt_ty _PyAST_ClassDef(identifier name, asdl_expr_seq * bases,
- asdl_keyword_seq * keywords, asdl_stmt_seq * body,
- asdl_expr_seq * decorator_list, int lineno, int
- col_offset, int end_lineno, int end_col_offset, PyArena
- *arena);
-stmt_ty _PyAST_Return(expr_ty value, int lineno, int col_offset, int
- end_lineno, int end_col_offset, PyArena *arena);
-stmt_ty _PyAST_Delete(asdl_expr_seq * targets, int lineno, int col_offset, int
- end_lineno, int end_col_offset, PyArena *arena);
-stmt_ty _PyAST_Assign(asdl_expr_seq * targets, expr_ty value, string
- type_comment, int lineno, int col_offset, int end_lineno,
- int end_col_offset, PyArena *arena);
-stmt_ty _PyAST_AugAssign(expr_ty target, operator_ty op, expr_ty value, int
- lineno, int col_offset, int end_lineno, int
- end_col_offset, PyArena *arena);
-stmt_ty _PyAST_AnnAssign(expr_ty target, expr_ty annotation, expr_ty value, int
- simple, int lineno, int col_offset, int end_lineno,
- int end_col_offset, PyArena *arena);
-stmt_ty _PyAST_For(expr_ty target, expr_ty iter, asdl_stmt_seq * body,
- asdl_stmt_seq * orelse, string type_comment, int lineno, int
- col_offset, int end_lineno, int end_col_offset, PyArena
- *arena);
-stmt_ty _PyAST_AsyncFor(expr_ty target, expr_ty iter, asdl_stmt_seq * body,
- asdl_stmt_seq * orelse, string type_comment, int
- lineno, int col_offset, int end_lineno, int
- end_col_offset, PyArena *arena);
-stmt_ty _PyAST_While(expr_ty test, asdl_stmt_seq * body, asdl_stmt_seq *
- orelse, int lineno, int col_offset, int end_lineno, int
- end_col_offset, PyArena *arena);
-stmt_ty _PyAST_If(expr_ty test, asdl_stmt_seq * body, asdl_stmt_seq * orelse,
- int lineno, int col_offset, int end_lineno, int
- end_col_offset, PyArena *arena);
-stmt_ty _PyAST_With(asdl_withitem_seq * items, asdl_stmt_seq * body, string
- type_comment, int lineno, int col_offset, int end_lineno,
- int end_col_offset, PyArena *arena);
-stmt_ty _PyAST_AsyncWith(asdl_withitem_seq * items, asdl_stmt_seq * body,
- string type_comment, int lineno, int col_offset, int
- end_lineno, int end_col_offset, PyArena *arena);
-stmt_ty _PyAST_Match(expr_ty subject, asdl_match_case_seq * cases, int lineno,
- int col_offset, int end_lineno, int end_col_offset,
- PyArena *arena);
-stmt_ty _PyAST_Raise(expr_ty exc, expr_ty cause, int lineno, int col_offset,
- int end_lineno, int end_col_offset, PyArena *arena);
-stmt_ty _PyAST_Try(asdl_stmt_seq * body, asdl_excepthandler_seq * handlers,
- asdl_stmt_seq * orelse, asdl_stmt_seq * finalbody, int
- lineno, int col_offset, int end_lineno, int end_col_offset,
- PyArena *arena);
-stmt_ty _PyAST_Assert(expr_ty test, expr_ty msg, int lineno, int col_offset,
- int end_lineno, int end_col_offset, PyArena *arena);
-stmt_ty _PyAST_Import(asdl_alias_seq * names, int lineno, int col_offset, int
- end_lineno, int end_col_offset, PyArena *arena);
-stmt_ty _PyAST_ImportFrom(identifier module, asdl_alias_seq * names, int level,
- int lineno, int col_offset, int end_lineno, int
- end_col_offset, PyArena *arena);
-stmt_ty _PyAST_Global(asdl_identifier_seq * names, int lineno, int col_offset,
- int end_lineno, int end_col_offset, PyArena *arena);
-stmt_ty _PyAST_Nonlocal(asdl_identifier_seq * names, int lineno, int
- col_offset, int end_lineno, int end_col_offset, PyArena
- *arena);
-stmt_ty _PyAST_Expr(expr_ty value, int lineno, int col_offset, int end_lineno,
- int end_col_offset, PyArena *arena);
-stmt_ty _PyAST_Pass(int lineno, int col_offset, int end_lineno, int
- end_col_offset, PyArena *arena);
-stmt_ty _PyAST_Break(int lineno, int col_offset, int end_lineno, int
- end_col_offset, PyArena *arena);
-stmt_ty _PyAST_Continue(int lineno, int col_offset, int end_lineno, int
- end_col_offset, PyArena *arena);
-expr_ty _PyAST_BoolOp(boolop_ty op, asdl_expr_seq * values, int lineno, int
- col_offset, int end_lineno, int end_col_offset, PyArena
- *arena);
-expr_ty _PyAST_NamedExpr(expr_ty target, expr_ty value, int lineno, int
- col_offset, int end_lineno, int end_col_offset,
- PyArena *arena);
-expr_ty _PyAST_BinOp(expr_ty left, operator_ty op, expr_ty right, int lineno,
- int col_offset, int end_lineno, int end_col_offset,
- PyArena *arena);
-expr_ty _PyAST_UnaryOp(unaryop_ty op, expr_ty operand, int lineno, int
- col_offset, int end_lineno, int end_col_offset, PyArena
- *arena);
-expr_ty _PyAST_Lambda(arguments_ty args, expr_ty body, int lineno, int
- col_offset, int end_lineno, int end_col_offset, PyArena
- *arena);
-expr_ty _PyAST_IfExp(expr_ty test, expr_ty body, expr_ty orelse, int lineno,
- int col_offset, int end_lineno, int end_col_offset,
- PyArena *arena);
-expr_ty _PyAST_Dict(asdl_expr_seq * keys, asdl_expr_seq * values, int lineno,
- int col_offset, int end_lineno, int end_col_offset, PyArena
- *arena);
-expr_ty _PyAST_Set(asdl_expr_seq * elts, int lineno, int col_offset, int
- end_lineno, int end_col_offset, PyArena *arena);
-expr_ty _PyAST_ListComp(expr_ty elt, asdl_comprehension_seq * generators, int
- lineno, int col_offset, int end_lineno, int
- end_col_offset, PyArena *arena);
-expr_ty _PyAST_SetComp(expr_ty elt, asdl_comprehension_seq * generators, int
- lineno, int col_offset, int end_lineno, int
- end_col_offset, PyArena *arena);
-expr_ty _PyAST_DictComp(expr_ty key, expr_ty value, asdl_comprehension_seq *
- generators, int lineno, int col_offset, int end_lineno,
- int end_col_offset, PyArena *arena);
-expr_ty _PyAST_GeneratorExp(expr_ty elt, asdl_comprehension_seq * generators,
- int lineno, int col_offset, int end_lineno, int
- end_col_offset, PyArena *arena);
-expr_ty _PyAST_Await(expr_ty value, int lineno, int col_offset, int end_lineno,
- int end_col_offset, PyArena *arena);
-expr_ty _PyAST_Yield(expr_ty value, int lineno, int col_offset, int end_lineno,
- int end_col_offset, PyArena *arena);
-expr_ty _PyAST_YieldFrom(expr_ty value, int lineno, int col_offset, int
- end_lineno, int end_col_offset, PyArena *arena);
-expr_ty _PyAST_Compare(expr_ty left, asdl_int_seq * ops, asdl_expr_seq *
- comparators, int lineno, int col_offset, int end_lineno,
- int end_col_offset, PyArena *arena);
-expr_ty _PyAST_Call(expr_ty func, asdl_expr_seq * args, asdl_keyword_seq *
- keywords, int lineno, int col_offset, int end_lineno, int
- end_col_offset, PyArena *arena);
-expr_ty _PyAST_FormattedValue(expr_ty value, int conversion, expr_ty
- format_spec, int lineno, int col_offset, int
- end_lineno, int end_col_offset, PyArena *arena);
-expr_ty _PyAST_JoinedStr(asdl_expr_seq * values, int lineno, int col_offset,
- int end_lineno, int end_col_offset, PyArena *arena);
-expr_ty _PyAST_Constant(constant value, string kind, int lineno, int
- col_offset, int end_lineno, int end_col_offset, PyArena
- *arena);
-expr_ty _PyAST_Attribute(expr_ty value, identifier attr, expr_context_ty ctx,
- int lineno, int col_offset, int end_lineno, int
- end_col_offset, PyArena *arena);
-expr_ty _PyAST_Subscript(expr_ty value, expr_ty slice, expr_context_ty ctx, int
- lineno, int col_offset, int end_lineno, int
- end_col_offset, PyArena *arena);
-expr_ty _PyAST_Starred(expr_ty value, expr_context_ty ctx, int lineno, int
- col_offset, int end_lineno, int end_col_offset, PyArena
- *arena);
-expr_ty _PyAST_Name(identifier id, expr_context_ty ctx, int lineno, int
- col_offset, int end_lineno, int end_col_offset, PyArena
- *arena);
-expr_ty _PyAST_List(asdl_expr_seq * elts, expr_context_ty ctx, int lineno, int
- col_offset, int end_lineno, int end_col_offset, PyArena
- *arena);
-expr_ty _PyAST_Tuple(asdl_expr_seq * elts, expr_context_ty ctx, int lineno, int
- col_offset, int end_lineno, int end_col_offset, PyArena
- *arena);
-expr_ty _PyAST_Slice(expr_ty lower, expr_ty upper, expr_ty step, int lineno,
- int col_offset, int end_lineno, int end_col_offset,
- PyArena *arena);
-comprehension_ty _PyAST_comprehension(expr_ty target, expr_ty iter,
- asdl_expr_seq * ifs, int is_async,
- PyArena *arena);
-excepthandler_ty _PyAST_ExceptHandler(expr_ty type, identifier name,
- asdl_stmt_seq * body, int lineno, int
- col_offset, int end_lineno, int
- end_col_offset, PyArena *arena);
-arguments_ty _PyAST_arguments(asdl_arg_seq * posonlyargs, asdl_arg_seq * args,
- arg_ty vararg, asdl_arg_seq * kwonlyargs,
- asdl_expr_seq * kw_defaults, arg_ty kwarg,
- asdl_expr_seq * defaults, PyArena *arena);
-arg_ty _PyAST_arg(identifier arg, expr_ty annotation, string type_comment, int
- lineno, int col_offset, int end_lineno, int end_col_offset,
- PyArena *arena);
-keyword_ty _PyAST_keyword(identifier arg, expr_ty value, int lineno, int
- col_offset, int end_lineno, int end_col_offset,
- PyArena *arena);
-alias_ty _PyAST_alias(identifier name, identifier asname, int lineno, int
- col_offset, int end_lineno, int end_col_offset, PyArena
- *arena);
-withitem_ty _PyAST_withitem(expr_ty context_expr, expr_ty optional_vars,
- PyArena *arena);
-match_case_ty _PyAST_match_case(pattern_ty pattern, expr_ty guard,
- asdl_stmt_seq * body, PyArena *arena);
-pattern_ty _PyAST_MatchValue(expr_ty value, int lineno, int col_offset, int
- end_lineno, int end_col_offset, PyArena *arena);
-pattern_ty _PyAST_MatchSingleton(constant value, int lineno, int col_offset,
- int end_lineno, int end_col_offset, PyArena
- *arena);
-pattern_ty _PyAST_MatchSequence(asdl_pattern_seq * patterns, int lineno, int
- col_offset, int end_lineno, int end_col_offset,
- PyArena *arena);
-pattern_ty _PyAST_MatchMapping(asdl_expr_seq * keys, asdl_pattern_seq *
- patterns, identifier rest, int lineno, int
- col_offset, int end_lineno, int end_col_offset,
- PyArena *arena);
-pattern_ty _PyAST_MatchClass(expr_ty cls, asdl_pattern_seq * patterns,
- asdl_identifier_seq * kwd_attrs, asdl_pattern_seq
- * kwd_patterns, int lineno, int col_offset, int
- end_lineno, int end_col_offset, PyArena *arena);
-pattern_ty _PyAST_MatchStar(identifier name, int lineno, int col_offset, int
- end_lineno, int end_col_offset, PyArena *arena);
-pattern_ty _PyAST_MatchAs(pattern_ty pattern, identifier name, int lineno, int
- col_offset, int end_lineno, int end_col_offset,
- PyArena *arena);
-pattern_ty _PyAST_MatchOr(asdl_pattern_seq * patterns, int lineno, int
- col_offset, int end_lineno, int end_col_offset,
- PyArena *arena);
-type_ignore_ty _PyAST_TypeIgnore(int lineno, string tag, PyArena *arena);
-
-
-PyObject* PyAST_mod2obj(mod_ty t);
-mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode);
-int PyAST_Check(PyObject* obj);
-
-extern int _PyAST_Validate(mod_ty);
-
-/* _PyAST_ExprAsUnicode is defined in ast_unparse.c */
-extern PyObject* _PyAST_ExprAsUnicode(expr_ty);
-
-/* Return the borrowed reference to the first literal string in the
- sequence of statements or NULL if it doesn't start from a literal string.
- Doesn't set exception. */
-extern PyObject* _PyAST_GetDocString(asdl_stmt_seq *);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_AST_H */
diff --git a/include/python3.10/internal/pycore_ast_state.h b/include/python3.10/internal/pycore_ast_state.h
deleted file mode 100644
index 882cd09..0000000
--- a/include/python3.10/internal/pycore_ast_state.h
+++ /dev/null
@@ -1,255 +0,0 @@
-// File automatically generated by Parser/asdl_c.py.
-
-#ifndef Py_INTERNAL_AST_STATE_H
-#define Py_INTERNAL_AST_STATE_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-struct ast_state {
- int initialized;
- PyObject *AST_type;
- PyObject *Add_singleton;
- PyObject *Add_type;
- PyObject *And_singleton;
- PyObject *And_type;
- PyObject *AnnAssign_type;
- PyObject *Assert_type;
- PyObject *Assign_type;
- PyObject *AsyncFor_type;
- PyObject *AsyncFunctionDef_type;
- PyObject *AsyncWith_type;
- PyObject *Attribute_type;
- PyObject *AugAssign_type;
- PyObject *Await_type;
- PyObject *BinOp_type;
- PyObject *BitAnd_singleton;
- PyObject *BitAnd_type;
- PyObject *BitOr_singleton;
- PyObject *BitOr_type;
- PyObject *BitXor_singleton;
- PyObject *BitXor_type;
- PyObject *BoolOp_type;
- PyObject *Break_type;
- PyObject *Call_type;
- PyObject *ClassDef_type;
- PyObject *Compare_type;
- PyObject *Constant_type;
- PyObject *Continue_type;
- PyObject *Del_singleton;
- PyObject *Del_type;
- PyObject *Delete_type;
- PyObject *DictComp_type;
- PyObject *Dict_type;
- PyObject *Div_singleton;
- PyObject *Div_type;
- PyObject *Eq_singleton;
- PyObject *Eq_type;
- PyObject *ExceptHandler_type;
- PyObject *Expr_type;
- PyObject *Expression_type;
- PyObject *FloorDiv_singleton;
- PyObject *FloorDiv_type;
- PyObject *For_type;
- PyObject *FormattedValue_type;
- PyObject *FunctionDef_type;
- PyObject *FunctionType_type;
- PyObject *GeneratorExp_type;
- PyObject *Global_type;
- PyObject *GtE_singleton;
- PyObject *GtE_type;
- PyObject *Gt_singleton;
- PyObject *Gt_type;
- PyObject *IfExp_type;
- PyObject *If_type;
- PyObject *ImportFrom_type;
- PyObject *Import_type;
- PyObject *In_singleton;
- PyObject *In_type;
- PyObject *Interactive_type;
- PyObject *Invert_singleton;
- PyObject *Invert_type;
- PyObject *IsNot_singleton;
- PyObject *IsNot_type;
- PyObject *Is_singleton;
- PyObject *Is_type;
- PyObject *JoinedStr_type;
- PyObject *LShift_singleton;
- PyObject *LShift_type;
- PyObject *Lambda_type;
- PyObject *ListComp_type;
- PyObject *List_type;
- PyObject *Load_singleton;
- PyObject *Load_type;
- PyObject *LtE_singleton;
- PyObject *LtE_type;
- PyObject *Lt_singleton;
- PyObject *Lt_type;
- PyObject *MatMult_singleton;
- PyObject *MatMult_type;
- PyObject *MatchAs_type;
- PyObject *MatchClass_type;
- PyObject *MatchMapping_type;
- PyObject *MatchOr_type;
- PyObject *MatchSequence_type;
- PyObject *MatchSingleton_type;
- PyObject *MatchStar_type;
- PyObject *MatchValue_type;
- PyObject *Match_type;
- PyObject *Mod_singleton;
- PyObject *Mod_type;
- PyObject *Module_type;
- PyObject *Mult_singleton;
- PyObject *Mult_type;
- PyObject *Name_type;
- PyObject *NamedExpr_type;
- PyObject *Nonlocal_type;
- PyObject *NotEq_singleton;
- PyObject *NotEq_type;
- PyObject *NotIn_singleton;
- PyObject *NotIn_type;
- PyObject *Not_singleton;
- PyObject *Not_type;
- PyObject *Or_singleton;
- PyObject *Or_type;
- PyObject *Pass_type;
- PyObject *Pow_singleton;
- PyObject *Pow_type;
- PyObject *RShift_singleton;
- PyObject *RShift_type;
- PyObject *Raise_type;
- PyObject *Return_type;
- PyObject *SetComp_type;
- PyObject *Set_type;
- PyObject *Slice_type;
- PyObject *Starred_type;
- PyObject *Store_singleton;
- PyObject *Store_type;
- PyObject *Sub_singleton;
- PyObject *Sub_type;
- PyObject *Subscript_type;
- PyObject *Try_type;
- PyObject *Tuple_type;
- PyObject *TypeIgnore_type;
- PyObject *UAdd_singleton;
- PyObject *UAdd_type;
- PyObject *USub_singleton;
- PyObject *USub_type;
- PyObject *UnaryOp_type;
- PyObject *While_type;
- PyObject *With_type;
- PyObject *YieldFrom_type;
- PyObject *Yield_type;
- PyObject *__dict__;
- PyObject *__doc__;
- PyObject *__match_args__;
- PyObject *__module__;
- PyObject *_attributes;
- PyObject *_fields;
- PyObject *alias_type;
- PyObject *annotation;
- PyObject *arg;
- PyObject *arg_type;
- PyObject *args;
- PyObject *argtypes;
- PyObject *arguments_type;
- PyObject *asname;
- PyObject *ast;
- PyObject *attr;
- PyObject *bases;
- PyObject *body;
- PyObject *boolop_type;
- PyObject *cases;
- PyObject *cause;
- PyObject *cls;
- PyObject *cmpop_type;
- PyObject *col_offset;
- PyObject *comparators;
- PyObject *comprehension_type;
- PyObject *context_expr;
- PyObject *conversion;
- PyObject *ctx;
- PyObject *decorator_list;
- PyObject *defaults;
- PyObject *elt;
- PyObject *elts;
- PyObject *end_col_offset;
- PyObject *end_lineno;
- PyObject *exc;
- PyObject *excepthandler_type;
- PyObject *expr_context_type;
- PyObject *expr_type;
- PyObject *finalbody;
- PyObject *format_spec;
- PyObject *func;
- PyObject *generators;
- PyObject *guard;
- PyObject *handlers;
- PyObject *id;
- PyObject *ifs;
- PyObject *is_async;
- PyObject *items;
- PyObject *iter;
- PyObject *key;
- PyObject *keys;
- PyObject *keyword_type;
- PyObject *keywords;
- PyObject *kind;
- PyObject *kw_defaults;
- PyObject *kwarg;
- PyObject *kwd_attrs;
- PyObject *kwd_patterns;
- PyObject *kwonlyargs;
- PyObject *left;
- PyObject *level;
- PyObject *lineno;
- PyObject *lower;
- PyObject *match_case_type;
- PyObject *mod_type;
- PyObject *module;
- PyObject *msg;
- PyObject *name;
- PyObject *names;
- PyObject *op;
- PyObject *operand;
- PyObject *operator_type;
- PyObject *ops;
- PyObject *optional_vars;
- PyObject *orelse;
- PyObject *pattern;
- PyObject *pattern_type;
- PyObject *patterns;
- PyObject *posonlyargs;
- PyObject *rest;
- PyObject *returns;
- PyObject *right;
- PyObject *simple;
- PyObject *slice;
- PyObject *step;
- PyObject *stmt_type;
- PyObject *subject;
- PyObject *tag;
- PyObject *target;
- PyObject *targets;
- PyObject *test;
- PyObject *type;
- PyObject *type_comment;
- PyObject *type_ignore_type;
- PyObject *type_ignores;
- PyObject *unaryop_type;
- PyObject *upper;
- PyObject *value;
- PyObject *values;
- PyObject *vararg;
- PyObject *withitem_type;
-};
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_AST_STATE_H */
-
diff --git a/include/python3.10/internal/pycore_atomic.h b/include/python3.10/internal/pycore_atomic.h
deleted file mode 100644
index 3d42e54..0000000
--- a/include/python3.10/internal/pycore_atomic.h
+++ /dev/null
@@ -1,557 +0,0 @@
-#ifndef Py_ATOMIC_H
-#define Py_ATOMIC_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-#include "dynamic_annotations.h" /* _Py_ANNOTATE_MEMORY_ORDER */
-#include "pyconfig.h"
-
-#ifdef HAVE_STD_ATOMIC
-# include <stdatomic.h>
-#endif
-
-
-#if defined(_MSC_VER)
-#include <intrin.h>
-#if defined(_M_IX86) || defined(_M_X64)
-# include <immintrin.h>
-#endif
-#endif
-
-/* This is modeled after the atomics interface from C1x, according to
- * the draft at
- * http://www.open-std.org/JTC1/SC22/wg14/www/docs/n1425.pdf.
- * Operations and types are named the same except with a _Py_ prefix
- * and have the same semantics.
- *
- * Beware, the implementations here are deep magic.
- */
-
-#if defined(HAVE_STD_ATOMIC)
-
-typedef enum _Py_memory_order {
- _Py_memory_order_relaxed = memory_order_relaxed,
- _Py_memory_order_acquire = memory_order_acquire,
- _Py_memory_order_release = memory_order_release,
- _Py_memory_order_acq_rel = memory_order_acq_rel,
- _Py_memory_order_seq_cst = memory_order_seq_cst
-} _Py_memory_order;
-
-typedef struct _Py_atomic_address {
- atomic_uintptr_t _value;
-} _Py_atomic_address;
-
-typedef struct _Py_atomic_int {
- atomic_int _value;
-} _Py_atomic_int;
-
-#define _Py_atomic_signal_fence(/*memory_order*/ ORDER) \
- atomic_signal_fence(ORDER)
-
-#define _Py_atomic_thread_fence(/*memory_order*/ ORDER) \
- atomic_thread_fence(ORDER)
-
-#define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \
- atomic_store_explicit(&((ATOMIC_VAL)->_value), NEW_VAL, ORDER)
-
-#define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \
- atomic_load_explicit(&((ATOMIC_VAL)->_value), ORDER)
-
-// Use builtin atomic operations in GCC >= 4.7 and clang
-#elif defined(HAVE_BUILTIN_ATOMIC)
-
-typedef enum _Py_memory_order {
- _Py_memory_order_relaxed = __ATOMIC_RELAXED,
- _Py_memory_order_acquire = __ATOMIC_ACQUIRE,
- _Py_memory_order_release = __ATOMIC_RELEASE,
- _Py_memory_order_acq_rel = __ATOMIC_ACQ_REL,
- _Py_memory_order_seq_cst = __ATOMIC_SEQ_CST
-} _Py_memory_order;
-
-typedef struct _Py_atomic_address {
- uintptr_t _value;
-} _Py_atomic_address;
-
-typedef struct _Py_atomic_int {
- int _value;
-} _Py_atomic_int;
-
-#define _Py_atomic_signal_fence(/*memory_order*/ ORDER) \
- __atomic_signal_fence(ORDER)
-
-#define _Py_atomic_thread_fence(/*memory_order*/ ORDER) \
- __atomic_thread_fence(ORDER)
-
-#define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \
- (assert((ORDER) == __ATOMIC_RELAXED \
- || (ORDER) == __ATOMIC_SEQ_CST \
- || (ORDER) == __ATOMIC_RELEASE), \
- __atomic_store_n(&((ATOMIC_VAL)->_value), NEW_VAL, ORDER))
-
-#define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \
- (assert((ORDER) == __ATOMIC_RELAXED \
- || (ORDER) == __ATOMIC_SEQ_CST \
- || (ORDER) == __ATOMIC_ACQUIRE \
- || (ORDER) == __ATOMIC_CONSUME), \
- __atomic_load_n(&((ATOMIC_VAL)->_value), ORDER))
-
-/* Only support GCC (for expression statements) and x86 (for simple
- * atomic semantics) and MSVC x86/x64/ARM */
-#elif defined(__GNUC__) && (defined(__i386__) || defined(__amd64))
-typedef enum _Py_memory_order {
- _Py_memory_order_relaxed,
- _Py_memory_order_acquire,
- _Py_memory_order_release,
- _Py_memory_order_acq_rel,
- _Py_memory_order_seq_cst
-} _Py_memory_order;
-
-typedef struct _Py_atomic_address {
- uintptr_t _value;
-} _Py_atomic_address;
-
-typedef struct _Py_atomic_int {
- int _value;
-} _Py_atomic_int;
-
-
-static __inline__ void
-_Py_atomic_signal_fence(_Py_memory_order order)
-{
- if (order != _Py_memory_order_relaxed)
- __asm__ volatile("":::"memory");
-}
-
-static __inline__ void
-_Py_atomic_thread_fence(_Py_memory_order order)
-{
- if (order != _Py_memory_order_relaxed)
- __asm__ volatile("mfence":::"memory");
-}
-
-/* Tell the race checker about this operation's effects. */
-static __inline__ void
-_Py_ANNOTATE_MEMORY_ORDER(const volatile void *address, _Py_memory_order order)
-{
- (void)address; /* shut up -Wunused-parameter */
- switch(order) {
- case _Py_memory_order_release:
- case _Py_memory_order_acq_rel:
- case _Py_memory_order_seq_cst:
- _Py_ANNOTATE_HAPPENS_BEFORE(address);
- break;
- case _Py_memory_order_relaxed:
- case _Py_memory_order_acquire:
- break;
- }
- switch(order) {
- case _Py_memory_order_acquire:
- case _Py_memory_order_acq_rel:
- case _Py_memory_order_seq_cst:
- _Py_ANNOTATE_HAPPENS_AFTER(address);
- break;
- case _Py_memory_order_relaxed:
- case _Py_memory_order_release:
- break;
- }
-}
-
-#define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \
- __extension__ ({ \
- __typeof__(ATOMIC_VAL) atomic_val = ATOMIC_VAL; \
- __typeof__(atomic_val->_value) new_val = NEW_VAL;\
- volatile __typeof__(new_val) *volatile_data = &atomic_val->_value; \
- _Py_memory_order order = ORDER; \
- _Py_ANNOTATE_MEMORY_ORDER(atomic_val, order); \
- \
- /* Perform the operation. */ \
- _Py_ANNOTATE_IGNORE_WRITES_BEGIN(); \
- switch(order) { \
- case _Py_memory_order_release: \
- _Py_atomic_signal_fence(_Py_memory_order_release); \
- /* fallthrough */ \
- case _Py_memory_order_relaxed: \
- *volatile_data = new_val; \
- break; \
- \
- case _Py_memory_order_acquire: \
- case _Py_memory_order_acq_rel: \
- case _Py_memory_order_seq_cst: \
- __asm__ volatile("xchg %0, %1" \
- : "+r"(new_val) \
- : "m"(atomic_val->_value) \
- : "memory"); \
- break; \
- } \
- _Py_ANNOTATE_IGNORE_WRITES_END(); \
- })
-
-#define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \
- __extension__ ({ \
- __typeof__(ATOMIC_VAL) atomic_val = ATOMIC_VAL; \
- __typeof__(atomic_val->_value) result; \
- volatile __typeof__(result) *volatile_data = &atomic_val->_value; \
- _Py_memory_order order = ORDER; \
- _Py_ANNOTATE_MEMORY_ORDER(atomic_val, order); \
- \
- /* Perform the operation. */ \
- _Py_ANNOTATE_IGNORE_READS_BEGIN(); \
- switch(order) { \
- case _Py_memory_order_release: \
- case _Py_memory_order_acq_rel: \
- case _Py_memory_order_seq_cst: \
- /* Loads on x86 are not releases by default, so need a */ \
- /* thread fence. */ \
- _Py_atomic_thread_fence(_Py_memory_order_release); \
- break; \
- default: \
- /* No fence */ \
- break; \
- } \
- result = *volatile_data; \
- switch(order) { \
- case _Py_memory_order_acquire: \
- case _Py_memory_order_acq_rel: \
- case _Py_memory_order_seq_cst: \
- /* Loads on x86 are automatically acquire operations so */ \
- /* can get by with just a compiler fence. */ \
- _Py_atomic_signal_fence(_Py_memory_order_acquire); \
- break; \
- default: \
- /* No fence */ \
- break; \
- } \
- _Py_ANNOTATE_IGNORE_READS_END(); \
- result; \
- })
-
-#elif defined(_MSC_VER)
-/* _Interlocked* functions provide a full memory barrier and are therefore
- enough for acq_rel and seq_cst. If the HLE variants aren't available
- in hardware they will fall back to a full memory barrier as well.
-
- This might affect performance but likely only in some very specific and
- hard to meassure scenario.
-*/
-#if defined(_M_IX86) || defined(_M_X64)
-typedef enum _Py_memory_order {
- _Py_memory_order_relaxed,
- _Py_memory_order_acquire,
- _Py_memory_order_release,
- _Py_memory_order_acq_rel,
- _Py_memory_order_seq_cst
-} _Py_memory_order;
-
-typedef struct _Py_atomic_address {
- volatile uintptr_t _value;
-} _Py_atomic_address;
-
-typedef struct _Py_atomic_int {
- volatile int _value;
-} _Py_atomic_int;
-
-
-#if defined(_M_X64)
-#define _Py_atomic_store_64bit(ATOMIC_VAL, NEW_VAL, ORDER) \
- switch (ORDER) { \
- case _Py_memory_order_acquire: \
- _InterlockedExchange64_HLEAcquire((__int64 volatile*)&((ATOMIC_VAL)->_value), (__int64)(NEW_VAL)); \
- break; \
- case _Py_memory_order_release: \
- _InterlockedExchange64_HLERelease((__int64 volatile*)&((ATOMIC_VAL)->_value), (__int64)(NEW_VAL)); \
- break; \
- default: \
- _InterlockedExchange64((__int64 volatile*)&((ATOMIC_VAL)->_value), (__int64)(NEW_VAL)); \
- break; \
- }
-#else
-#define _Py_atomic_store_64bit(ATOMIC_VAL, NEW_VAL, ORDER) ((void)0);
-#endif
-
-#define _Py_atomic_store_32bit(ATOMIC_VAL, NEW_VAL, ORDER) \
- switch (ORDER) { \
- case _Py_memory_order_acquire: \
- _InterlockedExchange_HLEAcquire((volatile long*)&((ATOMIC_VAL)->_value), (int)(NEW_VAL)); \
- break; \
- case _Py_memory_order_release: \
- _InterlockedExchange_HLERelease((volatile long*)&((ATOMIC_VAL)->_value), (int)(NEW_VAL)); \
- break; \
- default: \
- _InterlockedExchange((volatile long*)&((ATOMIC_VAL)->_value), (int)(NEW_VAL)); \
- break; \
- }
-
-#if defined(_M_X64)
-/* This has to be an intptr_t for now.
- gil_created() uses -1 as a sentinel value, if this returns
- a uintptr_t it will do an unsigned compare and crash
-*/
-inline intptr_t _Py_atomic_load_64bit_impl(volatile uintptr_t* value, int order) {
- __int64 old;
- switch (order) {
- case _Py_memory_order_acquire:
- {
- do {
- old = *value;
- } while(_InterlockedCompareExchange64_HLEAcquire((volatile __int64*)value, old, old) != old);
- break;
- }
- case _Py_memory_order_release:
- {
- do {
- old = *value;
- } while(_InterlockedCompareExchange64_HLERelease((volatile __int64*)value, old, old) != old);
- break;
- }
- case _Py_memory_order_relaxed:
- old = *value;
- break;
- default:
- {
- do {
- old = *value;
- } while(_InterlockedCompareExchange64((volatile __int64*)value, old, old) != old);
- break;
- }
- }
- return old;
-}
-
-#define _Py_atomic_load_64bit(ATOMIC_VAL, ORDER) \
- _Py_atomic_load_64bit_impl((volatile uintptr_t*)&((ATOMIC_VAL)->_value), (ORDER))
-
-#else
-#define _Py_atomic_load_64bit(ATOMIC_VAL, ORDER) ((ATOMIC_VAL)->_value)
-#endif
-
-inline int _Py_atomic_load_32bit_impl(volatile int* value, int order) {
- long old;
- switch (order) {
- case _Py_memory_order_acquire:
- {
- do {
- old = *value;
- } while(_InterlockedCompareExchange_HLEAcquire((volatile long*)value, old, old) != old);
- break;
- }
- case _Py_memory_order_release:
- {
- do {
- old = *value;
- } while(_InterlockedCompareExchange_HLERelease((volatile long*)value, old, old) != old);
- break;
- }
- case _Py_memory_order_relaxed:
- old = *value;
- break;
- default:
- {
- do {
- old = *value;
- } while(_InterlockedCompareExchange((volatile long*)value, old, old) != old);
- break;
- }
- }
- return old;
-}
-
-#define _Py_atomic_load_32bit(ATOMIC_VAL, ORDER) \
- _Py_atomic_load_32bit_impl((volatile int*)&((ATOMIC_VAL)->_value), (ORDER))
-
-#define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \
- if (sizeof((ATOMIC_VAL)->_value) == 8) { \
- _Py_atomic_store_64bit((ATOMIC_VAL), NEW_VAL, ORDER) } else { \
- _Py_atomic_store_32bit((ATOMIC_VAL), NEW_VAL, ORDER) }
-
-#define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \
- ( \
- sizeof((ATOMIC_VAL)->_value) == 8 ? \
- _Py_atomic_load_64bit((ATOMIC_VAL), ORDER) : \
- _Py_atomic_load_32bit((ATOMIC_VAL), ORDER) \
- )
-#elif defined(_M_ARM) || defined(_M_ARM64)
-typedef enum _Py_memory_order {
- _Py_memory_order_relaxed,
- _Py_memory_order_acquire,
- _Py_memory_order_release,
- _Py_memory_order_acq_rel,
- _Py_memory_order_seq_cst
-} _Py_memory_order;
-
-typedef struct _Py_atomic_address {
- volatile uintptr_t _value;
-} _Py_atomic_address;
-
-typedef struct _Py_atomic_int {
- volatile int _value;
-} _Py_atomic_int;
-
-
-#if defined(_M_ARM64)
-#define _Py_atomic_store_64bit(ATOMIC_VAL, NEW_VAL, ORDER) \
- switch (ORDER) { \
- case _Py_memory_order_acquire: \
- _InterlockedExchange64_acq((__int64 volatile*)&((ATOMIC_VAL)->_value), (__int64)NEW_VAL); \
- break; \
- case _Py_memory_order_release: \
- _InterlockedExchange64_rel((__int64 volatile*)&((ATOMIC_VAL)->_value), (__int64)NEW_VAL); \
- break; \
- default: \
- _InterlockedExchange64((__int64 volatile*)&((ATOMIC_VAL)->_value), (__int64)NEW_VAL); \
- break; \
- }
-#else
-#define _Py_atomic_store_64bit(ATOMIC_VAL, NEW_VAL, ORDER) ((void)0);
-#endif
-
-#define _Py_atomic_store_32bit(ATOMIC_VAL, NEW_VAL, ORDER) \
- switch (ORDER) { \
- case _Py_memory_order_acquire: \
- _InterlockedExchange_acq((volatile long*)&((ATOMIC_VAL)->_value), (int)NEW_VAL); \
- break; \
- case _Py_memory_order_release: \
- _InterlockedExchange_rel((volatile long*)&((ATOMIC_VAL)->_value), (int)NEW_VAL); \
- break; \
- default: \
- _InterlockedExchange((volatile long*)&((ATOMIC_VAL)->_value), (int)NEW_VAL); \
- break; \
- }
-
-#if defined(_M_ARM64)
-/* This has to be an intptr_t for now.
- gil_created() uses -1 as a sentinel value, if this returns
- a uintptr_t it will do an unsigned compare and crash
-*/
-inline intptr_t _Py_atomic_load_64bit_impl(volatile uintptr_t* value, int order) {
- uintptr_t old;
- switch (order) {
- case _Py_memory_order_acquire:
- {
- do {
- old = *value;
- } while(_InterlockedCompareExchange64_acq(value, old, old) != old);
- break;
- }
- case _Py_memory_order_release:
- {
- do {
- old = *value;
- } while(_InterlockedCompareExchange64_rel(value, old, old) != old);
- break;
- }
- case _Py_memory_order_relaxed:
- old = *value;
- break;
- default:
- {
- do {
- old = *value;
- } while(_InterlockedCompareExchange64(value, old, old) != old);
- break;
- }
- }
- return old;
-}
-
-#define _Py_atomic_load_64bit(ATOMIC_VAL, ORDER) \
- _Py_atomic_load_64bit_impl((volatile uintptr_t*)&((ATOMIC_VAL)->_value), (ORDER))
-
-#else
-#define _Py_atomic_load_64bit(ATOMIC_VAL, ORDER) ((ATOMIC_VAL)->_value)
-#endif
-
-inline int _Py_atomic_load_32bit_impl(volatile int* value, int order) {
- int old;
- switch (order) {
- case _Py_memory_order_acquire:
- {
- do {
- old = *value;
- } while(_InterlockedCompareExchange_acq(value, old, old) != old);
- break;
- }
- case _Py_memory_order_release:
- {
- do {
- old = *value;
- } while(_InterlockedCompareExchange_rel(value, old, old) != old);
- break;
- }
- case _Py_memory_order_relaxed:
- old = *value;
- break;
- default:
- {
- do {
- old = *value;
- } while(_InterlockedCompareExchange(value, old, old) != old);
- break;
- }
- }
- return old;
-}
-
-#define _Py_atomic_load_32bit(ATOMIC_VAL, ORDER) \
- _Py_atomic_load_32bit_impl((volatile int*)&((ATOMIC_VAL)->_value), (ORDER))
-
-#define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \
- if (sizeof((ATOMIC_VAL)->_value) == 8) { \
- _Py_atomic_store_64bit((ATOMIC_VAL), (NEW_VAL), (ORDER)) } else { \
- _Py_atomic_store_32bit((ATOMIC_VAL), (NEW_VAL), (ORDER)) }
-
-#define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \
- ( \
- sizeof((ATOMIC_VAL)->_value) == 8 ? \
- _Py_atomic_load_64bit((ATOMIC_VAL), (ORDER)) : \
- _Py_atomic_load_32bit((ATOMIC_VAL), (ORDER)) \
- )
-#endif
-#else /* !gcc x86 !_msc_ver */
-typedef enum _Py_memory_order {
- _Py_memory_order_relaxed,
- _Py_memory_order_acquire,
- _Py_memory_order_release,
- _Py_memory_order_acq_rel,
- _Py_memory_order_seq_cst
-} _Py_memory_order;
-
-typedef struct _Py_atomic_address {
- uintptr_t _value;
-} _Py_atomic_address;
-
-typedef struct _Py_atomic_int {
- int _value;
-} _Py_atomic_int;
-/* Fall back to other compilers and processors by assuming that simple
- volatile accesses are atomic. This is false, so people should port
- this. */
-#define _Py_atomic_signal_fence(/*memory_order*/ ORDER) ((void)0)
-#define _Py_atomic_thread_fence(/*memory_order*/ ORDER) ((void)0)
-#define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \
- ((ATOMIC_VAL)->_value = NEW_VAL)
-#define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \
- ((ATOMIC_VAL)->_value)
-#endif
-
-/* Standardized shortcuts. */
-#define _Py_atomic_store(ATOMIC_VAL, NEW_VAL) \
- _Py_atomic_store_explicit((ATOMIC_VAL), (NEW_VAL), _Py_memory_order_seq_cst)
-#define _Py_atomic_load(ATOMIC_VAL) \
- _Py_atomic_load_explicit((ATOMIC_VAL), _Py_memory_order_seq_cst)
-
-/* Python-local extensions */
-
-#define _Py_atomic_store_relaxed(ATOMIC_VAL, NEW_VAL) \
- _Py_atomic_store_explicit((ATOMIC_VAL), (NEW_VAL), _Py_memory_order_relaxed)
-#define _Py_atomic_load_relaxed(ATOMIC_VAL) \
- _Py_atomic_load_explicit((ATOMIC_VAL), _Py_memory_order_relaxed)
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* Py_ATOMIC_H */
diff --git a/include/python3.10/internal/pycore_bitutils.h b/include/python3.10/internal/pycore_bitutils.h
deleted file mode 100644
index e4aa7a3..0000000
--- a/include/python3.10/internal/pycore_bitutils.h
+++ /dev/null
@@ -1,176 +0,0 @@
-/* Bit and bytes utilities.
-
- Bytes swap functions, reverse order of bytes:
-
- - _Py_bswap16(uint16_t)
- - _Py_bswap32(uint32_t)
- - _Py_bswap64(uint64_t)
-*/
-
-#ifndef Py_INTERNAL_BITUTILS_H
-#define Py_INTERNAL_BITUTILS_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-#if defined(__GNUC__) \
- && ((__GNUC__ >= 5) || (__GNUC__ == 4) && (__GNUC_MINOR__ >= 8))
- /* __builtin_bswap16() is available since GCC 4.8,
- __builtin_bswap32() is available since GCC 4.3,
- __builtin_bswap64() is available since GCC 4.3. */
-# define _PY_HAVE_BUILTIN_BSWAP
-#endif
-
-#ifdef _MSC_VER
- /* Get _byteswap_ushort(), _byteswap_ulong(), _byteswap_uint64() */
-# include <intrin.h>
-#endif
-
-static inline uint16_t
-_Py_bswap16(uint16_t word)
-{
-#if defined(_PY_HAVE_BUILTIN_BSWAP) || _Py__has_builtin(__builtin_bswap16)
- return __builtin_bswap16(word);
-#elif defined(_MSC_VER)
- Py_BUILD_ASSERT(sizeof(word) == sizeof(unsigned short));
- return _byteswap_ushort(word);
-#else
- // Portable implementation which doesn't rely on circular bit shift
- return ( ((word & UINT16_C(0x00FF)) << 8)
- | ((word & UINT16_C(0xFF00)) >> 8));
-#endif
-}
-
-static inline uint32_t
-_Py_bswap32(uint32_t word)
-{
-#if defined(_PY_HAVE_BUILTIN_BSWAP) || _Py__has_builtin(__builtin_bswap32)
- return __builtin_bswap32(word);
-#elif defined(_MSC_VER)
- Py_BUILD_ASSERT(sizeof(word) == sizeof(unsigned long));
- return _byteswap_ulong(word);
-#else
- // Portable implementation which doesn't rely on circular bit shift
- return ( ((word & UINT32_C(0x000000FF)) << 24)
- | ((word & UINT32_C(0x0000FF00)) << 8)
- | ((word & UINT32_C(0x00FF0000)) >> 8)
- | ((word & UINT32_C(0xFF000000)) >> 24));
-#endif
-}
-
-static inline uint64_t
-_Py_bswap64(uint64_t word)
-{
-#if defined(_PY_HAVE_BUILTIN_BSWAP) || _Py__has_builtin(__builtin_bswap64)
- return __builtin_bswap64(word);
-#elif defined(_MSC_VER)
- return _byteswap_uint64(word);
-#else
- // Portable implementation which doesn't rely on circular bit shift
- return ( ((word & UINT64_C(0x00000000000000FF)) << 56)
- | ((word & UINT64_C(0x000000000000FF00)) << 40)
- | ((word & UINT64_C(0x0000000000FF0000)) << 24)
- | ((word & UINT64_C(0x00000000FF000000)) << 8)
- | ((word & UINT64_C(0x000000FF00000000)) >> 8)
- | ((word & UINT64_C(0x0000FF0000000000)) >> 24)
- | ((word & UINT64_C(0x00FF000000000000)) >> 40)
- | ((word & UINT64_C(0xFF00000000000000)) >> 56));
-#endif
-}
-
-
-// Population count: count the number of 1's in 'x'
-// (number of bits set to 1), also known as the hamming weight.
-//
-// Implementation note. CPUID is not used, to test if x86 POPCNT instruction
-// can be used, to keep the implementation simple. For example, Visual Studio
-// __popcnt() is not used this reason. The clang and GCC builtin function can
-// use the x86 POPCNT instruction if the target architecture has SSE4a or
-// newer.
-static inline int
-_Py_popcount32(uint32_t x)
-{
-#if (defined(__clang__) || defined(__GNUC__))
-
-#if SIZEOF_INT >= 4
- Py_BUILD_ASSERT(sizeof(x) <= sizeof(unsigned int));
- return __builtin_popcount(x);
-#else
- // The C standard guarantees that unsigned long will always be big enough
- // to hold a uint32_t value without losing information.
- Py_BUILD_ASSERT(sizeof(x) <= sizeof(unsigned long));
- return __builtin_popcountl(x);
-#endif
-
-#else
- // 32-bit SWAR (SIMD Within A Register) popcount
-
- // Binary: 0 1 0 1 ...
- const uint32_t M1 = 0x55555555;
- // Binary: 00 11 00 11. ..
- const uint32_t M2 = 0x33333333;
- // Binary: 0000 1111 0000 1111 ...
- const uint32_t M4 = 0x0F0F0F0F;
- // 256**4 + 256**3 + 256**2 + 256**1
- const uint32_t SUM = 0x01010101;
-
- // Put count of each 2 bits into those 2 bits
- x = x - ((x >> 1) & M1);
- // Put count of each 4 bits into those 4 bits
- x = (x & M2) + ((x >> 2) & M2);
- // Put count of each 8 bits into those 8 bits
- x = (x + (x >> 4)) & M4;
- // Sum of the 4 byte counts
- return (uint32_t)((uint64_t)x * (uint64_t)SUM) >> 24;
-#endif
-}
-
-
-// Return the index of the most significant 1 bit in 'x'. This is the smallest
-// integer k such that x < 2**k. Equivalent to floor(log2(x)) + 1 for x != 0.
-static inline int
-_Py_bit_length(unsigned long x)
-{
-#if (defined(__clang__) || defined(__GNUC__))
- if (x != 0) {
- // __builtin_clzl() is available since GCC 3.4.
- // Undefined behavior for x == 0.
- return (int)sizeof(unsigned long) * 8 - __builtin_clzl(x);
- }
- else {
- return 0;
- }
-#elif defined(_MSC_VER)
- // _BitScanReverse() is documented to search 32 bits.
- Py_BUILD_ASSERT(sizeof(unsigned long) <= 4);
- unsigned long msb;
- if (_BitScanReverse(&msb, x)) {
- return (int)msb + 1;
- }
- else {
- return 0;
- }
-#else
- const int BIT_LENGTH_TABLE[32] = {
- 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
- 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
- };
- int msb = 0;
- while (x >= 32) {
- msb += 6;
- x >>= 6;
- }
- msb += BIT_LENGTH_TABLE[x];
- return msb;
-#endif
-}
-
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_BITUTILS_H */
diff --git a/include/python3.10/internal/pycore_call.h b/include/python3.10/internal/pycore_call.h
deleted file mode 100644
index f7d856a..0000000
--- a/include/python3.10/internal/pycore_call.h
+++ /dev/null
@@ -1,39 +0,0 @@
-#ifndef Py_INTERNAL_CALL_H
-#define Py_INTERNAL_CALL_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-PyAPI_FUNC(PyObject *) _PyObject_Call_Prepend(
- PyThreadState *tstate,
- PyObject *callable,
- PyObject *obj,
- PyObject *args,
- PyObject *kwargs);
-
-PyAPI_FUNC(PyObject *) _PyObject_FastCallDictTstate(
- PyThreadState *tstate,
- PyObject *callable,
- PyObject *const *args,
- size_t nargsf,
- PyObject *kwargs);
-
-PyAPI_FUNC(PyObject *) _PyObject_Call(
- PyThreadState *tstate,
- PyObject *callable,
- PyObject *args,
- PyObject *kwargs);
-
-static inline PyObject *
-_PyObject_CallNoArgTstate(PyThreadState *tstate, PyObject *func) {
- return _PyObject_VectorcallTstate(tstate, func, NULL, 0, NULL);
-}
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_CALL_H */
diff --git a/include/python3.10/internal/pycore_ceval.h b/include/python3.10/internal/pycore_ceval.h
deleted file mode 100644
index f573c3e..0000000
--- a/include/python3.10/internal/pycore_ceval.h
+++ /dev/null
@@ -1,114 +0,0 @@
-#ifndef Py_INTERNAL_CEVAL_H
-#define Py_INTERNAL_CEVAL_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-/* Forward declarations */
-struct pyruntimestate;
-struct _ceval_runtime_state;
-
-#include "pycore_interp.h" /* PyInterpreterState.eval_frame */
-
-extern void _Py_FinishPendingCalls(PyThreadState *tstate);
-extern void _PyEval_InitRuntimeState(struct _ceval_runtime_state *);
-extern int _PyEval_InitState(struct _ceval_state *ceval);
-extern void _PyEval_FiniState(struct _ceval_state *ceval);
-PyAPI_FUNC(void) _PyEval_SignalReceived(PyInterpreterState *interp);
-PyAPI_FUNC(int) _PyEval_AddPendingCall(
- PyInterpreterState *interp,
- int (*func)(void *),
- void *arg);
-PyAPI_FUNC(void) _PyEval_SignalAsyncExc(PyInterpreterState *interp);
-#ifdef HAVE_FORK
-extern PyStatus _PyEval_ReInitThreads(PyThreadState *tstate);
-#endif
-PyAPI_FUNC(void) _PyEval_SetCoroutineOriginTrackingDepth(
- PyThreadState *tstate,
- int new_depth);
-
-void _PyEval_Fini(void);
-
-
-extern PyObject* _PyEval_GetBuiltins(PyThreadState *tstate);
-extern PyObject *_PyEval_BuiltinsFromGlobals(
- PyThreadState *tstate,
- PyObject *globals);
-
-
-static inline PyObject*
-_PyEval_EvalFrame(PyThreadState *tstate, PyFrameObject *f, int throwflag)
-{
- return tstate->interp->eval_frame(tstate, f, throwflag);
-}
-
-extern PyObject *
-_PyEval_Vector(PyThreadState *tstate,
- PyFrameConstructor *desc, PyObject *locals,
- PyObject* const* args, size_t argcount,
- PyObject *kwnames);
-
-#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
-extern int _PyEval_ThreadsInitialized(PyInterpreterState *interp);
-#else
-extern int _PyEval_ThreadsInitialized(struct pyruntimestate *runtime);
-#endif
-extern PyStatus _PyEval_InitGIL(PyThreadState *tstate);
-extern void _PyEval_FiniGIL(PyInterpreterState *interp);
-
-extern void _PyEval_ReleaseLock(PyThreadState *tstate);
-
-extern void _PyEval_DeactivateOpCache(void);
-
-
-/* --- _Py_EnterRecursiveCall() ----------------------------------------- */
-
-#ifdef USE_STACKCHECK
-/* With USE_STACKCHECK macro defined, trigger stack checks in
- _Py_CheckRecursiveCall() on every 64th call to Py_EnterRecursiveCall. */
-static inline int _Py_MakeRecCheck(PyThreadState *tstate) {
- return (++tstate->recursion_depth > tstate->interp->ceval.recursion_limit
- || ++tstate->stackcheck_counter > 64);
-}
-#else
-static inline int _Py_MakeRecCheck(PyThreadState *tstate) {
- return (++tstate->recursion_depth > tstate->interp->ceval.recursion_limit);
-}
-#endif
-
-PyAPI_FUNC(int) _Py_CheckRecursiveCall(
- PyThreadState *tstate,
- const char *where);
-
-static inline int _Py_EnterRecursiveCall(PyThreadState *tstate,
- const char *where) {
- return (_Py_MakeRecCheck(tstate) && _Py_CheckRecursiveCall(tstate, where));
-}
-
-static inline int _Py_EnterRecursiveCall_inline(const char *where) {
- PyThreadState *tstate = PyThreadState_GET();
- return _Py_EnterRecursiveCall(tstate, where);
-}
-
-#define Py_EnterRecursiveCall(where) _Py_EnterRecursiveCall_inline(where)
-
-static inline void _Py_LeaveRecursiveCall(PyThreadState *tstate) {
- tstate->recursion_depth--;
-}
-
-static inline void _Py_LeaveRecursiveCall_inline(void) {
- PyThreadState *tstate = PyThreadState_GET();
- _Py_LeaveRecursiveCall(tstate);
-}
-
-#define Py_LeaveRecursiveCall() _Py_LeaveRecursiveCall_inline()
-
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_CEVAL_H */
diff --git a/include/python3.10/internal/pycore_code.h b/include/python3.10/internal/pycore_code.h
deleted file mode 100644
index 8ff1863..0000000
--- a/include/python3.10/internal/pycore_code.h
+++ /dev/null
@@ -1,34 +0,0 @@
-#ifndef Py_INTERNAL_CODE_H
-#define Py_INTERNAL_CODE_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef struct {
- PyObject *ptr; /* Cached pointer (borrowed reference) */
- uint64_t globals_ver; /* ma_version of global dict */
- uint64_t builtins_ver; /* ma_version of builtin dict */
-} _PyOpcache_LoadGlobal;
-
-typedef struct {
- PyTypeObject *type;
- Py_ssize_t hint;
- unsigned int tp_version_tag;
-} _PyOpCodeOpt_LoadAttr;
-
-struct _PyOpcache {
- union {
- _PyOpcache_LoadGlobal lg;
- _PyOpCodeOpt_LoadAttr la;
- } u;
- char optimized;
-};
-
-/* Private API */
-int _PyCode_InitOpcache(PyCodeObject *co);
-
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_CODE_H */
diff --git a/include/python3.10/internal/pycore_condvar.h b/include/python3.10/internal/pycore_condvar.h
deleted file mode 100644
index 8b89d70..0000000
--- a/include/python3.10/internal/pycore_condvar.h
+++ /dev/null
@@ -1,95 +0,0 @@
-#ifndef Py_INTERNAL_CONDVAR_H
-#define Py_INTERNAL_CONDVAR_H
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-#ifndef _POSIX_THREADS
-/* This means pthreads are not implemented in libc headers, hence the macro
- not present in unistd.h. But they still can be implemented as an external
- library (e.g. gnu pth in pthread emulation) */
-# ifdef HAVE_PTHREAD_H
-# include <pthread.h> /* _POSIX_THREADS */
-# endif
-#endif
-
-#ifdef _POSIX_THREADS
-/*
- * POSIX support
- */
-#define Py_HAVE_CONDVAR
-
-#include <pthread.h>
-
-#define PyMUTEX_T pthread_mutex_t
-#define PyCOND_T pthread_cond_t
-
-#elif defined(NT_THREADS)
-/*
- * Windows (XP, 2003 server and later, as well as (hopefully) CE) support
- *
- * Emulated condition variables ones that work with XP and later, plus
- * example native support on VISTA and onwards.
- */
-#define Py_HAVE_CONDVAR
-
-/* include windows if it hasn't been done before */
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-
-/* options */
-/* non-emulated condition variables are provided for those that want
- * to target Windows Vista. Modify this macro to enable them.
- */
-#ifndef _PY_EMULATED_WIN_CV
-#define _PY_EMULATED_WIN_CV 1 /* use emulated condition variables */
-#endif
-
-/* fall back to emulation if not targeting Vista */
-#if !defined NTDDI_VISTA || NTDDI_VERSION < NTDDI_VISTA
-#undef _PY_EMULATED_WIN_CV
-#define _PY_EMULATED_WIN_CV 1
-#endif
-
-#if _PY_EMULATED_WIN_CV
-
-typedef CRITICAL_SECTION PyMUTEX_T;
-
-/* The ConditionVariable object. From XP onwards it is easily emulated
- with a Semaphore.
- Semaphores are available on Windows XP (2003 server) and later.
- We use a Semaphore rather than an auto-reset event, because although
- an auto-resent event might appear to solve the lost-wakeup bug (race
- condition between releasing the outer lock and waiting) because it
- maintains state even though a wait hasn't happened, there is still
- a lost wakeup problem if more than one thread are interrupted in the
- critical place. A semaphore solves that, because its state is
- counted, not Boolean.
- Because it is ok to signal a condition variable with no one
- waiting, we need to keep track of the number of
- waiting threads. Otherwise, the semaphore's state could rise
- without bound. This also helps reduce the number of "spurious wakeups"
- that would otherwise happen.
- */
-
-typedef struct _PyCOND_T
-{
- HANDLE sem;
- int waiting; /* to allow PyCOND_SIGNAL to be a no-op */
-} PyCOND_T;
-
-#else /* !_PY_EMULATED_WIN_CV */
-
-/* Use native Win7 primitives if build target is Win7 or higher */
-
-/* SRWLOCK is faster and better than CriticalSection */
-typedef SRWLOCK PyMUTEX_T;
-
-typedef CONDITION_VARIABLE PyCOND_T;
-
-#endif /* _PY_EMULATED_WIN_CV */
-
-#endif /* _POSIX_THREADS, NT_THREADS */
-
-#endif /* Py_INTERNAL_CONDVAR_H */
diff --git a/include/python3.10/internal/pycore_context.h b/include/python3.10/internal/pycore_context.h
deleted file mode 100644
index a482dd4..0000000
--- a/include/python3.10/internal/pycore_context.h
+++ /dev/null
@@ -1,42 +0,0 @@
-#ifndef Py_INTERNAL_CONTEXT_H
-#define Py_INTERNAL_CONTEXT_H
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-#include "pycore_hamt.h" /* PyHamtObject */
-
-struct _pycontextobject {
- PyObject_HEAD
- PyContext *ctx_prev;
- PyHamtObject *ctx_vars;
- PyObject *ctx_weakreflist;
- int ctx_entered;
-};
-
-
-struct _pycontextvarobject {
- PyObject_HEAD
- PyObject *var_name;
- PyObject *var_default;
- PyObject *var_cached;
- uint64_t var_cached_tsid;
- uint64_t var_cached_tsver;
- Py_hash_t var_hash;
-};
-
-
-struct _pycontexttokenobject {
- PyObject_HEAD
- PyContext *tok_ctx;
- PyContextVar *tok_var;
- PyObject *tok_oldval;
- int tok_used;
-};
-
-
-int _PyContext_Init(void);
-void _PyContext_Fini(PyInterpreterState *interp);
-
-#endif /* !Py_INTERNAL_CONTEXT_H */
diff --git a/include/python3.10/internal/pycore_dtoa.h b/include/python3.10/internal/pycore_dtoa.h
deleted file mode 100644
index 3faf8cf..0000000
--- a/include/python3.10/internal/pycore_dtoa.h
+++ /dev/null
@@ -1,23 +0,0 @@
-#ifndef PY_NO_SHORT_FLOAT_REPR
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-/* These functions are used by modules compiled as C extension like math:
- they must be exported. */
-
-PyAPI_FUNC(double) _Py_dg_strtod(const char *str, char **ptr);
-PyAPI_FUNC(char *) _Py_dg_dtoa(double d, int mode, int ndigits,
- int *decpt, int *sign, char **rve);
-PyAPI_FUNC(void) _Py_dg_freedtoa(char *s);
-PyAPI_FUNC(double) _Py_dg_stdnan(int sign);
-PyAPI_FUNC(double) _Py_dg_infinity(int sign);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !PY_NO_SHORT_FLOAT_REPR */
diff --git a/include/python3.10/internal/pycore_fileutils.h b/include/python3.10/internal/pycore_fileutils.h
deleted file mode 100644
index c1c9244..0000000
--- a/include/python3.10/internal/pycore_fileutils.h
+++ /dev/null
@@ -1,71 +0,0 @@
-#ifndef Py_INTERNAL_FILEUTILS_H
-#define Py_INTERNAL_FILEUTILS_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "Py_BUILD_CORE must be defined to include this header"
-#endif
-
-#include <locale.h> /* struct lconv */
-
-PyAPI_DATA(int) _Py_HasFileSystemDefaultEncodeErrors;
-
-PyAPI_FUNC(int) _Py_DecodeUTF8Ex(
- const char *arg,
- Py_ssize_t arglen,
- wchar_t **wstr,
- size_t *wlen,
- const char **reason,
- _Py_error_handler errors);
-
-PyAPI_FUNC(int) _Py_EncodeUTF8Ex(
- const wchar_t *text,
- char **str,
- size_t *error_pos,
- const char **reason,
- int raw_malloc,
- _Py_error_handler errors);
-
-PyAPI_FUNC(wchar_t*) _Py_DecodeUTF8_surrogateescape(
- const char *arg,
- Py_ssize_t arglen,
- size_t *wlen);
-
-PyAPI_FUNC(int) _Py_GetForceASCII(void);
-
-/* Reset "force ASCII" mode (if it was initialized).
-
- This function should be called when Python changes the LC_CTYPE locale,
- so the "force ASCII" mode can be detected again on the new locale
- encoding. */
-PyAPI_FUNC(void) _Py_ResetForceASCII(void);
-
-
-PyAPI_FUNC(int) _Py_GetLocaleconvNumeric(
- struct lconv *lc,
- PyObject **decimal_point,
- PyObject **thousands_sep);
-
-PyAPI_FUNC(void) _Py_closerange(int first, int last);
-
-PyAPI_FUNC(wchar_t*) _Py_GetLocaleEncoding(void);
-PyAPI_FUNC(PyObject*) _Py_GetLocaleEncodingObject(void);
-
-#ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
-extern int _Py_LocaleUsesNonUnicodeWchar(void);
-
-extern wchar_t* _Py_DecodeNonUnicodeWchar(
- const wchar_t* native,
- Py_ssize_t size);
-
-extern int _Py_EncodeNonUnicodeWchar_InPlace(
- wchar_t* unicode,
- Py_ssize_t size);
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_FILEUTILS_H */
diff --git a/include/python3.10/internal/pycore_gc.h b/include/python3.10/internal/pycore_gc.h
deleted file mode 100644
index 9db4a47..0000000
--- a/include/python3.10/internal/pycore_gc.h
+++ /dev/null
@@ -1,181 +0,0 @@
-#ifndef Py_INTERNAL_GC_H
-#define Py_INTERNAL_GC_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-/* GC information is stored BEFORE the object structure. */
-typedef struct {
- // Pointer to next object in the list.
- // 0 means the object is not tracked
- uintptr_t _gc_next;
-
- // Pointer to previous object in the list.
- // Lowest two bits are used for flags documented later.
- uintptr_t _gc_prev;
-} PyGC_Head;
-
-#define _Py_AS_GC(o) ((PyGC_Head *)(o)-1)
-
-/* True if the object is currently tracked by the GC. */
-#define _PyObject_GC_IS_TRACKED(o) (_Py_AS_GC(o)->_gc_next != 0)
-
-/* True if the object may be tracked by the GC in the future, or already is.
- This can be useful to implement some optimizations. */
-#define _PyObject_GC_MAY_BE_TRACKED(obj) \
- (PyObject_IS_GC(obj) && \
- (!PyTuple_CheckExact(obj) || _PyObject_GC_IS_TRACKED(obj)))
-
-
-/* Bit flags for _gc_prev */
-/* Bit 0 is set when tp_finalize is called */
-#define _PyGC_PREV_MASK_FINALIZED (1)
-/* Bit 1 is set when the object is in generation which is GCed currently. */
-#define _PyGC_PREV_MASK_COLLECTING (2)
-/* The (N-2) most significant bits contain the real address. */
-#define _PyGC_PREV_SHIFT (2)
-#define _PyGC_PREV_MASK (((uintptr_t) -1) << _PyGC_PREV_SHIFT)
-
-// Lowest bit of _gc_next is used for flags only in GC.
-// But it is always 0 for normal code.
-#define _PyGCHead_NEXT(g) ((PyGC_Head*)(g)->_gc_next)
-#define _PyGCHead_SET_NEXT(g, p) ((g)->_gc_next = (uintptr_t)(p))
-
-// Lowest two bits of _gc_prev is used for _PyGC_PREV_MASK_* flags.
-#define _PyGCHead_PREV(g) ((PyGC_Head*)((g)->_gc_prev & _PyGC_PREV_MASK))
-#define _PyGCHead_SET_PREV(g, p) do { \
- assert(((uintptr_t)p & ~_PyGC_PREV_MASK) == 0); \
- (g)->_gc_prev = ((g)->_gc_prev & ~_PyGC_PREV_MASK) \
- | ((uintptr_t)(p)); \
- } while (0)
-
-#define _PyGCHead_FINALIZED(g) \
- (((g)->_gc_prev & _PyGC_PREV_MASK_FINALIZED) != 0)
-#define _PyGCHead_SET_FINALIZED(g) \
- ((g)->_gc_prev |= _PyGC_PREV_MASK_FINALIZED)
-
-#define _PyGC_FINALIZED(o) \
- _PyGCHead_FINALIZED(_Py_AS_GC(o))
-#define _PyGC_SET_FINALIZED(o) \
- _PyGCHead_SET_FINALIZED(_Py_AS_GC(o))
-
-
-/* GC runtime state */
-
-/* If we change this, we need to change the default value in the
- signature of gc.collect. */
-#define NUM_GENERATIONS 3
-/*
- NOTE: about untracking of mutable objects.
-
- Certain types of container cannot participate in a reference cycle, and
- so do not need to be tracked by the garbage collector. Untracking these
- objects reduces the cost of garbage collections. However, determining
- which objects may be untracked is not free, and the costs must be
- weighed against the benefits for garbage collection.
-
- There are two possible strategies for when to untrack a container:
-
- i) When the container is created.
- ii) When the container is examined by the garbage collector.
-
- Tuples containing only immutable objects (integers, strings etc, and
- recursively, tuples of immutable objects) do not need to be tracked.
- The interpreter creates a large number of tuples, many of which will
- not survive until garbage collection. It is therefore not worthwhile
- to untrack eligible tuples at creation time.
-
- Instead, all tuples except the empty tuple are tracked when created.
- During garbage collection it is determined whether any surviving tuples
- can be untracked. A tuple can be untracked if all of its contents are
- already not tracked. Tuples are examined for untracking in all garbage
- collection cycles. It may take more than one cycle to untrack a tuple.
-
- Dictionaries containing only immutable objects also do not need to be
- tracked. Dictionaries are untracked when created. If a tracked item is
- inserted into a dictionary (either as a key or value), the dictionary
- becomes tracked. During a full garbage collection (all generations),
- the collector will untrack any dictionaries whose contents are not
- tracked.
-
- The module provides the python function is_tracked(obj), which returns
- the CURRENT tracking status of the object. Subsequent garbage
- collections may change the tracking status of the object.
-
- Untracking of certain containers was introduced in issue #4688, and
- the algorithm was refined in response to issue #14775.
-*/
-
-struct gc_generation {
- PyGC_Head head;
- int threshold; /* collection threshold */
- int count; /* count of allocations or collections of younger
- generations */
-};
-
-/* Running stats per generation */
-struct gc_generation_stats {
- /* total number of collections */
- Py_ssize_t collections;
- /* total number of collected objects */
- Py_ssize_t collected;
- /* total number of uncollectable objects (put into gc.garbage) */
- Py_ssize_t uncollectable;
-};
-
-struct _gc_runtime_state {
- /* List of objects that still need to be cleaned up, singly linked
- * via their gc headers' gc_prev pointers. */
- PyObject *trash_delete_later;
- /* Current call-stack depth of tp_dealloc calls. */
- int trash_delete_nesting;
-
- int enabled;
- int debug;
- /* linked lists of container objects */
- struct gc_generation generations[NUM_GENERATIONS];
- PyGC_Head *generation0;
- /* a permanent generation which won't be collected */
- struct gc_generation permanent_generation;
- struct gc_generation_stats generation_stats[NUM_GENERATIONS];
- /* true if we are currently running the collector */
- int collecting;
- /* list of uncollectable objects */
- PyObject *garbage;
- /* a list of callbacks to be invoked when collection is performed */
- PyObject *callbacks;
- /* This is the number of objects that survived the last full
- collection. It approximates the number of long lived objects
- tracked by the GC.
-
- (by "full collection", we mean a collection of the oldest
- generation). */
- Py_ssize_t long_lived_total;
- /* This is the number of objects that survived all "non-full"
- collections, and are awaiting to undergo a full collection for
- the first time. */
- Py_ssize_t long_lived_pending;
-};
-
-extern void _PyGC_InitState(struct _gc_runtime_state *);
-
-extern Py_ssize_t _PyGC_CollectNoFail(PyThreadState *tstate);
-
-
-// Functions to clear types free lists
-extern void _PyFrame_ClearFreeList(PyInterpreterState *interp);
-extern void _PyTuple_ClearFreeList(PyInterpreterState *interp);
-extern void _PyFloat_ClearFreeList(PyInterpreterState *interp);
-extern void _PyList_ClearFreeList(PyInterpreterState *interp);
-extern void _PyDict_ClearFreeList(PyInterpreterState *interp);
-extern void _PyAsyncGen_ClearFreeLists(PyInterpreterState *interp);
-extern void _PyContext_ClearFreeList(PyInterpreterState *interp);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_GC_H */
diff --git a/include/python3.10/internal/pycore_hamt.h b/include/python3.10/internal/pycore_hamt.h
deleted file mode 100644
index aaf6559..0000000
--- a/include/python3.10/internal/pycore_hamt.h
+++ /dev/null
@@ -1,116 +0,0 @@
-#ifndef Py_INTERNAL_HAMT_H
-#define Py_INTERNAL_HAMT_H
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-#define _Py_HAMT_MAX_TREE_DEPTH 7
-
-
-#define PyHamt_Check(o) Py_IS_TYPE(o, &_PyHamt_Type)
-
-
-/* Abstract tree node. */
-typedef struct {
- PyObject_HEAD
-} PyHamtNode;
-
-
-/* An HAMT immutable mapping collection. */
-typedef struct {
- PyObject_HEAD
- PyHamtNode *h_root;
- PyObject *h_weakreflist;
- Py_ssize_t h_count;
-} PyHamtObject;
-
-
-/* A struct to hold the state of depth-first traverse of the tree.
-
- HAMT is an immutable collection. Iterators will hold a strong reference
- to it, and every node in the HAMT has strong references to its children.
-
- So for iterators, we can implement zero allocations and zero reference
- inc/dec depth-first iteration.
-
- - i_nodes: an array of seven pointers to tree nodes
- - i_level: the current node in i_nodes
- - i_pos: an array of positions within nodes in i_nodes.
-*/
-typedef struct {
- PyHamtNode *i_nodes[_Py_HAMT_MAX_TREE_DEPTH];
- Py_ssize_t i_pos[_Py_HAMT_MAX_TREE_DEPTH];
- int8_t i_level;
-} PyHamtIteratorState;
-
-
-/* Base iterator object.
-
- Contains the iteration state, a pointer to the HAMT tree,
- and a pointer to the 'yield function'. The latter is a simple
- function that returns a key/value tuple for the 'Items' iterator,
- just a key for the 'Keys' iterator, and a value for the 'Values'
- iterator.
-*/
-typedef struct {
- PyObject_HEAD
- PyHamtObject *hi_obj;
- PyHamtIteratorState hi_iter;
- binaryfunc hi_yield;
-} PyHamtIterator;
-
-
-PyAPI_DATA(PyTypeObject) _PyHamt_Type;
-PyAPI_DATA(PyTypeObject) _PyHamt_ArrayNode_Type;
-PyAPI_DATA(PyTypeObject) _PyHamt_BitmapNode_Type;
-PyAPI_DATA(PyTypeObject) _PyHamt_CollisionNode_Type;
-PyAPI_DATA(PyTypeObject) _PyHamtKeys_Type;
-PyAPI_DATA(PyTypeObject) _PyHamtValues_Type;
-PyAPI_DATA(PyTypeObject) _PyHamtItems_Type;
-
-
-/* Create a new HAMT immutable mapping. */
-PyHamtObject * _PyHamt_New(void);
-
-/* Return a new collection based on "o", but with an additional
- key/val pair. */
-PyHamtObject * _PyHamt_Assoc(PyHamtObject *o, PyObject *key, PyObject *val);
-
-/* Return a new collection based on "o", but without "key". */
-PyHamtObject * _PyHamt_Without(PyHamtObject *o, PyObject *key);
-
-/* Find "key" in the "o" collection.
-
- Return:
- - -1: An error occurred.
- - 0: "key" wasn't found in "o".
- - 1: "key" is in "o"; "*val" is set to its value (a borrowed ref).
-*/
-int _PyHamt_Find(PyHamtObject *o, PyObject *key, PyObject **val);
-
-/* Check if "v" is equal to "w".
-
- Return:
- - 0: v != w
- - 1: v == w
- - -1: An error occurred.
-*/
-int _PyHamt_Eq(PyHamtObject *v, PyHamtObject *w);
-
-/* Return the size of "o"; equivalent of "len(o)". */
-Py_ssize_t _PyHamt_Len(PyHamtObject *o);
-
-/* Return a Keys iterator over "o". */
-PyObject * _PyHamt_NewIterKeys(PyHamtObject *o);
-
-/* Return a Values iterator over "o". */
-PyObject * _PyHamt_NewIterValues(PyHamtObject *o);
-
-/* Return a Items iterator over "o". */
-PyObject * _PyHamt_NewIterItems(PyHamtObject *o);
-
-int _PyHamt_Init(void);
-void _PyHamt_Fini(void);
-
-#endif /* !Py_INTERNAL_HAMT_H */
diff --git a/include/python3.10/internal/pycore_import.h b/include/python3.10/internal/pycore_import.h
deleted file mode 100644
index e21ed0a..0000000
--- a/include/python3.10/internal/pycore_import.h
+++ /dev/null
@@ -1,17 +0,0 @@
-#ifndef Py_LIMITED_API
-#ifndef Py_INTERNAL_IMPORT_H
-#define Py_INTERNAL_IMPORT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifdef HAVE_FORK
-extern PyStatus _PyImport_ReInitLock(void);
-#endif
-extern PyObject* _PyImport_BootstrapImp(PyThreadState *tstate);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_IMPORT_H */
-#endif /* !Py_LIMITED_API */
diff --git a/include/python3.10/internal/pycore_initconfig.h b/include/python3.10/internal/pycore_initconfig.h
deleted file mode 100644
index 4b009e8..0000000
--- a/include/python3.10/internal/pycore_initconfig.h
+++ /dev/null
@@ -1,176 +0,0 @@
-#ifndef Py_INTERNAL_CORECONFIG_H
-#define Py_INTERNAL_CORECONFIG_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-/* Forward declaration */
-struct pyruntimestate;
-
-/* --- PyStatus ----------------------------------------------- */
-
-/* Almost all errors causing Python initialization to fail */
-#ifdef _MSC_VER
- /* Visual Studio 2015 doesn't implement C99 __func__ in C */
-# define _PyStatus_GET_FUNC() __FUNCTION__
-#else
-# define _PyStatus_GET_FUNC() __func__
-#endif
-
-#define _PyStatus_OK() \
- (PyStatus){._type = _PyStatus_TYPE_OK,}
- /* other fields are set to 0 */
-#define _PyStatus_ERR(ERR_MSG) \
- (PyStatus){ \
- ._type = _PyStatus_TYPE_ERROR, \
- .func = _PyStatus_GET_FUNC(), \
- .err_msg = (ERR_MSG)}
- /* other fields are set to 0 */
-#define _PyStatus_NO_MEMORY() _PyStatus_ERR("memory allocation failed")
-#define _PyStatus_EXIT(EXITCODE) \
- (PyStatus){ \
- ._type = _PyStatus_TYPE_EXIT, \
- .exitcode = (EXITCODE)}
-#define _PyStatus_IS_ERROR(err) \
- (err._type == _PyStatus_TYPE_ERROR)
-#define _PyStatus_IS_EXIT(err) \
- (err._type == _PyStatus_TYPE_EXIT)
-#define _PyStatus_EXCEPTION(err) \
- (err._type != _PyStatus_TYPE_OK)
-#define _PyStatus_UPDATE_FUNC(err) \
- do { err.func = _PyStatus_GET_FUNC(); } while (0)
-
-PyObject* _PyErr_SetFromPyStatus(PyStatus status);
-
-/* --- PyWideStringList ------------------------------------------------ */
-
-#define _PyWideStringList_INIT (PyWideStringList){.length = 0, .items = NULL}
-
-#ifndef NDEBUG
-PyAPI_FUNC(int) _PyWideStringList_CheckConsistency(const PyWideStringList *list);
-#endif
-PyAPI_FUNC(void) _PyWideStringList_Clear(PyWideStringList *list);
-PyAPI_FUNC(int) _PyWideStringList_Copy(PyWideStringList *list,
- const PyWideStringList *list2);
-PyAPI_FUNC(PyStatus) _PyWideStringList_Extend(PyWideStringList *list,
- const PyWideStringList *list2);
-PyAPI_FUNC(PyObject*) _PyWideStringList_AsList(const PyWideStringList *list);
-
-
-/* --- _PyArgv ---------------------------------------------------- */
-
-typedef struct _PyArgv {
- Py_ssize_t argc;
- int use_bytes_argv;
- char * const *bytes_argv;
- wchar_t * const *wchar_argv;
-} _PyArgv;
-
-PyAPI_FUNC(PyStatus) _PyArgv_AsWstrList(const _PyArgv *args,
- PyWideStringList *list);
-
-
-/* --- Helper functions ------------------------------------------- */
-
-PyAPI_FUNC(int) _Py_str_to_int(
- const char *str,
- int *result);
-PyAPI_FUNC(const wchar_t*) _Py_get_xoption(
- const PyWideStringList *xoptions,
- const wchar_t *name);
-PyAPI_FUNC(const char*) _Py_GetEnv(
- int use_environment,
- const char *name);
-PyAPI_FUNC(void) _Py_get_env_flag(
- int use_environment,
- int *flag,
- const char *name);
-
-/* Py_GetArgcArgv() helper */
-PyAPI_FUNC(void) _Py_ClearArgcArgv(void);
-
-
-/* --- _PyPreCmdline ------------------------------------------------- */
-
-typedef struct {
- PyWideStringList argv;
- PyWideStringList xoptions; /* "-X value" option */
- int isolated; /* -I option */
- int use_environment; /* -E option */
- int dev_mode; /* -X dev and PYTHONDEVMODE */
- int warn_default_encoding; /* -X warn_default_encoding and PYTHONWARNDEFAULTENCODING */
-} _PyPreCmdline;
-
-#define _PyPreCmdline_INIT \
- (_PyPreCmdline){ \
- .use_environment = -1, \
- .isolated = -1, \
- .dev_mode = -1}
-/* Note: _PyPreCmdline_INIT sets other fields to 0/NULL */
-
-extern void _PyPreCmdline_Clear(_PyPreCmdline *cmdline);
-extern PyStatus _PyPreCmdline_SetArgv(_PyPreCmdline *cmdline,
- const _PyArgv *args);
-extern PyStatus _PyPreCmdline_SetConfig(
- const _PyPreCmdline *cmdline,
- PyConfig *config);
-extern PyStatus _PyPreCmdline_Read(_PyPreCmdline *cmdline,
- const PyPreConfig *preconfig);
-
-
-/* --- PyPreConfig ----------------------------------------------- */
-
-PyAPI_FUNC(void) _PyPreConfig_InitCompatConfig(PyPreConfig *preconfig);
-extern void _PyPreConfig_InitFromConfig(
- PyPreConfig *preconfig,
- const PyConfig *config);
-extern PyStatus _PyPreConfig_InitFromPreConfig(
- PyPreConfig *preconfig,
- const PyPreConfig *config2);
-extern PyObject* _PyPreConfig_AsDict(const PyPreConfig *preconfig);
-extern void _PyPreConfig_GetConfig(PyPreConfig *preconfig,
- const PyConfig *config);
-extern PyStatus _PyPreConfig_Read(PyPreConfig *preconfig,
- const _PyArgv *args);
-extern PyStatus _PyPreConfig_Write(const PyPreConfig *preconfig);
-
-
-/* --- PyConfig ---------------------------------------------- */
-
-typedef enum {
- /* Py_Initialize() API: backward compatibility with Python 3.6 and 3.7 */
- _PyConfig_INIT_COMPAT = 1,
- _PyConfig_INIT_PYTHON = 2,
- _PyConfig_INIT_ISOLATED = 3
-} _PyConfigInitEnum;
-
-PyAPI_FUNC(void) _PyConfig_InitCompatConfig(PyConfig *config);
-extern PyStatus _PyConfig_Copy(
- PyConfig *config,
- const PyConfig *config2);
-extern PyStatus _PyConfig_InitPathConfig(
- PyConfig *config,
- int compute_path_config);
-extern PyStatus _PyConfig_Read(PyConfig *config, int compute_path_config);
-extern PyStatus _PyConfig_Write(const PyConfig *config,
- struct pyruntimestate *runtime);
-extern PyStatus _PyConfig_SetPyArgv(
- PyConfig *config,
- const _PyArgv *args);
-
-PyAPI_FUNC(PyObject*) _PyConfig_AsDict(const PyConfig *config);
-PyAPI_FUNC(int) _PyConfig_FromDict(PyConfig *config, PyObject *dict);
-
-
-/* --- Function used for testing ---------------------------------- */
-
-PyAPI_FUNC(PyObject*) _Py_GetConfigsAsDict(void);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_CORECONFIG_H */
diff --git a/include/python3.10/internal/pycore_interp.h b/include/python3.10/internal/pycore_interp.h
deleted file mode 100644
index 4307b61..0000000
--- a/include/python3.10/internal/pycore_interp.h
+++ /dev/null
@@ -1,337 +0,0 @@
-#ifndef Py_INTERNAL_INTERP_H
-#define Py_INTERNAL_INTERP_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-#include "pycore_atomic.h" // _Py_atomic_address
-#include "pycore_ast_state.h" // struct ast_state
-#include "pycore_gil.h" // struct _gil_runtime_state
-#include "pycore_gc.h" // struct _gc_runtime_state
-#include "pycore_warnings.h" // struct _warnings_runtime_state
-
-struct _pending_calls {
- PyThread_type_lock lock;
- /* Request for running pending calls. */
- _Py_atomic_int calls_to_do;
- /* Request for looking at the `async_exc` field of the current
- thread state.
- Guarded by the GIL. */
- int async_exc;
-#define NPENDINGCALLS 32
- struct {
- int (*func)(void *);
- void *arg;
- } calls[NPENDINGCALLS];
- int first;
- int last;
-};
-
-struct _ceval_state {
- int recursion_limit;
- /* This single variable consolidates all requests to break out of
- the fast path in the eval loop. */
- _Py_atomic_int eval_breaker;
- /* Request for dropping the GIL */
- _Py_atomic_int gil_drop_request;
- struct _pending_calls pending;
-#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
- struct _gil_runtime_state gil;
-#endif
-};
-
-/* fs_codec.encoding is initialized to NULL.
- Later, it is set to a non-NULL string by _PyUnicode_InitEncodings(). */
-struct _Py_unicode_fs_codec {
- char *encoding; // Filesystem encoding (encoded to UTF-8)
- int utf8; // encoding=="utf-8"?
- char *errors; // Filesystem errors (encoded to UTF-8)
- _Py_error_handler error_handler;
-};
-
-struct _Py_bytes_state {
- PyObject *empty_string;
- PyBytesObject *characters[256];
-};
-
-struct _Py_unicode_ids {
- Py_ssize_t size;
- PyObject **array;
-};
-
-struct _Py_unicode_state {
- // The empty Unicode object is a singleton to improve performance.
- PyObject *empty_string;
- /* Single character Unicode strings in the Latin-1 range are being
- shared as well. */
- PyObject *latin1[256];
- struct _Py_unicode_fs_codec fs_codec;
-
- // Unused member kept for ABI backward compatibility with Python 3.10.0:
- // see bpo-46006.
- PyObject *unused_interned;
-
- // Unicode identifiers (_Py_Identifier): see _PyUnicode_FromId()
- struct _Py_unicode_ids ids;
-};
-
-struct _Py_float_state {
- /* Special free list
- free_list is a singly-linked list of available PyFloatObjects,
- linked via abuse of their ob_type members. */
- int numfree;
- PyFloatObject *free_list;
-};
-
-/* Speed optimization to avoid frequent malloc/free of small tuples */
-#ifndef PyTuple_MAXSAVESIZE
- // Largest tuple to save on free list
-# define PyTuple_MAXSAVESIZE 20
-#endif
-#ifndef PyTuple_MAXFREELIST
- // Maximum number of tuples of each size to save
-# define PyTuple_MAXFREELIST 2000
-#endif
-
-struct _Py_tuple_state {
-#if PyTuple_MAXSAVESIZE > 0
- /* Entries 1 up to PyTuple_MAXSAVESIZE are free lists,
- entry 0 is the empty tuple () of which at most one instance
- will be allocated. */
- PyTupleObject *free_list[PyTuple_MAXSAVESIZE];
- int numfree[PyTuple_MAXSAVESIZE];
-#endif
-};
-
-/* Empty list reuse scheme to save calls to malloc and free */
-#ifndef PyList_MAXFREELIST
-# define PyList_MAXFREELIST 80
-#endif
-
-struct _Py_list_state {
- PyListObject *free_list[PyList_MAXFREELIST];
- int numfree;
-};
-
-#ifndef PyDict_MAXFREELIST
-# define PyDict_MAXFREELIST 80
-#endif
-
-struct _Py_dict_state {
- /* Dictionary reuse scheme to save calls to malloc and free */
- PyDictObject *free_list[PyDict_MAXFREELIST];
- int numfree;
- PyDictKeysObject *keys_free_list[PyDict_MAXFREELIST];
- int keys_numfree;
-};
-
-struct _Py_frame_state {
- PyFrameObject *free_list;
- /* number of frames currently in free_list */
- int numfree;
-};
-
-#ifndef _PyAsyncGen_MAXFREELIST
-# define _PyAsyncGen_MAXFREELIST 80
-#endif
-
-struct _Py_async_gen_state {
- /* Freelists boost performance 6-10%; they also reduce memory
- fragmentation, as _PyAsyncGenWrappedValue and PyAsyncGenASend
- are short-living objects that are instantiated for every
- __anext__() call. */
- struct _PyAsyncGenWrappedValue* value_freelist[_PyAsyncGen_MAXFREELIST];
- int value_numfree;
-
- struct PyAsyncGenASend* asend_freelist[_PyAsyncGen_MAXFREELIST];
- int asend_numfree;
-};
-
-struct _Py_context_state {
- // List of free PyContext objects
- PyContext *freelist;
- int numfree;
-};
-
-struct _Py_exc_state {
- // The dict mapping from errno codes to OSError subclasses
- PyObject *errnomap;
- PyBaseExceptionObject *memerrors_freelist;
- int memerrors_numfree;
-};
-
-
-// atexit state
-typedef struct {
- PyObject *func;
- PyObject *args;
- PyObject *kwargs;
-} atexit_callback;
-
-struct atexit_state {
- atexit_callback **callbacks;
- int ncallbacks;
- int callback_len;
-};
-
-
-// Type attribute lookup cache: speed up attribute and method lookups,
-// see _PyType_Lookup().
-struct type_cache_entry {
- unsigned int version; // initialized from type->tp_version_tag
- PyObject *name; // reference to exactly a str or None
- PyObject *value; // borrowed reference or NULL
-};
-
-#define MCACHE_SIZE_EXP 12
-#define MCACHE_STATS 0
-
-struct type_cache {
- struct type_cache_entry hashtable[1 << MCACHE_SIZE_EXP];
-#if MCACHE_STATS
- size_t hits;
- size_t misses;
- size_t collisions;
-#endif
-};
-
-
-/* interpreter state */
-
-#define _PY_NSMALLPOSINTS 257
-#define _PY_NSMALLNEGINTS 5
-
-// _PyLong_GetZero() and _PyLong_GetOne() must always be available
-#if _PY_NSMALLPOSINTS < 2
-# error "_PY_NSMALLPOSINTS must be greater than 1"
-#endif
-
-// The PyInterpreterState typedef is in Include/pystate.h.
-struct _is {
-
- struct _is *next;
- struct _ts *tstate_head;
-
- /* Reference to the _PyRuntime global variable. This field exists
- to not have to pass runtime in addition to tstate to a function.
- Get runtime from tstate: tstate->interp->runtime. */
- struct pyruntimestate *runtime;
-
- int64_t id;
- int64_t id_refcount;
- int requires_idref;
- PyThread_type_lock id_mutex;
-
- int finalizing;
-
- struct _ceval_state ceval;
- struct _gc_runtime_state gc;
-
- // sys.modules dictionary
- PyObject *modules;
- PyObject *modules_by_index;
- // Dictionary of the sys module
- PyObject *sysdict;
- // Dictionary of the builtins module
- PyObject *builtins;
- // importlib module
- PyObject *importlib;
-
- /* Used in Modules/_threadmodule.c. */
- long num_threads;
- /* Support for runtime thread stack size tuning.
- A value of 0 means using the platform's default stack size
- or the size specified by the THREAD_STACK_SIZE macro. */
- /* Used in Python/thread.c. */
- size_t pythread_stacksize;
-
- PyObject *codec_search_path;
- PyObject *codec_search_cache;
- PyObject *codec_error_registry;
- int codecs_initialized;
-
- PyConfig config;
-#ifdef HAVE_DLOPEN
- int dlopenflags;
-#endif
-
- PyObject *dict; /* Stores per-interpreter state */
-
- PyObject *builtins_copy;
- PyObject *import_func;
- // Initialized to _PyEval_EvalFrameDefault().
- _PyFrameEvalFunction eval_frame;
-
- Py_ssize_t co_extra_user_count;
- freefunc co_extra_freefuncs[MAX_CO_EXTRA_USERS];
-
-#ifdef HAVE_FORK
- PyObject *before_forkers;
- PyObject *after_forkers_parent;
- PyObject *after_forkers_child;
-#endif
-
- uint64_t tstate_next_unique_id;
-
- struct _warnings_runtime_state warnings;
- struct atexit_state atexit;
-
- PyObject *audit_hooks;
-
- /* Small integers are preallocated in this array so that they
- can be shared.
- The integers that are preallocated are those in the range
- -_PY_NSMALLNEGINTS (inclusive) to _PY_NSMALLPOSINTS (not inclusive).
- */
- PyLongObject* small_ints[_PY_NSMALLNEGINTS + _PY_NSMALLPOSINTS];
- struct _Py_bytes_state bytes;
- struct _Py_unicode_state unicode;
- struct _Py_float_state float_state;
- /* Using a cache is very effective since typically only a single slice is
- created and then deleted again. */
- PySliceObject *slice_cache;
-
- struct _Py_tuple_state tuple;
- struct _Py_list_state list;
- struct _Py_dict_state dict_state;
- struct _Py_frame_state frame;
- struct _Py_async_gen_state async_gen;
- struct _Py_context_state context;
- struct _Py_exc_state exc_state;
-
- struct ast_state ast;
- struct type_cache type_cache;
-};
-
-extern void _PyInterpreterState_ClearModules(PyInterpreterState *interp);
-extern void _PyInterpreterState_Clear(PyThreadState *tstate);
-
-
-/* cross-interpreter data registry */
-
-/* For now we use a global registry of shareable classes. An
- alternative would be to add a tp_* slot for a class's
- crossinterpdatafunc. It would be simpler and more efficient. */
-
-struct _xidregitem;
-
-struct _xidregitem {
- PyTypeObject *cls;
- crossinterpdatafunc getdata;
- struct _xidregitem *next;
-};
-
-PyAPI_FUNC(struct _is*) _PyInterpreterState_LookUpID(int64_t);
-
-PyAPI_FUNC(int) _PyInterpreterState_IDInitref(struct _is *);
-PyAPI_FUNC(int) _PyInterpreterState_IDIncref(struct _is *);
-PyAPI_FUNC(void) _PyInterpreterState_IDDecref(struct _is *);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_INTERP_H */
diff --git a/include/python3.10/internal/pycore_list.h b/include/python3.10/internal/pycore_list.h
deleted file mode 100644
index f18fb05..0000000
--- a/include/python3.10/internal/pycore_list.h
+++ /dev/null
@@ -1,20 +0,0 @@
-#ifndef Py_INTERNAL_LIST_H
-#define Py_INTERNAL_LIST_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-#include "listobject.h" // _PyList_CAST()
-
-
-#define _PyList_ITEMS(op) (_PyList_CAST(op)->ob_item)
-
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_LIST_H */
diff --git a/include/python3.10/internal/pycore_long.h b/include/python3.10/internal/pycore_long.h
deleted file mode 100644
index 2bea3a5..0000000
--- a/include/python3.10/internal/pycore_long.h
+++ /dev/null
@@ -1,40 +0,0 @@
-#ifndef Py_INTERNAL_LONG_H
-#define Py_INTERNAL_LONG_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-#include "pycore_interp.h" // PyInterpreterState.small_ints
-#include "pycore_pystate.h" // _PyThreadState_GET()
-
-// Don't call this function but _PyLong_GetZero() and _PyLong_GetOne()
-static inline PyObject* __PyLong_GetSmallInt_internal(int value)
-{
- PyInterpreterState *interp = _PyInterpreterState_GET();
- assert(-_PY_NSMALLNEGINTS <= value && value < _PY_NSMALLPOSINTS);
- size_t index = _PY_NSMALLNEGINTS + value;
- PyObject *obj = (PyObject*)interp->small_ints[index];
- // _PyLong_GetZero(), _PyLong_GetOne() and get_small_int() must not be
- // called before _PyLong_Init() nor after _PyLong_Fini().
- assert(obj != NULL);
- return obj;
-}
-
-// Return a borrowed reference to the zero singleton.
-// The function cannot return NULL.
-static inline PyObject* _PyLong_GetZero(void)
-{ return __PyLong_GetSmallInt_internal(0); }
-
-// Return a borrowed reference to the one singleton.
-// The function cannot return NULL.
-static inline PyObject* _PyLong_GetOne(void)
-{ return __PyLong_GetSmallInt_internal(1); }
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_LONG_H */
diff --git a/include/python3.10/internal/pycore_moduleobject.h b/include/python3.10/internal/pycore_moduleobject.h
deleted file mode 100644
index e9978ab..0000000
--- a/include/python3.10/internal/pycore_moduleobject.h
+++ /dev/null
@@ -1,42 +0,0 @@
-#ifndef Py_INTERNAL_MODULEOBJECT_H
-#define Py_INTERNAL_MODULEOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-typedef struct {
- PyObject_HEAD
- PyObject *md_dict;
- struct PyModuleDef *md_def;
- void *md_state;
- PyObject *md_weaklist;
- // for logging purposes after md_dict is cleared
- PyObject *md_name;
-} PyModuleObject;
-
-static inline PyModuleDef* _PyModule_GetDef(PyObject *mod) {
- assert(PyModule_Check(mod));
- return ((PyModuleObject *)mod)->md_def;
-}
-
-static inline void* _PyModule_GetState(PyObject* mod) {
- assert(PyModule_Check(mod));
- return ((PyModuleObject *)mod)->md_state;
-}
-
-static inline PyObject* _PyModule_GetDict(PyObject *mod) {
- assert(PyModule_Check(mod));
- PyObject *dict = ((PyModuleObject *)mod) -> md_dict;
- // _PyModule_GetDict(mod) must not be used after calling module_clear(mod)
- assert(dict != NULL);
- return dict;
-}
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_MODULEOBJECT_H */
diff --git a/include/python3.10/internal/pycore_object.h b/include/python3.10/internal/pycore_object.h
deleted file mode 100644
index 90d9813..0000000
--- a/include/python3.10/internal/pycore_object.h
+++ /dev/null
@@ -1,186 +0,0 @@
-#ifndef Py_INTERNAL_OBJECT_H
-#define Py_INTERNAL_OBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-#include "pycore_gc.h" // _PyObject_GC_IS_TRACKED()
-#include "pycore_interp.h" // PyInterpreterState.gc
-#include "pycore_pystate.h" // _PyInterpreterState_GET()
-
-PyAPI_FUNC(int) _PyType_CheckConsistency(PyTypeObject *type);
-PyAPI_FUNC(int) _PyDict_CheckConsistency(PyObject *mp, int check_content);
-
-/* Update the Python traceback of an object. This function must be called
- when a memory block is reused from a free list.
-
- Internal function called by _Py_NewReference(). */
-extern int _PyTraceMalloc_NewReference(PyObject *op);
-
-// Fast inlined version of PyType_HasFeature()
-static inline int
-_PyType_HasFeature(PyTypeObject *type, unsigned long feature) {
- return ((type->tp_flags & feature) != 0);
-}
-
-extern void _PyType_InitCache(PyInterpreterState *interp);
-
-/* Only private in Python 3.10 and 3.9.8+; public in 3.11 */
-extern PyObject *_PyType_GetQualName(PyTypeObject *type);
-
-/* Inline functions trading binary compatibility for speed:
- _PyObject_Init() is the fast version of PyObject_Init(), and
- _PyObject_InitVar() is the fast version of PyObject_InitVar().
-
- These inline functions must not be called with op=NULL. */
-static inline void
-_PyObject_Init(PyObject *op, PyTypeObject *typeobj)
-{
- assert(op != NULL);
- Py_SET_TYPE(op, typeobj);
- if (_PyType_HasFeature(typeobj, Py_TPFLAGS_HEAPTYPE)) {
- Py_INCREF(typeobj);
- }
- _Py_NewReference(op);
-}
-
-static inline void
-_PyObject_InitVar(PyVarObject *op, PyTypeObject *typeobj, Py_ssize_t size)
-{
- assert(op != NULL);
- Py_SET_SIZE(op, size);
- _PyObject_Init((PyObject *)op, typeobj);
-}
-
-
-/* Tell the GC to track this object.
- *
- * The object must not be tracked by the GC.
- *
- * NB: While the object is tracked by the collector, it must be safe to call the
- * ob_traverse method.
- *
- * Internal note: interp->gc.generation0->_gc_prev doesn't have any bit flags
- * because it's not object header. So we don't use _PyGCHead_PREV() and
- * _PyGCHead_SET_PREV() for it to avoid unnecessary bitwise operations.
- *
- * See also the public PyObject_GC_Track() function.
- */
-static inline void _PyObject_GC_TRACK(
-// The preprocessor removes _PyObject_ASSERT_FROM() calls if NDEBUG is defined
-#ifndef NDEBUG
- const char *filename, int lineno,
-#endif
- PyObject *op)
-{
- _PyObject_ASSERT_FROM(op, !_PyObject_GC_IS_TRACKED(op),
- "object already tracked by the garbage collector",
- filename, lineno, __func__);
-
- PyGC_Head *gc = _Py_AS_GC(op);
- _PyObject_ASSERT_FROM(op,
- (gc->_gc_prev & _PyGC_PREV_MASK_COLLECTING) == 0,
- "object is in generation which is garbage collected",
- filename, lineno, __func__);
-
- PyInterpreterState *interp = _PyInterpreterState_GET();
- PyGC_Head *generation0 = interp->gc.generation0;
- PyGC_Head *last = (PyGC_Head*)(generation0->_gc_prev);
- _PyGCHead_SET_NEXT(last, gc);
- _PyGCHead_SET_PREV(gc, last);
- _PyGCHead_SET_NEXT(gc, generation0);
- generation0->_gc_prev = (uintptr_t)gc;
-}
-
-/* Tell the GC to stop tracking this object.
- *
- * Internal note: This may be called while GC. So _PyGC_PREV_MASK_COLLECTING
- * must be cleared. But _PyGC_PREV_MASK_FINALIZED bit is kept.
- *
- * The object must be tracked by the GC.
- *
- * See also the public PyObject_GC_UnTrack() which accept an object which is
- * not tracked.
- */
-static inline void _PyObject_GC_UNTRACK(
-// The preprocessor removes _PyObject_ASSERT_FROM() calls if NDEBUG is defined
-#ifndef NDEBUG
- const char *filename, int lineno,
-#endif
- PyObject *op)
-{
- _PyObject_ASSERT_FROM(op, _PyObject_GC_IS_TRACKED(op),
- "object not tracked by the garbage collector",
- filename, lineno, __func__);
-
- PyGC_Head *gc = _Py_AS_GC(op);
- PyGC_Head *prev = _PyGCHead_PREV(gc);
- PyGC_Head *next = _PyGCHead_NEXT(gc);
- _PyGCHead_SET_NEXT(prev, next);
- _PyGCHead_SET_PREV(next, prev);
- gc->_gc_next = 0;
- gc->_gc_prev &= _PyGC_PREV_MASK_FINALIZED;
-}
-
-// Macros to accept any type for the parameter, and to automatically pass
-// the filename and the filename (if NDEBUG is not defined) where the macro
-// is called.
-#ifdef NDEBUG
-# define _PyObject_GC_TRACK(op) \
- _PyObject_GC_TRACK(_PyObject_CAST(op))
-# define _PyObject_GC_UNTRACK(op) \
- _PyObject_GC_UNTRACK(_PyObject_CAST(op))
-#else
-# define _PyObject_GC_TRACK(op) \
- _PyObject_GC_TRACK(__FILE__, __LINE__, _PyObject_CAST(op))
-# define _PyObject_GC_UNTRACK(op) \
- _PyObject_GC_UNTRACK(__FILE__, __LINE__, _PyObject_CAST(op))
-#endif
-
-#ifdef Py_REF_DEBUG
-extern void _PyDebug_PrintTotalRefs(void);
-#endif
-
-#ifdef Py_TRACE_REFS
-extern void _Py_AddToAllObjects(PyObject *op, int force);
-extern void _Py_PrintReferences(FILE *);
-extern void _Py_PrintReferenceAddresses(FILE *);
-#endif
-
-static inline PyObject **
-_PyObject_GET_WEAKREFS_LISTPTR(PyObject *op)
-{
- Py_ssize_t offset = Py_TYPE(op)->tp_weaklistoffset;
- return (PyObject **)((char *)op + offset);
-}
-
-// Fast inlined version of PyObject_IS_GC()
-static inline int
-_PyObject_IS_GC(PyObject *obj)
-{
- return (PyType_IS_GC(Py_TYPE(obj))
- && (Py_TYPE(obj)->tp_is_gc == NULL
- || Py_TYPE(obj)->tp_is_gc(obj)));
-}
-
-// Fast inlined version of PyType_IS_GC()
-#define _PyType_IS_GC(t) _PyType_HasFeature((t), Py_TPFLAGS_HAVE_GC)
-
-// Usage: assert(_Py_CheckSlotResult(obj, "__getitem__", result != NULL));
-extern int _Py_CheckSlotResult(
- PyObject *obj,
- const char *slot_name,
- int success);
-
-// PyType_Ready() must be called if _PyType_IsReady() is false.
-// See also the Py_TPFLAGS_READY flag.
-#define _PyType_IsReady(type) ((type)->tp_dict != NULL)
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_OBJECT_H */
diff --git a/include/python3.10/internal/pycore_pathconfig.h b/include/python3.10/internal/pycore_pathconfig.h
deleted file mode 100644
index 15447f5..0000000
--- a/include/python3.10/internal/pycore_pathconfig.h
+++ /dev/null
@@ -1,73 +0,0 @@
-#ifndef Py_INTERNAL_PATHCONFIG_H
-#define Py_INTERNAL_PATHCONFIG_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-typedef struct _PyPathConfig {
- /* Full path to the Python program */
- wchar_t *program_full_path;
- wchar_t *prefix;
- wchar_t *exec_prefix;
- /* Set by Py_SetPath(), or computed by _PyConfig_InitPathConfig() */
- wchar_t *module_search_path;
- /* Python program name */
- wchar_t *program_name;
- /* Set by Py_SetPythonHome() or PYTHONHOME environment variable */
- wchar_t *home;
-#ifdef MS_WINDOWS
- /* isolated and site_import are used to set Py_IsolatedFlag and
- Py_NoSiteFlag flags on Windows in read_pth_file(). These fields
- are ignored when their value are equal to -1 (unset). */
- int isolated;
- int site_import;
- /* Set when a venv is detected */
- wchar_t *base_executable;
-#endif
-} _PyPathConfig;
-
-#ifdef MS_WINDOWS
-# define _PyPathConfig_INIT \
- {.module_search_path = NULL, \
- .isolated = -1, \
- .site_import = -1}
-#else
-# define _PyPathConfig_INIT \
- {.module_search_path = NULL}
-#endif
-/* Note: _PyPathConfig_INIT sets other fields to 0/NULL */
-
-PyAPI_DATA(_PyPathConfig) _Py_path_config;
-#ifdef MS_WINDOWS
-PyAPI_DATA(wchar_t*) _Py_dll_path;
-#endif
-
-extern void _PyPathConfig_ClearGlobal(void);
-
-extern PyStatus _PyPathConfig_Calculate(
- _PyPathConfig *pathconfig,
- const PyConfig *config);
-extern int _PyPathConfig_ComputeSysPath0(
- const PyWideStringList *argv,
- PyObject **path0);
-extern PyStatus _Py_FindEnvConfigValue(
- FILE *env_file,
- const wchar_t *key,
- wchar_t **value_p);
-
-#ifdef MS_WINDOWS
-extern wchar_t* _Py_GetDLLPath(void);
-#endif
-
-extern PyStatus _PyConfig_WritePathConfig(const PyConfig *config);
-extern void _Py_DumpPathConfig(PyThreadState *tstate);
-extern PyObject* _PyPathConfig_AsDict(void);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_PATHCONFIG_H */
diff --git a/include/python3.10/internal/pycore_pyerrors.h b/include/python3.10/internal/pycore_pyerrors.h
deleted file mode 100644
index a5e97fe..0000000
--- a/include/python3.10/internal/pycore_pyerrors.h
+++ /dev/null
@@ -1,96 +0,0 @@
-#ifndef Py_INTERNAL_PYERRORS_H
-#define Py_INTERNAL_PYERRORS_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-static inline PyObject* _PyErr_Occurred(PyThreadState *tstate)
-{
- assert(tstate != NULL);
- return tstate->curexc_type;
-}
-
-static inline void _PyErr_ClearExcState(_PyErr_StackItem *exc_state)
-{
- PyObject *t, *v, *tb;
- t = exc_state->exc_type;
- v = exc_state->exc_value;
- tb = exc_state->exc_traceback;
- exc_state->exc_type = NULL;
- exc_state->exc_value = NULL;
- exc_state->exc_traceback = NULL;
- Py_XDECREF(t);
- Py_XDECREF(v);
- Py_XDECREF(tb);
-}
-
-
-PyAPI_FUNC(void) _PyErr_Fetch(
- PyThreadState *tstate,
- PyObject **type,
- PyObject **value,
- PyObject **traceback);
-
-PyAPI_FUNC(int) _PyErr_ExceptionMatches(
- PyThreadState *tstate,
- PyObject *exc);
-
-PyAPI_FUNC(void) _PyErr_Restore(
- PyThreadState *tstate,
- PyObject *type,
- PyObject *value,
- PyObject *traceback);
-
-PyAPI_FUNC(void) _PyErr_SetObject(
- PyThreadState *tstate,
- PyObject *type,
- PyObject *value);
-
-PyAPI_FUNC(void) _PyErr_ChainStackItem(
- _PyErr_StackItem *exc_info);
-
-PyAPI_FUNC(void) _PyErr_Clear(PyThreadState *tstate);
-
-PyAPI_FUNC(void) _PyErr_SetNone(PyThreadState *tstate, PyObject *exception);
-
-PyAPI_FUNC(PyObject *) _PyErr_NoMemory(PyThreadState *tstate);
-
-PyAPI_FUNC(void) _PyErr_SetString(
- PyThreadState *tstate,
- PyObject *exception,
- const char *string);
-
-PyAPI_FUNC(PyObject *) _PyErr_Format(
- PyThreadState *tstate,
- PyObject *exception,
- const char *format,
- ...);
-
-PyAPI_FUNC(void) _PyErr_NormalizeException(
- PyThreadState *tstate,
- PyObject **exc,
- PyObject **val,
- PyObject **tb);
-
-PyAPI_FUNC(PyObject *) _PyErr_FormatFromCauseTstate(
- PyThreadState *tstate,
- PyObject *exception,
- const char *format,
- ...);
-
-PyAPI_FUNC(int) _PyErr_CheckSignalsTstate(PyThreadState *tstate);
-
-PyAPI_FUNC(void) _Py_DumpExtensionModules(int fd, PyInterpreterState *interp);
-
-extern PyObject* _Py_Offer_Suggestions(PyObject* exception);
-PyAPI_FUNC(Py_ssize_t) _Py_UTF8_Edit_Cost(PyObject *str_a, PyObject *str_b,
- Py_ssize_t max_cost);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_PYERRORS_H */
diff --git a/include/python3.10/internal/pycore_pylifecycle.h b/include/python3.10/internal/pycore_pylifecycle.h
deleted file mode 100644
index 524be9d..0000000
--- a/include/python3.10/internal/pycore_pylifecycle.h
+++ /dev/null
@@ -1,141 +0,0 @@
-#ifndef Py_INTERNAL_LIFECYCLE_H
-#define Py_INTERNAL_LIFECYCLE_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-#ifdef HAVE_SIGNAL_H
-#include <signal.h>
-#endif
-
-#include "pycore_runtime.h" // _PyRuntimeState
-
-#ifndef NSIG
-# if defined(_NSIG)
-# define NSIG _NSIG /* For BSD/SysV */
-# elif defined(_SIGMAX)
-# define NSIG (_SIGMAX + 1) /* For QNX */
-# elif defined(SIGMAX)
-# define NSIG (SIGMAX + 1) /* For djgpp */
-# else
-# define NSIG 64 /* Use a reasonable default value */
-# endif
-#endif
-
-/* Forward declarations */
-struct _PyArgv;
-struct pyruntimestate;
-
-/* True if the main interpreter thread exited due to an unhandled
- * KeyboardInterrupt exception, suggesting the user pressed ^C. */
-PyAPI_DATA(int) _Py_UnhandledKeyboardInterrupt;
-
-extern int _Py_SetFileSystemEncoding(
- const char *encoding,
- const char *errors);
-extern void _Py_ClearFileSystemEncoding(void);
-extern PyStatus _PyUnicode_InitEncodings(PyThreadState *tstate);
-#ifdef MS_WINDOWS
-extern int _PyUnicode_EnableLegacyWindowsFSEncoding(void);
-#endif
-
-PyAPI_FUNC(void) _Py_ClearStandardStreamEncoding(void);
-
-PyAPI_FUNC(int) _Py_IsLocaleCoercionTarget(const char *ctype_loc);
-
-/* Various one-time initializers */
-
-extern PyStatus _PyUnicode_Init(PyInterpreterState *interp);
-extern PyStatus _PyUnicode_InitTypes(void);
-extern PyStatus _PyBytes_Init(PyInterpreterState *interp);
-extern int _PyStructSequence_Init(void);
-extern int _PyLong_Init(PyInterpreterState *interp);
-extern int _PyLong_InitTypes(void);
-extern PyStatus _PyTuple_Init(PyInterpreterState *interp);
-extern PyStatus _PyFaulthandler_Init(int enable);
-extern int _PyTraceMalloc_Init(int enable);
-extern PyObject * _PyBuiltin_Init(PyInterpreterState *interp);
-extern PyStatus _PySys_Create(
- PyThreadState *tstate,
- PyObject **sysmod_p);
-extern PyStatus _PySys_ReadPreinitWarnOptions(PyWideStringList *options);
-extern PyStatus _PySys_ReadPreinitXOptions(PyConfig *config);
-extern int _PySys_UpdateConfig(PyThreadState *tstate);
-extern PyStatus _PyExc_Init(PyInterpreterState *interp);
-extern PyStatus _PyErr_InitTypes(void);
-extern PyStatus _PyBuiltins_AddExceptions(PyObject * bltinmod);
-extern void _PyFloat_Init(void);
-extern int _PyFloat_InitTypes(void);
-extern PyStatus _Py_HashRandomization_Init(const PyConfig *);
-
-extern PyStatus _PyTypes_Init(void);
-extern PyStatus _PyTypes_InitSlotDefs(void);
-extern PyStatus _PyImportZip_Init(PyThreadState *tstate);
-extern PyStatus _PyGC_Init(PyInterpreterState *interp);
-extern PyStatus _PyAtExit_Init(PyInterpreterState *interp);
-
-
-/* Various internal finalizers */
-
-extern void _PyFrame_Fini(PyInterpreterState *interp);
-extern void _PyDict_Fini(PyInterpreterState *interp);
-extern void _PyTuple_Fini(PyInterpreterState *interp);
-extern void _PyList_Fini(PyInterpreterState *interp);
-extern void _PyBytes_Fini(PyInterpreterState *interp);
-extern void _PyFloat_Fini(PyInterpreterState *interp);
-extern void _PySlice_Fini(PyInterpreterState *interp);
-extern void _PyAsyncGen_Fini(PyInterpreterState *interp);
-
-extern int _PySignal_Init(int install_signal_handlers);
-extern void _PySignal_Fini(void);
-
-extern void _PyExc_Fini(PyInterpreterState *interp);
-extern void _PyImport_Fini(void);
-extern void _PyImport_Fini2(void);
-extern void _PyGC_Fini(PyInterpreterState *interp);
-extern void _PyType_Fini(PyInterpreterState *interp);
-extern void _Py_HashRandomization_Fini(void);
-extern void _PyUnicode_Fini(PyInterpreterState *interp);
-extern void _PyUnicode_ClearInterned(PyInterpreterState *interp);
-extern void _PyLong_Fini(PyInterpreterState *interp);
-extern void _PyFaulthandler_Fini(void);
-extern void _PyHash_Fini(void);
-extern void _PyTraceMalloc_Fini(void);
-extern void _PyWarnings_Fini(PyInterpreterState *interp);
-extern void _PyAST_Fini(PyInterpreterState *interp);
-extern void _PyAtExit_Fini(PyInterpreterState *interp);
-
-extern PyStatus _PyGILState_Init(_PyRuntimeState *runtime);
-extern PyStatus _PyGILState_SetTstate(PyThreadState *tstate);
-extern void _PyGILState_Fini(PyInterpreterState *interp);
-
-PyAPI_FUNC(void) _PyGC_DumpShutdownStats(PyInterpreterState *interp);
-
-PyAPI_FUNC(PyStatus) _Py_PreInitializeFromPyArgv(
- const PyPreConfig *src_config,
- const struct _PyArgv *args);
-PyAPI_FUNC(PyStatus) _Py_PreInitializeFromConfig(
- const PyConfig *config,
- const struct _PyArgv *args);
-
-
-PyAPI_FUNC(int) _Py_HandleSystemExit(int *exitcode_p);
-
-PyAPI_FUNC(PyObject*) _PyErr_WriteUnraisableDefaultHook(PyObject *unraisable);
-
-PyAPI_FUNC(void) _PyErr_Print(PyThreadState *tstate);
-PyAPI_FUNC(void) _PyErr_Display(PyObject *file, PyObject *exception,
- PyObject *value, PyObject *tb);
-
-PyAPI_FUNC(void) _PyThreadState_DeleteCurrent(PyThreadState *tstate);
-
-extern void _PyAtExit_Call(PyInterpreterState *interp);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_LIFECYCLE_H */
diff --git a/include/python3.10/internal/pycore_pymem.h b/include/python3.10/internal/pycore_pymem.h
deleted file mode 100644
index 49af171..0000000
--- a/include/python3.10/internal/pycore_pymem.h
+++ /dev/null
@@ -1,101 +0,0 @@
-#ifndef Py_INTERNAL_PYMEM_H
-#define Py_INTERNAL_PYMEM_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-#include "pymem.h" // PyMemAllocatorName
-
-
-/* Set the memory allocator of the specified domain to the default.
- Save the old allocator into *old_alloc if it's non-NULL.
- Return on success, or return -1 if the domain is unknown. */
-PyAPI_FUNC(int) _PyMem_SetDefaultAllocator(
- PyMemAllocatorDomain domain,
- PyMemAllocatorEx *old_alloc);
-
-/* Special bytes broadcast into debug memory blocks at appropriate times.
- Strings of these are unlikely to be valid addresses, floats, ints or
- 7-bit ASCII.
-
- - PYMEM_CLEANBYTE: clean (newly allocated) memory
- - PYMEM_DEADBYTE dead (newly freed) memory
- - PYMEM_FORBIDDENBYTE: untouchable bytes at each end of a block
-
- Byte patterns 0xCB, 0xDB and 0xFB have been replaced with 0xCD, 0xDD and
- 0xFD to use the same values than Windows CRT debug malloc() and free().
- If modified, _PyMem_IsPtrFreed() should be updated as well. */
-#define PYMEM_CLEANBYTE 0xCD
-#define PYMEM_DEADBYTE 0xDD
-#define PYMEM_FORBIDDENBYTE 0xFD
-
-/* Heuristic checking if a pointer value is newly allocated
- (uninitialized), newly freed or NULL (is equal to zero).
-
- The pointer is not dereferenced, only the pointer value is checked.
-
- The heuristic relies on the debug hooks on Python memory allocators which
- fills newly allocated memory with CLEANBYTE (0xCD) and newly freed memory
- with DEADBYTE (0xDD). Detect also "untouchable bytes" marked
- with FORBIDDENBYTE (0xFD). */
-static inline int _PyMem_IsPtrFreed(const void *ptr)
-{
- uintptr_t value = (uintptr_t)ptr;
-#if SIZEOF_VOID_P == 8
- return (value == 0
- || value == (uintptr_t)0xCDCDCDCDCDCDCDCD
- || value == (uintptr_t)0xDDDDDDDDDDDDDDDD
- || value == (uintptr_t)0xFDFDFDFDFDFDFDFD);
-#elif SIZEOF_VOID_P == 4
- return (value == 0
- || value == (uintptr_t)0xCDCDCDCD
- || value == (uintptr_t)0xDDDDDDDD
- || value == (uintptr_t)0xFDFDFDFD);
-#else
-# error "unknown pointer size"
-#endif
-}
-
-PyAPI_FUNC(int) _PyMem_GetAllocatorName(
- const char *name,
- PyMemAllocatorName *allocator);
-
-/* Configure the Python memory allocators.
- Pass PYMEM_ALLOCATOR_DEFAULT to use default allocators.
- PYMEM_ALLOCATOR_NOT_SET does nothing. */
-PyAPI_FUNC(int) _PyMem_SetupAllocators(PyMemAllocatorName allocator);
-
-struct _PyTraceMalloc_Config {
- /* Module initialized?
- Variable protected by the GIL */
- enum {
- TRACEMALLOC_NOT_INITIALIZED,
- TRACEMALLOC_INITIALIZED,
- TRACEMALLOC_FINALIZED
- } initialized;
-
- /* Is tracemalloc tracing memory allocations?
- Variable protected by the GIL */
- int tracing;
-
- /* limit of the number of frames in a traceback, 1 by default.
- Variable protected by the GIL. */
- int max_nframe;
-};
-
-#define _PyTraceMalloc_Config_INIT \
- {.initialized = TRACEMALLOC_NOT_INITIALIZED, \
- .tracing = 0, \
- .max_nframe = 1}
-
-PyAPI_DATA(struct _PyTraceMalloc_Config) _Py_tracemalloc_config;
-
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_PYMEM_H */
diff --git a/include/python3.10/internal/pycore_pystate.h b/include/python3.10/internal/pycore_pystate.h
deleted file mode 100644
index 4b894f3..0000000
--- a/include/python3.10/internal/pycore_pystate.h
+++ /dev/null
@@ -1,153 +0,0 @@
-#ifndef Py_INTERNAL_PYSTATE_H
-#define Py_INTERNAL_PYSTATE_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-#include "pycore_runtime.h" /* PyRuntimeState */
-
-
-/* Check if the current thread is the main thread.
- Use _Py_IsMainInterpreter() to check if it's the main interpreter. */
-static inline int
-_Py_IsMainThread(void)
-{
- unsigned long thread = PyThread_get_thread_ident();
- return (thread == _PyRuntime.main_thread);
-}
-
-
-static inline int
-_Py_IsMainInterpreter(PyInterpreterState *interp)
-{
- /* Use directly _PyRuntime rather than tstate->interp->runtime, since
- this function is used in performance critical code path (ceval) */
- return (interp == _PyRuntime.interpreters.main);
-}
-
-
-/* Only handle signals on the main thread of the main interpreter. */
-static inline int
-_Py_ThreadCanHandleSignals(PyInterpreterState *interp)
-{
- return (_Py_IsMainThread() && interp == _PyRuntime.interpreters.main);
-}
-
-
-/* Only execute pending calls on the main thread. */
-static inline int
-_Py_ThreadCanHandlePendingCalls(void)
-{
- return _Py_IsMainThread();
-}
-
-
-/* Variable and macro for in-line access to current thread
- and interpreter state */
-
-#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
-PyAPI_FUNC(PyThreadState*) _PyThreadState_GetTSS(void);
-#endif
-
-static inline PyThreadState*
-_PyRuntimeState_GetThreadState(_PyRuntimeState *runtime)
-{
-#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
- return _PyThreadState_GetTSS();
-#else
- return (PyThreadState*)_Py_atomic_load_relaxed(&runtime->gilstate.tstate_current);
-#endif
-}
-
-/* Get the current Python thread state.
-
- Efficient macro reading directly the 'gilstate.tstate_current' atomic
- variable. The macro is unsafe: it does not check for error and it can
- return NULL.
-
- The caller must hold the GIL.
-
- See also PyThreadState_Get() and PyThreadState_GET(). */
-static inline PyThreadState*
-_PyThreadState_GET(void)
-{
-#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
- return _PyThreadState_GetTSS();
-#else
- return _PyRuntimeState_GetThreadState(&_PyRuntime);
-#endif
-}
-
-/* Redefine PyThreadState_GET() as an alias to _PyThreadState_GET() */
-#undef PyThreadState_GET
-#define PyThreadState_GET() _PyThreadState_GET()
-
-PyAPI_FUNC(void) _Py_NO_RETURN _Py_FatalError_TstateNULL(const char *func);
-
-static inline void
-_Py_EnsureFuncTstateNotNULL(const char *func, PyThreadState *tstate)
-{
- if (tstate == NULL) {
- _Py_FatalError_TstateNULL(func);
- }
-}
-
-// Call Py_FatalError() if tstate is NULL
-#define _Py_EnsureTstateNotNULL(tstate) \
- _Py_EnsureFuncTstateNotNULL(__func__, tstate)
-
-
-/* Get the current interpreter state.
-
- The macro is unsafe: it does not check for error and it can return NULL.
-
- The caller must hold the GIL.
-
- See also _PyInterpreterState_Get()
- and _PyGILState_GetInterpreterStateUnsafe(). */
-static inline PyInterpreterState* _PyInterpreterState_GET(void) {
- PyThreadState *tstate = _PyThreadState_GET();
-#ifdef Py_DEBUG
- _Py_EnsureTstateNotNULL(tstate);
-#endif
- return tstate->interp;
-}
-
-
-/* Other */
-
-PyAPI_FUNC(void) _PyThreadState_Init(
- PyThreadState *tstate);
-PyAPI_FUNC(void) _PyThreadState_DeleteExcept(
- _PyRuntimeState *runtime,
- PyThreadState *tstate);
-
-PyAPI_FUNC(PyThreadState *) _PyThreadState_Swap(
- struct _gilstate_runtime_state *gilstate,
- PyThreadState *newts);
-
-PyAPI_FUNC(PyStatus) _PyInterpreterState_Enable(_PyRuntimeState *runtime);
-
-#ifdef HAVE_FORK
-extern PyStatus _PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime);
-extern PyStatus _PyGILState_Reinit(_PyRuntimeState *runtime);
-extern void _PySignal_AfterFork(void);
-#endif
-
-
-PyAPI_FUNC(int) _PyState_AddModule(
- PyThreadState *tstate,
- PyObject* module,
- struct PyModuleDef* def);
-
-
-PyAPI_FUNC(int) _PyOS_InterruptOccurred(PyThreadState *tstate);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_PYSTATE_H */
diff --git a/include/python3.10/internal/pycore_runtime.h b/include/python3.10/internal/pycore_runtime.h
deleted file mode 100644
index bcd710c..0000000
--- a/include/python3.10/internal/pycore_runtime.h
+++ /dev/null
@@ -1,157 +0,0 @@
-#ifndef Py_INTERNAL_RUNTIME_H
-#define Py_INTERNAL_RUNTIME_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-#include "pycore_atomic.h" /* _Py_atomic_address */
-#include "pycore_gil.h" // struct _gil_runtime_state
-
-/* ceval state */
-
-struct _ceval_runtime_state {
- /* Request for checking signals. It is shared by all interpreters (see
- bpo-40513). Any thread of any interpreter can receive a signal, but only
- the main thread of the main interpreter can handle signals: see
- _Py_ThreadCanHandleSignals(). */
- _Py_atomic_int signals_pending;
-#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
- struct _gil_runtime_state gil;
-#endif
-};
-
-/* GIL state */
-
-struct _gilstate_runtime_state {
- /* bpo-26558: Flag to disable PyGILState_Check().
- If set to non-zero, PyGILState_Check() always return 1. */
- int check_enabled;
- /* Assuming the current thread holds the GIL, this is the
- PyThreadState for the current thread. */
- _Py_atomic_address tstate_current;
- /* The single PyInterpreterState used by this process'
- GILState implementation
- */
- /* TODO: Given interp_main, it may be possible to kill this ref */
- PyInterpreterState *autoInterpreterState;
- Py_tss_t autoTSSkey;
-};
-
-/* Runtime audit hook state */
-
-typedef struct _Py_AuditHookEntry {
- struct _Py_AuditHookEntry *next;
- Py_AuditHookFunction hookCFunction;
- void *userData;
-} _Py_AuditHookEntry;
-
-struct _Py_unicode_runtime_ids {
- PyThread_type_lock lock;
- // next_index value must be preserved when Py_Initialize()/Py_Finalize()
- // is called multiple times: see _PyUnicode_FromId() implementation.
- Py_ssize_t next_index;
-};
-
-/* Full Python runtime state */
-
-typedef struct pyruntimestate {
- /* Is running Py_PreInitialize()? */
- int preinitializing;
-
- /* Is Python preinitialized? Set to 1 by Py_PreInitialize() */
- int preinitialized;
-
- /* Is Python core initialized? Set to 1 by _Py_InitializeCore() */
- int core_initialized;
-
- /* Is Python fully initialized? Set to 1 by Py_Initialize() */
- int initialized;
-
- /* Set by Py_FinalizeEx(). Only reset to NULL if Py_Initialize()
- is called again.
-
- Use _PyRuntimeState_GetFinalizing() and _PyRuntimeState_SetFinalizing()
- to access it, don't access it directly. */
- _Py_atomic_address _finalizing;
-
- struct pyinterpreters {
- PyThread_type_lock mutex;
- PyInterpreterState *head;
- PyInterpreterState *main;
- /* _next_interp_id is an auto-numbered sequence of small
- integers. It gets initialized in _PyInterpreterState_Init(),
- which is called in Py_Initialize(), and used in
- PyInterpreterState_New(). A negative interpreter ID
- indicates an error occurred. The main interpreter will
- always have an ID of 0. Overflow results in a RuntimeError.
- If that becomes a problem later then we can adjust, e.g. by
- using a Python int. */
- int64_t next_id;
- } interpreters;
- // XXX Remove this field once we have a tp_* slot.
- struct _xidregistry {
- PyThread_type_lock mutex;
- struct _xidregitem *head;
- } xidregistry;
-
- unsigned long main_thread;
-
-#define NEXITFUNCS 32
- void (*exitfuncs[NEXITFUNCS])(void);
- int nexitfuncs;
-
- struct _ceval_runtime_state ceval;
- struct _gilstate_runtime_state gilstate;
-
- PyPreConfig preconfig;
-
- // Audit values must be preserved when Py_Initialize()/Py_Finalize()
- // is called multiple times.
- Py_OpenCodeHookFunction open_code_hook;
- void *open_code_userdata;
- _Py_AuditHookEntry *audit_hook_head;
-
- struct _Py_unicode_runtime_ids unicode_ids;
-
- // XXX Consolidate globals found via the check-c-globals script.
-} _PyRuntimeState;
-
-#define _PyRuntimeState_INIT \
- {.preinitialized = 0, .core_initialized = 0, .initialized = 0}
-/* Note: _PyRuntimeState_INIT sets other fields to 0/NULL */
-
-
-PyAPI_DATA(_PyRuntimeState) _PyRuntime;
-
-PyAPI_FUNC(PyStatus) _PyRuntimeState_Init(_PyRuntimeState *runtime);
-PyAPI_FUNC(void) _PyRuntimeState_Fini(_PyRuntimeState *runtime);
-
-#ifdef HAVE_FORK
-extern PyStatus _PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime);
-#endif
-
-/* Initialize _PyRuntimeState.
- Return NULL on success, or return an error message on failure. */
-PyAPI_FUNC(PyStatus) _PyRuntime_Initialize(void);
-
-PyAPI_FUNC(void) _PyRuntime_Finalize(void);
-
-
-static inline PyThreadState*
-_PyRuntimeState_GetFinalizing(_PyRuntimeState *runtime) {
- return (PyThreadState*)_Py_atomic_load_relaxed(&runtime->_finalizing);
-}
-
-static inline void
-_PyRuntimeState_SetFinalizing(_PyRuntimeState *runtime, PyThreadState *tstate) {
- _Py_atomic_store_relaxed(&runtime->_finalizing, (uintptr_t)tstate);
-}
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_RUNTIME_H */
diff --git a/include/python3.10/internal/pycore_structseq.h b/include/python3.10/internal/pycore_structseq.h
deleted file mode 100644
index 84c8d47..0000000
--- a/include/python3.10/internal/pycore_structseq.h
+++ /dev/null
@@ -1,21 +0,0 @@
-#ifndef Py_INTERNAL_STRUCTSEQ_H
-#define Py_INTERNAL_STRUCTSEQ_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-
-PyAPI_FUNC(int) _PyStructSequence_InitType(
- PyTypeObject *type,
- PyStructSequence_Desc *desc,
- unsigned long tp_flags);
-
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_STRUCTSEQ_H */
diff --git a/include/python3.10/internal/pycore_symtable.h b/include/python3.10/internal/pycore_symtable.h
deleted file mode 100644
index a2e520b..0000000
--- a/include/python3.10/internal/pycore_symtable.h
+++ /dev/null
@@ -1,133 +0,0 @@
-#ifndef Py_INTERNAL_SYMTABLE_H
-#define Py_INTERNAL_SYMTABLE_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-struct _mod; // Type defined in pycore_ast.h
-
-typedef enum _block_type { FunctionBlock, ClassBlock, ModuleBlock, AnnotationBlock }
- _Py_block_ty;
-
-typedef enum _comprehension_type {
- NoComprehension = 0,
- ListComprehension = 1,
- DictComprehension = 2,
- SetComprehension = 3,
- GeneratorExpression = 4 } _Py_comprehension_ty;
-
-struct _symtable_entry;
-
-struct symtable {
- PyObject *st_filename; /* name of file being compiled,
- decoded from the filesystem encoding */
- struct _symtable_entry *st_cur; /* current symbol table entry */
- struct _symtable_entry *st_top; /* symbol table entry for module */
- PyObject *st_blocks; /* dict: map AST node addresses
- * to symbol table entries */
- PyObject *st_stack; /* list: stack of namespace info */
- PyObject *st_global; /* borrowed ref to st_top->ste_symbols */
- int st_nblocks; /* number of blocks used. kept for
- consistency with the corresponding
- compiler structure */
- PyObject *st_private; /* name of current class or NULL */
- PyFutureFeatures *st_future; /* module's future features that affect
- the symbol table */
- int recursion_depth; /* current recursion depth */
- int recursion_limit; /* recursion limit */
-};
-
-typedef struct _symtable_entry {
- PyObject_HEAD
- PyObject *ste_id; /* int: key in ste_table->st_blocks */
- PyObject *ste_symbols; /* dict: variable names to flags */
- PyObject *ste_name; /* string: name of current block */
- PyObject *ste_varnames; /* list of function parameters */
- PyObject *ste_children; /* list of child blocks */
- PyObject *ste_directives;/* locations of global and nonlocal statements */
- _Py_block_ty ste_type; /* module, class or function */
- int ste_nested; /* true if block is nested */
- unsigned ste_free : 1; /* true if block has free variables */
- unsigned ste_child_free : 1; /* true if a child block has free vars,
- including free refs to globals */
- unsigned ste_generator : 1; /* true if namespace is a generator */
- unsigned ste_coroutine : 1; /* true if namespace is a coroutine */
- _Py_comprehension_ty ste_comprehension; /* Kind of comprehension (if any) */
- unsigned ste_varargs : 1; /* true if block has varargs */
- unsigned ste_varkeywords : 1; /* true if block has varkeywords */
- unsigned ste_returns_value : 1; /* true if namespace uses return with
- an argument */
- unsigned ste_needs_class_closure : 1; /* for class scopes, true if a
- closure over __class__
- should be created */
- unsigned ste_comp_iter_target : 1; /* true if visiting comprehension target */
- int ste_comp_iter_expr; /* non-zero if visiting a comprehension range expression */
- int ste_lineno; /* first line of block */
- int ste_col_offset; /* offset of first line of block */
- int ste_end_lineno; /* end line of block */
- int ste_end_col_offset; /* end offset of first line of block */
- int ste_opt_lineno; /* lineno of last exec or import * */
- int ste_opt_col_offset; /* offset of last exec or import * */
- struct symtable *ste_table;
-} PySTEntryObject;
-
-extern PyTypeObject PySTEntry_Type;
-
-#define PySTEntry_Check(op) Py_IS_TYPE(op, &PySTEntry_Type)
-
-extern int _PyST_GetScope(PySTEntryObject *, PyObject *);
-
-extern struct symtable* _PySymtable_Build(
- struct _mod *mod,
- PyObject *filename,
- PyFutureFeatures *future);
-PyAPI_FUNC(PySTEntryObject *) PySymtable_Lookup(struct symtable *, void *);
-
-extern void _PySymtable_Free(struct symtable *);
-
-/* Flags for def-use information */
-
-#define DEF_GLOBAL 1 /* global stmt */
-#define DEF_LOCAL 2 /* assignment in code block */
-#define DEF_PARAM 2<<1 /* formal parameter */
-#define DEF_NONLOCAL 2<<2 /* nonlocal stmt */
-#define USE 2<<3 /* name is used */
-#define DEF_FREE 2<<4 /* name used but not defined in nested block */
-#define DEF_FREE_CLASS 2<<5 /* free variable from class's method */
-#define DEF_IMPORT 2<<6 /* assignment occurred via import */
-#define DEF_ANNOT 2<<7 /* this name is annotated */
-#define DEF_COMP_ITER 2<<8 /* this name is a comprehension iteration variable */
-
-#define DEF_BOUND (DEF_LOCAL | DEF_PARAM | DEF_IMPORT)
-
-/* GLOBAL_EXPLICIT and GLOBAL_IMPLICIT are used internally by the symbol
- table. GLOBAL is returned from PyST_GetScope() for either of them.
- It is stored in ste_symbols at bits 12-15.
-*/
-#define SCOPE_OFFSET 11
-#define SCOPE_MASK (DEF_GLOBAL | DEF_LOCAL | DEF_PARAM | DEF_NONLOCAL)
-
-#define LOCAL 1
-#define GLOBAL_EXPLICIT 2
-#define GLOBAL_IMPLICIT 3
-#define FREE 4
-#define CELL 5
-
-#define GENERATOR 1
-#define GENERATOR_EXPRESSION 2
-
-// Used by symtablemodule.c
-extern struct symtable* _Py_SymtableStringObjectFlags(
- const char *str,
- PyObject *filename,
- int start,
- PyCompilerFlags *flags);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_SYMTABLE_H */
diff --git a/include/python3.10/internal/pycore_sysmodule.h b/include/python3.10/internal/pycore_sysmodule.h
deleted file mode 100644
index 738a774..0000000
--- a/include/python3.10/internal/pycore_sysmodule.h
+++ /dev/null
@@ -1,24 +0,0 @@
-#ifndef Py_INTERNAL_SYSMODULE_H
-#define Py_INTERNAL_SYSMODULE_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-PyAPI_FUNC(int) _PySys_Audit(
- PyThreadState *tstate,
- const char *event,
- const char *argFormat,
- ...);
-
-/* We want minimal exposure of this function, so use extern rather than
- PyAPI_FUNC() to not export the symbol. */
-extern void _PySys_ClearAuditHooks(PyThreadState *tstate);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_SYSMODULE_H */
diff --git a/include/python3.10/internal/pycore_traceback.h b/include/python3.10/internal/pycore_traceback.h
deleted file mode 100644
index c01a476..0000000
--- a/include/python3.10/internal/pycore_traceback.h
+++ /dev/null
@@ -1,93 +0,0 @@
-#ifndef Py_INTERNAL_TRACEBACK_H
-#define Py_INTERNAL_TRACEBACK_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-/* Forward declaration */
-struct _is;
-
-/* Write the Python traceback into the file 'fd'. For example:
-
- Traceback (most recent call first):
- File "xxx", line xxx in <xxx>
- File "xxx", line xxx in <xxx>
- ...
- File "xxx", line xxx in <xxx>
-
- This function is written for debug purpose only, to dump the traceback in
- the worst case: after a segmentation fault, at fatal error, etc. That's why,
- it is very limited. Strings are truncated to 100 characters and encoded to
- ASCII with backslashreplace. It doesn't write the source code, only the
- function name, filename and line number of each frame. Write only the first
- 100 frames: if the traceback is truncated, write the line " ...".
-
- This function is signal safe. */
-
-PyAPI_FUNC(void) _Py_DumpTraceback(
- int fd,
- PyThreadState *tstate);
-
-/* Write the traceback of all threads into the file 'fd'. current_thread can be
- NULL.
-
- Return NULL on success, or an error message on error.
-
- This function is written for debug purpose only. It calls
- _Py_DumpTraceback() for each thread, and so has the same limitations. It
- only write the traceback of the first 100 threads: write "..." if there are
- more threads.
-
- If current_tstate is NULL, the function tries to get the Python thread state
- of the current thread. It is not an error if the function is unable to get
- the current Python thread state.
-
- If interp is NULL, the function tries to get the interpreter state from
- the current Python thread state, or from
- _PyGILState_GetInterpreterStateUnsafe() in last resort.
-
- It is better to pass NULL to interp and current_tstate, the function tries
- different options to retrieve this information.
-
- This function is signal safe. */
-
-PyAPI_FUNC(const char*) _Py_DumpTracebackThreads(
- int fd,
- struct _is *interp,
- PyThreadState *current_tstate);
-
-/* Write a Unicode object into the file descriptor fd. Encode the string to
- ASCII using the backslashreplace error handler.
-
- Do nothing if text is not a Unicode object. The function accepts Unicode
- string which is not ready (PyUnicode_WCHAR_KIND).
-
- This function is signal safe. */
-PyAPI_FUNC(void) _Py_DumpASCII(int fd, PyObject *text);
-
-/* Format an integer as decimal into the file descriptor fd.
-
- This function is signal safe. */
-PyAPI_FUNC(void) _Py_DumpDecimal(
- int fd,
- size_t value);
-
-/* Format an integer as hexadecimal with width digits into fd file descriptor.
- The function is signal safe. */
-PyAPI_FUNC(void) _Py_DumpHexadecimal(
- int fd,
- uintptr_t value,
- Py_ssize_t width);
-
-PyAPI_FUNC(PyObject*) _PyTraceBack_FromFrame(
- PyObject *tb_next,
- PyFrameObject *frame);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_TRACEBACK_H */
diff --git a/include/python3.10/internal/pycore_tuple.h b/include/python3.10/internal/pycore_tuple.h
deleted file mode 100644
index 5353e18..0000000
--- a/include/python3.10/internal/pycore_tuple.h
+++ /dev/null
@@ -1,20 +0,0 @@
-#ifndef Py_INTERNAL_TUPLE_H
-#define Py_INTERNAL_TUPLE_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-#include "tupleobject.h" /* _PyTuple_CAST() */
-
-#define _PyTuple_ITEMS(op) (_PyTuple_CAST(op)->ob_item)
-
-PyAPI_FUNC(PyObject *) _PyTuple_FromArray(PyObject *const *, Py_ssize_t);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_TUPLE_H */
diff --git a/include/python3.10/internal/pycore_unionobject.h b/include/python3.10/internal/pycore_unionobject.h
deleted file mode 100644
index 9962f57..0000000
--- a/include/python3.10/internal/pycore_unionobject.h
+++ /dev/null
@@ -1,22 +0,0 @@
-#ifndef Py_INTERNAL_UNIONOBJECT_H
-#define Py_INTERNAL_UNIONOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-extern PyTypeObject _PyUnion_Type;
-#define _PyUnion_Check(op) Py_IS_TYPE(op, &_PyUnion_Type)
-extern PyObject *_Py_union_type_or(PyObject *, PyObject *);
-
-#define _PyGenericAlias_Check(op) PyObject_TypeCheck(op, &Py_GenericAliasType)
-extern PyObject *_Py_subs_parameters(PyObject *, PyObject *, PyObject *, PyObject *);
-extern PyObject *_Py_make_parameters(PyObject *);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_UNIONOBJECT_H */
diff --git a/include/python3.10/internal/pycore_warnings.h b/include/python3.10/internal/pycore_warnings.h
deleted file mode 100644
index f728ec3..0000000
--- a/include/python3.10/internal/pycore_warnings.h
+++ /dev/null
@@ -1,25 +0,0 @@
-#ifndef Py_INTERNAL_WARNINGS_H
-#define Py_INTERNAL_WARNINGS_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_BUILD_CORE
-# error "this header requires Py_BUILD_CORE define"
-#endif
-
-struct _warnings_runtime_state {
- /* Both 'filters' and 'onceregistry' can be set in warnings.py;
- get_warnings_attr() will reset these variables accordingly. */
- PyObject *filters; /* List */
- PyObject *once_registry; /* Dict */
- PyObject *default_action; /* String */
- long filters_version;
-};
-
-extern int _PyWarnings_InitState(PyInterpreterState *interp);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERNAL_WARNINGS_H */
diff --git a/include/python3.10/interpreteridobject.h b/include/python3.10/interpreteridobject.h
deleted file mode 100644
index e744fcd..0000000
--- a/include/python3.10/interpreteridobject.h
+++ /dev/null
@@ -1,17 +0,0 @@
-#ifndef Py_INTERPRETERIDOBJECT_H
-#define Py_INTERPRETERIDOBJECT_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_INTERPRETERIDOBJECT_H
-# include "cpython/interpreteridobject.h"
-# undef Py_CPYTHON_INTERPRETERIDOBJECT_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_INTERPRETERIDOBJECT_H */
diff --git a/include/python3.10/listobject.h b/include/python3.10/listobject.h
deleted file mode 100644
index 2a8a255..0000000
--- a/include/python3.10/listobject.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/* List object interface
-
- Another generally useful object type is a list of object pointers.
- This is a mutable type: the list items can be changed, and items can be
- added or removed. Out-of-range indices or non-list objects are ignored.
-
- WARNING: PyList_SetItem does not increment the new item's reference count,
- but does decrement the reference count of the item it replaces, if not nil.
- It does *decrement* the reference count if it is *not* inserted in the list.
- Similarly, PyList_GetItem does not increment the returned item's reference
- count.
-*/
-
-#ifndef Py_LISTOBJECT_H
-#define Py_LISTOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-PyAPI_DATA(PyTypeObject) PyList_Type;
-PyAPI_DATA(PyTypeObject) PyListIter_Type;
-PyAPI_DATA(PyTypeObject) PyListRevIter_Type;
-
-#define PyList_Check(op) \
- PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_LIST_SUBCLASS)
-#define PyList_CheckExact(op) Py_IS_TYPE(op, &PyList_Type)
-
-PyAPI_FUNC(PyObject *) PyList_New(Py_ssize_t size);
-PyAPI_FUNC(Py_ssize_t) PyList_Size(PyObject *);
-
-PyAPI_FUNC(PyObject *) PyList_GetItem(PyObject *, Py_ssize_t);
-PyAPI_FUNC(int) PyList_SetItem(PyObject *, Py_ssize_t, PyObject *);
-PyAPI_FUNC(int) PyList_Insert(PyObject *, Py_ssize_t, PyObject *);
-PyAPI_FUNC(int) PyList_Append(PyObject *, PyObject *);
-
-PyAPI_FUNC(PyObject *) PyList_GetSlice(PyObject *, Py_ssize_t, Py_ssize_t);
-PyAPI_FUNC(int) PyList_SetSlice(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);
-
-PyAPI_FUNC(int) PyList_Sort(PyObject *);
-PyAPI_FUNC(int) PyList_Reverse(PyObject *);
-PyAPI_FUNC(PyObject *) PyList_AsTuple(PyObject *);
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_LISTOBJECT_H
-# include "cpython/listobject.h"
-# undef Py_CPYTHON_LISTOBJECT_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_LISTOBJECT_H */
diff --git a/include/python3.10/longintrepr.h b/include/python3.10/longintrepr.h
deleted file mode 100644
index ff4155f..0000000
--- a/include/python3.10/longintrepr.h
+++ /dev/null
@@ -1,99 +0,0 @@
-#ifndef Py_LIMITED_API
-#ifndef Py_LONGINTREPR_H
-#define Py_LONGINTREPR_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-/* This is published for the benefit of "friends" marshal.c and _decimal.c. */
-
-/* Parameters of the integer representation. There are two different
- sets of parameters: one set for 30-bit digits, stored in an unsigned 32-bit
- integer type, and one set for 15-bit digits with each digit stored in an
- unsigned short. The value of PYLONG_BITS_IN_DIGIT, defined either at
- configure time or in pyport.h, is used to decide which digit size to use.
-
- Type 'digit' should be able to hold 2*PyLong_BASE-1, and type 'twodigits'
- should be an unsigned integer type able to hold all integers up to
- PyLong_BASE*PyLong_BASE-1. x_sub assumes that 'digit' is an unsigned type,
- and that overflow is handled by taking the result modulo 2**N for some N >
- PyLong_SHIFT. The majority of the code doesn't care about the precise
- value of PyLong_SHIFT, but there are some notable exceptions:
-
- - long_pow() requires that PyLong_SHIFT be divisible by 5
-
- - PyLong_{As,From}ByteArray require that PyLong_SHIFT be at least 8
-
- - long_hash() requires that PyLong_SHIFT is *strictly* less than the number
- of bits in an unsigned long, as do the PyLong <-> long (or unsigned long)
- conversion functions
-
- - the Python int <-> size_t/Py_ssize_t conversion functions expect that
- PyLong_SHIFT is strictly less than the number of bits in a size_t
-
- - the marshal code currently expects that PyLong_SHIFT is a multiple of 15
-
- - NSMALLNEGINTS and NSMALLPOSINTS should be small enough to fit in a single
- digit; with the current values this forces PyLong_SHIFT >= 9
-
- The values 15 and 30 should fit all of the above requirements, on any
- platform.
-*/
-
-#if PYLONG_BITS_IN_DIGIT == 30
-typedef uint32_t digit;
-typedef int32_t sdigit; /* signed variant of digit */
-typedef uint64_t twodigits;
-typedef int64_t stwodigits; /* signed variant of twodigits */
-#define PyLong_SHIFT 30
-#define _PyLong_DECIMAL_SHIFT 9 /* max(e such that 10**e fits in a digit) */
-#define _PyLong_DECIMAL_BASE ((digit)1000000000) /* 10 ** DECIMAL_SHIFT */
-#elif PYLONG_BITS_IN_DIGIT == 15
-typedef unsigned short digit;
-typedef short sdigit; /* signed variant of digit */
-typedef unsigned long twodigits;
-typedef long stwodigits; /* signed variant of twodigits */
-#define PyLong_SHIFT 15
-#define _PyLong_DECIMAL_SHIFT 4 /* max(e such that 10**e fits in a digit) */
-#define _PyLong_DECIMAL_BASE ((digit)10000) /* 10 ** DECIMAL_SHIFT */
-#else
-#error "PYLONG_BITS_IN_DIGIT should be 15 or 30"
-#endif
-#define PyLong_BASE ((digit)1 << PyLong_SHIFT)
-#define PyLong_MASK ((digit)(PyLong_BASE - 1))
-
-#if PyLong_SHIFT % 5 != 0
-#error "longobject.c requires that PyLong_SHIFT be divisible by 5"
-#endif
-
-/* Long integer representation.
- The absolute value of a number is equal to
- SUM(for i=0 through abs(ob_size)-1) ob_digit[i] * 2**(SHIFT*i)
- Negative numbers are represented with ob_size < 0;
- zero is represented by ob_size == 0.
- In a normalized number, ob_digit[abs(ob_size)-1] (the most significant
- digit) is never zero. Also, in all cases, for all valid i,
- 0 <= ob_digit[i] <= MASK.
- The allocation function takes care of allocating extra memory
- so that ob_digit[0] ... ob_digit[abs(ob_size)-1] are actually available.
-
- CAUTION: Generic code manipulating subtypes of PyVarObject has to
- aware that ints abuse ob_size's sign bit.
-*/
-
-struct _longobject {
- PyObject_VAR_HEAD
- digit ob_digit[1];
-};
-
-PyAPI_FUNC(PyLongObject *) _PyLong_New(Py_ssize_t);
-
-/* Return a copy of src. */
-PyAPI_FUNC(PyObject *) _PyLong_Copy(PyLongObject *src);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_LONGINTREPR_H */
-#endif /* Py_LIMITED_API */
diff --git a/include/python3.10/longobject.h b/include/python3.10/longobject.h
deleted file mode 100644
index e2301d7..0000000
--- a/include/python3.10/longobject.h
+++ /dev/null
@@ -1,220 +0,0 @@
-#ifndef Py_LONGOBJECT_H
-#define Py_LONGOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-/* Long (arbitrary precision) integer object interface */
-
-typedef struct _longobject PyLongObject; /* Revealed in longintrepr.h */
-
-PyAPI_DATA(PyTypeObject) PyLong_Type;
-
-#define PyLong_Check(op) \
- PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_LONG_SUBCLASS)
-#define PyLong_CheckExact(op) Py_IS_TYPE(op, &PyLong_Type)
-
-PyAPI_FUNC(PyObject *) PyLong_FromLong(long);
-PyAPI_FUNC(PyObject *) PyLong_FromUnsignedLong(unsigned long);
-PyAPI_FUNC(PyObject *) PyLong_FromSize_t(size_t);
-PyAPI_FUNC(PyObject *) PyLong_FromSsize_t(Py_ssize_t);
-PyAPI_FUNC(PyObject *) PyLong_FromDouble(double);
-PyAPI_FUNC(long) PyLong_AsLong(PyObject *);
-PyAPI_FUNC(long) PyLong_AsLongAndOverflow(PyObject *, int *);
-PyAPI_FUNC(Py_ssize_t) PyLong_AsSsize_t(PyObject *);
-PyAPI_FUNC(size_t) PyLong_AsSize_t(PyObject *);
-PyAPI_FUNC(unsigned long) PyLong_AsUnsignedLong(PyObject *);
-PyAPI_FUNC(unsigned long) PyLong_AsUnsignedLongMask(PyObject *);
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(int) _PyLong_AsInt(PyObject *);
-#endif
-PyAPI_FUNC(PyObject *) PyLong_GetInfo(void);
-
-/* It may be useful in the future. I've added it in the PyInt -> PyLong
- cleanup to keep the extra information. [CH] */
-#define PyLong_AS_LONG(op) PyLong_AsLong(op)
-
-/* Issue #1983: pid_t can be longer than a C long on some systems */
-#if !defined(SIZEOF_PID_T) || SIZEOF_PID_T == SIZEOF_INT
-#define _Py_PARSE_PID "i"
-#define PyLong_FromPid PyLong_FromLong
-#define PyLong_AsPid PyLong_AsLong
-#elif SIZEOF_PID_T == SIZEOF_LONG
-#define _Py_PARSE_PID "l"
-#define PyLong_FromPid PyLong_FromLong
-#define PyLong_AsPid PyLong_AsLong
-#elif defined(SIZEOF_LONG_LONG) && SIZEOF_PID_T == SIZEOF_LONG_LONG
-#define _Py_PARSE_PID "L"
-#define PyLong_FromPid PyLong_FromLongLong
-#define PyLong_AsPid PyLong_AsLongLong
-#else
-#error "sizeof(pid_t) is neither sizeof(int), sizeof(long) or sizeof(long long)"
-#endif /* SIZEOF_PID_T */
-
-#if SIZEOF_VOID_P == SIZEOF_INT
-# define _Py_PARSE_INTPTR "i"
-# define _Py_PARSE_UINTPTR "I"
-#elif SIZEOF_VOID_P == SIZEOF_LONG
-# define _Py_PARSE_INTPTR "l"
-# define _Py_PARSE_UINTPTR "k"
-#elif defined(SIZEOF_LONG_LONG) && SIZEOF_VOID_P == SIZEOF_LONG_LONG
-# define _Py_PARSE_INTPTR "L"
-# define _Py_PARSE_UINTPTR "K"
-#else
-# error "void* different in size from int, long and long long"
-#endif /* SIZEOF_VOID_P */
-
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(int) _PyLong_UnsignedShort_Converter(PyObject *, void *);
-PyAPI_FUNC(int) _PyLong_UnsignedInt_Converter(PyObject *, void *);
-PyAPI_FUNC(int) _PyLong_UnsignedLong_Converter(PyObject *, void *);
-PyAPI_FUNC(int) _PyLong_UnsignedLongLong_Converter(PyObject *, void *);
-PyAPI_FUNC(int) _PyLong_Size_t_Converter(PyObject *, void *);
-#endif
-
-/* Used by Python/mystrtoul.c, _PyBytes_FromHex(),
- _PyBytes_DecodeEscape(), etc. */
-#ifndef Py_LIMITED_API
-PyAPI_DATA(unsigned char) _PyLong_DigitValue[256];
-#endif
-
-/* _PyLong_Frexp returns a double x and an exponent e such that the
- true value is approximately equal to x * 2**e. e is >= 0. x is
- 0.0 if and only if the input is 0 (in which case, e and x are both
- zeroes); otherwise, 0.5 <= abs(x) < 1.0. On overflow, which is
- possible if the number of bits doesn't fit into a Py_ssize_t, sets
- OverflowError and returns -1.0 for x, 0 for e. */
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(double) _PyLong_Frexp(PyLongObject *a, Py_ssize_t *e);
-#endif
-
-PyAPI_FUNC(double) PyLong_AsDouble(PyObject *);
-PyAPI_FUNC(PyObject *) PyLong_FromVoidPtr(void *);
-PyAPI_FUNC(void *) PyLong_AsVoidPtr(PyObject *);
-
-PyAPI_FUNC(PyObject *) PyLong_FromLongLong(long long);
-PyAPI_FUNC(PyObject *) PyLong_FromUnsignedLongLong(unsigned long long);
-PyAPI_FUNC(long long) PyLong_AsLongLong(PyObject *);
-PyAPI_FUNC(unsigned long long) PyLong_AsUnsignedLongLong(PyObject *);
-PyAPI_FUNC(unsigned long long) PyLong_AsUnsignedLongLongMask(PyObject *);
-PyAPI_FUNC(long long) PyLong_AsLongLongAndOverflow(PyObject *, int *);
-
-PyAPI_FUNC(PyObject *) PyLong_FromString(const char *, char **, int);
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(PyObject *) PyLong_FromUnicodeObject(PyObject *u, int base);
-PyAPI_FUNC(PyObject *) _PyLong_FromBytes(const char *, Py_ssize_t, int);
-#endif
-
-#ifndef Py_LIMITED_API
-/* _PyLong_Sign. Return 0 if v is 0, -1 if v < 0, +1 if v > 0.
- v must not be NULL, and must be a normalized long.
- There are no error cases.
-*/
-PyAPI_FUNC(int) _PyLong_Sign(PyObject *v);
-
-
-/* _PyLong_NumBits. Return the number of bits needed to represent the
- absolute value of a long. For example, this returns 1 for 1 and -1, 2
- for 2 and -2, and 2 for 3 and -3. It returns 0 for 0.
- v must not be NULL, and must be a normalized long.
- (size_t)-1 is returned and OverflowError set if the true result doesn't
- fit in a size_t.
-*/
-PyAPI_FUNC(size_t) _PyLong_NumBits(PyObject *v);
-
-/* _PyLong_DivmodNear. Given integers a and b, compute the nearest
- integer q to the exact quotient a / b, rounding to the nearest even integer
- in the case of a tie. Return (q, r), where r = a - q*b. The remainder r
- will satisfy abs(r) <= abs(b)/2, with equality possible only if q is
- even.
-*/
-PyAPI_FUNC(PyObject *) _PyLong_DivmodNear(PyObject *, PyObject *);
-
-/* _PyLong_FromByteArray: View the n unsigned bytes as a binary integer in
- base 256, and return a Python int with the same numeric value.
- If n is 0, the integer is 0. Else:
- If little_endian is 1/true, bytes[n-1] is the MSB and bytes[0] the LSB;
- else (little_endian is 0/false) bytes[0] is the MSB and bytes[n-1] the
- LSB.
- If is_signed is 0/false, view the bytes as a non-negative integer.
- If is_signed is 1/true, view the bytes as a 2's-complement integer,
- non-negative if bit 0x80 of the MSB is clear, negative if set.
- Error returns:
- + Return NULL with the appropriate exception set if there's not
- enough memory to create the Python int.
-*/
-PyAPI_FUNC(PyObject *) _PyLong_FromByteArray(
- const unsigned char* bytes, size_t n,
- int little_endian, int is_signed);
-
-/* _PyLong_AsByteArray: Convert the least-significant 8*n bits of long
- v to a base-256 integer, stored in array bytes. Normally return 0,
- return -1 on error.
- If little_endian is 1/true, store the MSB at bytes[n-1] and the LSB at
- bytes[0]; else (little_endian is 0/false) store the MSB at bytes[0] and
- the LSB at bytes[n-1].
- If is_signed is 0/false, it's an error if v < 0; else (v >= 0) n bytes
- are filled and there's nothing special about bit 0x80 of the MSB.
- If is_signed is 1/true, bytes is filled with the 2's-complement
- representation of v's value. Bit 0x80 of the MSB is the sign bit.
- Error returns (-1):
- + is_signed is 0 and v < 0. TypeError is set in this case, and bytes
- isn't altered.
- + n isn't big enough to hold the full mathematical value of v. For
- example, if is_signed is 0 and there are more digits in the v than
- fit in n; or if is_signed is 1, v < 0, and n is just 1 bit shy of
- being large enough to hold a sign bit. OverflowError is set in this
- case, but bytes holds the least-significant n bytes of the true value.
-*/
-PyAPI_FUNC(int) _PyLong_AsByteArray(PyLongObject* v,
- unsigned char* bytes, size_t n,
- int little_endian, int is_signed);
-
-/* _PyLong_Format: Convert the long to a string object with given base,
- appending a base prefix of 0[box] if base is 2, 8 or 16. */
-PyAPI_FUNC(PyObject *) _PyLong_Format(PyObject *obj, int base);
-
-PyAPI_FUNC(int) _PyLong_FormatWriter(
- _PyUnicodeWriter *writer,
- PyObject *obj,
- int base,
- int alternate);
-
-PyAPI_FUNC(char*) _PyLong_FormatBytesWriter(
- _PyBytesWriter *writer,
- char *str,
- PyObject *obj,
- int base,
- int alternate);
-
-/* Format the object based on the format_spec, as defined in PEP 3101
- (Advanced String Formatting). */
-PyAPI_FUNC(int) _PyLong_FormatAdvancedWriter(
- _PyUnicodeWriter *writer,
- PyObject *obj,
- PyObject *format_spec,
- Py_ssize_t start,
- Py_ssize_t end);
-#endif /* Py_LIMITED_API */
-
-/* These aren't really part of the int object, but they're handy. The
- functions are in Python/mystrtoul.c.
- */
-PyAPI_FUNC(unsigned long) PyOS_strtoul(const char *, char **, int);
-PyAPI_FUNC(long) PyOS_strtol(const char *, char **, int);
-
-#ifndef Py_LIMITED_API
-/* For use by the gcd function in mathmodule.c */
-PyAPI_FUNC(PyObject *) _PyLong_GCD(PyObject *, PyObject *);
-#endif /* !Py_LIMITED_API */
-
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(PyObject *) _PyLong_Rshift(PyObject *, size_t);
-PyAPI_FUNC(PyObject *) _PyLong_Lshift(PyObject *, size_t);
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_LONGOBJECT_H */
diff --git a/include/python3.10/marshal.h b/include/python3.10/marshal.h
deleted file mode 100644
index 09d9337..0000000
--- a/include/python3.10/marshal.h
+++ /dev/null
@@ -1,28 +0,0 @@
-
-/* Interface for marshal.c */
-
-#ifndef Py_MARSHAL_H
-#define Py_MARSHAL_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define Py_MARSHAL_VERSION 4
-
-PyAPI_FUNC(void) PyMarshal_WriteLongToFile(long, FILE *, int);
-PyAPI_FUNC(void) PyMarshal_WriteObjectToFile(PyObject *, FILE *, int);
-PyAPI_FUNC(PyObject *) PyMarshal_WriteObjectToString(PyObject *, int);
-
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(long) PyMarshal_ReadLongFromFile(FILE *);
-PyAPI_FUNC(int) PyMarshal_ReadShortFromFile(FILE *);
-PyAPI_FUNC(PyObject *) PyMarshal_ReadObjectFromFile(FILE *);
-PyAPI_FUNC(PyObject *) PyMarshal_ReadLastObjectFromFile(FILE *);
-#endif
-PyAPI_FUNC(PyObject *) PyMarshal_ReadObjectFromString(const char *,
- Py_ssize_t);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_MARSHAL_H */
diff --git a/include/python3.10/memoryobject.h b/include/python3.10/memoryobject.h
deleted file mode 100644
index 306028f..0000000
--- a/include/python3.10/memoryobject.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/* Memory view object. In Python this is available as "memoryview". */
-
-#ifndef Py_MEMORYOBJECT_H
-#define Py_MEMORYOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_LIMITED_API
-PyAPI_DATA(PyTypeObject) _PyManagedBuffer_Type;
-#endif
-PyAPI_DATA(PyTypeObject) PyMemoryView_Type;
-
-#define PyMemoryView_Check(op) Py_IS_TYPE(op, &PyMemoryView_Type)
-
-#ifndef Py_LIMITED_API
-/* Get a pointer to the memoryview's private copy of the exporter's buffer. */
-#define PyMemoryView_GET_BUFFER(op) (&((PyMemoryViewObject *)(op))->view)
-/* Get a pointer to the exporting object (this may be NULL!). */
-#define PyMemoryView_GET_BASE(op) (((PyMemoryViewObject *)(op))->view.obj)
-#endif
-
-PyAPI_FUNC(PyObject *) PyMemoryView_FromObject(PyObject *base);
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-PyAPI_FUNC(PyObject *) PyMemoryView_FromMemory(char *mem, Py_ssize_t size,
- int flags);
-#endif
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(PyObject *) PyMemoryView_FromBuffer(Py_buffer *info);
-#endif
-PyAPI_FUNC(PyObject *) PyMemoryView_GetContiguous(PyObject *base,
- int buffertype,
- char order);
-
-
-/* The structs are declared here so that macros can work, but they shouldn't
- be considered public. Don't access their fields directly, use the macros
- and functions instead! */
-#ifndef Py_LIMITED_API
-#define _Py_MANAGED_BUFFER_RELEASED 0x001 /* access to exporter blocked */
-#define _Py_MANAGED_BUFFER_FREE_FORMAT 0x002 /* free format */
-typedef struct {
- PyObject_HEAD
- int flags; /* state flags */
- Py_ssize_t exports; /* number of direct memoryview exports */
- Py_buffer master; /* snapshot buffer obtained from the original exporter */
-} _PyManagedBufferObject;
-
-
-/* memoryview state flags */
-#define _Py_MEMORYVIEW_RELEASED 0x001 /* access to master buffer blocked */
-#define _Py_MEMORYVIEW_C 0x002 /* C-contiguous layout */
-#define _Py_MEMORYVIEW_FORTRAN 0x004 /* Fortran contiguous layout */
-#define _Py_MEMORYVIEW_SCALAR 0x008 /* scalar: ndim = 0 */
-#define _Py_MEMORYVIEW_PIL 0x010 /* PIL-style layout */
-
-typedef struct {
- PyObject_VAR_HEAD
- _PyManagedBufferObject *mbuf; /* managed buffer */
- Py_hash_t hash; /* hash value for read-only views */
- int flags; /* state flags */
- Py_ssize_t exports; /* number of buffer re-exports */
- Py_buffer view; /* private copy of the exporter's view */
- PyObject *weakreflist;
- Py_ssize_t ob_array[1]; /* shape, strides, suboffsets */
-} PyMemoryViewObject;
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_MEMORYOBJECT_H */
diff --git a/include/python3.10/methodobject.h b/include/python3.10/methodobject.h
deleted file mode 100644
index 9ffe8e1..0000000
--- a/include/python3.10/methodobject.h
+++ /dev/null
@@ -1,116 +0,0 @@
-
-/* Method object interface */
-
-#ifndef Py_METHODOBJECT_H
-#define Py_METHODOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* This is about the type 'builtin_function_or_method',
- not Python methods in user-defined classes. See classobject.h
- for the latter. */
-
-PyAPI_DATA(PyTypeObject) PyCFunction_Type;
-
-#define PyCFunction_CheckExact(op) Py_IS_TYPE(op, &PyCFunction_Type)
-#define PyCFunction_Check(op) PyObject_TypeCheck(op, &PyCFunction_Type)
-
-typedef PyObject *(*PyCFunction)(PyObject *, PyObject *);
-typedef PyObject *(*_PyCFunctionFast) (PyObject *, PyObject *const *, Py_ssize_t);
-typedef PyObject *(*PyCFunctionWithKeywords)(PyObject *, PyObject *,
- PyObject *);
-typedef PyObject *(*_PyCFunctionFastWithKeywords) (PyObject *,
- PyObject *const *, Py_ssize_t,
- PyObject *);
-typedef PyObject *(*PyCMethod)(PyObject *, PyTypeObject *, PyObject *const *,
- size_t, PyObject *);
-
-PyAPI_FUNC(PyCFunction) PyCFunction_GetFunction(PyObject *);
-PyAPI_FUNC(PyObject *) PyCFunction_GetSelf(PyObject *);
-PyAPI_FUNC(int) PyCFunction_GetFlags(PyObject *);
-
-Py_DEPRECATED(3.9) PyAPI_FUNC(PyObject *) PyCFunction_Call(PyObject *, PyObject *, PyObject *);
-
-struct PyMethodDef {
- const char *ml_name; /* The name of the built-in function/method */
- PyCFunction ml_meth; /* The C function that implements it */
- int ml_flags; /* Combination of METH_xxx flags, which mostly
- describe the args expected by the C func */
- const char *ml_doc; /* The __doc__ attribute, or NULL */
-};
-typedef struct PyMethodDef PyMethodDef;
-
-/* PyCFunction_New is declared as a function for stable ABI (declaration is
- * needed for e.g. GCC with -fvisibility=hidden), but redefined as a macro
- * that calls PyCFunction_NewEx. */
-PyAPI_FUNC(PyObject *) PyCFunction_New(PyMethodDef *, PyObject *);
-#define PyCFunction_New(ML, SELF) PyCFunction_NewEx((ML), (SELF), NULL)
-
-/* PyCFunction_NewEx is similar: on 3.9+, this calls PyCMethod_New. */
-PyAPI_FUNC(PyObject *) PyCFunction_NewEx(PyMethodDef *, PyObject *,
- PyObject *);
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03090000
-#define PyCFunction_NewEx(ML, SELF, MOD) PyCMethod_New((ML), (SELF), (MOD), NULL)
-PyAPI_FUNC(PyObject *) PyCMethod_New(PyMethodDef *, PyObject *,
- PyObject *, PyTypeObject *);
-#endif
-
-
-/* Flag passed to newmethodobject */
-/* #define METH_OLDARGS 0x0000 -- unsupported now */
-#define METH_VARARGS 0x0001
-#define METH_KEYWORDS 0x0002
-/* METH_NOARGS and METH_O must not be combined with the flags above. */
-#define METH_NOARGS 0x0004
-#define METH_O 0x0008
-
-/* METH_CLASS and METH_STATIC are a little different; these control
- the construction of methods for a class. These cannot be used for
- functions in modules. */
-#define METH_CLASS 0x0010
-#define METH_STATIC 0x0020
-
-/* METH_COEXIST allows a method to be entered even though a slot has
- already filled the entry. When defined, the flag allows a separate
- method, "__contains__" for example, to coexist with a defined
- slot like sq_contains. */
-
-#define METH_COEXIST 0x0040
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030a0000
-# define METH_FASTCALL 0x0080
-#endif
-
-/* This bit is preserved for Stackless Python */
-#ifdef STACKLESS
-# define METH_STACKLESS 0x0100
-#else
-# define METH_STACKLESS 0x0000
-#endif
-
-/* METH_METHOD means the function stores an
- * additional reference to the class that defines it;
- * both self and class are passed to it.
- * It uses PyCMethodObject instead of PyCFunctionObject.
- * May not be combined with METH_NOARGS, METH_O, METH_CLASS or METH_STATIC.
- */
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03090000
-#define METH_METHOD 0x0200
-#endif
-
-
-#ifndef Py_LIMITED_API
-
-#define Py_CPYTHON_METHODOBJECT_H
-#include "cpython/methodobject.h"
-#undef Py_CPYTHON_METHODOBJECT_H
-
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_METHODOBJECT_H */
diff --git a/include/python3.10/modsupport.h b/include/python3.10/modsupport.h
deleted file mode 100644
index f009d58..0000000
--- a/include/python3.10/modsupport.h
+++ /dev/null
@@ -1,263 +0,0 @@
-
-#ifndef Py_MODSUPPORT_H
-#define Py_MODSUPPORT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Module support interface */
-
-#include <stdarg.h>
-
-/* If PY_SSIZE_T_CLEAN is defined, each functions treats #-specifier
- to mean Py_ssize_t */
-#ifdef PY_SSIZE_T_CLEAN
-#define PyArg_Parse _PyArg_Parse_SizeT
-#define PyArg_ParseTuple _PyArg_ParseTuple_SizeT
-#define PyArg_ParseTupleAndKeywords _PyArg_ParseTupleAndKeywords_SizeT
-#define PyArg_VaParse _PyArg_VaParse_SizeT
-#define PyArg_VaParseTupleAndKeywords _PyArg_VaParseTupleAndKeywords_SizeT
-#define Py_BuildValue _Py_BuildValue_SizeT
-#define Py_VaBuildValue _Py_VaBuildValue_SizeT
-#ifndef Py_LIMITED_API
-#define _Py_VaBuildStack _Py_VaBuildStack_SizeT
-#endif
-#else
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(PyObject *) _Py_VaBuildValue_SizeT(const char *, va_list);
-PyAPI_FUNC(PyObject **) _Py_VaBuildStack_SizeT(
- PyObject **small_stack,
- Py_ssize_t small_stack_len,
- const char *format,
- va_list va,
- Py_ssize_t *p_nargs);
-#endif /* !Py_LIMITED_API */
-#endif
-
-/* Due to a glitch in 3.2, the _SizeT versions weren't exported from the DLL. */
-#if !defined(PY_SSIZE_T_CLEAN) || !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-PyAPI_FUNC(int) PyArg_Parse(PyObject *, const char *, ...);
-PyAPI_FUNC(int) PyArg_ParseTuple(PyObject *, const char *, ...);
-PyAPI_FUNC(int) PyArg_ParseTupleAndKeywords(PyObject *, PyObject *,
- const char *, char **, ...);
-PyAPI_FUNC(int) PyArg_VaParse(PyObject *, const char *, va_list);
-PyAPI_FUNC(int) PyArg_VaParseTupleAndKeywords(PyObject *, PyObject *,
- const char *, char **, va_list);
-#endif
-PyAPI_FUNC(int) PyArg_ValidateKeywordArguments(PyObject *);
-PyAPI_FUNC(int) PyArg_UnpackTuple(PyObject *, const char *, Py_ssize_t, Py_ssize_t, ...);
-PyAPI_FUNC(PyObject *) Py_BuildValue(const char *, ...);
-PyAPI_FUNC(PyObject *) _Py_BuildValue_SizeT(const char *, ...);
-
-
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(int) _PyArg_UnpackStack(
- PyObject *const *args,
- Py_ssize_t nargs,
- const char *name,
- Py_ssize_t min,
- Py_ssize_t max,
- ...);
-
-PyAPI_FUNC(int) _PyArg_NoKeywords(const char *funcname, PyObject *kwargs);
-PyAPI_FUNC(int) _PyArg_NoKwnames(const char *funcname, PyObject *kwnames);
-PyAPI_FUNC(int) _PyArg_NoPositional(const char *funcname, PyObject *args);
-#define _PyArg_NoKeywords(funcname, kwargs) \
- ((kwargs) == NULL || _PyArg_NoKeywords((funcname), (kwargs)))
-#define _PyArg_NoKwnames(funcname, kwnames) \
- ((kwnames) == NULL || _PyArg_NoKwnames((funcname), (kwnames)))
-#define _PyArg_NoPositional(funcname, args) \
- ((args) == NULL || _PyArg_NoPositional((funcname), (args)))
-
-PyAPI_FUNC(void) _PyArg_BadArgument(const char *, const char *, const char *, PyObject *);
-PyAPI_FUNC(int) _PyArg_CheckPositional(const char *, Py_ssize_t,
- Py_ssize_t, Py_ssize_t);
-#define _PyArg_CheckPositional(funcname, nargs, min, max) \
- (((min) <= (nargs) && (nargs) <= (max)) \
- || _PyArg_CheckPositional((funcname), (nargs), (min), (max)))
-
-#endif
-
-PyAPI_FUNC(PyObject *) Py_VaBuildValue(const char *, va_list);
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(PyObject **) _Py_VaBuildStack(
- PyObject **small_stack,
- Py_ssize_t small_stack_len,
- const char *format,
- va_list va,
- Py_ssize_t *p_nargs);
-#endif
-
-#ifndef Py_LIMITED_API
-typedef struct _PyArg_Parser {
- const char *format;
- const char * const *keywords;
- const char *fname;
- const char *custom_msg;
- int pos; /* number of positional-only arguments */
- int min; /* minimal number of arguments */
- int max; /* maximal number of positional arguments */
- PyObject *kwtuple; /* tuple of keyword parameter names */
- struct _PyArg_Parser *next;
-} _PyArg_Parser;
-#ifdef PY_SSIZE_T_CLEAN
-#define _PyArg_ParseTupleAndKeywordsFast _PyArg_ParseTupleAndKeywordsFast_SizeT
-#define _PyArg_ParseStack _PyArg_ParseStack_SizeT
-#define _PyArg_ParseStackAndKeywords _PyArg_ParseStackAndKeywords_SizeT
-#define _PyArg_VaParseTupleAndKeywordsFast _PyArg_VaParseTupleAndKeywordsFast_SizeT
-#endif
-PyAPI_FUNC(int) _PyArg_ParseTupleAndKeywordsFast(PyObject *, PyObject *,
- struct _PyArg_Parser *, ...);
-PyAPI_FUNC(int) _PyArg_ParseStack(
- PyObject *const *args,
- Py_ssize_t nargs,
- const char *format,
- ...);
-PyAPI_FUNC(int) _PyArg_ParseStackAndKeywords(
- PyObject *const *args,
- Py_ssize_t nargs,
- PyObject *kwnames,
- struct _PyArg_Parser *,
- ...);
-PyAPI_FUNC(int) _PyArg_VaParseTupleAndKeywordsFast(PyObject *, PyObject *,
- struct _PyArg_Parser *, va_list);
-PyAPI_FUNC(PyObject * const *) _PyArg_UnpackKeywords(
- PyObject *const *args, Py_ssize_t nargs,
- PyObject *kwargs, PyObject *kwnames,
- struct _PyArg_Parser *parser,
- int minpos, int maxpos, int minkw,
- PyObject **buf);
-#define _PyArg_UnpackKeywords(args, nargs, kwargs, kwnames, parser, minpos, maxpos, minkw, buf) \
- (((minkw) == 0 && (kwargs) == NULL && (kwnames) == NULL && \
- (minpos) <= (nargs) && (nargs) <= (maxpos) && args != NULL) ? (args) : \
- _PyArg_UnpackKeywords((args), (nargs), (kwargs), (kwnames), (parser), \
- (minpos), (maxpos), (minkw), (buf)))
-
-void _PyArg_Fini(void);
-#endif /* Py_LIMITED_API */
-
-// Add an attribute with name 'name' and value 'obj' to the module 'mod.
-// On success, return 0 on success.
-// On error, raise an exception and return -1.
-PyAPI_FUNC(int) PyModule_AddObjectRef(PyObject *mod, const char *name, PyObject *value);
-
-// Similar to PyModule_AddObjectRef() but steal a reference to 'obj'
-// (Py_DECREF(obj)) on success (if it returns 0).
-PyAPI_FUNC(int) PyModule_AddObject(PyObject *mod, const char *, PyObject *value);
-
-PyAPI_FUNC(int) PyModule_AddIntConstant(PyObject *, const char *, long);
-PyAPI_FUNC(int) PyModule_AddStringConstant(PyObject *, const char *, const char *);
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03090000
-/* New in 3.9 */
-PyAPI_FUNC(int) PyModule_AddType(PyObject *module, PyTypeObject *type);
-#endif /* Py_LIMITED_API */
-#define PyModule_AddIntMacro(m, c) PyModule_AddIntConstant(m, #c, c)
-#define PyModule_AddStringMacro(m, c) PyModule_AddStringConstant(m, #c, c)
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
-/* New in 3.5 */
-PyAPI_FUNC(int) PyModule_SetDocString(PyObject *, const char *);
-PyAPI_FUNC(int) PyModule_AddFunctions(PyObject *, PyMethodDef *);
-PyAPI_FUNC(int) PyModule_ExecDef(PyObject *module, PyModuleDef *def);
-#endif
-
-#define Py_CLEANUP_SUPPORTED 0x20000
-
-#define PYTHON_API_VERSION 1013
-#define PYTHON_API_STRING "1013"
-/* The API version is maintained (independently from the Python version)
- so we can detect mismatches between the interpreter and dynamically
- loaded modules. These are diagnosed by an error message but
- the module is still loaded (because the mismatch can only be tested
- after loading the module). The error message is intended to
- explain the core dump a few seconds later.
-
- The symbol PYTHON_API_STRING defines the same value as a string
- literal. *** PLEASE MAKE SURE THE DEFINITIONS MATCH. ***
-
- Please add a line or two to the top of this log for each API
- version change:
-
- 22-Feb-2006 MvL 1013 PEP 353 - long indices for sequence lengths
-
- 19-Aug-2002 GvR 1012 Changes to string object struct for
- interning changes, saving 3 bytes.
-
- 17-Jul-2001 GvR 1011 Descr-branch, just to be on the safe side
-
- 25-Jan-2001 FLD 1010 Parameters added to PyCode_New() and
- PyFrame_New(); Python 2.1a2
-
- 14-Mar-2000 GvR 1009 Unicode API added
-
- 3-Jan-1999 GvR 1007 Decided to change back! (Don't reuse 1008!)
-
- 3-Dec-1998 GvR 1008 Python 1.5.2b1
-
- 18-Jan-1997 GvR 1007 string interning and other speedups
-
- 11-Oct-1996 GvR renamed Py_Ellipses to Py_Ellipsis :-(
-
- 30-Jul-1996 GvR Slice and ellipses syntax added
-
- 23-Jul-1996 GvR For 1.4 -- better safe than sorry this time :-)
-
- 7-Nov-1995 GvR Keyword arguments (should've been done at 1.3 :-( )
-
- 10-Jan-1995 GvR Renamed globals to new naming scheme
-
- 9-Jan-1995 GvR Initial version (incompatible with older API)
-*/
-
-/* The PYTHON_ABI_VERSION is introduced in PEP 384. For the lifetime of
- Python 3, it will stay at the value of 3; changes to the limited API
- must be performed in a strictly backwards-compatible manner. */
-#define PYTHON_ABI_VERSION 3
-#define PYTHON_ABI_STRING "3"
-
-#ifdef Py_TRACE_REFS
- /* When we are tracing reference counts, rename module creation functions so
- modules compiled with incompatible settings will generate a
- link-time error. */
- #define PyModule_Create2 PyModule_Create2TraceRefs
- #define PyModule_FromDefAndSpec2 PyModule_FromDefAndSpec2TraceRefs
-#endif
-
-PyAPI_FUNC(PyObject *) PyModule_Create2(struct PyModuleDef*,
- int apiver);
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(PyObject *) _PyModule_CreateInitialized(struct PyModuleDef*,
- int apiver);
-#endif
-
-#ifdef Py_LIMITED_API
-#define PyModule_Create(module) \
- PyModule_Create2(module, PYTHON_ABI_VERSION)
-#else
-#define PyModule_Create(module) \
- PyModule_Create2(module, PYTHON_API_VERSION)
-#endif
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
-/* New in 3.5 */
-PyAPI_FUNC(PyObject *) PyModule_FromDefAndSpec2(PyModuleDef *def,
- PyObject *spec,
- int module_api_version);
-
-#ifdef Py_LIMITED_API
-#define PyModule_FromDefAndSpec(module, spec) \
- PyModule_FromDefAndSpec2(module, spec, PYTHON_ABI_VERSION)
-#else
-#define PyModule_FromDefAndSpec(module, spec) \
- PyModule_FromDefAndSpec2(module, spec, PYTHON_API_VERSION)
-#endif /* Py_LIMITED_API */
-#endif /* New in 3.5 */
-
-#ifndef Py_LIMITED_API
-PyAPI_DATA(const char *) _Py_PackageContext;
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_MODSUPPORT_H */
diff --git a/include/python3.10/moduleobject.h b/include/python3.10/moduleobject.h
deleted file mode 100644
index 49b116c..0000000
--- a/include/python3.10/moduleobject.h
+++ /dev/null
@@ -1,96 +0,0 @@
-
-/* Module object interface */
-
-#ifndef Py_MODULEOBJECT_H
-#define Py_MODULEOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-PyAPI_DATA(PyTypeObject) PyModule_Type;
-
-#define PyModule_Check(op) PyObject_TypeCheck(op, &PyModule_Type)
-#define PyModule_CheckExact(op) Py_IS_TYPE(op, &PyModule_Type)
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-PyAPI_FUNC(PyObject *) PyModule_NewObject(
- PyObject *name
- );
-#endif
-PyAPI_FUNC(PyObject *) PyModule_New(
- const char *name /* UTF-8 encoded string */
- );
-PyAPI_FUNC(PyObject *) PyModule_GetDict(PyObject *);
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-PyAPI_FUNC(PyObject *) PyModule_GetNameObject(PyObject *);
-#endif
-PyAPI_FUNC(const char *) PyModule_GetName(PyObject *);
-Py_DEPRECATED(3.2) PyAPI_FUNC(const char *) PyModule_GetFilename(PyObject *);
-PyAPI_FUNC(PyObject *) PyModule_GetFilenameObject(PyObject *);
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(void) _PyModule_Clear(PyObject *);
-PyAPI_FUNC(void) _PyModule_ClearDict(PyObject *);
-PyAPI_FUNC(int) _PyModuleSpec_IsInitializing(PyObject *);
-#endif
-PyAPI_FUNC(struct PyModuleDef*) PyModule_GetDef(PyObject*);
-PyAPI_FUNC(void*) PyModule_GetState(PyObject*);
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
-/* New in 3.5 */
-PyAPI_FUNC(PyObject *) PyModuleDef_Init(struct PyModuleDef*);
-PyAPI_DATA(PyTypeObject) PyModuleDef_Type;
-#endif
-
-typedef struct PyModuleDef_Base {
- PyObject_HEAD
- PyObject* (*m_init)(void);
- Py_ssize_t m_index;
- PyObject* m_copy;
-} PyModuleDef_Base;
-
-#define PyModuleDef_HEAD_INIT { \
- PyObject_HEAD_INIT(NULL) \
- NULL, /* m_init */ \
- 0, /* m_index */ \
- NULL, /* m_copy */ \
- }
-
-struct PyModuleDef_Slot;
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
-/* New in 3.5 */
-typedef struct PyModuleDef_Slot{
- int slot;
- void *value;
-} PyModuleDef_Slot;
-
-#define Py_mod_create 1
-#define Py_mod_exec 2
-
-#ifndef Py_LIMITED_API
-#define _Py_mod_LAST_SLOT 2
-#endif
-
-#endif /* New in 3.5 */
-
-typedef struct PyModuleDef{
- PyModuleDef_Base m_base;
- const char* m_name;
- const char* m_doc;
- Py_ssize_t m_size;
- PyMethodDef *m_methods;
- struct PyModuleDef_Slot* m_slots;
- traverseproc m_traverse;
- inquiry m_clear;
- freefunc m_free;
-} PyModuleDef;
-
-
-// Internal C API
-#ifdef Py_BUILD_CORE
-extern int _PyModule_IsExtension(PyObject *obj);
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_MODULEOBJECT_H */
diff --git a/include/python3.10/namespaceobject.h b/include/python3.10/namespaceobject.h
deleted file mode 100644
index 0c8d95c..0000000
--- a/include/python3.10/namespaceobject.h
+++ /dev/null
@@ -1,19 +0,0 @@
-
-/* simple namespace object interface */
-
-#ifndef NAMESPACEOBJECT_H
-#define NAMESPACEOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_LIMITED_API
-PyAPI_DATA(PyTypeObject) _PyNamespace_Type;
-
-PyAPI_FUNC(PyObject *) _PyNamespace_New(PyObject *kwds);
-#endif /* !Py_LIMITED_API */
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !NAMESPACEOBJECT_H */
diff --git a/include/python3.10/object.h b/include/python3.10/object.h
deleted file mode 100644
index 61e638c..0000000
--- a/include/python3.10/object.h
+++ /dev/null
@@ -1,749 +0,0 @@
-#ifndef Py_OBJECT_H
-#define Py_OBJECT_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-/* Object and type object interface */
-
-/*
-Objects are structures allocated on the heap. Special rules apply to
-the use of objects to ensure they are properly garbage-collected.
-Objects are never allocated statically or on the stack; they must be
-accessed through special macros and functions only. (Type objects are
-exceptions to the first rule; the standard types are represented by
-statically initialized type objects, although work on type/class unification
-for Python 2.2 made it possible to have heap-allocated type objects too).
-
-An object has a 'reference count' that is increased or decreased when a
-pointer to the object is copied or deleted; when the reference count
-reaches zero there are no references to the object left and it can be
-removed from the heap.
-
-An object has a 'type' that determines what it represents and what kind
-of data it contains. An object's type is fixed when it is created.
-Types themselves are represented as objects; an object contains a
-pointer to the corresponding type object. The type itself has a type
-pointer pointing to the object representing the type 'type', which
-contains a pointer to itself!.
-
-Objects do not float around in memory; once allocated an object keeps
-the same size and address. Objects that must hold variable-size data
-can contain pointers to variable-size parts of the object. Not all
-objects of the same type have the same size; but the size cannot change
-after allocation. (These restrictions are made so a reference to an
-object can be simply a pointer -- moving an object would require
-updating all the pointers, and changing an object's size would require
-moving it if there was another object right next to it.)
-
-Objects are always accessed through pointers of the type 'PyObject *'.
-The type 'PyObject' is a structure that only contains the reference count
-and the type pointer. The actual memory allocated for an object
-contains other data that can only be accessed after casting the pointer
-to a pointer to a longer structure type. This longer type must start
-with the reference count and type fields; the macro PyObject_HEAD should be
-used for this (to accommodate for future changes). The implementation
-of a particular object type can cast the object pointer to the proper
-type and back.
-
-A standard interface exists for objects that contain an array of items
-whose size is determined when the object is allocated.
-*/
-
-/* Py_DEBUG implies Py_REF_DEBUG. */
-#if defined(Py_DEBUG) && !defined(Py_REF_DEBUG)
-# define Py_REF_DEBUG
-#endif
-
-#if defined(Py_LIMITED_API) && defined(Py_TRACE_REFS)
-# error Py_LIMITED_API is incompatible with Py_TRACE_REFS
-#endif
-
-/* PyTypeObject structure is defined in cpython/object.h.
- In Py_LIMITED_API, PyTypeObject is an opaque structure. */
-typedef struct _typeobject PyTypeObject;
-
-#ifdef Py_TRACE_REFS
-/* Define pointers to support a doubly-linked list of all live heap objects. */
-#define _PyObject_HEAD_EXTRA \
- struct _object *_ob_next; \
- struct _object *_ob_prev;
-
-#define _PyObject_EXTRA_INIT 0, 0,
-
-#else
-# define _PyObject_HEAD_EXTRA
-# define _PyObject_EXTRA_INIT
-#endif
-
-/* PyObject_HEAD defines the initial segment of every PyObject. */
-#define PyObject_HEAD PyObject ob_base;
-
-#define PyObject_HEAD_INIT(type) \
- { _PyObject_EXTRA_INIT \
- 1, type },
-
-#define PyVarObject_HEAD_INIT(type, size) \
- { PyObject_HEAD_INIT(type) size },
-
-/* PyObject_VAR_HEAD defines the initial segment of all variable-size
- * container objects. These end with a declaration of an array with 1
- * element, but enough space is malloc'ed so that the array actually
- * has room for ob_size elements. Note that ob_size is an element count,
- * not necessarily a byte count.
- */
-#define PyObject_VAR_HEAD PyVarObject ob_base;
-#define Py_INVALID_SIZE (Py_ssize_t)-1
-
-/* Nothing is actually declared to be a PyObject, but every pointer to
- * a Python object can be cast to a PyObject*. This is inheritance built
- * by hand. Similarly every pointer to a variable-size Python object can,
- * in addition, be cast to PyVarObject*.
- */
-typedef struct _object {
- _PyObject_HEAD_EXTRA
- Py_ssize_t ob_refcnt;
- PyTypeObject *ob_type;
-} PyObject;
-
-/* Cast argument to PyObject* type. */
-#define _PyObject_CAST(op) ((PyObject*)(op))
-#define _PyObject_CAST_CONST(op) ((const PyObject*)(op))
-
-typedef struct {
- PyObject ob_base;
- Py_ssize_t ob_size; /* Number of items in variable part */
-} PyVarObject;
-
-/* Cast argument to PyVarObject* type. */
-#define _PyVarObject_CAST(op) ((PyVarObject*)(op))
-#define _PyVarObject_CAST_CONST(op) ((const PyVarObject*)(op))
-
-
-// Test if the 'x' object is the 'y' object, the same as "x is y" in Python.
-PyAPI_FUNC(int) Py_Is(PyObject *x, PyObject *y);
-#define Py_Is(x, y) ((x) == (y))
-
-
-static inline Py_ssize_t _Py_REFCNT(const PyObject *ob) {
- return ob->ob_refcnt;
-}
-#define Py_REFCNT(ob) _Py_REFCNT(_PyObject_CAST_CONST(ob))
-
-
-// bpo-39573: The Py_SET_TYPE() function must be used to set an object type.
-#define Py_TYPE(ob) (_PyObject_CAST(ob)->ob_type)
-
-// bpo-39573: The Py_SET_SIZE() function must be used to set an object size.
-#define Py_SIZE(ob) (_PyVarObject_CAST(ob)->ob_size)
-
-
-static inline int _Py_IS_TYPE(const PyObject *ob, const PyTypeObject *type) {
- // bpo-44378: Don't use Py_TYPE() since Py_TYPE() requires a non-const
- // object.
- return ob->ob_type == type;
-}
-#define Py_IS_TYPE(ob, type) _Py_IS_TYPE(_PyObject_CAST_CONST(ob), type)
-
-
-static inline void _Py_SET_REFCNT(PyObject *ob, Py_ssize_t refcnt) {
- ob->ob_refcnt = refcnt;
-}
-#define Py_SET_REFCNT(ob, refcnt) _Py_SET_REFCNT(_PyObject_CAST(ob), refcnt)
-
-
-static inline void _Py_SET_TYPE(PyObject *ob, PyTypeObject *type) {
- ob->ob_type = type;
-}
-#define Py_SET_TYPE(ob, type) _Py_SET_TYPE(_PyObject_CAST(ob), type)
-
-
-static inline void _Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size) {
- ob->ob_size = size;
-}
-#define Py_SET_SIZE(ob, size) _Py_SET_SIZE(_PyVarObject_CAST(ob), size)
-
-
-/*
-Type objects contain a string containing the type name (to help somewhat
-in debugging), the allocation parameters (see PyObject_New() and
-PyObject_NewVar()),
-and methods for accessing objects of the type. Methods are optional, a
-nil pointer meaning that particular kind of access is not available for
-this type. The Py_DECREF() macro uses the tp_dealloc method without
-checking for a nil pointer; it should always be implemented except if
-the implementation can guarantee that the reference count will never
-reach zero (e.g., for statically allocated type objects).
-
-NB: the methods for certain type groups are now contained in separate
-method blocks.
-*/
-
-typedef PyObject * (*unaryfunc)(PyObject *);
-typedef PyObject * (*binaryfunc)(PyObject *, PyObject *);
-typedef PyObject * (*ternaryfunc)(PyObject *, PyObject *, PyObject *);
-typedef int (*inquiry)(PyObject *);
-typedef Py_ssize_t (*lenfunc)(PyObject *);
-typedef PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t);
-typedef PyObject *(*ssizessizeargfunc)(PyObject *, Py_ssize_t, Py_ssize_t);
-typedef int(*ssizeobjargproc)(PyObject *, Py_ssize_t, PyObject *);
-typedef int(*ssizessizeobjargproc)(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);
-typedef int(*objobjargproc)(PyObject *, PyObject *, PyObject *);
-
-typedef int (*objobjproc)(PyObject *, PyObject *);
-typedef int (*visitproc)(PyObject *, void *);
-typedef int (*traverseproc)(PyObject *, visitproc, void *);
-
-
-typedef void (*freefunc)(void *);
-typedef void (*destructor)(PyObject *);
-typedef PyObject *(*getattrfunc)(PyObject *, char *);
-typedef PyObject *(*getattrofunc)(PyObject *, PyObject *);
-typedef int (*setattrfunc)(PyObject *, char *, PyObject *);
-typedef int (*setattrofunc)(PyObject *, PyObject *, PyObject *);
-typedef PyObject *(*reprfunc)(PyObject *);
-typedef Py_hash_t (*hashfunc)(PyObject *);
-typedef PyObject *(*richcmpfunc) (PyObject *, PyObject *, int);
-typedef PyObject *(*getiterfunc) (PyObject *);
-typedef PyObject *(*iternextfunc) (PyObject *);
-typedef PyObject *(*descrgetfunc) (PyObject *, PyObject *, PyObject *);
-typedef int (*descrsetfunc) (PyObject *, PyObject *, PyObject *);
-typedef int (*initproc)(PyObject *, PyObject *, PyObject *);
-typedef PyObject *(*newfunc)(PyTypeObject *, PyObject *, PyObject *);
-typedef PyObject *(*allocfunc)(PyTypeObject *, Py_ssize_t);
-
-typedef struct{
- int slot; /* slot id, see below */
- void *pfunc; /* function pointer */
-} PyType_Slot;
-
-typedef struct{
- const char* name;
- int basicsize;
- int itemsize;
- unsigned int flags;
- PyType_Slot *slots; /* terminated by slot==0. */
-} PyType_Spec;
-
-PyAPI_FUNC(PyObject*) PyType_FromSpec(PyType_Spec*);
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-PyAPI_FUNC(PyObject*) PyType_FromSpecWithBases(PyType_Spec*, PyObject*);
-#endif
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000
-PyAPI_FUNC(void*) PyType_GetSlot(PyTypeObject*, int);
-#endif
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03090000
-PyAPI_FUNC(PyObject*) PyType_FromModuleAndSpec(PyObject *, PyType_Spec *, PyObject *);
-PyAPI_FUNC(PyObject *) PyType_GetModule(struct _typeobject *);
-PyAPI_FUNC(void *) PyType_GetModuleState(struct _typeobject *);
-#endif
-
-/* Generic type check */
-PyAPI_FUNC(int) PyType_IsSubtype(PyTypeObject *, PyTypeObject *);
-
-static inline int _PyObject_TypeCheck(PyObject *ob, PyTypeObject *type) {
- return Py_IS_TYPE(ob, type) || PyType_IsSubtype(Py_TYPE(ob), type);
-}
-#define PyObject_TypeCheck(ob, type) _PyObject_TypeCheck(_PyObject_CAST(ob), type)
-
-PyAPI_DATA(PyTypeObject) PyType_Type; /* built-in 'type' */
-PyAPI_DATA(PyTypeObject) PyBaseObject_Type; /* built-in 'object' */
-PyAPI_DATA(PyTypeObject) PySuper_Type; /* built-in 'super' */
-
-PyAPI_FUNC(unsigned long) PyType_GetFlags(PyTypeObject*);
-
-PyAPI_FUNC(int) PyType_Ready(PyTypeObject *);
-PyAPI_FUNC(PyObject *) PyType_GenericAlloc(PyTypeObject *, Py_ssize_t);
-PyAPI_FUNC(PyObject *) PyType_GenericNew(PyTypeObject *,
- PyObject *, PyObject *);
-PyAPI_FUNC(unsigned int) PyType_ClearCache(void);
-PyAPI_FUNC(void) PyType_Modified(PyTypeObject *);
-
-/* Generic operations on objects */
-PyAPI_FUNC(PyObject *) PyObject_Repr(PyObject *);
-PyAPI_FUNC(PyObject *) PyObject_Str(PyObject *);
-PyAPI_FUNC(PyObject *) PyObject_ASCII(PyObject *);
-PyAPI_FUNC(PyObject *) PyObject_Bytes(PyObject *);
-PyAPI_FUNC(PyObject *) PyObject_RichCompare(PyObject *, PyObject *, int);
-PyAPI_FUNC(int) PyObject_RichCompareBool(PyObject *, PyObject *, int);
-PyAPI_FUNC(PyObject *) PyObject_GetAttrString(PyObject *, const char *);
-PyAPI_FUNC(int) PyObject_SetAttrString(PyObject *, const char *, PyObject *);
-PyAPI_FUNC(int) PyObject_HasAttrString(PyObject *, const char *);
-PyAPI_FUNC(PyObject *) PyObject_GetAttr(PyObject *, PyObject *);
-PyAPI_FUNC(int) PyObject_SetAttr(PyObject *, PyObject *, PyObject *);
-PyAPI_FUNC(int) PyObject_HasAttr(PyObject *, PyObject *);
-PyAPI_FUNC(PyObject *) PyObject_SelfIter(PyObject *);
-PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *);
-PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *, PyObject *, PyObject *);
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-PyAPI_FUNC(int) PyObject_GenericSetDict(PyObject *, PyObject *, void *);
-#endif
-PyAPI_FUNC(Py_hash_t) PyObject_Hash(PyObject *);
-PyAPI_FUNC(Py_hash_t) PyObject_HashNotImplemented(PyObject *);
-PyAPI_FUNC(int) PyObject_IsTrue(PyObject *);
-PyAPI_FUNC(int) PyObject_Not(PyObject *);
-PyAPI_FUNC(int) PyCallable_Check(PyObject *);
-PyAPI_FUNC(void) PyObject_ClearWeakRefs(PyObject *);
-
-/* PyObject_Dir(obj) acts like Python builtins.dir(obj), returning a
- list of strings. PyObject_Dir(NULL) is like builtins.dir(),
- returning the names of the current locals. In this case, if there are
- no current locals, NULL is returned, and PyErr_Occurred() is false.
-*/
-PyAPI_FUNC(PyObject *) PyObject_Dir(PyObject *);
-
-
-/* Helpers for printing recursive container types */
-PyAPI_FUNC(int) Py_ReprEnter(PyObject *);
-PyAPI_FUNC(void) Py_ReprLeave(PyObject *);
-
-/* Flag bits for printing: */
-#define Py_PRINT_RAW 1 /* No string quotes etc. */
-
-/*
-Type flags (tp_flags)
-
-These flags are used to change expected features and behavior for a
-particular type.
-
-Arbitration of the flag bit positions will need to be coordinated among
-all extension writers who publicly release their extensions (this will
-be fewer than you might expect!).
-
-Most flags were removed as of Python 3.0 to make room for new flags. (Some
-flags are not for backwards compatibility but to indicate the presence of an
-optional feature; these flags remain of course.)
-
-Type definitions should use Py_TPFLAGS_DEFAULT for their tp_flags value.
-
-Code can use PyType_HasFeature(type_ob, flag_value) to test whether the
-given type object has a specified feature.
-*/
-
-#ifndef Py_LIMITED_API
-/* Set if instances of the type object are treated as sequences for pattern matching */
-#define Py_TPFLAGS_SEQUENCE (1 << 5)
-/* Set if instances of the type object are treated as mappings for pattern matching */
-#define Py_TPFLAGS_MAPPING (1 << 6)
-#endif
-
-/* Disallow creating instances of the type: set tp_new to NULL and don't create
- * the "__new__" key in the type dictionary. */
-#define Py_TPFLAGS_DISALLOW_INSTANTIATION (1UL << 7)
-
-/* Set if the type object is immutable: type attributes cannot be set nor deleted */
-#define Py_TPFLAGS_IMMUTABLETYPE (1UL << 8)
-
-/* Set if the type object is dynamically allocated */
-#define Py_TPFLAGS_HEAPTYPE (1UL << 9)
-
-/* Set if the type allows subclassing */
-#define Py_TPFLAGS_BASETYPE (1UL << 10)
-
-/* Set if the type implements the vectorcall protocol (PEP 590) */
-#ifndef Py_LIMITED_API
-#define Py_TPFLAGS_HAVE_VECTORCALL (1UL << 11)
-// Backwards compatibility alias for API that was provisional in Python 3.8
-#define _Py_TPFLAGS_HAVE_VECTORCALL Py_TPFLAGS_HAVE_VECTORCALL
-#endif
-
-/* Set if the type is 'ready' -- fully initialized */
-#define Py_TPFLAGS_READY (1UL << 12)
-
-/* Set while the type is being 'readied', to prevent recursive ready calls */
-#define Py_TPFLAGS_READYING (1UL << 13)
-
-/* Objects support garbage collection (see objimpl.h) */
-#define Py_TPFLAGS_HAVE_GC (1UL << 14)
-
-/* These two bits are preserved for Stackless Python, next after this is 17 */
-#ifdef STACKLESS
-#define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION (3UL << 15)
-#else
-#define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION 0
-#endif
-
-/* Objects behave like an unbound method */
-#define Py_TPFLAGS_METHOD_DESCRIPTOR (1UL << 17)
-
-/* Object has up-to-date type attribute cache */
-#define Py_TPFLAGS_VALID_VERSION_TAG (1UL << 19)
-
-/* Type is abstract and cannot be instantiated */
-#define Py_TPFLAGS_IS_ABSTRACT (1UL << 20)
-
-// This undocumented flag gives certain built-ins their unique pattern-matching
-// behavior, which allows a single positional subpattern to match against the
-// subject itself (rather than a mapped attribute on it):
-#define _Py_TPFLAGS_MATCH_SELF (1UL << 22)
-
-/* These flags are used to determine if a type is a subclass. */
-#define Py_TPFLAGS_LONG_SUBCLASS (1UL << 24)
-#define Py_TPFLAGS_LIST_SUBCLASS (1UL << 25)
-#define Py_TPFLAGS_TUPLE_SUBCLASS (1UL << 26)
-#define Py_TPFLAGS_BYTES_SUBCLASS (1UL << 27)
-#define Py_TPFLAGS_UNICODE_SUBCLASS (1UL << 28)
-#define Py_TPFLAGS_DICT_SUBCLASS (1UL << 29)
-#define Py_TPFLAGS_BASE_EXC_SUBCLASS (1UL << 30)
-#define Py_TPFLAGS_TYPE_SUBCLASS (1UL << 31)
-
-#define Py_TPFLAGS_DEFAULT ( \
- Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \
- 0)
-
-/* NOTE: Some of the following flags reuse lower bits (removed as part of the
- * Python 3.0 transition). */
-
-/* The following flags are kept for compatibility; in previous
- * versions they indicated presence of newer tp_* fields on the
- * type struct.
- * Starting with 3.8, binary compatibility of C extensions across
- * feature releases of Python is not supported anymore (except when
- * using the stable ABI, in which all classes are created dynamically,
- * using the interpreter's memory layout.)
- * Note that older extensions using the stable ABI set these flags,
- * so the bits must not be repurposed.
- */
-#define Py_TPFLAGS_HAVE_FINALIZE (1UL << 0)
-#define Py_TPFLAGS_HAVE_VERSION_TAG (1UL << 18)
-
-
-/*
-The macros Py_INCREF(op) and Py_DECREF(op) are used to increment or decrement
-reference counts. Py_DECREF calls the object's deallocator function when
-the refcount falls to 0; for
-objects that don't contain references to other objects or heap memory
-this can be the standard function free(). Both macros can be used
-wherever a void expression is allowed. The argument must not be a
-NULL pointer. If it may be NULL, use Py_XINCREF/Py_XDECREF instead.
-The macro _Py_NewReference(op) initialize reference counts to 1, and
-in special builds (Py_REF_DEBUG, Py_TRACE_REFS) performs additional
-bookkeeping appropriate to the special build.
-
-We assume that the reference count field can never overflow; this can
-be proven when the size of the field is the same as the pointer size, so
-we ignore the possibility. Provided a C int is at least 32 bits (which
-is implicitly assumed in many parts of this code), that's enough for
-about 2**31 references to an object.
-
-XXX The following became out of date in Python 2.2, but I'm not sure
-XXX what the full truth is now. Certainly, heap-allocated type objects
-XXX can and should be deallocated.
-Type objects should never be deallocated; the type pointer in an object
-is not considered to be a reference to the type object, to save
-complications in the deallocation function. (This is actually a
-decision that's up to the implementer of each new type so if you want,
-you can count such references to the type object.)
-*/
-
-#ifdef Py_REF_DEBUG
-PyAPI_DATA(Py_ssize_t) _Py_RefTotal;
-PyAPI_FUNC(void) _Py_NegativeRefcount(const char *filename, int lineno,
- PyObject *op);
-#endif /* Py_REF_DEBUG */
-
-PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
-
-/*
-These are provided as conveniences to Python runtime embedders, so that
-they can have object code that is not dependent on Python compilation flags.
-*/
-PyAPI_FUNC(void) Py_IncRef(PyObject *);
-PyAPI_FUNC(void) Py_DecRef(PyObject *);
-
-// Similar to Py_IncRef() and Py_DecRef() but the argument must be non-NULL.
-// Private functions used by Py_INCREF() and Py_DECREF().
-PyAPI_FUNC(void) _Py_IncRef(PyObject *);
-PyAPI_FUNC(void) _Py_DecRef(PyObject *);
-
-static inline void _Py_INCREF(PyObject *op)
-{
-#if defined(Py_REF_DEBUG) && defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030A0000
- // Stable ABI for Python 3.10 built in debug mode.
- _Py_IncRef(op);
-#else
- // Non-limited C API and limited C API for Python 3.9 and older access
- // directly PyObject.ob_refcnt.
-#ifdef Py_REF_DEBUG
- _Py_RefTotal++;
-#endif
- op->ob_refcnt++;
-#endif
-}
-#define Py_INCREF(op) _Py_INCREF(_PyObject_CAST(op))
-
-static inline void _Py_DECREF(
-#if defined(Py_REF_DEBUG) && !(defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030A0000)
- const char *filename, int lineno,
-#endif
- PyObject *op)
-{
-#if defined(Py_REF_DEBUG) && defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030A0000
- // Stable ABI for Python 3.10 built in debug mode.
- _Py_DecRef(op);
-#else
- // Non-limited C API and limited C API for Python 3.9 and older access
- // directly PyObject.ob_refcnt.
-#ifdef Py_REF_DEBUG
- _Py_RefTotal--;
-#endif
- if (--op->ob_refcnt != 0) {
-#ifdef Py_REF_DEBUG
- if (op->ob_refcnt < 0) {
- _Py_NegativeRefcount(filename, lineno, op);
- }
-#endif
- }
- else {
- _Py_Dealloc(op);
- }
-#endif
-}
-#if defined(Py_REF_DEBUG) && !(defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030A0000)
-# define Py_DECREF(op) _Py_DECREF(__FILE__, __LINE__, _PyObject_CAST(op))
-#else
-# define Py_DECREF(op) _Py_DECREF(_PyObject_CAST(op))
-#endif
-
-
-/* Safely decref `op` and set `op` to NULL, especially useful in tp_clear
- * and tp_dealloc implementations.
- *
- * Note that "the obvious" code can be deadly:
- *
- * Py_XDECREF(op);
- * op = NULL;
- *
- * Typically, `op` is something like self->containee, and `self` is done
- * using its `containee` member. In the code sequence above, suppose
- * `containee` is non-NULL with a refcount of 1. Its refcount falls to
- * 0 on the first line, which can trigger an arbitrary amount of code,
- * possibly including finalizers (like __del__ methods or weakref callbacks)
- * coded in Python, which in turn can release the GIL and allow other threads
- * to run, etc. Such code may even invoke methods of `self` again, or cause
- * cyclic gc to trigger, but-- oops! --self->containee still points to the
- * object being torn down, and it may be in an insane state while being torn
- * down. This has in fact been a rich historic source of miserable (rare &
- * hard-to-diagnose) segfaulting (and other) bugs.
- *
- * The safe way is:
- *
- * Py_CLEAR(op);
- *
- * That arranges to set `op` to NULL _before_ decref'ing, so that any code
- * triggered as a side-effect of `op` getting torn down no longer believes
- * `op` points to a valid object.
- *
- * There are cases where it's safe to use the naive code, but they're brittle.
- * For example, if `op` points to a Python integer, you know that destroying
- * one of those can't cause problems -- but in part that relies on that
- * Python integers aren't currently weakly referencable. Best practice is
- * to use Py_CLEAR() even if you can't think of a reason for why you need to.
- */
-#define Py_CLEAR(op) \
- do { \
- PyObject *_py_tmp = _PyObject_CAST(op); \
- if (_py_tmp != NULL) { \
- (op) = NULL; \
- Py_DECREF(_py_tmp); \
- } \
- } while (0)
-
-/* Function to use in case the object pointer can be NULL: */
-static inline void _Py_XINCREF(PyObject *op)
-{
- if (op != NULL) {
- Py_INCREF(op);
- }
-}
-
-#define Py_XINCREF(op) _Py_XINCREF(_PyObject_CAST(op))
-
-static inline void _Py_XDECREF(PyObject *op)
-{
- if (op != NULL) {
- Py_DECREF(op);
- }
-}
-
-#define Py_XDECREF(op) _Py_XDECREF(_PyObject_CAST(op))
-
-// Create a new strong reference to an object:
-// increment the reference count of the object and return the object.
-PyAPI_FUNC(PyObject*) Py_NewRef(PyObject *obj);
-
-// Similar to Py_NewRef(), but the object can be NULL.
-PyAPI_FUNC(PyObject*) Py_XNewRef(PyObject *obj);
-
-static inline PyObject* _Py_NewRef(PyObject *obj)
-{
- Py_INCREF(obj);
- return obj;
-}
-
-static inline PyObject* _Py_XNewRef(PyObject *obj)
-{
- Py_XINCREF(obj);
- return obj;
-}
-
-// Py_NewRef() and Py_XNewRef() are exported as functions for the stable ABI.
-// Names overridden with macros by static inline functions for best
-// performances.
-#define Py_NewRef(obj) _Py_NewRef(_PyObject_CAST(obj))
-#define Py_XNewRef(obj) _Py_XNewRef(_PyObject_CAST(obj))
-
-
-/*
-_Py_NoneStruct is an object of undefined type which can be used in contexts
-where NULL (nil) is not suitable (since NULL often means 'error').
-
-Don't forget to apply Py_INCREF() when returning this value!!!
-*/
-PyAPI_DATA(PyObject) _Py_NoneStruct; /* Don't use this directly */
-#define Py_None (&_Py_NoneStruct)
-
-// Test if an object is the None singleton, the same as "x is None" in Python.
-PyAPI_FUNC(int) Py_IsNone(PyObject *x);
-#define Py_IsNone(x) Py_Is((x), Py_None)
-
-/* Macro for returning Py_None from a function */
-#define Py_RETURN_NONE return Py_NewRef(Py_None)
-
-/*
-Py_NotImplemented is a singleton used to signal that an operation is
-not implemented for a given type combination.
-*/
-PyAPI_DATA(PyObject) _Py_NotImplementedStruct; /* Don't use this directly */
-#define Py_NotImplemented (&_Py_NotImplementedStruct)
-
-/* Macro for returning Py_NotImplemented from a function */
-#define Py_RETURN_NOTIMPLEMENTED return Py_NewRef(Py_NotImplemented)
-
-/* Rich comparison opcodes */
-#define Py_LT 0
-#define Py_LE 1
-#define Py_EQ 2
-#define Py_NE 3
-#define Py_GT 4
-#define Py_GE 5
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000
-/* Result of calling PyIter_Send */
-typedef enum {
- PYGEN_RETURN = 0,
- PYGEN_ERROR = -1,
- PYGEN_NEXT = 1,
-} PySendResult;
-#endif
-
-/*
- * Macro for implementing rich comparisons
- *
- * Needs to be a macro because any C-comparable type can be used.
- */
-#define Py_RETURN_RICHCOMPARE(val1, val2, op) \
- do { \
- switch (op) { \
- case Py_EQ: if ((val1) == (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
- case Py_NE: if ((val1) != (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
- case Py_LT: if ((val1) < (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
- case Py_GT: if ((val1) > (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
- case Py_LE: if ((val1) <= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
- case Py_GE: if ((val1) >= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
- default: \
- Py_UNREACHABLE(); \
- } \
- } while (0)
-
-
-/*
-More conventions
-================
-
-Argument Checking
------------------
-
-Functions that take objects as arguments normally don't check for nil
-arguments, but they do check the type of the argument, and return an
-error if the function doesn't apply to the type.
-
-Failure Modes
--------------
-
-Functions may fail for a variety of reasons, including running out of
-memory. This is communicated to the caller in two ways: an error string
-is set (see errors.h), and the function result differs: functions that
-normally return a pointer return NULL for failure, functions returning
-an integer return -1 (which could be a legal return value too!), and
-other functions return 0 for success and -1 for failure.
-Callers should always check for errors before using the result. If
-an error was set, the caller must either explicitly clear it, or pass
-the error on to its caller.
-
-Reference Counts
-----------------
-
-It takes a while to get used to the proper usage of reference counts.
-
-Functions that create an object set the reference count to 1; such new
-objects must be stored somewhere or destroyed again with Py_DECREF().
-Some functions that 'store' objects, such as PyTuple_SetItem() and
-PyList_SetItem(),
-don't increment the reference count of the object, since the most
-frequent use is to store a fresh object. Functions that 'retrieve'
-objects, such as PyTuple_GetItem() and PyDict_GetItemString(), also
-don't increment
-the reference count, since most frequently the object is only looked at
-quickly. Thus, to retrieve an object and store it again, the caller
-must call Py_INCREF() explicitly.
-
-NOTE: functions that 'consume' a reference count, like
-PyList_SetItem(), consume the reference even if the object wasn't
-successfully stored, to simplify error handling.
-
-It seems attractive to make other functions that take an object as
-argument consume a reference count; however, this may quickly get
-confusing (even the current practice is already confusing). Consider
-it carefully, it may save lots of calls to Py_INCREF() and Py_DECREF() at
-times.
-*/
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_OBJECT_H
-# include "cpython/object.h"
-# undef Py_CPYTHON_OBJECT_H
-#endif
-
-
-static inline int
-PyType_HasFeature(PyTypeObject *type, unsigned long feature)
-{
- unsigned long flags;
-#ifdef Py_LIMITED_API
- // PyTypeObject is opaque in the limited C API
- flags = PyType_GetFlags(type);
-#else
- flags = type->tp_flags;
-#endif
- return ((flags & feature) != 0);
-}
-
-#define PyType_FastSubclass(type, flag) PyType_HasFeature(type, flag)
-
-static inline int _PyType_Check(PyObject *op) {
- return PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS);
-}
-#define PyType_Check(op) _PyType_Check(_PyObject_CAST(op))
-
-static inline int _PyType_CheckExact(PyObject *op) {
- return Py_IS_TYPE(op, &PyType_Type);
-}
-#define PyType_CheckExact(op) _PyType_CheckExact(_PyObject_CAST(op))
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_OBJECT_H */
diff --git a/include/python3.10/objimpl.h b/include/python3.10/objimpl.h
deleted file mode 100644
index 450befa..0000000
--- a/include/python3.10/objimpl.h
+++ /dev/null
@@ -1,215 +0,0 @@
-/* The PyObject_ memory family: high-level object memory interfaces.
- See pymem.h for the low-level PyMem_ family.
-*/
-
-#ifndef Py_OBJIMPL_H
-#define Py_OBJIMPL_H
-
-#include "pymem.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* BEWARE:
-
- Each interface exports both functions and macros. Extension modules should
- use the functions, to ensure binary compatibility across Python versions.
- Because the Python implementation is free to change internal details, and
- the macros may (or may not) expose details for speed, if you do use the
- macros you must recompile your extensions with each Python release.
-
- Never mix calls to PyObject_ memory functions with calls to the platform
- malloc/realloc/ calloc/free, or with calls to PyMem_.
-*/
-
-/*
-Functions and macros for modules that implement new object types.
-
- - PyObject_New(type, typeobj) allocates memory for a new object of the given
- type, and initializes part of it. 'type' must be the C structure type used
- to represent the object, and 'typeobj' the address of the corresponding
- type object. Reference count and type pointer are filled in; the rest of
- the bytes of the object are *undefined*! The resulting expression type is
- 'type *'. The size of the object is determined by the tp_basicsize field
- of the type object.
-
- - PyObject_NewVar(type, typeobj, n) is similar but allocates a variable-size
- object with room for n items. In addition to the refcount and type pointer
- fields, this also fills in the ob_size field.
-
- - PyObject_Free(op) releases the memory allocated for an object. It does not
- run a destructor -- it only frees the memory. PyObject_Free is identical.
-
- - PyObject_Init(op, typeobj) and PyObject_InitVar(op, typeobj, n) don't
- allocate memory. Instead of a 'type' parameter, they take a pointer to a
- new object (allocated by an arbitrary allocator), and initialize its object
- header fields.
-
-Note that objects created with PyObject_{New, NewVar} are allocated using the
-specialized Python allocator (implemented in obmalloc.c), if WITH_PYMALLOC is
-enabled. In addition, a special debugging allocator is used if Py_DEBUG
-macro is also defined.
-
-In case a specific form of memory management is needed (for example, if you
-must use the platform malloc heap(s), or shared memory, or C++ local storage or
-operator new), you must first allocate the object with your custom allocator,
-then pass its pointer to PyObject_{Init, InitVar} for filling in its Python-
-specific fields: reference count, type pointer, possibly others. You should
-be aware that Python has no control over these objects because they don't
-cooperate with the Python memory manager. Such objects may not be eligible
-for automatic garbage collection and you have to make sure that they are
-released accordingly whenever their destructor gets called (cf. the specific
-form of memory management you're using).
-
-Unless you have specific memory management requirements, use
-PyObject_{New, NewVar, Del}.
-*/
-
-/*
- * Raw object memory interface
- * ===========================
- */
-
-/* Functions to call the same malloc/realloc/free as used by Python's
- object allocator. If WITH_PYMALLOC is enabled, these may differ from
- the platform malloc/realloc/free. The Python object allocator is
- designed for fast, cache-conscious allocation of many "small" objects,
- and with low hidden memory overhead.
-
- PyObject_Malloc(0) returns a unique non-NULL pointer if possible.
-
- PyObject_Realloc(NULL, n) acts like PyObject_Malloc(n).
- PyObject_Realloc(p != NULL, 0) does not return NULL, or free the memory
- at p.
-
- Returned pointers must be checked for NULL explicitly; no action is
- performed on failure other than to return NULL (no warning it printed, no
- exception is set, etc).
-
- For allocating objects, use PyObject_{New, NewVar} instead whenever
- possible. The PyObject_{Malloc, Realloc, Free} family is exposed
- so that you can exploit Python's small-block allocator for non-object
- uses. If you must use these routines to allocate object memory, make sure
- the object gets initialized via PyObject_{Init, InitVar} after obtaining
- the raw memory.
-*/
-PyAPI_FUNC(void *) PyObject_Malloc(size_t size);
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
-PyAPI_FUNC(void *) PyObject_Calloc(size_t nelem, size_t elsize);
-#endif
-PyAPI_FUNC(void *) PyObject_Realloc(void *ptr, size_t new_size);
-PyAPI_FUNC(void) PyObject_Free(void *ptr);
-
-
-// Deprecated aliases only kept for backward compatibility.
-// PyObject_Del and PyObject_DEL are defined with no parameter to be able to
-// use them as function pointers (ex: tp_free = PyObject_Del).
-#define PyObject_MALLOC PyObject_Malloc
-#define PyObject_REALLOC PyObject_Realloc
-#define PyObject_FREE PyObject_Free
-#define PyObject_Del PyObject_Free
-#define PyObject_DEL PyObject_Free
-
-
-/*
- * Generic object allocator interface
- * ==================================
- */
-
-/* Functions */
-PyAPI_FUNC(PyObject *) PyObject_Init(PyObject *, PyTypeObject *);
-PyAPI_FUNC(PyVarObject *) PyObject_InitVar(PyVarObject *,
- PyTypeObject *, Py_ssize_t);
-
-#define PyObject_INIT(op, typeobj) \
- PyObject_Init(_PyObject_CAST(op), (typeobj))
-#define PyObject_INIT_VAR(op, typeobj, size) \
- PyObject_InitVar(_PyVarObject_CAST(op), (typeobj), (size))
-
-
-PyAPI_FUNC(PyObject *) _PyObject_New(PyTypeObject *);
-PyAPI_FUNC(PyVarObject *) _PyObject_NewVar(PyTypeObject *, Py_ssize_t);
-
-#define PyObject_New(type, typeobj) ((type *)_PyObject_New(typeobj))
-
-// Alias to PyObject_New(). In Python 3.8, PyObject_NEW() called directly
-// PyObject_MALLOC() with _PyObject_SIZE().
-#define PyObject_NEW(type, typeobj) PyObject_New(type, typeobj)
-
-#define PyObject_NewVar(type, typeobj, n) \
- ( (type *) _PyObject_NewVar((typeobj), (n)) )
-
-// Alias to PyObject_NewVar(). In Python 3.8, PyObject_NEW_VAR() called
-// directly PyObject_MALLOC() with _PyObject_VAR_SIZE().
-#define PyObject_NEW_VAR(type, typeobj, n) PyObject_NewVar(type, typeobj, n)
-
-
-/*
- * Garbage Collection Support
- * ==========================
- */
-
-/* C equivalent of gc.collect(). */
-PyAPI_FUNC(Py_ssize_t) PyGC_Collect(void);
-/* C API for controlling the state of the garbage collector */
-PyAPI_FUNC(int) PyGC_Enable(void);
-PyAPI_FUNC(int) PyGC_Disable(void);
-PyAPI_FUNC(int) PyGC_IsEnabled(void);
-
-/* Test if a type has a GC head */
-#define PyType_IS_GC(t) PyType_HasFeature((t), Py_TPFLAGS_HAVE_GC)
-
-PyAPI_FUNC(PyVarObject *) _PyObject_GC_Resize(PyVarObject *, Py_ssize_t);
-#define PyObject_GC_Resize(type, op, n) \
- ( (type *) _PyObject_GC_Resize(_PyVarObject_CAST(op), (n)) )
-
-
-
-PyAPI_FUNC(PyObject *) _PyObject_GC_New(PyTypeObject *);
-PyAPI_FUNC(PyVarObject *) _PyObject_GC_NewVar(PyTypeObject *, Py_ssize_t);
-
-/* Tell the GC to track this object.
- *
- * See also private _PyObject_GC_TRACK() macro. */
-PyAPI_FUNC(void) PyObject_GC_Track(void *);
-
-/* Tell the GC to stop tracking this object.
- *
- * See also private _PyObject_GC_UNTRACK() macro. */
-PyAPI_FUNC(void) PyObject_GC_UnTrack(void *);
-
-PyAPI_FUNC(void) PyObject_GC_Del(void *);
-
-#define PyObject_GC_New(type, typeobj) \
- ( (type *) _PyObject_GC_New(typeobj) )
-#define PyObject_GC_NewVar(type, typeobj, n) \
- ( (type *) _PyObject_GC_NewVar((typeobj), (n)) )
-
-PyAPI_FUNC(int) PyObject_GC_IsTracked(PyObject *);
-PyAPI_FUNC(int) PyObject_GC_IsFinalized(PyObject *);
-
-/* Utility macro to help write tp_traverse functions.
- * To use this macro, the tp_traverse function must name its arguments
- * "visit" and "arg". This is intended to keep tp_traverse functions
- * looking as much alike as possible.
- */
-#define Py_VISIT(op) \
- do { \
- if (op) { \
- int vret = visit(_PyObject_CAST(op), arg); \
- if (vret) \
- return vret; \
- } \
- } while (0)
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_OBJIMPL_H
-# include "cpython/objimpl.h"
-# undef Py_CPYTHON_OBJIMPL_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_OBJIMPL_H */
diff --git a/include/python3.10/opcode.h b/include/python3.10/opcode.h
deleted file mode 100644
index 5203975..0000000
--- a/include/python3.10/opcode.h
+++ /dev/null
@@ -1,172 +0,0 @@
-/* Auto-generated by Tools/scripts/generate_opcode_h.py from Lib/opcode.py */
-#ifndef Py_OPCODE_H
-#define Py_OPCODE_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
- /* Instruction opcodes for compiled code */
-#define POP_TOP 1
-#define ROT_TWO 2
-#define ROT_THREE 3
-#define DUP_TOP 4
-#define DUP_TOP_TWO 5
-#define ROT_FOUR 6
-#define NOP 9
-#define UNARY_POSITIVE 10
-#define UNARY_NEGATIVE 11
-#define UNARY_NOT 12
-#define UNARY_INVERT 15
-#define BINARY_MATRIX_MULTIPLY 16
-#define INPLACE_MATRIX_MULTIPLY 17
-#define BINARY_POWER 19
-#define BINARY_MULTIPLY 20
-#define BINARY_MODULO 22
-#define BINARY_ADD 23
-#define BINARY_SUBTRACT 24
-#define BINARY_SUBSCR 25
-#define BINARY_FLOOR_DIVIDE 26
-#define BINARY_TRUE_DIVIDE 27
-#define INPLACE_FLOOR_DIVIDE 28
-#define INPLACE_TRUE_DIVIDE 29
-#define GET_LEN 30
-#define MATCH_MAPPING 31
-#define MATCH_SEQUENCE 32
-#define MATCH_KEYS 33
-#define COPY_DICT_WITHOUT_KEYS 34
-#define WITH_EXCEPT_START 49
-#define GET_AITER 50
-#define GET_ANEXT 51
-#define BEFORE_ASYNC_WITH 52
-#define END_ASYNC_FOR 54
-#define INPLACE_ADD 55
-#define INPLACE_SUBTRACT 56
-#define INPLACE_MULTIPLY 57
-#define INPLACE_MODULO 59
-#define STORE_SUBSCR 60
-#define DELETE_SUBSCR 61
-#define BINARY_LSHIFT 62
-#define BINARY_RSHIFT 63
-#define BINARY_AND 64
-#define BINARY_XOR 65
-#define BINARY_OR 66
-#define INPLACE_POWER 67
-#define GET_ITER 68
-#define GET_YIELD_FROM_ITER 69
-#define PRINT_EXPR 70
-#define LOAD_BUILD_CLASS 71
-#define YIELD_FROM 72
-#define GET_AWAITABLE 73
-#define LOAD_ASSERTION_ERROR 74
-#define INPLACE_LSHIFT 75
-#define INPLACE_RSHIFT 76
-#define INPLACE_AND 77
-#define INPLACE_XOR 78
-#define INPLACE_OR 79
-#define LIST_TO_TUPLE 82
-#define RETURN_VALUE 83
-#define IMPORT_STAR 84
-#define SETUP_ANNOTATIONS 85
-#define YIELD_VALUE 86
-#define POP_BLOCK 87
-#define POP_EXCEPT 89
-#define HAVE_ARGUMENT 90
-#define STORE_NAME 90
-#define DELETE_NAME 91
-#define UNPACK_SEQUENCE 92
-#define FOR_ITER 93
-#define UNPACK_EX 94
-#define STORE_ATTR 95
-#define DELETE_ATTR 96
-#define STORE_GLOBAL 97
-#define DELETE_GLOBAL 98
-#define ROT_N 99
-#define LOAD_CONST 100
-#define LOAD_NAME 101
-#define BUILD_TUPLE 102
-#define BUILD_LIST 103
-#define BUILD_SET 104
-#define BUILD_MAP 105
-#define LOAD_ATTR 106
-#define COMPARE_OP 107
-#define IMPORT_NAME 108
-#define IMPORT_FROM 109
-#define JUMP_FORWARD 110
-#define JUMP_IF_FALSE_OR_POP 111
-#define JUMP_IF_TRUE_OR_POP 112
-#define JUMP_ABSOLUTE 113
-#define POP_JUMP_IF_FALSE 114
-#define POP_JUMP_IF_TRUE 115
-#define LOAD_GLOBAL 116
-#define IS_OP 117
-#define CONTAINS_OP 118
-#define RERAISE 119
-#define JUMP_IF_NOT_EXC_MATCH 121
-#define SETUP_FINALLY 122
-#define LOAD_FAST 124
-#define STORE_FAST 125
-#define DELETE_FAST 126
-#define GEN_START 129
-#define RAISE_VARARGS 130
-#define CALL_FUNCTION 131
-#define MAKE_FUNCTION 132
-#define BUILD_SLICE 133
-#define LOAD_CLOSURE 135
-#define LOAD_DEREF 136
-#define STORE_DEREF 137
-#define DELETE_DEREF 138
-#define CALL_FUNCTION_KW 141
-#define CALL_FUNCTION_EX 142
-#define SETUP_WITH 143
-#define EXTENDED_ARG 144
-#define LIST_APPEND 145
-#define SET_ADD 146
-#define MAP_ADD 147
-#define LOAD_CLASSDEREF 148
-#define MATCH_CLASS 152
-#define SETUP_ASYNC_WITH 154
-#define FORMAT_VALUE 155
-#define BUILD_CONST_KEY_MAP 156
-#define BUILD_STRING 157
-#define LOAD_METHOD 160
-#define CALL_METHOD 161
-#define LIST_EXTEND 162
-#define SET_UPDATE 163
-#define DICT_MERGE 164
-#define DICT_UPDATE 165
-#ifdef NEED_OPCODE_JUMP_TABLES
-static uint32_t _PyOpcode_RelativeJump[8] = {
- 0U,
- 0U,
- 536870912U,
- 67125248U,
- 67141632U,
- 0U,
- 0U,
- 0U,
-};
-static uint32_t _PyOpcode_Jump[8] = {
- 0U,
- 0U,
- 536870912U,
- 101695488U,
- 67141632U,
- 0U,
- 0U,
- 0U,
-};
-#endif /* OPCODE_TABLES */
-
-/* EXCEPT_HANDLER is a special, implicit block type which is created when
- entering an except handler. It is not an opcode but we define it here
- as we want it to be available to both frameobject.c and ceval.c, while
- remaining private.*/
-#define EXCEPT_HANDLER 257
-
-#define HAS_ARG(op) ((op) >= HAVE_ARGUMENT)
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_OPCODE_H */
diff --git a/include/python3.10/patchlevel.h b/include/python3.10/patchlevel.h
deleted file mode 100644
index 5bb246e..0000000
--- a/include/python3.10/patchlevel.h
+++ /dev/null
@@ -1,35 +0,0 @@
-
-/* Python version identification scheme.
-
- When the major or minor version changes, the VERSION variable in
- configure.ac must also be changed.
-
- There is also (independent) API version information in modsupport.h.
-*/
-
-/* Values for PY_RELEASE_LEVEL */
-#define PY_RELEASE_LEVEL_ALPHA 0xA
-#define PY_RELEASE_LEVEL_BETA 0xB
-#define PY_RELEASE_LEVEL_GAMMA 0xC /* For release candidates */
-#define PY_RELEASE_LEVEL_FINAL 0xF /* Serial should be 0 here */
- /* Higher for patch releases */
-
-/* Version parsed out into numeric values */
-/*--start constants--*/
-#define PY_MAJOR_VERSION 3
-#define PY_MINOR_VERSION 10
-#define PY_MICRO_VERSION 3
-#define PY_RELEASE_LEVEL PY_RELEASE_LEVEL_FINAL
-#define PY_RELEASE_SERIAL 0
-
-/* Version as a string */
-#define PY_VERSION "3.10.3"
-/*--end constants--*/
-
-/* Version as a single 4-byte hex number, e.g. 0x010502B2 == 1.5.2b2.
- Use this for numeric comparisons, e.g. #if PY_VERSION_HEX >= ... */
-#define PY_VERSION_HEX ((PY_MAJOR_VERSION << 24) | \
- (PY_MINOR_VERSION << 16) | \
- (PY_MICRO_VERSION << 8) | \
- (PY_RELEASE_LEVEL << 4) | \
- (PY_RELEASE_SERIAL << 0))
diff --git a/include/python3.10/py_curses.h b/include/python3.10/py_curses.h
deleted file mode 100644
index b70252d..0000000
--- a/include/python3.10/py_curses.h
+++ /dev/null
@@ -1,99 +0,0 @@
-
-#ifndef Py_CURSES_H
-#define Py_CURSES_H
-
-#ifdef __APPLE__
-/*
-** On Mac OS X 10.2 [n]curses.h and stdlib.h use different guards
-** against multiple definition of wchar_t.
-*/
-#ifdef _BSD_WCHAR_T_DEFINED_
-#define _WCHAR_T
-#endif
-#endif /* __APPLE__ */
-
-/* On FreeBSD, [n]curses.h and stdlib.h/wchar.h use different guards
- against multiple definition of wchar_t and wint_t. */
-#if defined(__FreeBSD__) && defined(_XOPEN_SOURCE_EXTENDED)
-# ifndef __wchar_t
-# define __wchar_t
-# endif
-# ifndef __wint_t
-# define __wint_t
-# endif
-#endif
-
-#if !defined(HAVE_CURSES_IS_PAD) && defined(WINDOW_HAS_FLAGS)
-/* The following definition is necessary for ncurses 5.7; without it,
- some of [n]curses.h set NCURSES_OPAQUE to 1, and then Python
- can't get at the WINDOW flags field. */
-#define NCURSES_OPAQUE 0
-#endif
-
-#ifdef HAVE_NCURSES_H
-#include <ncurses.h>
-#else
-#include <curses.h>
-#endif
-
-#ifdef HAVE_NCURSES_H
-/* configure was checking <curses.h>, but we will
- use <ncurses.h>, which has some or all these features. */
-#if !defined(WINDOW_HAS_FLAGS) && !(NCURSES_OPAQUE+0)
-#define WINDOW_HAS_FLAGS 1
-#endif
-#if !defined(HAVE_CURSES_IS_PAD) && NCURSES_VERSION_PATCH+0 >= 20090906
-#define HAVE_CURSES_IS_PAD 1
-#endif
-#ifndef MVWDELCH_IS_EXPRESSION
-#define MVWDELCH_IS_EXPRESSION 1
-#endif
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define PyCurses_API_pointers 4
-
-/* Type declarations */
-
-typedef struct {
- PyObject_HEAD
- WINDOW *win;
- char *encoding;
-} PyCursesWindowObject;
-
-#define PyCursesWindow_Check(v) Py_IS_TYPE(v, &PyCursesWindow_Type)
-
-#define PyCurses_CAPSULE_NAME "_curses._C_API"
-
-
-#ifdef CURSES_MODULE
-/* This section is used when compiling _cursesmodule.c */
-
-#else
-/* This section is used in modules that use the _cursesmodule API */
-
-static void **PyCurses_API;
-
-#define PyCursesWindow_Type (*(PyTypeObject *) PyCurses_API[0])
-#define PyCursesSetupTermCalled {if (! ((int (*)(void))PyCurses_API[1]) () ) return NULL;}
-#define PyCursesInitialised {if (! ((int (*)(void))PyCurses_API[2]) () ) return NULL;}
-#define PyCursesInitialisedColor {if (! ((int (*)(void))PyCurses_API[3]) () ) return NULL;}
-
-#define import_curses() \
- PyCurses_API = (void **)PyCapsule_Import(PyCurses_CAPSULE_NAME, 1);
-
-#endif
-
-/* general error messages */
-static const char catchall_ERR[] = "curses function returned ERR";
-static const char catchall_NULL[] = "curses function returned NULL";
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* !defined(Py_CURSES_H) */
-
diff --git a/include/python3.10/pyconfig.h b/include/python3.10/pyconfig.h
deleted file mode 100644
index d9288ed..0000000
--- a/include/python3.10/pyconfig.h
+++ /dev/null
@@ -1,1700 +0,0 @@
-/* pyconfig.h. Generated from pyconfig.h.in by configure. */
-/* pyconfig.h.in. Generated from configure.ac by autoheader. */
-
-
-#ifndef Py_PYCONFIG_H
-#define Py_PYCONFIG_H
-
-
-/* Define if building universal (internal helper macro) */
-/* #undef AC_APPLE_UNIVERSAL_BUILD */
-
-/* BUILD_GNU_TYPE + AIX_BUILDDATE are used to construct the PEP425 tag of the
- build system. */
-/* #undef AIX_BUILDDATE */
-
-/* Define for AIX if your compiler is a genuine IBM xlC/xlC_r and you want
- support for AIX C++ shared extension modules. */
-/* #undef AIX_GENUINE_CPLUSPLUS */
-
-/* The normal alignment of `long', in bytes. */
-#define ALIGNOF_LONG 8
-
-/* The normal alignment of `size_t', in bytes. */
-#define ALIGNOF_SIZE_T 8
-
-/* Alternative SOABI used in debug build to load C extensions built in release
- mode */
-/* #undef ALT_SOABI */
-
-/* The Android API level. */
-/* #undef ANDROID_API_LEVEL */
-
-/* Define if C doubles are 64-bit IEEE 754 binary format, stored in ARM
- mixed-endian order (byte order 45670123) */
-/* #undef DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754 */
-
-/* Define if C doubles are 64-bit IEEE 754 binary format, stored with the most
- significant byte first */
-/* #undef DOUBLE_IS_BIG_ENDIAN_IEEE754 */
-
-/* Define if C doubles are 64-bit IEEE 754 binary format, stored with the
- least significant byte first */
-#define DOUBLE_IS_LITTLE_ENDIAN_IEEE754 1
-
-/* Define if --enable-ipv6 is specified */
-#define ENABLE_IPV6 1
-
-/* Better isolate subinterpreters, experimental build mode. */
-/* #undef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS */
-
-/* Define to 1 if your system stores words within floats with the most
- significant word first */
-/* #undef FLOAT_WORDS_BIGENDIAN */
-
-/* Define if flock needs to be linked with bsd library. */
-/* #undef FLOCK_NEEDS_LIBBSD */
-
-/* Define if getpgrp() must be called as getpgrp(0). */
-/* #undef GETPGRP_HAVE_ARG */
-
-/* Define to 1 if you have the `accept4' function. */
-#define HAVE_ACCEPT4 1
-
-/* Define to 1 if you have the `acosh' function. */
-#define HAVE_ACOSH 1
-
-/* struct addrinfo (netdb.h) */
-#define HAVE_ADDRINFO 1
-
-/* Define to 1 if you have the `alarm' function. */
-#define HAVE_ALARM 1
-
-/* Define if aligned memory access is required */
-/* #undef HAVE_ALIGNED_REQUIRED */
-
-/* Define to 1 if you have the <alloca.h> header file. */
-#define HAVE_ALLOCA_H 1
-
-/* Define this if your time.h defines altzone. */
-/* #undef HAVE_ALTZONE */
-
-/* Define to 1 if you have the `asinh' function. */
-#define HAVE_ASINH 1
-
-/* Define to 1 if you have the <asm/types.h> header file. */
-#define HAVE_ASM_TYPES_H 1
-
-/* Define to 1 if you have the `atanh' function. */
-#define HAVE_ATANH 1
-
-/* Define to 1 if you have the `bind_textdomain_codeset' function. */
-#define HAVE_BIND_TEXTDOMAIN_CODESET 1
-
-/* Define to 1 if you have the <bluetooth/bluetooth.h> header file. */
-/* #undef HAVE_BLUETOOTH_BLUETOOTH_H */
-
-/* Define to 1 if you have the <bluetooth.h> header file. */
-/* #undef HAVE_BLUETOOTH_H */
-
-/* Define if mbstowcs(NULL, "text", 0) does not return the number of wide
- chars that would be converted. */
-/* #undef HAVE_BROKEN_MBSTOWCS */
-
-/* Define if nice() returns success/failure instead of the new priority. */
-/* #undef HAVE_BROKEN_NICE */
-
-/* Define if the system reports an invalid PIPE_BUF value. */
-/* #undef HAVE_BROKEN_PIPE_BUF */
-
-/* Define if poll() sets errno on invalid file descriptors. */
-/* #undef HAVE_BROKEN_POLL */
-
-/* Define if the Posix semaphores do not work on your system */
-/* #undef HAVE_BROKEN_POSIX_SEMAPHORES */
-
-/* Define if pthread_sigmask() does not work on your system. */
-/* #undef HAVE_BROKEN_PTHREAD_SIGMASK */
-
-/* define to 1 if your sem_getvalue is broken. */
-/* #undef HAVE_BROKEN_SEM_GETVALUE */
-
-/* Define if `unsetenv` does not return an int. */
-/* #undef HAVE_BROKEN_UNSETENV */
-
-/* Has builtin __atomic_load_n() and __atomic_store_n() functions */
-#define HAVE_BUILTIN_ATOMIC 1
-
-/* Define to 1 if you have the 'chflags' function. */
-/* #undef HAVE_CHFLAGS */
-
-/* Define to 1 if you have the `chown' function. */
-#define HAVE_CHOWN 1
-
-/* Define if you have the 'chroot' function. */
-#define HAVE_CHROOT 1
-
-/* Define to 1 if you have the `clock' function. */
-#define HAVE_CLOCK 1
-
-/* Define to 1 if you have the `clock_getres' function. */
-#define HAVE_CLOCK_GETRES 1
-
-/* Define to 1 if you have the `clock_gettime' function. */
-#define HAVE_CLOCK_GETTIME 1
-
-/* Define to 1 if you have the `clock_settime' function. */
-#define HAVE_CLOCK_SETTIME 1
-
-/* Define to 1 if you have the `close_range' function. */
-/* #undef HAVE_CLOSE_RANGE */
-
-/* Define if the C compiler supports computed gotos. */
-#define HAVE_COMPUTED_GOTOS 1
-
-/* Define to 1 if you have the `confstr' function. */
-#define HAVE_CONFSTR 1
-
-/* Define to 1 if you have the <conio.h> header file. */
-/* #undef HAVE_CONIO_H */
-
-/* Define to 1 if you have the `copysign' function. */
-#define HAVE_COPYSIGN 1
-
-/* Define to 1 if you have the `copy_file_range' function. */
-/* #undef HAVE_COPY_FILE_RANGE */
-
-/* Define to 1 if you have the <crypt.h> header file. */
-#define HAVE_CRYPT_H 1
-
-/* Define if you have the crypt_r() function. */
-#define HAVE_CRYPT_R 1
-
-/* Define to 1 if you have the `ctermid' function. */
-#define HAVE_CTERMID 1
-
-/* Define if you have the 'ctermid_r' function. */
-/* #undef HAVE_CTERMID_R */
-
-/* Define if you have the 'filter' function. */
-#define HAVE_CURSES_FILTER 1
-
-/* Define to 1 if you have the <curses.h> header file. */
-#define HAVE_CURSES_H 1
-
-/* Define if you have the 'has_key' function. */
-#define HAVE_CURSES_HAS_KEY 1
-
-/* Define if you have the 'immedok' function. */
-#define HAVE_CURSES_IMMEDOK 1
-
-/* Define if you have the 'is_pad' function or macro. */
-#define HAVE_CURSES_IS_PAD 1
-
-/* Define if you have the 'is_term_resized' function. */
-#define HAVE_CURSES_IS_TERM_RESIZED 1
-
-/* Define if you have the 'resizeterm' function. */
-#define HAVE_CURSES_RESIZETERM 1
-
-/* Define if you have the 'resize_term' function. */
-#define HAVE_CURSES_RESIZE_TERM 1
-
-/* Define if you have the 'syncok' function. */
-#define HAVE_CURSES_SYNCOK 1
-
-/* Define if you have the 'typeahead' function. */
-#define HAVE_CURSES_TYPEAHEAD 1
-
-/* Define if you have the 'use_env' function. */
-#define HAVE_CURSES_USE_ENV 1
-
-/* Define if you have the 'wchgat' function. */
-#define HAVE_CURSES_WCHGAT 1
-
-/* Define to 1 if you have the declaration of `isfinite', and to 0 if you
- don't. */
-#define HAVE_DECL_ISFINITE 1
-
-/* Define to 1 if you have the declaration of `isinf', and to 0 if you don't.
- */
-#define HAVE_DECL_ISINF 1
-
-/* Define to 1 if you have the declaration of `isnan', and to 0 if you don't.
- */
-#define HAVE_DECL_ISNAN 1
-
-/* Define to 1 if you have the declaration of `RTLD_DEEPBIND', and to 0 if you
- don't. */
-#define HAVE_DECL_RTLD_DEEPBIND 1
-
-/* Define to 1 if you have the declaration of `RTLD_GLOBAL', and to 0 if you
- don't. */
-#define HAVE_DECL_RTLD_GLOBAL 1
-
-/* Define to 1 if you have the declaration of `RTLD_LAZY', and to 0 if you
- don't. */
-#define HAVE_DECL_RTLD_LAZY 1
-
-/* Define to 1 if you have the declaration of `RTLD_LOCAL', and to 0 if you
- don't. */
-#define HAVE_DECL_RTLD_LOCAL 1
-
-/* Define to 1 if you have the declaration of `RTLD_MEMBER', and to 0 if you
- don't. */
-#define HAVE_DECL_RTLD_MEMBER 0
-
-/* Define to 1 if you have the declaration of `RTLD_NODELETE', and to 0 if you
- don't. */
-#define HAVE_DECL_RTLD_NODELETE 1
-
-/* Define to 1 if you have the declaration of `RTLD_NOLOAD', and to 0 if you
- don't. */
-#define HAVE_DECL_RTLD_NOLOAD 1
-
-/* Define to 1 if you have the declaration of `RTLD_NOW', and to 0 if you
- don't. */
-#define HAVE_DECL_RTLD_NOW 1
-
-/* Define to 1 if you have the declaration of `tzname', and to 0 if you don't.
- */
-/* #undef HAVE_DECL_TZNAME */
-
-/* Define to 1 if you have the device macros. */
-#define HAVE_DEVICE_MACROS 1
-
-/* Define to 1 if you have the /dev/ptc device file. */
-/* #undef HAVE_DEV_PTC */
-
-/* Define to 1 if you have the /dev/ptmx device file. */
-#define HAVE_DEV_PTMX 1
-
-/* Define to 1 if you have the <direct.h> header file. */
-/* #undef HAVE_DIRECT_H */
-
-/* Define to 1 if the dirent structure has a d_type field */
-#define HAVE_DIRENT_D_TYPE 1
-
-/* Define to 1 if you have the <dirent.h> header file, and it defines `DIR'.
- */
-#define HAVE_DIRENT_H 1
-
-/* Define if you have the 'dirfd' function or macro. */
-#define HAVE_DIRFD 1
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define to 1 if you have the `dlopen' function. */
-#define HAVE_DLOPEN 1
-
-/* Define to 1 if you have the `dup2' function. */
-#define HAVE_DUP2 1
-
-/* Define to 1 if you have the `dup3' function. */
-#define HAVE_DUP3 1
-
-/* Define if you have the '_dyld_shared_cache_contains_path' function. */
-/* #undef HAVE_DYLD_SHARED_CACHE_CONTAINS_PATH */
-
-/* Defined when any dynamic module loading is enabled. */
-#define HAVE_DYNAMIC_LOADING 1
-
-/* Define to 1 if you have the <endian.h> header file. */
-#define HAVE_ENDIAN_H 1
-
-/* Define if you have the 'epoll' functions. */
-#define HAVE_EPOLL 1
-
-/* Define if you have the 'epoll_create1' function. */
-#define HAVE_EPOLL_CREATE1 1
-
-/* Define to 1 if you have the `erf' function. */
-#define HAVE_ERF 1
-
-/* Define to 1 if you have the `erfc' function. */
-#define HAVE_ERFC 1
-
-/* Define to 1 if you have the <errno.h> header file. */
-#define HAVE_ERRNO_H 1
-
-/* Define if you have the 'eventfd' function. */
-#define HAVE_EVENTFD 1
-
-/* Define to 1 if you have the `execv' function. */
-#define HAVE_EXECV 1
-
-/* Define to 1 if you have the `explicit_bzero' function. */
-/* #undef HAVE_EXPLICIT_BZERO */
-
-/* Define to 1 if you have the `explicit_memset' function. */
-/* #undef HAVE_EXPLICIT_MEMSET */
-
-/* Define to 1 if you have the `expm1' function. */
-#define HAVE_EXPM1 1
-
-/* Define to 1 if you have the `faccessat' function. */
-#define HAVE_FACCESSAT 1
-
-/* Define if you have the 'fchdir' function. */
-#define HAVE_FCHDIR 1
-
-/* Define to 1 if you have the `fchmod' function. */
-#define HAVE_FCHMOD 1
-
-/* Define to 1 if you have the `fchmodat' function. */
-#define HAVE_FCHMODAT 1
-
-/* Define to 1 if you have the `fchown' function. */
-#define HAVE_FCHOWN 1
-
-/* Define to 1 if you have the `fchownat' function. */
-#define HAVE_FCHOWNAT 1
-
-/* Define to 1 if you have the <fcntl.h> header file. */
-#define HAVE_FCNTL_H 1
-
-/* Define if you have the 'fdatasync' function. */
-#define HAVE_FDATASYNC 1
-
-/* Define to 1 if you have the `fdopendir' function. */
-#define HAVE_FDOPENDIR 1
-
-/* Define to 1 if you have the `fdwalk' function. */
-/* #undef HAVE_FDWALK */
-
-/* Define to 1 if you have the `fexecve' function. */
-#define HAVE_FEXECVE 1
-
-/* Define to 1 if you have the `finite' function. */
-#define HAVE_FINITE 1
-
-/* Define to 1 if you have the `flock' function. */
-#define HAVE_FLOCK 1
-
-/* Define to 1 if you have the `fork' function. */
-#define HAVE_FORK 1
-
-/* Define to 1 if you have the `forkpty' function. */
-#define HAVE_FORKPTY 1
-
-/* Define to 1 if you have the `fpathconf' function. */
-#define HAVE_FPATHCONF 1
-
-/* Define to 1 if you have the `fseek64' function. */
-/* #undef HAVE_FSEEK64 */
-
-/* Define to 1 if you have the `fseeko' function. */
-#define HAVE_FSEEKO 1
-
-/* Define to 1 if you have the `fstatat' function. */
-#define HAVE_FSTATAT 1
-
-/* Define to 1 if you have the `fstatvfs' function. */
-#define HAVE_FSTATVFS 1
-
-/* Define if you have the 'fsync' function. */
-#define HAVE_FSYNC 1
-
-/* Define to 1 if you have the `ftell64' function. */
-/* #undef HAVE_FTELL64 */
-
-/* Define to 1 if you have the `ftello' function. */
-#define HAVE_FTELLO 1
-
-/* Define to 1 if you have the `ftime' function. */
-#define HAVE_FTIME 1
-
-/* Define to 1 if you have the `ftruncate' function. */
-#define HAVE_FTRUNCATE 1
-
-/* Define to 1 if you have the `futimens' function. */
-#define HAVE_FUTIMENS 1
-
-/* Define to 1 if you have the `futimes' function. */
-#define HAVE_FUTIMES 1
-
-/* Define to 1 if you have the `futimesat' function. */
-#define HAVE_FUTIMESAT 1
-
-/* Define to 1 if you have the `gai_strerror' function. */
-#define HAVE_GAI_STRERROR 1
-
-/* Define to 1 if you have the `gamma' function. */
-#define HAVE_GAMMA 1
-
-/* Define if we can use gcc inline assembler to get and set mc68881 fpcr */
-/* #undef HAVE_GCC_ASM_FOR_MC68881 */
-
-/* Define if we can use x64 gcc inline assembler */
-#define HAVE_GCC_ASM_FOR_X64 1
-
-/* Define if we can use gcc inline assembler to get and set x87 control word
- */
-#define HAVE_GCC_ASM_FOR_X87 1
-
-/* Define if your compiler provides __uint128_t */
-#define HAVE_GCC_UINT128_T 1
-
-/* Define if you have the getaddrinfo function. */
-#define HAVE_GETADDRINFO 1
-
-/* Define this if you have flockfile(), getc_unlocked(), and funlockfile() */
-#define HAVE_GETC_UNLOCKED 1
-
-/* Define to 1 if you have the `getentropy' function. */
-/* #undef HAVE_GETENTROPY */
-
-/* Define to 1 if you have the `getgrgid_r' function. */
-#define HAVE_GETGRGID_R 1
-
-/* Define to 1 if you have the `getgrnam_r' function. */
-#define HAVE_GETGRNAM_R 1
-
-/* Define to 1 if you have the `getgrouplist' function. */
-#define HAVE_GETGROUPLIST 1
-
-/* Define to 1 if you have the `getgroups' function. */
-#define HAVE_GETGROUPS 1
-
-/* Define to 1 if you have the `gethostbyname' function. */
-/* #undef HAVE_GETHOSTBYNAME */
-
-/* Define this if you have some version of gethostbyname_r() */
-#define HAVE_GETHOSTBYNAME_R 1
-
-/* Define this if you have the 3-arg version of gethostbyname_r(). */
-/* #undef HAVE_GETHOSTBYNAME_R_3_ARG */
-
-/* Define this if you have the 5-arg version of gethostbyname_r(). */
-/* #undef HAVE_GETHOSTBYNAME_R_5_ARG */
-
-/* Define this if you have the 6-arg version of gethostbyname_r(). */
-#define HAVE_GETHOSTBYNAME_R_6_ARG 1
-
-/* Define to 1 if you have the `getitimer' function. */
-#define HAVE_GETITIMER 1
-
-/* Define to 1 if you have the `getloadavg' function. */
-#define HAVE_GETLOADAVG 1
-
-/* Define to 1 if you have the `getlogin' function. */
-#define HAVE_GETLOGIN 1
-
-/* Define to 1 if you have the `getnameinfo' function. */
-#define HAVE_GETNAMEINFO 1
-
-/* Define if you have the 'getpagesize' function. */
-#define HAVE_GETPAGESIZE 1
-
-/* Define to 1 if you have the `getpeername' function. */
-#define HAVE_GETPEERNAME 1
-
-/* Define to 1 if you have the `getpgid' function. */
-#define HAVE_GETPGID 1
-
-/* Define to 1 if you have the `getpgrp' function. */
-#define HAVE_GETPGRP 1
-
-/* Define to 1 if you have the `getpid' function. */
-#define HAVE_GETPID 1
-
-/* Define to 1 if you have the `getpriority' function. */
-#define HAVE_GETPRIORITY 1
-
-/* Define to 1 if you have the `getpwent' function. */
-#define HAVE_GETPWENT 1
-
-/* Define to 1 if you have the `getpwnam_r' function. */
-#define HAVE_GETPWNAM_R 1
-
-/* Define to 1 if you have the `getpwuid_r' function. */
-#define HAVE_GETPWUID_R 1
-
-/* Define to 1 if the getrandom() function is available */
-/* #undef HAVE_GETRANDOM */
-
-/* Define to 1 if the Linux getrandom() syscall is available */
-#define HAVE_GETRANDOM_SYSCALL 1
-
-/* Define to 1 if you have the `getresgid' function. */
-#define HAVE_GETRESGID 1
-
-/* Define to 1 if you have the `getresuid' function. */
-#define HAVE_GETRESUID 1
-
-/* Define to 1 if you have the `getsid' function. */
-#define HAVE_GETSID 1
-
-/* Define to 1 if you have the `getspent' function. */
-#define HAVE_GETSPENT 1
-
-/* Define to 1 if you have the `getspnam' function. */
-#define HAVE_GETSPNAM 1
-
-/* Define to 1 if you have the `getwd' function. */
-#define HAVE_GETWD 1
-
-/* Define if glibc has incorrect _FORTIFY_SOURCE wrappers for memmove and
- bcopy. */
-/* #undef HAVE_GLIBC_MEMMOVE_BUG */
-
-/* Define to 1 if you have the <grp.h> header file. */
-#define HAVE_GRP_H 1
-
-/* Define if you have the 'hstrerror' function. */
-#define HAVE_HSTRERROR 1
-
-/* Define this if you have le64toh() */
-#define HAVE_HTOLE64 1
-
-/* Define to 1 if you have the `hypot' function. */
-#define HAVE_HYPOT 1
-
-/* Define to 1 if you have the <ieeefp.h> header file. */
-/* #undef HAVE_IEEEFP_H */
-
-/* Define to 1 if you have the `if_nameindex' function. */
-#define HAVE_IF_NAMEINDEX 1
-
-/* Define if you have the 'inet_aton' function. */
-#define HAVE_INET_ATON 1
-
-/* Define if you have the 'inet_pton' function. */
-#define HAVE_INET_PTON 1
-
-/* Define to 1 if you have the `initgroups' function. */
-#define HAVE_INITGROUPS 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define to 1 if you have the <io.h> header file. */
-/* #undef HAVE_IO_H */
-
-/* Define if gcc has the ipa-pure-const bug. */
-/* #undef HAVE_IPA_PURE_CONST_BUG */
-
-/* Define to 1 if you have the `kill' function. */
-#define HAVE_KILL 1
-
-/* Define to 1 if you have the `killpg' function. */
-#define HAVE_KILLPG 1
-
-/* Define if you have the 'kqueue' functions. */
-/* #undef HAVE_KQUEUE */
-
-/* Define to 1 if you have the <langinfo.h> header file. */
-#define HAVE_LANGINFO_H 1
-
-/* Defined to enable large file support when an off_t is bigger than a long
- and long long is at least as big as an off_t. You may need to add some
- flags for configuration and compilation to enable this mode. (For Solaris
- and Linux, the necessary defines are already defined.) */
-/* #undef HAVE_LARGEFILE_SUPPORT */
-
-/* Define to 1 if you have the 'lchflags' function. */
-/* #undef HAVE_LCHFLAGS */
-
-/* Define to 1 if you have the `lchmod' function. */
-/* #undef HAVE_LCHMOD */
-
-/* Define to 1 if you have the `lchown' function. */
-#define HAVE_LCHOWN 1
-
-/* Define to 1 if you have the `lgamma' function. */
-#define HAVE_LGAMMA 1
-
-/* Define to 1 if you have the `dl' library (-ldl). */
-#define HAVE_LIBDL 1
-
-/* Define to 1 if you have the `dld' library (-ldld). */
-/* #undef HAVE_LIBDLD */
-
-/* Define to 1 if you have the `ieee' library (-lieee). */
-/* #undef HAVE_LIBIEEE */
-
-/* Define to 1 if you have the <libintl.h> header file. */
-#define HAVE_LIBINTL_H 1
-
-/* Define to build the readline module. */
-/* #undef HAVE_LIBREADLINE */
-
-/* Define to 1 if you have the `resolv' library (-lresolv). */
-/* #undef HAVE_LIBRESOLV */
-
-/* Define to 1 if you have the `sendfile' library (-lsendfile). */
-/* #undef HAVE_LIBSENDFILE */
-
-/* Define to 1 if you have the <libutil.h> header file. */
-/* #undef HAVE_LIBUTIL_H */
-
-/* Define to 1 if you have the `uuid' library (-luuid). */
-/* #undef HAVE_LIBUUID */
-
-/* Define if you have the 'link' function. */
-#define HAVE_LINK 1
-
-/* Define to 1 if you have the `linkat' function. */
-#define HAVE_LINKAT 1
-
-/* Define to 1 if you have the <linux/auxvec.h> header file. */
-#define HAVE_LINUX_AUXVEC_H 1
-
-/* Define to 1 if you have the <linux/can/bcm.h> header file. */
-#define HAVE_LINUX_CAN_BCM_H 1
-
-/* Define to 1 if you have the <linux/can.h> header file. */
-#define HAVE_LINUX_CAN_H 1
-
-/* Define to 1 if you have the <linux/can/j1939.h> header file. */
-/* #undef HAVE_LINUX_CAN_J1939_H */
-
-/* Define if compiling using Linux 3.6 or later. */
-#define HAVE_LINUX_CAN_RAW_FD_FRAMES 1
-
-/* Define to 1 if you have the <linux/can/raw.h> header file. */
-#define HAVE_LINUX_CAN_RAW_H 1
-
-/* Define if compiling using Linux 4.1 or later. */
-#define HAVE_LINUX_CAN_RAW_JOIN_FILTERS 1
-
-/* Define to 1 if you have the <linux/memfd.h> header file. */
-#define HAVE_LINUX_MEMFD_H 1
-
-/* Define to 1 if you have the <linux/netlink.h> header file. */
-#define HAVE_LINUX_NETLINK_H 1
-
-/* Define to 1 if you have the <linux/qrtr.h> header file. */
-/* #undef HAVE_LINUX_QRTR_H */
-
-/* Define to 1 if you have the <linux/random.h> header file. */
-#define HAVE_LINUX_RANDOM_H 1
-
-/* Define to 1 if you have the <linux/tipc.h> header file. */
-#define HAVE_LINUX_TIPC_H 1
-
-/* Define to 1 if you have the <linux/vm_sockets.h> header file. */
-#define HAVE_LINUX_VM_SOCKETS_H 1
-
-/* Define to 1 if you have the <linux/wait.h> header file. */
-#define HAVE_LINUX_WAIT_H 1
-
-/* Define to 1 if you have the `lockf' function. */
-#define HAVE_LOCKF 1
-
-/* Define to 1 if you have the `log1p' function. */
-#define HAVE_LOG1P 1
-
-/* Define to 1 if you have the `log2' function. */
-#define HAVE_LOG2 1
-
-/* Define to 1 if the system has the type `long double'. */
-#define HAVE_LONG_DOUBLE 1
-
-/* Define to 1 if you have the `lstat' function. */
-#define HAVE_LSTAT 1
-
-/* Define to 1 if you have the `lutimes' function. */
-#define HAVE_LUTIMES 1
-
-/* Define to 1 if you have the `madvise' function. */
-#define HAVE_MADVISE 1
-
-/* Define this if you have the makedev macro. */
-#define HAVE_MAKEDEV 1
-
-/* Define to 1 if you have the `mbrtowc' function. */
-#define HAVE_MBRTOWC 1
-
-/* Define if you have the 'memfd_create' function. */
-/* #undef HAVE_MEMFD_CREATE */
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the `memrchr' function. */
-#define HAVE_MEMRCHR 1
-
-/* Define to 1 if you have the `mkdirat' function. */
-#define HAVE_MKDIRAT 1
-
-/* Define to 1 if you have the `mkfifo' function. */
-#define HAVE_MKFIFO 1
-
-/* Define to 1 if you have the `mkfifoat' function. */
-#define HAVE_MKFIFOAT 1
-
-/* Define to 1 if you have the `mknod' function. */
-#define HAVE_MKNOD 1
-
-/* Define to 1 if you have the `mknodat' function. */
-#define HAVE_MKNODAT 1
-
-/* Define to 1 if you have the `mktime' function. */
-#define HAVE_MKTIME 1
-
-/* Define to 1 if you have the `mmap' function. */
-#define HAVE_MMAP 1
-
-/* Define to 1 if you have the `mremap' function. */
-#define HAVE_MREMAP 1
-
-/* Define to 1 if you have the <ncurses.h> header file. */
-#define HAVE_NCURSES_H 1
-
-/* Define to 1 if you have the <ndir.h> header file, and it defines `DIR'. */
-/* #undef HAVE_NDIR_H */
-
-/* Define to 1 if you have the <netpacket/packet.h> header file. */
-#define HAVE_NETPACKET_PACKET_H 1
-
-/* Define to 1 if you have the <net/if.h> header file. */
-#define HAVE_NET_IF_H 1
-
-/* Define to 1 if you have the `nice' function. */
-#define HAVE_NICE 1
-
-/* Define if the internal form of wchar_t in non-Unicode locales is not
- Unicode. */
-/* #undef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION */
-
-/* Define to 1 if you have the `openat' function. */
-#define HAVE_OPENAT 1
-
-/* Define to 1 if you have the `openpty' function. */
-#define HAVE_OPENPTY 1
-
-/* Define to 1 if you have the `pathconf' function. */
-#define HAVE_PATHCONF 1
-
-/* Define to 1 if you have the `pause' function. */
-#define HAVE_PAUSE 1
-
-/* Define to 1 if you have the `pipe2' function. */
-#define HAVE_PIPE2 1
-
-/* Define to 1 if you have the `plock' function. */
-/* #undef HAVE_PLOCK */
-
-/* Define to 1 if you have the `poll' function. */
-#define HAVE_POLL 1
-
-/* Define to 1 if you have the <poll.h> header file. */
-#define HAVE_POLL_H 1
-
-/* Define to 1 if you have the `posix_fadvise' function. */
-#define HAVE_POSIX_FADVISE 1
-
-/* Define to 1 if you have the `posix_fallocate' function. */
-#define HAVE_POSIX_FALLOCATE 1
-
-/* Define to 1 if you have the `posix_spawn' function. */
-#define HAVE_POSIX_SPAWN 1
-
-/* Define to 1 if you have the `posix_spawnp' function. */
-#define HAVE_POSIX_SPAWNP 1
-
-/* Define to 1 if you have the `pread' function. */
-#define HAVE_PREAD 1
-
-/* Define to 1 if you have the `preadv' function. */
-#define HAVE_PREADV 1
-
-/* Define to 1 if you have the `preadv2' function. */
-/* #undef HAVE_PREADV2 */
-
-/* Define if you have the 'prlimit' functions. */
-#define HAVE_PRLIMIT 1
-
-/* Define to 1 if you have the <process.h> header file. */
-/* #undef HAVE_PROCESS_H */
-
-/* Define if your compiler supports function prototype */
-#define HAVE_PROTOTYPES 1
-
-/* Define to 1 if you have the `pthread_condattr_setclock' function. */
-#define HAVE_PTHREAD_CONDATTR_SETCLOCK 1
-
-/* Defined for Solaris 2.6 bug in pthread header. */
-/* #undef HAVE_PTHREAD_DESTRUCTOR */
-
-/* Define to 1 if you have the `pthread_getcpuclockid' function. */
-#define HAVE_PTHREAD_GETCPUCLOCKID 1
-
-/* Define to 1 if you have the <pthread.h> header file. */
-#define HAVE_PTHREAD_H 1
-
-/* Define to 1 if you have the `pthread_init' function. */
-/* #undef HAVE_PTHREAD_INIT */
-
-/* Define to 1 if you have the `pthread_kill' function. */
-#define HAVE_PTHREAD_KILL 1
-
-/* Define to 1 if you have the `pthread_sigmask' function. */
-#define HAVE_PTHREAD_SIGMASK 1
-
-/* Define to 1 if you have the <pty.h> header file. */
-#define HAVE_PTY_H 1
-
-/* Define to 1 if you have the `pwrite' function. */
-#define HAVE_PWRITE 1
-
-/* Define to 1 if you have the `pwritev' function. */
-#define HAVE_PWRITEV 1
-
-/* Define to 1 if you have the `pwritev2' function. */
-/* #undef HAVE_PWRITEV2 */
-
-/* Define to 1 if you have the `readlink' function. */
-#define HAVE_READLINK 1
-
-/* Define to 1 if you have the `readlinkat' function. */
-#define HAVE_READLINKAT 1
-
-/* Define to 1 if you have the `readv' function. */
-#define HAVE_READV 1
-
-/* Define to 1 if you have the `realpath' function. */
-#define HAVE_REALPATH 1
-
-/* Define to 1 if you have the `renameat' function. */
-#define HAVE_RENAMEAT 1
-
-/* Define if readline supports append_history */
-/* #undef HAVE_RL_APPEND_HISTORY */
-
-/* Define if you can turn off readline's signal handling. */
-/* #undef HAVE_RL_CATCH_SIGNAL */
-
-/* Define if you have readline 2.2 */
-/* #undef HAVE_RL_COMPLETION_APPEND_CHARACTER */
-
-/* Define if you have readline 4.0 */
-/* #undef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK */
-
-/* Define if you have readline 4.2 */
-/* #undef HAVE_RL_COMPLETION_MATCHES */
-
-/* Define if you have rl_completion_suppress_append */
-/* #undef HAVE_RL_COMPLETION_SUPPRESS_APPEND */
-
-/* Define if you have readline 4.0 */
-/* #undef HAVE_RL_PRE_INPUT_HOOK */
-
-/* Define if you have readline 4.0 */
-/* #undef HAVE_RL_RESIZE_TERMINAL */
-
-/* Define to 1 if you have the `round' function. */
-#define HAVE_ROUND 1
-
-/* Define to 1 if you have the `rtpSpawn' function. */
-/* #undef HAVE_RTPSPAWN */
-
-/* Define to 1 if you have the `sched_get_priority_max' function. */
-#define HAVE_SCHED_GET_PRIORITY_MAX 1
-
-/* Define to 1 if you have the <sched.h> header file. */
-#define HAVE_SCHED_H 1
-
-/* Define to 1 if you have the `sched_rr_get_interval' function. */
-#define HAVE_SCHED_RR_GET_INTERVAL 1
-
-/* Define to 1 if you have the `sched_setaffinity' function. */
-#define HAVE_SCHED_SETAFFINITY 1
-
-/* Define to 1 if you have the `sched_setparam' function. */
-#define HAVE_SCHED_SETPARAM 1
-
-/* Define to 1 if you have the `sched_setscheduler' function. */
-#define HAVE_SCHED_SETSCHEDULER 1
-
-/* Define to 1 if you have the `sem_clockwait' function. */
-/* #undef HAVE_SEM_CLOCKWAIT */
-
-/* Define to 1 if you have the `sem_getvalue' function. */
-#define HAVE_SEM_GETVALUE 1
-
-/* Define to 1 if you have the `sem_open' function. */
-#define HAVE_SEM_OPEN 1
-
-/* Define to 1 if you have the `sem_timedwait' function. */
-#define HAVE_SEM_TIMEDWAIT 1
-
-/* Define to 1 if you have the `sem_unlink' function. */
-#define HAVE_SEM_UNLINK 1
-
-/* Define to 1 if you have the `sendfile' function. */
-#define HAVE_SENDFILE 1
-
-/* Define to 1 if you have the `setegid' function. */
-#define HAVE_SETEGID 1
-
-/* Define to 1 if you have the `seteuid' function. */
-#define HAVE_SETEUID 1
-
-/* Define to 1 if you have the `setgid' function. */
-#define HAVE_SETGID 1
-
-/* Define if you have the 'setgroups' function. */
-#define HAVE_SETGROUPS 1
-
-/* Define to 1 if you have the `sethostname' function. */
-#define HAVE_SETHOSTNAME 1
-
-/* Define to 1 if you have the `setitimer' function. */
-#define HAVE_SETITIMER 1
-
-/* Define to 1 if you have the `setlocale' function. */
-#define HAVE_SETLOCALE 1
-
-/* Define to 1 if you have the `setpgid' function. */
-#define HAVE_SETPGID 1
-
-/* Define to 1 if you have the `setpgrp' function. */
-#define HAVE_SETPGRP 1
-
-/* Define to 1 if you have the `setpriority' function. */
-#define HAVE_SETPRIORITY 1
-
-/* Define to 1 if you have the `setregid' function. */
-#define HAVE_SETREGID 1
-
-/* Define to 1 if you have the `setresgid' function. */
-#define HAVE_SETRESGID 1
-
-/* Define to 1 if you have the `setresuid' function. */
-#define HAVE_SETRESUID 1
-
-/* Define to 1 if you have the `setreuid' function. */
-#define HAVE_SETREUID 1
-
-/* Define to 1 if you have the `setsid' function. */
-#define HAVE_SETSID 1
-
-/* Define to 1 if you have the `setuid' function. */
-#define HAVE_SETUID 1
-
-/* Define to 1 if you have the `setvbuf' function. */
-#define HAVE_SETVBUF 1
-
-/* Define to 1 if you have the <shadow.h> header file. */
-#define HAVE_SHADOW_H 1
-
-/* Define to 1 if you have the `shm_open' function. */
-#define HAVE_SHM_OPEN 1
-
-/* Define to 1 if you have the `shm_unlink' function. */
-#define HAVE_SHM_UNLINK 1
-
-/* Define to 1 if you have the `sigaction' function. */
-#define HAVE_SIGACTION 1
-
-/* Define to 1 if you have the `sigaltstack' function. */
-#define HAVE_SIGALTSTACK 1
-
-/* Define to 1 if you have the `sigfillset' function. */
-#define HAVE_SIGFILLSET 1
-
-/* Define to 1 if `si_band' is a member of `siginfo_t'. */
-#define HAVE_SIGINFO_T_SI_BAND 1
-
-/* Define to 1 if you have the `siginterrupt' function. */
-#define HAVE_SIGINTERRUPT 1
-
-/* Define to 1 if you have the <signal.h> header file. */
-#define HAVE_SIGNAL_H 1
-
-/* Define to 1 if you have the `sigpending' function. */
-#define HAVE_SIGPENDING 1
-
-/* Define to 1 if you have the `sigrelse' function. */
-#define HAVE_SIGRELSE 1
-
-/* Define to 1 if you have the `sigtimedwait' function. */
-#define HAVE_SIGTIMEDWAIT 1
-
-/* Define to 1 if you have the `sigwait' function. */
-#define HAVE_SIGWAIT 1
-
-/* Define to 1 if you have the `sigwaitinfo' function. */
-#define HAVE_SIGWAITINFO 1
-
-/* Define to 1 if you have the `snprintf' function. */
-#define HAVE_SNPRINTF 1
-
-/* struct sockaddr_alg (linux/if_alg.h) */
-#define HAVE_SOCKADDR_ALG 1
-
-/* Define if sockaddr has sa_len member */
-/* #undef HAVE_SOCKADDR_SA_LEN */
-
-/* struct sockaddr_storage (sys/socket.h) */
-#define HAVE_SOCKADDR_STORAGE 1
-
-/* Define if you have the 'socketpair' function. */
-#define HAVE_SOCKETPAIR 1
-
-/* Define to 1 if you have the <spawn.h> header file. */
-#define HAVE_SPAWN_H 1
-
-/* Define to 1 if you have the `splice' function. */
-#define HAVE_SPLICE 1
-
-/* Define if your compiler provides ssize_t */
-#define HAVE_SSIZE_T 1
-
-/* Define to 1 if you have the `statvfs' function. */
-#define HAVE_STATVFS 1
-
-/* Define if you have struct stat.st_mtim.tv_nsec */
-#define HAVE_STAT_TV_NSEC 1
-
-/* Define if you have struct stat.st_mtimensec */
-/* #undef HAVE_STAT_TV_NSEC2 */
-
-/* Define if your compiler supports variable length function prototypes (e.g.
- void fprintf(FILE *, char *, ...);) *and* <stdarg.h> */
-#define HAVE_STDARG_PROTOTYPES 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Has stdatomic.h with atomic_int and atomic_uintptr_t */
-/* #undef HAVE_STD_ATOMIC */
-
-/* Define to 1 if you have the `strftime' function. */
-#define HAVE_STRFTIME 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the `strlcpy' function. */
-/* #undef HAVE_STRLCPY */
-
-/* Define to 1 if you have the <stropts.h> header file. */
-/* #undef HAVE_STROPTS_H */
-
-/* Define to 1 if you have the `strsignal' function. */
-#define HAVE_STRSIGNAL 1
-
-/* Define to 1 if `pw_gecos' is a member of `struct passwd'. */
-#define HAVE_STRUCT_PASSWD_PW_GECOS 1
-
-/* Define to 1 if `pw_passwd' is a member of `struct passwd'. */
-#define HAVE_STRUCT_PASSWD_PW_PASSWD 1
-
-/* Define to 1 if `st_birthtime' is a member of `struct stat'. */
-/* #undef HAVE_STRUCT_STAT_ST_BIRTHTIME */
-
-/* Define to 1 if `st_blksize' is a member of `struct stat'. */
-#define HAVE_STRUCT_STAT_ST_BLKSIZE 1
-
-/* Define to 1 if `st_blocks' is a member of `struct stat'. */
-#define HAVE_STRUCT_STAT_ST_BLOCKS 1
-
-/* Define to 1 if `st_flags' is a member of `struct stat'. */
-/* #undef HAVE_STRUCT_STAT_ST_FLAGS */
-
-/* Define to 1 if `st_gen' is a member of `struct stat'. */
-/* #undef HAVE_STRUCT_STAT_ST_GEN */
-
-/* Define to 1 if `st_rdev' is a member of `struct stat'. */
-#define HAVE_STRUCT_STAT_ST_RDEV 1
-
-/* Define to 1 if `tm_zone' is a member of `struct tm'. */
-#define HAVE_STRUCT_TM_TM_ZONE 1
-
-/* Define if you have the 'symlink' function. */
-#define HAVE_SYMLINK 1
-
-/* Define to 1 if you have the `symlinkat' function. */
-#define HAVE_SYMLINKAT 1
-
-/* Define to 1 if you have the `sync' function. */
-#define HAVE_SYNC 1
-
-/* Define to 1 if you have the `sysconf' function. */
-#define HAVE_SYSCONF 1
-
-/* Define to 1 if you have the <sysexits.h> header file. */
-#define HAVE_SYSEXITS_H 1
-
-/* Define to 1 if you have the <sys/audioio.h> header file. */
-/* #undef HAVE_SYS_AUDIOIO_H */
-
-/* Define to 1 if you have the <sys/bsdtty.h> header file. */
-/* #undef HAVE_SYS_BSDTTY_H */
-
-/* Define to 1 if you have the <sys/devpoll.h> header file. */
-/* #undef HAVE_SYS_DEVPOLL_H */
-
-/* Define to 1 if you have the <sys/dir.h> header file, and it defines `DIR'.
- */
-/* #undef HAVE_SYS_DIR_H */
-
-/* Define to 1 if you have the <sys/endian.h> header file. */
-/* #undef HAVE_SYS_ENDIAN_H */
-
-/* Define to 1 if you have the <sys/epoll.h> header file. */
-#define HAVE_SYS_EPOLL_H 1
-
-/* Define to 1 if you have the <sys/eventfd.h> header file. */
-#define HAVE_SYS_EVENTFD_H 1
-
-/* Define to 1 if you have the <sys/event.h> header file. */
-/* #undef HAVE_SYS_EVENT_H */
-
-/* Define to 1 if you have the <sys/file.h> header file. */
-#define HAVE_SYS_FILE_H 1
-
-/* Define to 1 if you have the <sys/ioctl.h> header file. */
-#define HAVE_SYS_IOCTL_H 1
-
-/* Define to 1 if you have the <sys/kern_control.h> header file. */
-/* #undef HAVE_SYS_KERN_CONTROL_H */
-
-/* Define to 1 if you have the <sys/loadavg.h> header file. */
-/* #undef HAVE_SYS_LOADAVG_H */
-
-/* Define to 1 if you have the <sys/lock.h> header file. */
-/* #undef HAVE_SYS_LOCK_H */
-
-/* Define to 1 if you have the <sys/memfd.h> header file. */
-/* #undef HAVE_SYS_MEMFD_H */
-
-/* Define to 1 if you have the <sys/mkdev.h> header file. */
-/* #undef HAVE_SYS_MKDEV_H */
-
-/* Define to 1 if you have the <sys/mman.h> header file. */
-#define HAVE_SYS_MMAN_H 1
-
-/* Define to 1 if you have the <sys/modem.h> header file. */
-/* #undef HAVE_SYS_MODEM_H */
-
-/* Define to 1 if you have the <sys/ndir.h> header file, and it defines `DIR'.
- */
-/* #undef HAVE_SYS_NDIR_H */
-
-/* Define to 1 if you have the <sys/param.h> header file. */
-#define HAVE_SYS_PARAM_H 1
-
-/* Define to 1 if you have the <sys/poll.h> header file. */
-#define HAVE_SYS_POLL_H 1
-
-/* Define to 1 if you have the <sys/random.h> header file. */
-/* #undef HAVE_SYS_RANDOM_H */
-
-/* Define to 1 if you have the <sys/resource.h> header file. */
-#define HAVE_SYS_RESOURCE_H 1
-
-/* Define to 1 if you have the <sys/select.h> header file. */
-#define HAVE_SYS_SELECT_H 1
-
-/* Define to 1 if you have the <sys/sendfile.h> header file. */
-#define HAVE_SYS_SENDFILE_H 1
-
-/* Define to 1 if you have the <sys/socket.h> header file. */
-#define HAVE_SYS_SOCKET_H 1
-
-/* Define to 1 if you have the <sys/statvfs.h> header file. */
-#define HAVE_SYS_STATVFS_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/syscall.h> header file. */
-#define HAVE_SYS_SYSCALL_H 1
-
-/* Define to 1 if you have the <sys/sysmacros.h> header file. */
-#define HAVE_SYS_SYSMACROS_H 1
-
-/* Define to 1 if you have the <sys/sys_domain.h> header file. */
-/* #undef HAVE_SYS_SYS_DOMAIN_H */
-
-/* Define to 1 if you have the <sys/termio.h> header file. */
-/* #undef HAVE_SYS_TERMIO_H */
-
-/* Define to 1 if you have the <sys/times.h> header file. */
-#define HAVE_SYS_TIMES_H 1
-
-/* Define to 1 if you have the <sys/time.h> header file. */
-#define HAVE_SYS_TIME_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the <sys/uio.h> header file. */
-#define HAVE_SYS_UIO_H 1
-
-/* Define to 1 if you have the <sys/un.h> header file. */
-#define HAVE_SYS_UN_H 1
-
-/* Define to 1 if you have the <sys/utsname.h> header file. */
-#define HAVE_SYS_UTSNAME_H 1
-
-/* Define to 1 if you have the <sys/wait.h> header file. */
-#define HAVE_SYS_WAIT_H 1
-
-/* Define to 1 if you have the <sys/xattr.h> header file. */
-#define HAVE_SYS_XATTR_H 1
-
-/* Define to 1 if you have the `tcgetpgrp' function. */
-#define HAVE_TCGETPGRP 1
-
-/* Define to 1 if you have the `tcsetpgrp' function. */
-#define HAVE_TCSETPGRP 1
-
-/* Define to 1 if you have the `tempnam' function. */
-#define HAVE_TEMPNAM 1
-
-/* Define to 1 if you have the <termios.h> header file. */
-#define HAVE_TERMIOS_H 1
-
-/* Define to 1 if you have the <term.h> header file. */
-#define HAVE_TERM_H 1
-
-/* Define to 1 if you have the `tgamma' function. */
-#define HAVE_TGAMMA 1
-
-/* Define to 1 if you have the `timegm' function. */
-#define HAVE_TIMEGM 1
-
-/* Define to 1 if you have the `times' function. */
-#define HAVE_TIMES 1
-
-/* Define to 1 if you have the `tmpfile' function. */
-#define HAVE_TMPFILE 1
-
-/* Define to 1 if you have the `tmpnam' function. */
-#define HAVE_TMPNAM 1
-
-/* Define to 1 if you have the `tmpnam_r' function. */
-#define HAVE_TMPNAM_R 1
-
-/* Define to 1 if your `struct tm' has `tm_zone'. Deprecated, use
- `HAVE_STRUCT_TM_TM_ZONE' instead. */
-#define HAVE_TM_ZONE 1
-
-/* Define to 1 if you have the `truncate' function. */
-#define HAVE_TRUNCATE 1
-
-/* Define to 1 if you don't have `tm_zone' but do have the external array
- `tzname'. */
-/* #undef HAVE_TZNAME */
-
-/* Define this if you have tcl and TCL_UTF_MAX==6 */
-/* #undef HAVE_UCS4_TCL */
-
-/* Define to 1 if you have the `uname' function. */
-#define HAVE_UNAME 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if you have the `unlinkat' function. */
-#define HAVE_UNLINKAT 1
-
-/* Define if you have a useable wchar_t type defined in wchar.h; useable means
- wchar_t must be an unsigned type with at least 16 bits. (see
- Include/unicodeobject.h). */
-/* #undef HAVE_USABLE_WCHAR_T */
-
-/* Define to 1 if you have the <util.h> header file. */
-/* #undef HAVE_UTIL_H */
-
-/* Define to 1 if you have the `utimensat' function. */
-#define HAVE_UTIMENSAT 1
-
-/* Define to 1 if you have the `utimes' function. */
-#define HAVE_UTIMES 1
-
-/* Define to 1 if you have the <utime.h> header file. */
-#define HAVE_UTIME_H 1
-
-/* Define if uuid_create() exists. */
-/* #undef HAVE_UUID_CREATE */
-
-/* Define if uuid_enc_be() exists. */
-/* #undef HAVE_UUID_ENC_BE */
-
-/* Define if uuid_generate_time_safe() exists. */
-/* #undef HAVE_UUID_GENERATE_TIME_SAFE */
-
-/* Define to 1 if you have the <uuid.h> header file. */
-/* #undef HAVE_UUID_H */
-
-/* Define to 1 if you have the <uuid/uuid.h> header file. */
-/* #undef HAVE_UUID_UUID_H */
-
-/* Define to 1 if you have the `vfork' function. */
-#define HAVE_VFORK 1
-
-/* Define to 1 if you have the `wait3' function. */
-#define HAVE_WAIT3 1
-
-/* Define to 1 if you have the `wait4' function. */
-#define HAVE_WAIT4 1
-
-/* Define to 1 if you have the `waitid' function. */
-#define HAVE_WAITID 1
-
-/* Define to 1 if you have the `waitpid' function. */
-#define HAVE_WAITPID 1
-
-/* Define if the compiler provides a wchar.h header file. */
-#define HAVE_WCHAR_H 1
-
-/* Define to 1 if you have the `wcscoll' function. */
-#define HAVE_WCSCOLL 1
-
-/* Define to 1 if you have the `wcsftime' function. */
-#define HAVE_WCSFTIME 1
-
-/* Define to 1 if you have the `wcsxfrm' function. */
-#define HAVE_WCSXFRM 1
-
-/* Define to 1 if you have the `wmemcmp' function. */
-#define HAVE_WMEMCMP 1
-
-/* Define if tzset() actually switches the local timezone in a meaningful way.
- */
-#define HAVE_WORKING_TZSET 1
-
-/* Define to 1 if you have the `writev' function. */
-#define HAVE_WRITEV 1
-
-/* Define if the zlib library has inflateCopy */
-#define HAVE_ZLIB_COPY 1
-
-/* Define to 1 if you have the `_getpty' function. */
-/* #undef HAVE__GETPTY */
-
-/* Define to 1 if `major', `minor', and `makedev' are declared in <mkdev.h>.
- */
-/* #undef MAJOR_IN_MKDEV */
-
-/* Define to 1 if `major', `minor', and `makedev' are declared in
- <sysmacros.h>. */
-/* #undef MAJOR_IN_SYSMACROS */
-
-/* Define if mvwdelch in curses.h is an expression. */
-#define MVWDELCH_IS_EXPRESSION 1
-
-/* Define to the address where bug reports for this package should be sent. */
-/* #undef PACKAGE_BUGREPORT */
-
-/* Define to the full name of this package. */
-/* #undef PACKAGE_NAME */
-
-/* Define to the full name and version of this package. */
-/* #undef PACKAGE_STRING */
-
-/* Define to the one symbol short name of this package. */
-/* #undef PACKAGE_TARNAME */
-
-/* Define to the home page for this package. */
-/* #undef PACKAGE_URL */
-
-/* Define to the version of this package. */
-/* #undef PACKAGE_VERSION */
-
-/* Define if POSIX semaphores aren't enabled on your system */
-/* #undef POSIX_SEMAPHORES_NOT_ENABLED */
-
-/* Define if pthread_key_t is compatible with int. */
-#define PTHREAD_KEY_T_IS_COMPATIBLE_WITH_INT 1
-
-/* Defined if PTHREAD_SCOPE_SYSTEM supported. */
-#define PTHREAD_SYSTEM_SCHED_SUPPORTED 1
-
-/* Define as the preferred size in bits of long digits */
-/* #undef PYLONG_BITS_IN_DIGIT */
-
-/* enabled builtin hash modules */
-#define PY_BUILTIN_HASHLIB_HASHES "md5,sha1,sha256,sha512,sha3,blake2"
-
-/* Define if you want to coerce the C locale to a UTF-8 based locale */
-#define PY_COERCE_C_LOCALE 1
-
-/* Define to printf format modifier for Py_ssize_t */
-#define PY_FORMAT_SIZE_T "z"
-
-/* Default cipher suites list for ssl module. 1: Python's preferred selection,
- 2: leave OpenSSL defaults untouched, 0: custom string */
-#define PY_SSL_DEFAULT_CIPHERS 1
-
-/* Cipher suite string for PY_SSL_DEFAULT_CIPHERS=0 */
-/* #undef PY_SSL_DEFAULT_CIPHER_STRING */
-
-/* Define if you want to build an interpreter with many run-time checks. */
-/* #undef Py_DEBUG */
-
-/* Defined if Python is built as a shared library. */
-#define Py_ENABLE_SHARED 1
-
-/* Define hash algorithm for str, bytes and memoryview. SipHash24: 1, FNV: 2,
- externally defined: 0 */
-/* #undef Py_HASH_ALGORITHM */
-
-/* Define if you want to enable tracing references for debugging purpose */
-/* #undef Py_TRACE_REFS */
-
-/* assume C89 semantics that RETSIGTYPE is always void */
-#define RETSIGTYPE void
-
-/* Define if setpgrp() must be called as setpgrp(0, 0). */
-/* #undef SETPGRP_HAVE_ARG */
-
-/* Define to 1 if you must link with -lrt for shm_open(). */
-#define SHM_NEEDS_LIBRT 1
-
-/* Define if i>>j for signed int i does not extend the sign bit when i < 0 */
-/* #undef SIGNED_RIGHT_SHIFT_ZERO_FILLS */
-
-/* The size of `double', as computed by sizeof. */
-#define SIZEOF_DOUBLE 8
-
-/* The size of `float', as computed by sizeof. */
-#define SIZEOF_FLOAT 4
-
-/* The size of `fpos_t', as computed by sizeof. */
-#define SIZEOF_FPOS_T 16
-
-/* The size of `int', as computed by sizeof. */
-#define SIZEOF_INT 4
-
-/* The size of `long', as computed by sizeof. */
-#define SIZEOF_LONG 8
-
-/* The size of `long double', as computed by sizeof. */
-#define SIZEOF_LONG_DOUBLE 16
-
-/* The size of `long long', as computed by sizeof. */
-#define SIZEOF_LONG_LONG 8
-
-/* The size of `off_t', as computed by sizeof. */
-#define SIZEOF_OFF_T 8
-
-/* The size of `pid_t', as computed by sizeof. */
-#define SIZEOF_PID_T 4
-
-/* The size of `pthread_key_t', as computed by sizeof. */
-#define SIZEOF_PTHREAD_KEY_T 4
-
-/* The size of `pthread_t', as computed by sizeof. */
-#define SIZEOF_PTHREAD_T 8
-
-/* The size of `short', as computed by sizeof. */
-#define SIZEOF_SHORT 2
-
-/* The size of `size_t', as computed by sizeof. */
-#define SIZEOF_SIZE_T 8
-
-/* The size of `time_t', as computed by sizeof. */
-#define SIZEOF_TIME_T 8
-
-/* The size of `uintptr_t', as computed by sizeof. */
-#define SIZEOF_UINTPTR_T 8
-
-/* The size of `void *', as computed by sizeof. */
-#define SIZEOF_VOID_P 8
-
-/* The size of `wchar_t', as computed by sizeof. */
-#define SIZEOF_WCHAR_T 4
-
-/* The size of `_Bool', as computed by sizeof. */
-#define SIZEOF__BOOL 1
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define if you can safely include both <sys/select.h> and <sys/time.h>
- (which you can't on SCO ODT 3.0). */
-#define SYS_SELECT_WITH_SYS_TIME 1
-
-/* Custom thread stack size depending on chosen sanitizer runtimes. */
-/* #undef THREAD_STACK_SIZE */
-
-/* Library needed by timemodule.c: librt may be needed for clock_gettime() */
-/* #undef TIMEMODULE_LIB */
-
-/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
-#define TIME_WITH_SYS_TIME 1
-
-/* Define to 1 if your <sys/time.h> declares `struct tm'. */
-/* #undef TM_IN_SYS_TIME */
-
-/* Define if you want to use computed gotos in ceval.c. */
-/* #undef USE_COMPUTED_GOTOS */
-
-/* Enable extensions on AIX 3, Interix. */
-#ifndef _ALL_SOURCE
-# define _ALL_SOURCE 1
-#endif
-/* Enable GNU extensions on systems that have them. */
-#ifndef _GNU_SOURCE
-# define _GNU_SOURCE 1
-#endif
-/* Enable threading extensions on Solaris. */
-#ifndef _POSIX_PTHREAD_SEMANTICS
-# define _POSIX_PTHREAD_SEMANTICS 1
-#endif
-/* Enable extensions on HP NonStop. */
-#ifndef _TANDEM_SOURCE
-# define _TANDEM_SOURCE 1
-#endif
-/* Enable general extensions on Solaris. */
-#ifndef __EXTENSIONS__
-# define __EXTENSIONS__ 1
-#endif
-
-
-/* Define if WINDOW in curses.h offers a field _flags. */
-#define WINDOW_HAS_FLAGS 1
-
-/* Define if you want build the _decimal module using a coroutine-local rather
- than a thread-local context */
-#define WITH_DECIMAL_CONTEXTVAR 1
-
-/* Define if you want documentation strings in extension modules */
-#define WITH_DOC_STRINGS 1
-
-/* Define if you want to compile in DTrace support */
-/* #undef WITH_DTRACE */
-
-/* Define if you want to use the new-style (Openstep, Rhapsody, MacOS) dynamic
- linker (dyld) instead of the old-style (NextStep) dynamic linker (rld).
- Dyld is necessary to support frameworks. */
-/* #undef WITH_DYLD */
-
-/* Define to build the readline module against Editline. */
-/* #undef WITH_EDITLINE */
-
-/* Define to 1 if libintl is needed for locale functions. */
-/* #undef WITH_LIBINTL */
-
-/* Define if you want to produce an OpenStep/Rhapsody framework (shared
- library plus accessory files). */
-/* #undef WITH_NEXT_FRAMEWORK */
-
-/* Define if you want to compile in Python-specific mallocs */
-#define WITH_PYMALLOC 1
-
-/* Define if you want pymalloc to be disabled when running under valgrind */
-/* #undef WITH_VALGRIND */
-
-/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
- significant byte first (like Motorola and SPARC, unlike Intel). */
-#if defined AC_APPLE_UNIVERSAL_BUILD
-# if defined __BIG_ENDIAN__
-# define WORDS_BIGENDIAN 1
-# endif
-#else
-# ifndef WORDS_BIGENDIAN
-/* # undef WORDS_BIGENDIAN */
-# endif
-#endif
-
-/* Define if arithmetic is subject to x87-style double rounding issue */
-/* #undef X87_DOUBLE_ROUNDING */
-
-/* Define on OpenBSD to activate all library features */
-/* #undef _BSD_SOURCE */
-
-/* Define on Darwin to activate all library features */
-#define _DARWIN_C_SOURCE 1
-
-/* This must be set to 64 on some systems to enable large file support. */
-#define _FILE_OFFSET_BITS 64
-
-/* Define on Linux to activate all library features */
-#define _GNU_SOURCE 1
-
-/* Define to include mbstate_t for mbrtowc */
-/* #undef _INCLUDE__STDC_A1_SOURCE */
-
-/* This must be defined on some systems to enable large file support. */
-#define _LARGEFILE_SOURCE 1
-
-/* This must be defined on AIX systems to enable large file support. */
-/* #undef _LARGE_FILES */
-
-/* Define to 1 if on MINIX. */
-/* #undef _MINIX */
-
-/* Define on NetBSD to activate all library features */
-#define _NETBSD_SOURCE 1
-
-/* Define to 2 if the system does not provide POSIX.1 features except with
- this defined. */
-/* #undef _POSIX_1_SOURCE */
-
-/* Define to activate features from IEEE Stds 1003.1-2008 */
-#define _POSIX_C_SOURCE 200809L
-
-/* Define to 1 if you need to in order for `stat' and other things to work. */
-/* #undef _POSIX_SOURCE */
-
-/* Define if you have POSIX threads, and your system does not define that. */
-/* #undef _POSIX_THREADS */
-
-/* framework name */
-#define _PYTHONFRAMEWORK ""
-
-/* Define to force use of thread-safe errno, h_errno, and other functions */
-/* #undef _REENTRANT */
-
-/* Define to the level of X/Open that your system supports */
-#define _XOPEN_SOURCE 700
-
-/* Define to activate Unix95-and-earlier features */
-#define _XOPEN_SOURCE_EXTENDED 1
-
-/* Define on FreeBSD to activate all library features */
-#define __BSD_VISIBLE 1
-
-/* Define to 'long' if <time.h> doesn't define. */
-/* #undef clock_t */
-
-/* Define to empty if `const' does not conform to ANSI C. */
-/* #undef const */
-
-/* Define to `int' if <sys/types.h> doesn't define. */
-/* #undef gid_t */
-
-/* Define to `int' if <sys/types.h> does not define. */
-/* #undef mode_t */
-
-/* Define to `long int' if <sys/types.h> does not define. */
-/* #undef off_t */
-
-/* Define to `int' if <sys/types.h> does not define. */
-/* #undef pid_t */
-
-/* Define to empty if the keyword does not work. */
-/* #undef signed */
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-/* Define to `int' if <sys/socket.h> does not define. */
-/* #undef socklen_t */
-
-/* Define to `int' if <sys/types.h> doesn't define. */
-/* #undef uid_t */
-
-
-/* Define the macros needed if on a UnixWare 7.x system. */
-#if defined(__USLC__) && defined(__SCO_VERSION__)
-#define STRICT_SYSV_CURSES /* Don't use ncurses extensions */
-#endif
-
-#endif /*Py_PYCONFIG_H*/
-
diff --git a/include/python3.10/pyerrors.h b/include/python3.10/pyerrors.h
deleted file mode 100644
index f5d1c71..0000000
--- a/include/python3.10/pyerrors.h
+++ /dev/null
@@ -1,324 +0,0 @@
-#ifndef Py_ERRORS_H
-#define Py_ERRORS_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <stdarg.h> // va_list
-
-/* Error handling definitions */
-
-PyAPI_FUNC(void) PyErr_SetNone(PyObject *);
-PyAPI_FUNC(void) PyErr_SetObject(PyObject *, PyObject *);
-PyAPI_FUNC(void) PyErr_SetString(
- PyObject *exception,
- const char *string /* decoded from utf-8 */
- );
-PyAPI_FUNC(PyObject *) PyErr_Occurred(void);
-PyAPI_FUNC(void) PyErr_Clear(void);
-PyAPI_FUNC(void) PyErr_Fetch(PyObject **, PyObject **, PyObject **);
-PyAPI_FUNC(void) PyErr_Restore(PyObject *, PyObject *, PyObject *);
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-PyAPI_FUNC(void) PyErr_GetExcInfo(PyObject **, PyObject **, PyObject **);
-PyAPI_FUNC(void) PyErr_SetExcInfo(PyObject *, PyObject *, PyObject *);
-#endif
-
-/* Defined in Python/pylifecycle.c
-
- The Py_FatalError() function is replaced with a macro which logs
- automatically the name of the current function, unless the Py_LIMITED_API
- macro is defined. */
-PyAPI_FUNC(void) _Py_NO_RETURN Py_FatalError(const char *message);
-
-/* Error testing and normalization */
-PyAPI_FUNC(int) PyErr_GivenExceptionMatches(PyObject *, PyObject *);
-PyAPI_FUNC(int) PyErr_ExceptionMatches(PyObject *);
-PyAPI_FUNC(void) PyErr_NormalizeException(PyObject**, PyObject**, PyObject**);
-
-/* Traceback manipulation (PEP 3134) */
-PyAPI_FUNC(int) PyException_SetTraceback(PyObject *, PyObject *);
-PyAPI_FUNC(PyObject *) PyException_GetTraceback(PyObject *);
-
-/* Cause manipulation (PEP 3134) */
-PyAPI_FUNC(PyObject *) PyException_GetCause(PyObject *);
-PyAPI_FUNC(void) PyException_SetCause(PyObject *, PyObject *);
-
-/* Context manipulation (PEP 3134) */
-PyAPI_FUNC(PyObject *) PyException_GetContext(PyObject *);
-PyAPI_FUNC(void) PyException_SetContext(PyObject *, PyObject *);
-
-/* */
-
-#define PyExceptionClass_Check(x) \
- (PyType_Check((x)) && \
- PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS))
-
-#define PyExceptionInstance_Check(x) \
- PyType_FastSubclass(Py_TYPE(x), Py_TPFLAGS_BASE_EXC_SUBCLASS)
-
-PyAPI_FUNC(const char *) PyExceptionClass_Name(PyObject *);
-
-#define PyExceptionInstance_Class(x) ((PyObject*)Py_TYPE(x))
-
-
-/* Predefined exceptions */
-
-PyAPI_DATA(PyObject *) PyExc_BaseException;
-PyAPI_DATA(PyObject *) PyExc_Exception;
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
-PyAPI_DATA(PyObject *) PyExc_StopAsyncIteration;
-#endif
-PyAPI_DATA(PyObject *) PyExc_StopIteration;
-PyAPI_DATA(PyObject *) PyExc_GeneratorExit;
-PyAPI_DATA(PyObject *) PyExc_ArithmeticError;
-PyAPI_DATA(PyObject *) PyExc_LookupError;
-
-PyAPI_DATA(PyObject *) PyExc_AssertionError;
-PyAPI_DATA(PyObject *) PyExc_AttributeError;
-PyAPI_DATA(PyObject *) PyExc_BufferError;
-PyAPI_DATA(PyObject *) PyExc_EOFError;
-PyAPI_DATA(PyObject *) PyExc_FloatingPointError;
-PyAPI_DATA(PyObject *) PyExc_OSError;
-PyAPI_DATA(PyObject *) PyExc_ImportError;
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000
-PyAPI_DATA(PyObject *) PyExc_ModuleNotFoundError;
-#endif
-PyAPI_DATA(PyObject *) PyExc_IndexError;
-PyAPI_DATA(PyObject *) PyExc_KeyError;
-PyAPI_DATA(PyObject *) PyExc_KeyboardInterrupt;
-PyAPI_DATA(PyObject *) PyExc_MemoryError;
-PyAPI_DATA(PyObject *) PyExc_NameError;
-PyAPI_DATA(PyObject *) PyExc_OverflowError;
-PyAPI_DATA(PyObject *) PyExc_RuntimeError;
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
-PyAPI_DATA(PyObject *) PyExc_RecursionError;
-#endif
-PyAPI_DATA(PyObject *) PyExc_NotImplementedError;
-PyAPI_DATA(PyObject *) PyExc_SyntaxError;
-PyAPI_DATA(PyObject *) PyExc_IndentationError;
-PyAPI_DATA(PyObject *) PyExc_TabError;
-PyAPI_DATA(PyObject *) PyExc_ReferenceError;
-PyAPI_DATA(PyObject *) PyExc_SystemError;
-PyAPI_DATA(PyObject *) PyExc_SystemExit;
-PyAPI_DATA(PyObject *) PyExc_TypeError;
-PyAPI_DATA(PyObject *) PyExc_UnboundLocalError;
-PyAPI_DATA(PyObject *) PyExc_UnicodeError;
-PyAPI_DATA(PyObject *) PyExc_UnicodeEncodeError;
-PyAPI_DATA(PyObject *) PyExc_UnicodeDecodeError;
-PyAPI_DATA(PyObject *) PyExc_UnicodeTranslateError;
-PyAPI_DATA(PyObject *) PyExc_ValueError;
-PyAPI_DATA(PyObject *) PyExc_ZeroDivisionError;
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-PyAPI_DATA(PyObject *) PyExc_BlockingIOError;
-PyAPI_DATA(PyObject *) PyExc_BrokenPipeError;
-PyAPI_DATA(PyObject *) PyExc_ChildProcessError;
-PyAPI_DATA(PyObject *) PyExc_ConnectionError;
-PyAPI_DATA(PyObject *) PyExc_ConnectionAbortedError;
-PyAPI_DATA(PyObject *) PyExc_ConnectionRefusedError;
-PyAPI_DATA(PyObject *) PyExc_ConnectionResetError;
-PyAPI_DATA(PyObject *) PyExc_FileExistsError;
-PyAPI_DATA(PyObject *) PyExc_FileNotFoundError;
-PyAPI_DATA(PyObject *) PyExc_InterruptedError;
-PyAPI_DATA(PyObject *) PyExc_IsADirectoryError;
-PyAPI_DATA(PyObject *) PyExc_NotADirectoryError;
-PyAPI_DATA(PyObject *) PyExc_PermissionError;
-PyAPI_DATA(PyObject *) PyExc_ProcessLookupError;
-PyAPI_DATA(PyObject *) PyExc_TimeoutError;
-#endif
-
-
-/* Compatibility aliases */
-PyAPI_DATA(PyObject *) PyExc_EnvironmentError;
-PyAPI_DATA(PyObject *) PyExc_IOError;
-#ifdef MS_WINDOWS
-PyAPI_DATA(PyObject *) PyExc_WindowsError;
-#endif
-
-/* Predefined warning categories */
-PyAPI_DATA(PyObject *) PyExc_Warning;
-PyAPI_DATA(PyObject *) PyExc_UserWarning;
-PyAPI_DATA(PyObject *) PyExc_DeprecationWarning;
-PyAPI_DATA(PyObject *) PyExc_PendingDeprecationWarning;
-PyAPI_DATA(PyObject *) PyExc_SyntaxWarning;
-PyAPI_DATA(PyObject *) PyExc_RuntimeWarning;
-PyAPI_DATA(PyObject *) PyExc_FutureWarning;
-PyAPI_DATA(PyObject *) PyExc_ImportWarning;
-PyAPI_DATA(PyObject *) PyExc_UnicodeWarning;
-PyAPI_DATA(PyObject *) PyExc_BytesWarning;
-PyAPI_DATA(PyObject *) PyExc_EncodingWarning;
-PyAPI_DATA(PyObject *) PyExc_ResourceWarning;
-
-
-/* Convenience functions */
-
-PyAPI_FUNC(int) PyErr_BadArgument(void);
-PyAPI_FUNC(PyObject *) PyErr_NoMemory(void);
-PyAPI_FUNC(PyObject *) PyErr_SetFromErrno(PyObject *);
-PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilenameObject(
- PyObject *, PyObject *);
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000
-PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilenameObjects(
- PyObject *, PyObject *, PyObject *);
-#endif
-PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilename(
- PyObject *exc,
- const char *filename /* decoded from the filesystem encoding */
- );
-
-PyAPI_FUNC(PyObject *) PyErr_Format(
- PyObject *exception,
- const char *format, /* ASCII-encoded string */
- ...
- );
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
-PyAPI_FUNC(PyObject *) PyErr_FormatV(
- PyObject *exception,
- const char *format,
- va_list vargs);
-#endif
-
-#ifdef MS_WINDOWS
-PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithFilename(
- int ierr,
- const char *filename /* decoded from the filesystem encoding */
- );
-PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErr(int);
-PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilenameObject(
- PyObject *,int, PyObject *);
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000
-PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilenameObjects(
- PyObject *,int, PyObject *, PyObject *);
-#endif
-PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilename(
- PyObject *exc,
- int ierr,
- const char *filename /* decoded from the filesystem encoding */
- );
-PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErr(PyObject *, int);
-#endif /* MS_WINDOWS */
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000
-PyAPI_FUNC(PyObject *) PyErr_SetImportErrorSubclass(PyObject *, PyObject *,
- PyObject *, PyObject *);
-#endif
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-PyAPI_FUNC(PyObject *) PyErr_SetImportError(PyObject *, PyObject *,
- PyObject *);
-#endif
-
-/* Export the old function so that the existing API remains available: */
-PyAPI_FUNC(void) PyErr_BadInternalCall(void);
-PyAPI_FUNC(void) _PyErr_BadInternalCall(const char *filename, int lineno);
-/* Mask the old API with a call to the new API for code compiled under
- Python 2.0: */
-#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
-
-/* Function to create a new exception */
-PyAPI_FUNC(PyObject *) PyErr_NewException(
- const char *name, PyObject *base, PyObject *dict);
-PyAPI_FUNC(PyObject *) PyErr_NewExceptionWithDoc(
- const char *name, const char *doc, PyObject *base, PyObject *dict);
-PyAPI_FUNC(void) PyErr_WriteUnraisable(PyObject *);
-
-
-/* In signalmodule.c */
-PyAPI_FUNC(int) PyErr_CheckSignals(void);
-PyAPI_FUNC(void) PyErr_SetInterrupt(void);
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000
-PyAPI_FUNC(int) PyErr_SetInterruptEx(int signum);
-#endif
-
-/* Support for adding program text to SyntaxErrors */
-PyAPI_FUNC(void) PyErr_SyntaxLocation(
- const char *filename, /* decoded from the filesystem encoding */
- int lineno);
-PyAPI_FUNC(void) PyErr_SyntaxLocationEx(
- const char *filename, /* decoded from the filesystem encoding */
- int lineno,
- int col_offset);
-PyAPI_FUNC(PyObject *) PyErr_ProgramText(
- const char *filename, /* decoded from the filesystem encoding */
- int lineno);
-
-/* The following functions are used to create and modify unicode
- exceptions from C */
-
-/* create a UnicodeDecodeError object */
-PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_Create(
- const char *encoding, /* UTF-8 encoded string */
- const char *object,
- Py_ssize_t length,
- Py_ssize_t start,
- Py_ssize_t end,
- const char *reason /* UTF-8 encoded string */
- );
-
-/* get the encoding attribute */
-PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_GetEncoding(PyObject *);
-PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_GetEncoding(PyObject *);
-
-/* get the object attribute */
-PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_GetObject(PyObject *);
-PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_GetObject(PyObject *);
-PyAPI_FUNC(PyObject *) PyUnicodeTranslateError_GetObject(PyObject *);
-
-/* get the value of the start attribute (the int * may not be NULL)
- return 0 on success, -1 on failure */
-PyAPI_FUNC(int) PyUnicodeEncodeError_GetStart(PyObject *, Py_ssize_t *);
-PyAPI_FUNC(int) PyUnicodeDecodeError_GetStart(PyObject *, Py_ssize_t *);
-PyAPI_FUNC(int) PyUnicodeTranslateError_GetStart(PyObject *, Py_ssize_t *);
-
-/* assign a new value to the start attribute
- return 0 on success, -1 on failure */
-PyAPI_FUNC(int) PyUnicodeEncodeError_SetStart(PyObject *, Py_ssize_t);
-PyAPI_FUNC(int) PyUnicodeDecodeError_SetStart(PyObject *, Py_ssize_t);
-PyAPI_FUNC(int) PyUnicodeTranslateError_SetStart(PyObject *, Py_ssize_t);
-
-/* get the value of the end attribute (the int *may not be NULL)
- return 0 on success, -1 on failure */
-PyAPI_FUNC(int) PyUnicodeEncodeError_GetEnd(PyObject *, Py_ssize_t *);
-PyAPI_FUNC(int) PyUnicodeDecodeError_GetEnd(PyObject *, Py_ssize_t *);
-PyAPI_FUNC(int) PyUnicodeTranslateError_GetEnd(PyObject *, Py_ssize_t *);
-
-/* assign a new value to the end attribute
- return 0 on success, -1 on failure */
-PyAPI_FUNC(int) PyUnicodeEncodeError_SetEnd(PyObject *, Py_ssize_t);
-PyAPI_FUNC(int) PyUnicodeDecodeError_SetEnd(PyObject *, Py_ssize_t);
-PyAPI_FUNC(int) PyUnicodeTranslateError_SetEnd(PyObject *, Py_ssize_t);
-
-/* get the value of the reason attribute */
-PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_GetReason(PyObject *);
-PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_GetReason(PyObject *);
-PyAPI_FUNC(PyObject *) PyUnicodeTranslateError_GetReason(PyObject *);
-
-/* assign a new value to the reason attribute
- return 0 on success, -1 on failure */
-PyAPI_FUNC(int) PyUnicodeEncodeError_SetReason(
- PyObject *exc,
- const char *reason /* UTF-8 encoded string */
- );
-PyAPI_FUNC(int) PyUnicodeDecodeError_SetReason(
- PyObject *exc,
- const char *reason /* UTF-8 encoded string */
- );
-PyAPI_FUNC(int) PyUnicodeTranslateError_SetReason(
- PyObject *exc,
- const char *reason /* UTF-8 encoded string */
- );
-
-PyAPI_FUNC(int) PyOS_snprintf(char *str, size_t size, const char *format, ...)
- Py_GCC_ATTRIBUTE((format(printf, 3, 4)));
-PyAPI_FUNC(int) PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va)
- Py_GCC_ATTRIBUTE((format(printf, 3, 0)));
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_ERRORS_H
-# include "cpython/pyerrors.h"
-# undef Py_CPYTHON_ERRORS_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_ERRORS_H */
diff --git a/include/python3.10/pyframe.h b/include/python3.10/pyframe.h
deleted file mode 100644
index 3816224..0000000
--- a/include/python3.10/pyframe.h
+++ /dev/null
@@ -1,22 +0,0 @@
-/* Limited C API of PyFrame API
- *
- * Include "frameobject.h" to get the PyFrameObject structure.
- */
-
-#ifndef Py_PYFRAME_H
-#define Py_PYFRAME_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef struct _frame PyFrameObject;
-
-/* Return the line of code the frame is currently executing. */
-PyAPI_FUNC(int) PyFrame_GetLineNumber(PyFrameObject *);
-
-PyAPI_FUNC(PyCodeObject *) PyFrame_GetCode(PyFrameObject *frame);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_PYFRAME_H */
diff --git a/include/python3.10/pyhash.h b/include/python3.10/pyhash.h
deleted file mode 100644
index a314ea9..0000000
--- a/include/python3.10/pyhash.h
+++ /dev/null
@@ -1,144 +0,0 @@
-#ifndef Py_HASH_H
-
-#define Py_HASH_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Helpers for hash functions */
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(Py_hash_t) _Py_HashDouble(PyObject *, double);
-PyAPI_FUNC(Py_hash_t) _Py_HashPointer(const void*);
-// Similar to _Py_HashPointer(), but don't replace -1 with -2
-PyAPI_FUNC(Py_hash_t) _Py_HashPointerRaw(const void*);
-PyAPI_FUNC(Py_hash_t) _Py_HashBytes(const void*, Py_ssize_t);
-#endif
-
-/* Prime multiplier used in string and various other hashes. */
-#define _PyHASH_MULTIPLIER 1000003UL /* 0xf4243 */
-
-/* Parameters used for the numeric hash implementation. See notes for
- _Py_HashDouble in Python/pyhash.c. Numeric hashes are based on
- reduction modulo the prime 2**_PyHASH_BITS - 1. */
-
-#if SIZEOF_VOID_P >= 8
-# define _PyHASH_BITS 61
-#else
-# define _PyHASH_BITS 31
-#endif
-
-#define _PyHASH_MODULUS (((size_t)1 << _PyHASH_BITS) - 1)
-#define _PyHASH_INF 314159
-#define _PyHASH_IMAG _PyHASH_MULTIPLIER
-
-
-/* hash secret
- *
- * memory layout on 64 bit systems
- * cccccccc cccccccc cccccccc uc -- unsigned char[24]
- * pppppppp ssssssss ........ fnv -- two Py_hash_t
- * k0k0k0k0 k1k1k1k1 ........ siphash -- two uint64_t
- * ........ ........ ssssssss djbx33a -- 16 bytes padding + one Py_hash_t
- * ........ ........ eeeeeeee pyexpat XML hash salt
- *
- * memory layout on 32 bit systems
- * cccccccc cccccccc cccccccc uc
- * ppppssss ........ ........ fnv -- two Py_hash_t
- * k0k0k0k0 k1k1k1k1 ........ siphash -- two uint64_t (*)
- * ........ ........ ssss.... djbx33a -- 16 bytes padding + one Py_hash_t
- * ........ ........ eeee.... pyexpat XML hash salt
- *
- * (*) The siphash member may not be available on 32 bit platforms without
- * an unsigned int64 data type.
- */
-#ifndef Py_LIMITED_API
-typedef union {
- /* ensure 24 bytes */
- unsigned char uc[24];
- /* two Py_hash_t for FNV */
- struct {
- Py_hash_t prefix;
- Py_hash_t suffix;
- } fnv;
- /* two uint64 for SipHash24 */
- struct {
- uint64_t k0;
- uint64_t k1;
- } siphash;
- /* a different (!) Py_hash_t for small string optimization */
- struct {
- unsigned char padding[16];
- Py_hash_t suffix;
- } djbx33a;
- struct {
- unsigned char padding[16];
- Py_hash_t hashsalt;
- } expat;
-} _Py_HashSecret_t;
-PyAPI_DATA(_Py_HashSecret_t) _Py_HashSecret;
-
-#ifdef Py_DEBUG
-PyAPI_DATA(int) _Py_HashSecret_Initialized;
-#endif
-
-
-/* hash function definition */
-typedef struct {
- Py_hash_t (*const hash)(const void *, Py_ssize_t);
- const char *name;
- const int hash_bits;
- const int seed_bits;
-} PyHash_FuncDef;
-
-PyAPI_FUNC(PyHash_FuncDef*) PyHash_GetFuncDef(void);
-#endif
-
-
-/* cutoff for small string DJBX33A optimization in range [1, cutoff).
- *
- * About 50% of the strings in a typical Python application are smaller than
- * 6 to 7 chars. However DJBX33A is vulnerable to hash collision attacks.
- * NEVER use DJBX33A for long strings!
- *
- * A Py_HASH_CUTOFF of 0 disables small string optimization. 32 bit platforms
- * should use a smaller cutoff because it is easier to create colliding
- * strings. A cutoff of 7 on 64bit platforms and 5 on 32bit platforms should
- * provide a decent safety margin.
- */
-#ifndef Py_HASH_CUTOFF
-# define Py_HASH_CUTOFF 0
-#elif (Py_HASH_CUTOFF > 7 || Py_HASH_CUTOFF < 0)
-# error Py_HASH_CUTOFF must in range 0...7.
-#endif /* Py_HASH_CUTOFF */
-
-
-/* hash algorithm selection
- *
- * The values for Py_HASH_SIPHASH24 and Py_HASH_FNV are hard-coded in the
- * configure script.
- *
- * - FNV is available on all platforms and architectures.
- * - SIPHASH24 only works on platforms that don't require aligned memory for integers.
- * - With EXTERNAL embedders can provide an alternative implementation with::
- *
- * PyHash_FuncDef PyHash_Func = {...};
- *
- * XXX: Figure out __declspec() for extern PyHash_FuncDef.
- */
-#define Py_HASH_EXTERNAL 0
-#define Py_HASH_SIPHASH24 1
-#define Py_HASH_FNV 2
-
-#ifndef Py_HASH_ALGORITHM
-# ifndef HAVE_ALIGNED_REQUIRED
-# define Py_HASH_ALGORITHM Py_HASH_SIPHASH24
-# else
-# define Py_HASH_ALGORITHM Py_HASH_FNV
-# endif /* uint64_t && uint32_t && aligned */
-#endif /* Py_HASH_ALGORITHM */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* !Py_HASH_H */
diff --git a/include/python3.10/pylifecycle.h b/include/python3.10/pylifecycle.h
deleted file mode 100644
index 2df7fe6..0000000
--- a/include/python3.10/pylifecycle.h
+++ /dev/null
@@ -1,74 +0,0 @@
-
-/* Interfaces to configure, query, create & destroy the Python runtime */
-
-#ifndef Py_PYLIFECYCLE_H
-#define Py_PYLIFECYCLE_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-/* Initialization and finalization */
-PyAPI_FUNC(void) Py_Initialize(void);
-PyAPI_FUNC(void) Py_InitializeEx(int);
-PyAPI_FUNC(void) Py_Finalize(void);
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000
-PyAPI_FUNC(int) Py_FinalizeEx(void);
-#endif
-PyAPI_FUNC(int) Py_IsInitialized(void);
-
-/* Subinterpreter support */
-PyAPI_FUNC(PyThreadState *) Py_NewInterpreter(void);
-PyAPI_FUNC(void) Py_EndInterpreter(PyThreadState *);
-
-
-/* Py_PyAtExit is for the atexit module, Py_AtExit is for low-level
- * exit functions.
- */
-PyAPI_FUNC(int) Py_AtExit(void (*func)(void));
-
-PyAPI_FUNC(void) _Py_NO_RETURN Py_Exit(int);
-
-/* Bootstrap __main__ (defined in Modules/main.c) */
-PyAPI_FUNC(int) Py_Main(int argc, wchar_t **argv);
-PyAPI_FUNC(int) Py_BytesMain(int argc, char **argv);
-
-/* In pathconfig.c */
-PyAPI_FUNC(void) Py_SetProgramName(const wchar_t *);
-PyAPI_FUNC(wchar_t *) Py_GetProgramName(void);
-
-PyAPI_FUNC(void) Py_SetPythonHome(const wchar_t *);
-PyAPI_FUNC(wchar_t *) Py_GetPythonHome(void);
-
-PyAPI_FUNC(wchar_t *) Py_GetProgramFullPath(void);
-
-PyAPI_FUNC(wchar_t *) Py_GetPrefix(void);
-PyAPI_FUNC(wchar_t *) Py_GetExecPrefix(void);
-PyAPI_FUNC(wchar_t *) Py_GetPath(void);
-PyAPI_FUNC(void) Py_SetPath(const wchar_t *);
-#ifdef MS_WINDOWS
-int _Py_CheckPython3(void);
-#endif
-
-/* In their own files */
-PyAPI_FUNC(const char *) Py_GetVersion(void);
-PyAPI_FUNC(const char *) Py_GetPlatform(void);
-PyAPI_FUNC(const char *) Py_GetCopyright(void);
-PyAPI_FUNC(const char *) Py_GetCompiler(void);
-PyAPI_FUNC(const char *) Py_GetBuildInfo(void);
-
-/* Signals */
-typedef void (*PyOS_sighandler_t)(int);
-PyAPI_FUNC(PyOS_sighandler_t) PyOS_getsig(int);
-PyAPI_FUNC(PyOS_sighandler_t) PyOS_setsig(int, PyOS_sighandler_t);
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_PYLIFECYCLE_H
-# include "cpython/pylifecycle.h"
-# undef Py_CPYTHON_PYLIFECYCLE_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_PYLIFECYCLE_H */
diff --git a/include/python3.10/pymacro.h b/include/python3.10/pymacro.h
deleted file mode 100644
index 202b936..0000000
--- a/include/python3.10/pymacro.h
+++ /dev/null
@@ -1,132 +0,0 @@
-#ifndef Py_PYMACRO_H
-#define Py_PYMACRO_H
-
-/* Minimum value between x and y */
-#define Py_MIN(x, y) (((x) > (y)) ? (y) : (x))
-
-/* Maximum value between x and y */
-#define Py_MAX(x, y) (((x) > (y)) ? (x) : (y))
-
-/* Absolute value of the number x */
-#define Py_ABS(x) ((x) < 0 ? -(x) : (x))
-
-#define _Py_XSTRINGIFY(x) #x
-
-/* Convert the argument to a string. For example, Py_STRINGIFY(123) is replaced
- with "123" by the preprocessor. Defines are also replaced by their value.
- For example Py_STRINGIFY(__LINE__) is replaced by the line number, not
- by "__LINE__". */
-#define Py_STRINGIFY(x) _Py_XSTRINGIFY(x)
-
-/* Get the size of a structure member in bytes */
-#define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member)
-
-/* Argument must be a char or an int in [-128, 127] or [0, 255]. */
-#define Py_CHARMASK(c) ((unsigned char)((c) & 0xff))
-
-/* Assert a build-time dependency, as an expression.
-
- Your compile will fail if the condition isn't true, or can't be evaluated
- by the compiler. This can be used in an expression: its value is 0.
-
- Example:
-
- #define foo_to_char(foo) \
- ((char *)(foo) \
- + Py_BUILD_ASSERT_EXPR(offsetof(struct foo, string) == 0))
-
- Written by Rusty Russell, public domain, http://ccodearchive.net/ */
-#define Py_BUILD_ASSERT_EXPR(cond) \
- (sizeof(char [1 - 2*!(cond)]) - 1)
-
-#define Py_BUILD_ASSERT(cond) do { \
- (void)Py_BUILD_ASSERT_EXPR(cond); \
- } while(0)
-
-/* Get the number of elements in a visible array
-
- This does not work on pointers, or arrays declared as [], or function
- parameters. With correct compiler support, such usage will cause a build
- error (see Py_BUILD_ASSERT_EXPR).
-
- Written by Rusty Russell, public domain, http://ccodearchive.net/
-
- Requires at GCC 3.1+ */
-#if (defined(__GNUC__) && !defined(__STRICT_ANSI__) && \
- (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)) || (__GNUC__ >= 4)))
-/* Two gcc extensions.
- &a[0] degrades to a pointer: a different type from an array */
-#define Py_ARRAY_LENGTH(array) \
- (sizeof(array) / sizeof((array)[0]) \
- + Py_BUILD_ASSERT_EXPR(!__builtin_types_compatible_p(typeof(array), \
- typeof(&(array)[0]))))
-#else
-#define Py_ARRAY_LENGTH(array) \
- (sizeof(array) / sizeof((array)[0]))
-#endif
-
-
-/* Define macros for inline documentation. */
-#define PyDoc_VAR(name) static const char name[]
-#define PyDoc_STRVAR(name,str) PyDoc_VAR(name) = PyDoc_STR(str)
-#ifdef WITH_DOC_STRINGS
-#define PyDoc_STR(str) str
-#else
-#define PyDoc_STR(str) ""
-#endif
-
-/* Below "a" is a power of 2. */
-/* Round down size "n" to be a multiple of "a". */
-#define _Py_SIZE_ROUND_DOWN(n, a) ((size_t)(n) & ~(size_t)((a) - 1))
-/* Round up size "n" to be a multiple of "a". */
-#define _Py_SIZE_ROUND_UP(n, a) (((size_t)(n) + \
- (size_t)((a) - 1)) & ~(size_t)((a) - 1))
-/* Round pointer "p" down to the closest "a"-aligned address <= "p". */
-#define _Py_ALIGN_DOWN(p, a) ((void *)((uintptr_t)(p) & ~(uintptr_t)((a) - 1)))
-/* Round pointer "p" up to the closest "a"-aligned address >= "p". */
-#define _Py_ALIGN_UP(p, a) ((void *)(((uintptr_t)(p) + \
- (uintptr_t)((a) - 1)) & ~(uintptr_t)((a) - 1)))
-/* Check if pointer "p" is aligned to "a"-bytes boundary. */
-#define _Py_IS_ALIGNED(p, a) (!((uintptr_t)(p) & (uintptr_t)((a) - 1)))
-
-/* Use this for unused arguments in a function definition to silence compiler
- * warnings. Example:
- *
- * int func(int a, int Py_UNUSED(b)) { return a; }
- */
-#if defined(__GNUC__) || defined(__clang__)
-# define Py_UNUSED(name) _unused_ ## name __attribute__((unused))
-#else
-# define Py_UNUSED(name) _unused_ ## name
-#endif
-
-#if defined(RANDALL_WAS_HERE)
-# define Py_UNREACHABLE() \
- Py_FatalError( \
- "If you're seeing this, the code is in what I thought was\n" \
- "an unreachable state.\n\n" \
- "I could give you advice for what to do, but honestly, why\n" \
- "should you trust me? I clearly screwed this up. I'm writing\n" \
- "a message that should never appear, yet I know it will\n" \
- "probably appear someday.\n\n" \
- "On a deep level, I know I'm not up to this task.\n" \
- "I'm so sorry.\n" \
- "https://xkcd.com/2200")
-#elif defined(Py_DEBUG)
-# define Py_UNREACHABLE() \
- Py_FatalError( \
- "We've reached an unreachable state. Anything is possible.\n" \
- "The limits were in our heads all along. Follow your dreams.\n" \
- "https://xkcd.com/2200")
-#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
-# define Py_UNREACHABLE() __builtin_unreachable()
-#elif defined(__clang__) || defined(__INTEL_COMPILER)
-# define Py_UNREACHABLE() __builtin_unreachable()
-#elif defined(_MSC_VER)
-# define Py_UNREACHABLE() __assume(0)
-#else
-# define Py_UNREACHABLE() \
- Py_FatalError("Unreachable C code path reached")
-#endif
-
-#endif /* Py_PYMACRO_H */
diff --git a/include/python3.10/pymath.h b/include/python3.10/pymath.h
deleted file mode 100644
index f869724..0000000
--- a/include/python3.10/pymath.h
+++ /dev/null
@@ -1,230 +0,0 @@
-#ifndef Py_PYMATH_H
-#define Py_PYMATH_H
-
-#include "pyconfig.h" /* include for defines */
-
-/**************************************************************************
-Symbols and macros to supply platform-independent interfaces to mathematical
-functions and constants
-**************************************************************************/
-
-/* Python provides implementations for copysign, round and hypot in
- * Python/pymath.c just in case your math library doesn't provide the
- * functions.
- *
- *Note: PC/pyconfig.h defines copysign as _copysign
- */
-#ifndef HAVE_COPYSIGN
-extern double copysign(double, double);
-#endif
-
-#ifndef HAVE_ROUND
-extern double round(double);
-#endif
-
-#ifndef HAVE_HYPOT
-extern double hypot(double, double);
-#endif
-
-/* extra declarations */
-#ifndef _MSC_VER
-#ifndef __STDC__
-extern double fmod (double, double);
-extern double frexp (double, int *);
-extern double ldexp (double, int);
-extern double modf (double, double *);
-extern double pow(double, double);
-#endif /* __STDC__ */
-#endif /* _MSC_VER */
-
-/* High precision definition of pi and e (Euler)
- * The values are taken from libc6's math.h.
- */
-#ifndef Py_MATH_PIl
-#define Py_MATH_PIl 3.1415926535897932384626433832795029L
-#endif
-#ifndef Py_MATH_PI
-#define Py_MATH_PI 3.14159265358979323846
-#endif
-
-#ifndef Py_MATH_El
-#define Py_MATH_El 2.7182818284590452353602874713526625L
-#endif
-
-#ifndef Py_MATH_E
-#define Py_MATH_E 2.7182818284590452354
-#endif
-
-/* Tau (2pi) to 40 digits, taken from tauday.com/tau-digits. */
-#ifndef Py_MATH_TAU
-#define Py_MATH_TAU 6.2831853071795864769252867665590057683943L
-#endif
-
-
-/* On x86, Py_FORCE_DOUBLE forces a floating-point number out of an x87 FPU
- register and into a 64-bit memory location, rounding from extended
- precision to double precision in the process. On other platforms it does
- nothing. */
-
-/* we take double rounding as evidence of x87 usage */
-#ifndef Py_LIMITED_API
-#ifndef Py_FORCE_DOUBLE
-# ifdef X87_DOUBLE_ROUNDING
-PyAPI_FUNC(double) _Py_force_double(double);
-# define Py_FORCE_DOUBLE(X) (_Py_force_double(X))
-# else
-# define Py_FORCE_DOUBLE(X) (X)
-# endif
-#endif
-#endif
-
-#ifndef Py_LIMITED_API
-#ifdef HAVE_GCC_ASM_FOR_X87
-PyAPI_FUNC(unsigned short) _Py_get_387controlword(void);
-PyAPI_FUNC(void) _Py_set_387controlword(unsigned short);
-#endif
-#endif
-
-/* Py_IS_NAN(X)
- * Return 1 if float or double arg is a NaN, else 0.
- * Caution:
- * X is evaluated more than once.
- * This may not work on all platforms. Each platform has *some*
- * way to spell this, though -- override in pyconfig.h if you have
- * a platform where it doesn't work.
- * Note: PC/pyconfig.h defines Py_IS_NAN as _isnan
- */
-#ifndef Py_IS_NAN
-#if defined HAVE_DECL_ISNAN && HAVE_DECL_ISNAN == 1
-#define Py_IS_NAN(X) isnan(X)
-#else
-#define Py_IS_NAN(X) ((X) != (X))
-#endif
-#endif
-
-/* Py_IS_INFINITY(X)
- * Return 1 if float or double arg is an infinity, else 0.
- * Caution:
- * X is evaluated more than once.
- * This implementation may set the underflow flag if |X| is very small;
- * it really can't be implemented correctly (& easily) before C99.
- * Override in pyconfig.h if you have a better spelling on your platform.
- * Py_FORCE_DOUBLE is used to avoid getting false negatives from a
- * non-infinite value v sitting in an 80-bit x87 register such that
- * v becomes infinite when spilled from the register to 64-bit memory.
- * Note: PC/pyconfig.h defines Py_IS_INFINITY as _isinf
- */
-#ifndef Py_IS_INFINITY
-# if defined HAVE_DECL_ISINF && HAVE_DECL_ISINF == 1
-# define Py_IS_INFINITY(X) isinf(X)
-# else
-# define Py_IS_INFINITY(X) ((X) && \
- (Py_FORCE_DOUBLE(X)*0.5 == Py_FORCE_DOUBLE(X)))
-# endif
-#endif
-
-/* Py_IS_FINITE(X)
- * Return 1 if float or double arg is neither infinite nor NAN, else 0.
- * Some compilers (e.g. VisualStudio) have intrinsics for this, so a special
- * macro for this particular test is useful
- * Note: PC/pyconfig.h defines Py_IS_FINITE as _finite
- */
-#ifndef Py_IS_FINITE
-#if defined HAVE_DECL_ISFINITE && HAVE_DECL_ISFINITE == 1
-#define Py_IS_FINITE(X) isfinite(X)
-#elif defined HAVE_FINITE
-#define Py_IS_FINITE(X) finite(X)
-#else
-#define Py_IS_FINITE(X) (!Py_IS_INFINITY(X) && !Py_IS_NAN(X))
-#endif
-#endif
-
-/* HUGE_VAL is supposed to expand to a positive double infinity. Python
- * uses Py_HUGE_VAL instead because some platforms are broken in this
- * respect. We used to embed code in pyport.h to try to worm around that,
- * but different platforms are broken in conflicting ways. If you're on
- * a platform where HUGE_VAL is defined incorrectly, fiddle your Python
- * config to #define Py_HUGE_VAL to something that works on your platform.
- */
-#ifndef Py_HUGE_VAL
-#define Py_HUGE_VAL HUGE_VAL
-#endif
-
-/* Py_NAN
- * A value that evaluates to a NaN. On IEEE 754 platforms INF*0 or
- * INF/INF works. Define Py_NO_NAN in pyconfig.h if your platform
- * doesn't support NaNs.
- */
-#if !defined(Py_NAN) && !defined(Py_NO_NAN)
-#if !defined(__INTEL_COMPILER)
- #define Py_NAN (Py_HUGE_VAL * 0.)
-#else /* __INTEL_COMPILER */
- #if defined(ICC_NAN_STRICT)
- #pragma float_control(push)
- #pragma float_control(precise, on)
- #pragma float_control(except, on)
- #if defined(_MSC_VER)
- __declspec(noinline)
- #else /* Linux */
- __attribute__((noinline))
- #endif /* _MSC_VER */
- static double __icc_nan()
- {
- return sqrt(-1.0);
- }
- #pragma float_control (pop)
- #define Py_NAN __icc_nan()
- #else /* ICC_NAN_RELAXED as default for Intel Compiler */
- static const union { unsigned char buf[8]; double __icc_nan; } __nan_store = {0,0,0,0,0,0,0xf8,0x7f};
- #define Py_NAN (__nan_store.__icc_nan)
- #endif /* ICC_NAN_STRICT */
-#endif /* __INTEL_COMPILER */
-#endif
-
-/* Py_OVERFLOWED(X)
- * Return 1 iff a libm function overflowed. Set errno to 0 before calling
- * a libm function, and invoke this macro after, passing the function
- * result.
- * Caution:
- * This isn't reliable. C99 no longer requires libm to set errno under
- * any exceptional condition, but does require +- HUGE_VAL return
- * values on overflow. A 754 box *probably* maps HUGE_VAL to a
- * double infinity, and we're cool if that's so, unless the input
- * was an infinity and an infinity is the expected result. A C89
- * system sets errno to ERANGE, so we check for that too. We're
- * out of luck if a C99 754 box doesn't map HUGE_VAL to +Inf, or
- * if the returned result is a NaN, or if a C89 box returns HUGE_VAL
- * in non-overflow cases.
- * X is evaluated more than once.
- * Some platforms have better way to spell this, so expect some #ifdef'ery.
- *
- * OpenBSD uses 'isinf()' because a compiler bug on that platform causes
- * the longer macro version to be mis-compiled. This isn't optimal, and
- * should be removed once a newer compiler is available on that platform.
- * The system that had the failure was running OpenBSD 3.2 on Intel, with
- * gcc 2.95.3.
- *
- * According to Tim's checkin, the FreeBSD systems use isinf() to work
- * around a FPE bug on that platform.
- */
-#if defined(__FreeBSD__) || defined(__OpenBSD__)
-#define Py_OVERFLOWED(X) isinf(X)
-#else
-#define Py_OVERFLOWED(X) ((X) != 0.0 && (errno == ERANGE || \
- (X) == Py_HUGE_VAL || \
- (X) == -Py_HUGE_VAL))
-#endif
-
-/* Return whether integral type *type* is signed or not. */
-#define _Py_IntegralTypeSigned(type) ((type)(-1) < 0)
-/* Return the maximum value of integral type *type*. */
-#define _Py_IntegralTypeMax(type) ((_Py_IntegralTypeSigned(type)) ? (((((type)1 << (sizeof(type)*CHAR_BIT - 2)) - 1) << 1) + 1) : ~(type)0)
-/* Return the minimum value of integral type *type*. */
-#define _Py_IntegralTypeMin(type) ((_Py_IntegralTypeSigned(type)) ? -_Py_IntegralTypeMax(type) - 1 : 0)
-/* Check whether *v* is in the range of integral type *type*. This is most
- * useful if *v* is floating-point, since demoting a floating-point *v* to an
- * integral type that cannot represent *v*'s integral part is undefined
- * behavior. */
-#define _Py_InIntegralTypeRange(type, v) (_Py_IntegralTypeMin(type) <= v && v <= _Py_IntegralTypeMax(type))
-
-#endif /* Py_PYMATH_H */
diff --git a/include/python3.10/pymem.h b/include/python3.10/pymem.h
deleted file mode 100644
index 66cdb0d..0000000
--- a/include/python3.10/pymem.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/* The PyMem_ family: low-level memory allocation interfaces.
- See objimpl.h for the PyObject_ memory family.
-*/
-
-#ifndef Py_PYMEM_H
-#define Py_PYMEM_H
-
-#include "pyport.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* BEWARE:
-
- Each interface exports both functions and macros. Extension modules should
- use the functions, to ensure binary compatibility across Python versions.
- Because the Python implementation is free to change internal details, and
- the macros may (or may not) expose details for speed, if you do use the
- macros you must recompile your extensions with each Python release.
-
- Never mix calls to PyMem_ with calls to the platform malloc/realloc/
- calloc/free. For example, on Windows different DLLs may end up using
- different heaps, and if you use PyMem_Malloc you'll get the memory from the
- heap used by the Python DLL; it could be a disaster if you free()'ed that
- directly in your own extension. Using PyMem_Free instead ensures Python
- can return the memory to the proper heap. As another example, in
- a debug build (Py_DEBUG macro), Python wraps all calls to all PyMem_ and
- PyObject_ memory functions in special debugging wrappers that add additional
- debugging info to dynamic memory blocks. The system routines have no idea
- what to do with that stuff, and the Python wrappers have no idea what to do
- with raw blocks obtained directly by the system routines then.
-
- The GIL must be held when using these APIs.
-*/
-
-/*
- * Raw memory interface
- * ====================
- */
-
-/* Functions
-
- Functions supplying platform-independent semantics for malloc/realloc/
- free. These functions make sure that allocating 0 bytes returns a distinct
- non-NULL pointer (whenever possible -- if we're flat out of memory, NULL
- may be returned), even if the platform malloc and realloc don't.
- Returned pointers must be checked for NULL explicitly. No action is
- performed on failure (no exception is set, no warning is printed, etc).
-*/
-
-PyAPI_FUNC(void *) PyMem_Malloc(size_t size);
-PyAPI_FUNC(void *) PyMem_Calloc(size_t nelem, size_t elsize);
-PyAPI_FUNC(void *) PyMem_Realloc(void *ptr, size_t new_size);
-PyAPI_FUNC(void) PyMem_Free(void *ptr);
-
-/*
- * Type-oriented memory interface
- * ==============================
- *
- * Allocate memory for n objects of the given type. Returns a new pointer
- * or NULL if the request was too large or memory allocation failed. Use
- * these macros rather than doing the multiplication yourself so that proper
- * overflow checking is always done.
- */
-
-#define PyMem_New(type, n) \
- ( ((size_t)(n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \
- ( (type *) PyMem_Malloc((n) * sizeof(type)) ) )
-
-/*
- * The value of (p) is always clobbered by this macro regardless of success.
- * The caller MUST check if (p) is NULL afterwards and deal with the memory
- * error if so. This means the original value of (p) MUST be saved for the
- * caller's memory error handler to not lose track of it.
- */
-#define PyMem_Resize(p, type, n) \
- ( (p) = ((size_t)(n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \
- (type *) PyMem_Realloc((p), (n) * sizeof(type)) )
-
-
-// Deprecated aliases only kept for backward compatibility.
-// PyMem_Del and PyMem_DEL are defined with no parameter to be able to use
-// them as function pointers (ex: dealloc = PyMem_Del).
-#define PyMem_MALLOC(n) PyMem_Malloc(n)
-#define PyMem_NEW(type, n) PyMem_New(type, n)
-#define PyMem_REALLOC(p, n) PyMem_Realloc(p, n)
-#define PyMem_RESIZE(p, type, n) PyMem_Resize(p, type, n)
-#define PyMem_FREE(p) PyMem_Free(p)
-#define PyMem_Del PyMem_Free
-#define PyMem_DEL PyMem_Free
-
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_PYMEM_H
-# include "cpython/pymem.h"
-# undef Py_CPYTHON_PYMEM_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* !Py_PYMEM_H */
diff --git a/include/python3.10/pyport.h b/include/python3.10/pyport.h
deleted file mode 100644
index 6ab0ae4..0000000
--- a/include/python3.10/pyport.h
+++ /dev/null
@@ -1,889 +0,0 @@
-#ifndef Py_PYPORT_H
-#define Py_PYPORT_H
-
-#include "pyconfig.h" /* include for defines */
-
-#include <inttypes.h>
-
-
-/* Defines to build Python and its standard library:
- *
- * - Py_BUILD_CORE: Build Python core. Give access to Python internals, but
- * should not be used by third-party modules.
- * - Py_BUILD_CORE_BUILTIN: Build a Python stdlib module as a built-in module.
- * - Py_BUILD_CORE_MODULE: Build a Python stdlib module as a dynamic library.
- *
- * Py_BUILD_CORE_BUILTIN and Py_BUILD_CORE_MODULE imply Py_BUILD_CORE.
- *
- * On Windows, Py_BUILD_CORE_MODULE exports "PyInit_xxx" symbol, whereas
- * Py_BUILD_CORE_BUILTIN does not.
- */
-#if defined(Py_BUILD_CORE_BUILTIN) && !defined(Py_BUILD_CORE)
-# define Py_BUILD_CORE
-#endif
-#if defined(Py_BUILD_CORE_MODULE) && !defined(Py_BUILD_CORE)
-# define Py_BUILD_CORE
-#endif
-
-
-/**************************************************************************
-Symbols and macros to supply platform-independent interfaces to basic
-C language & library operations whose spellings vary across platforms.
-
-Please try to make documentation here as clear as possible: by definition,
-the stuff here is trying to illuminate C's darkest corners.
-
-Config #defines referenced here:
-
-SIGNED_RIGHT_SHIFT_ZERO_FILLS
-Meaning: To be defined iff i>>j does not extend the sign bit when i is a
- signed integral type and i < 0.
-Used in: Py_ARITHMETIC_RIGHT_SHIFT
-
-Py_DEBUG
-Meaning: Extra checks compiled in for debug mode.
-Used in: Py_SAFE_DOWNCAST
-
-**************************************************************************/
-
-/* typedefs for some C9X-defined synonyms for integral types.
- *
- * The names in Python are exactly the same as the C9X names, except with a
- * Py_ prefix. Until C9X is universally implemented, this is the only way
- * to ensure that Python gets reliable names that don't conflict with names
- * in non-Python code that are playing their own tricks to define the C9X
- * names.
- *
- * NOTE: don't go nuts here! Python has no use for *most* of the C9X
- * integral synonyms. Only define the ones we actually need.
- */
-
-/* long long is required. Ensure HAVE_LONG_LONG is defined for compatibility. */
-#ifndef HAVE_LONG_LONG
-#define HAVE_LONG_LONG 1
-#endif
-#ifndef PY_LONG_LONG
-#define PY_LONG_LONG long long
-/* If LLONG_MAX is defined in limits.h, use that. */
-#define PY_LLONG_MIN LLONG_MIN
-#define PY_LLONG_MAX LLONG_MAX
-#define PY_ULLONG_MAX ULLONG_MAX
-#endif
-
-#define PY_UINT32_T uint32_t
-#define PY_UINT64_T uint64_t
-
-/* Signed variants of the above */
-#define PY_INT32_T int32_t
-#define PY_INT64_T int64_t
-
-/* If PYLONG_BITS_IN_DIGIT is not defined then we'll use 30-bit digits if all
- the necessary integer types are available, and we're on a 64-bit platform
- (as determined by SIZEOF_VOID_P); otherwise we use 15-bit digits. */
-
-#ifndef PYLONG_BITS_IN_DIGIT
-#if SIZEOF_VOID_P >= 8
-#define PYLONG_BITS_IN_DIGIT 30
-#else
-#define PYLONG_BITS_IN_DIGIT 15
-#endif
-#endif
-
-/* uintptr_t is the C9X name for an unsigned integral type such that a
- * legitimate void* can be cast to uintptr_t and then back to void* again
- * without loss of information. Similarly for intptr_t, wrt a signed
- * integral type.
- */
-typedef uintptr_t Py_uintptr_t;
-typedef intptr_t Py_intptr_t;
-
-/* Py_ssize_t is a signed integral type such that sizeof(Py_ssize_t) ==
- * sizeof(size_t). C99 doesn't define such a thing directly (size_t is an
- * unsigned integral type). See PEP 353 for details.
- */
-#ifdef HAVE_PY_SSIZE_T
-
-#elif HAVE_SSIZE_T
-typedef ssize_t Py_ssize_t;
-#elif SIZEOF_VOID_P == SIZEOF_SIZE_T
-typedef Py_intptr_t Py_ssize_t;
-#else
-# error "Python needs a typedef for Py_ssize_t in pyport.h."
-#endif
-
-/* Py_hash_t is the same size as a pointer. */
-#define SIZEOF_PY_HASH_T SIZEOF_SIZE_T
-typedef Py_ssize_t Py_hash_t;
-/* Py_uhash_t is the unsigned equivalent needed to calculate numeric hash. */
-#define SIZEOF_PY_UHASH_T SIZEOF_SIZE_T
-typedef size_t Py_uhash_t;
-
-/* Only used for compatibility with code that may not be PY_SSIZE_T_CLEAN. */
-#ifdef PY_SSIZE_T_CLEAN
-typedef Py_ssize_t Py_ssize_clean_t;
-#else
-typedef int Py_ssize_clean_t;
-#endif
-
-/* Largest possible value of size_t. */
-#define PY_SIZE_MAX SIZE_MAX
-
-/* Largest positive value of type Py_ssize_t. */
-#define PY_SSIZE_T_MAX ((Py_ssize_t)(((size_t)-1)>>1))
-/* Smallest negative value of type Py_ssize_t. */
-#define PY_SSIZE_T_MIN (-PY_SSIZE_T_MAX-1)
-
-/* Macro kept for backward compatibility: use "z" in new code.
- *
- * PY_FORMAT_SIZE_T is a platform-specific modifier for use in a printf
- * format to convert an argument with the width of a size_t or Py_ssize_t.
- * C99 introduced "z" for this purpose, but old MSVCs had not supported it.
- * Since MSVC supports "z" since (at least) 2015, we can just use "z"
- * for new code.
- *
- * These "high level" Python format functions interpret "z" correctly on
- * all platforms (Python interprets the format string itself, and does whatever
- * the platform C requires to convert a size_t/Py_ssize_t argument):
- *
- * PyBytes_FromFormat
- * PyErr_Format
- * PyBytes_FromFormatV
- * PyUnicode_FromFormatV
- *
- * Lower-level uses require that you interpolate the correct format modifier
- * yourself (e.g., calling printf, fprintf, sprintf, PyOS_snprintf); for
- * example,
- *
- * Py_ssize_t index;
- * fprintf(stderr, "index %" PY_FORMAT_SIZE_T "d sucks\n", index);
- *
- * That will expand to %zd or to something else correct for a Py_ssize_t on
- * the platform.
- */
-#ifndef PY_FORMAT_SIZE_T
-# define PY_FORMAT_SIZE_T "z"
-#endif
-
-/* Py_LOCAL can be used instead of static to get the fastest possible calling
- * convention for functions that are local to a given module.
- *
- * Py_LOCAL_INLINE does the same thing, and also explicitly requests inlining,
- * for platforms that support that.
- *
- * If PY_LOCAL_AGGRESSIVE is defined before python.h is included, more
- * "aggressive" inlining/optimization is enabled for the entire module. This
- * may lead to code bloat, and may slow things down for those reasons. It may
- * also lead to errors, if the code relies on pointer aliasing. Use with
- * care.
- *
- * NOTE: You can only use this for functions that are entirely local to a
- * module; functions that are exported via method tables, callbacks, etc,
- * should keep using static.
- */
-
-#if defined(_MSC_VER)
-# if defined(PY_LOCAL_AGGRESSIVE)
- /* enable more aggressive optimization for MSVC */
- /* active in both release and debug builds - see bpo-43271 */
-# pragma optimize("gt", on)
-#endif
- /* ignore warnings if the compiler decides not to inline a function */
-# pragma warning(disable: 4710)
- /* fastest possible local call under MSVC */
-# define Py_LOCAL(type) static type __fastcall
-# define Py_LOCAL_INLINE(type) static __inline type __fastcall
-#else
-# define Py_LOCAL(type) static type
-# define Py_LOCAL_INLINE(type) static inline type
-#endif
-
-/* Py_MEMCPY is kept for backwards compatibility,
- * see https://bugs.python.org/issue28126 */
-#define Py_MEMCPY memcpy
-
-#include <stdlib.h>
-
-#ifdef HAVE_IEEEFP_H
-#include <ieeefp.h> /* needed for 'finite' declaration on some platforms */
-#endif
-
-#include <math.h> /* Moved here from the math section, before extern "C" */
-
-/********************************************
- * WRAPPER FOR <time.h> and/or <sys/time.h> *
- ********************************************/
-
-#ifdef TIME_WITH_SYS_TIME
-#include <sys/time.h>
-#include <time.h>
-#else /* !TIME_WITH_SYS_TIME */
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#else /* !HAVE_SYS_TIME_H */
-#include <time.h>
-#endif /* !HAVE_SYS_TIME_H */
-#endif /* !TIME_WITH_SYS_TIME */
-
-
-/******************************
- * WRAPPER FOR <sys/select.h> *
- ******************************/
-
-/* NB caller must include <sys/types.h> */
-
-#ifdef HAVE_SYS_SELECT_H
-#include <sys/select.h>
-#endif /* !HAVE_SYS_SELECT_H */
-
-/*******************************
- * stat() and fstat() fiddling *
- *******************************/
-
-#ifdef HAVE_SYS_STAT_H
-#include <sys/stat.h>
-#elif defined(HAVE_STAT_H)
-#include <stat.h>
-#endif
-
-#ifndef S_IFMT
-/* VisualAge C/C++ Failed to Define MountType Field in sys/stat.h */
-#define S_IFMT 0170000
-#endif
-
-#ifndef S_IFLNK
-/* Windows doesn't define S_IFLNK but posixmodule.c maps
- * IO_REPARSE_TAG_SYMLINK to S_IFLNK */
-# define S_IFLNK 0120000
-#endif
-
-#ifndef S_ISREG
-#define S_ISREG(x) (((x) & S_IFMT) == S_IFREG)
-#endif
-
-#ifndef S_ISDIR
-#define S_ISDIR(x) (((x) & S_IFMT) == S_IFDIR)
-#endif
-
-#ifndef S_ISCHR
-#define S_ISCHR(x) (((x) & S_IFMT) == S_IFCHR)
-#endif
-
-#ifdef __cplusplus
-/* Move this down here since some C++ #include's don't like to be included
- inside an extern "C" */
-extern "C" {
-#endif
-
-
-/* Py_ARITHMETIC_RIGHT_SHIFT
- * C doesn't define whether a right-shift of a signed integer sign-extends
- * or zero-fills. Here a macro to force sign extension:
- * Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J)
- * Return I >> J, forcing sign extension. Arithmetically, return the
- * floor of I/2**J.
- * Requirements:
- * I should have signed integer type. In the terminology of C99, this can
- * be either one of the five standard signed integer types (signed char,
- * short, int, long, long long) or an extended signed integer type.
- * J is an integer >= 0 and strictly less than the number of bits in the
- * type of I (because C doesn't define what happens for J outside that
- * range either).
- * TYPE used to specify the type of I, but is now ignored. It's been left
- * in for backwards compatibility with versions <= 2.6 or 3.0.
- * Caution:
- * I may be evaluated more than once.
- */
-#ifdef SIGNED_RIGHT_SHIFT_ZERO_FILLS
-#define Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J) \
- ((I) < 0 ? -1-((-1-(I)) >> (J)) : (I) >> (J))
-#else
-#define Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J) ((I) >> (J))
-#endif
-
-/* Py_FORCE_EXPANSION(X)
- * "Simply" returns its argument. However, macro expansions within the
- * argument are evaluated. This unfortunate trickery is needed to get
- * token-pasting to work as desired in some cases.
- */
-#define Py_FORCE_EXPANSION(X) X
-
-/* Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW)
- * Cast VALUE to type NARROW from type WIDE. In Py_DEBUG mode, this
- * assert-fails if any information is lost.
- * Caution:
- * VALUE may be evaluated more than once.
- */
-#ifdef Py_DEBUG
-#define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) \
- (assert((WIDE)(NARROW)(VALUE) == (VALUE)), (NARROW)(VALUE))
-#else
-#define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) (NARROW)(VALUE)
-#endif
-
-/* Py_SET_ERRNO_ON_MATH_ERROR(x)
- * If a libm function did not set errno, but it looks like the result
- * overflowed or not-a-number, set errno to ERANGE or EDOM. Set errno
- * to 0 before calling a libm function, and invoke this macro after,
- * passing the function result.
- * Caution:
- * This isn't reliable. See Py_OVERFLOWED comments.
- * X is evaluated more than once.
- */
-#if defined(__FreeBSD__) || defined(__OpenBSD__) || (defined(__hpux) && defined(__ia64))
-#define _Py_SET_EDOM_FOR_NAN(X) if (isnan(X)) errno = EDOM;
-#else
-#define _Py_SET_EDOM_FOR_NAN(X) ;
-#endif
-#define Py_SET_ERRNO_ON_MATH_ERROR(X) \
- do { \
- if (errno == 0) { \
- if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \
- errno = ERANGE; \
- else _Py_SET_EDOM_FOR_NAN(X) \
- } \
- } while(0)
-
-/* Py_SET_ERANGE_IF_OVERFLOW(x)
- * An alias of Py_SET_ERRNO_ON_MATH_ERROR for backward-compatibility.
- */
-#define Py_SET_ERANGE_IF_OVERFLOW(X) Py_SET_ERRNO_ON_MATH_ERROR(X)
-
-/* Py_ADJUST_ERANGE1(x)
- * Py_ADJUST_ERANGE2(x, y)
- * Set errno to 0 before calling a libm function, and invoke one of these
- * macros after, passing the function result(s) (Py_ADJUST_ERANGE2 is useful
- * for functions returning complex results). This makes two kinds of
- * adjustments to errno: (A) If it looks like the platform libm set
- * errno=ERANGE due to underflow, clear errno. (B) If it looks like the
- * platform libm overflowed but didn't set errno, force errno to ERANGE. In
- * effect, we're trying to force a useful implementation of C89 errno
- * behavior.
- * Caution:
- * This isn't reliable. See Py_OVERFLOWED comments.
- * X and Y may be evaluated more than once.
- */
-#define Py_ADJUST_ERANGE1(X) \
- do { \
- if (errno == 0) { \
- if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \
- errno = ERANGE; \
- } \
- else if (errno == ERANGE && (X) == 0.0) \
- errno = 0; \
- } while(0)
-
-#define Py_ADJUST_ERANGE2(X, Y) \
- do { \
- if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL || \
- (Y) == Py_HUGE_VAL || (Y) == -Py_HUGE_VAL) { \
- if (errno == 0) \
- errno = ERANGE; \
- } \
- else if (errno == ERANGE) \
- errno = 0; \
- } while(0)
-
-/* The functions _Py_dg_strtod and _Py_dg_dtoa in Python/dtoa.c (which are
- * required to support the short float repr introduced in Python 3.1) require
- * that the floating-point unit that's being used for arithmetic operations
- * on C doubles is set to use 53-bit precision. It also requires that the
- * FPU rounding mode is round-half-to-even, but that's less often an issue.
- *
- * If your FPU isn't already set to 53-bit precision/round-half-to-even, and
- * you want to make use of _Py_dg_strtod and _Py_dg_dtoa, then you should
- *
- * #define HAVE_PY_SET_53BIT_PRECISION 1
- *
- * and also give appropriate definitions for the following three macros:
- *
- * _PY_SET_53BIT_PRECISION_START : store original FPU settings, and
- * set FPU to 53-bit precision/round-half-to-even
- * _PY_SET_53BIT_PRECISION_END : restore original FPU settings
- * _PY_SET_53BIT_PRECISION_HEADER : any variable declarations needed to
- * use the two macros above.
- *
- * The macros are designed to be used within a single C function: see
- * Python/pystrtod.c for an example of their use.
- */
-
-/* get and set x87 control word for gcc/x86 */
-#ifdef HAVE_GCC_ASM_FOR_X87
-#define HAVE_PY_SET_53BIT_PRECISION 1
-/* _Py_get/set_387controlword functions are defined in Python/pymath.c */
-#define _Py_SET_53BIT_PRECISION_HEADER \
- unsigned short old_387controlword, new_387controlword
-#define _Py_SET_53BIT_PRECISION_START \
- do { \
- old_387controlword = _Py_get_387controlword(); \
- new_387controlword = (old_387controlword & ~0x0f00) | 0x0200; \
- if (new_387controlword != old_387controlword) \
- _Py_set_387controlword(new_387controlword); \
- } while (0)
-#define _Py_SET_53BIT_PRECISION_END \
- if (new_387controlword != old_387controlword) \
- _Py_set_387controlword(old_387controlword)
-#endif
-
-/* get and set x87 control word for VisualStudio/x86 */
-#if defined(_MSC_VER) && !defined(_WIN64) && !defined(_M_ARM) /* x87 not supported in 64-bit or ARM */
-#define HAVE_PY_SET_53BIT_PRECISION 1
-#define _Py_SET_53BIT_PRECISION_HEADER \
- unsigned int old_387controlword, new_387controlword, out_387controlword
-/* We use the __control87_2 function to set only the x87 control word.
- The SSE control word is unaffected. */
-#define _Py_SET_53BIT_PRECISION_START \
- do { \
- __control87_2(0, 0, &old_387controlword, NULL); \
- new_387controlword = \
- (old_387controlword & ~(_MCW_PC | _MCW_RC)) | (_PC_53 | _RC_NEAR); \
- if (new_387controlword != old_387controlword) \
- __control87_2(new_387controlword, _MCW_PC | _MCW_RC, \
- &out_387controlword, NULL); \
- } while (0)
-#define _Py_SET_53BIT_PRECISION_END \
- do { \
- if (new_387controlword != old_387controlword) \
- __control87_2(old_387controlword, _MCW_PC | _MCW_RC, \
- &out_387controlword, NULL); \
- } while (0)
-#endif
-
-#ifdef HAVE_GCC_ASM_FOR_MC68881
-#define HAVE_PY_SET_53BIT_PRECISION 1
-#define _Py_SET_53BIT_PRECISION_HEADER \
- unsigned int old_fpcr, new_fpcr
-#define _Py_SET_53BIT_PRECISION_START \
- do { \
- __asm__ ("fmove.l %%fpcr,%0" : "=g" (old_fpcr)); \
- /* Set double precision / round to nearest. */ \
- new_fpcr = (old_fpcr & ~0xf0) | 0x80; \
- if (new_fpcr != old_fpcr) \
- __asm__ volatile ("fmove.l %0,%%fpcr" : : "g" (new_fpcr)); \
- } while (0)
-#define _Py_SET_53BIT_PRECISION_END \
- do { \
- if (new_fpcr != old_fpcr) \
- __asm__ volatile ("fmove.l %0,%%fpcr" : : "g" (old_fpcr)); \
- } while (0)
-#endif
-
-/* default definitions are empty */
-#ifndef HAVE_PY_SET_53BIT_PRECISION
-#define _Py_SET_53BIT_PRECISION_HEADER
-#define _Py_SET_53BIT_PRECISION_START
-#define _Py_SET_53BIT_PRECISION_END
-#endif
-
-/* If we can't guarantee 53-bit precision, don't use the code
- in Python/dtoa.c, but fall back to standard code. This
- means that repr of a float will be long (17 sig digits).
-
- Realistically, there are two things that could go wrong:
-
- (1) doubles aren't IEEE 754 doubles, or
- (2) we're on x86 with the rounding precision set to 64-bits
- (extended precision), and we don't know how to change
- the rounding precision.
- */
-
-#if !defined(DOUBLE_IS_LITTLE_ENDIAN_IEEE754) && \
- !defined(DOUBLE_IS_BIG_ENDIAN_IEEE754) && \
- !defined(DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754)
-#define PY_NO_SHORT_FLOAT_REPR
-#endif
-
-/* double rounding is symptomatic of use of extended precision on x86. If
- we're seeing double rounding, and we don't have any mechanism available for
- changing the FPU rounding precision, then don't use Python/dtoa.c. */
-#if defined(X87_DOUBLE_ROUNDING) && !defined(HAVE_PY_SET_53BIT_PRECISION)
-#define PY_NO_SHORT_FLOAT_REPR
-#endif
-
-
-/* Py_DEPRECATED(version)
- * Declare a variable, type, or function deprecated.
- * The macro must be placed before the declaration.
- * Usage:
- * Py_DEPRECATED(3.3) extern int old_var;
- * Py_DEPRECATED(3.4) typedef int T1;
- * Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);
- */
-#if defined(__GNUC__) \
- && ((__GNUC__ >= 4) || (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1))
-#define Py_DEPRECATED(VERSION_UNUSED) __attribute__((__deprecated__))
-#elif defined(_MSC_VER)
-#define Py_DEPRECATED(VERSION) __declspec(deprecated( \
- "deprecated in " #VERSION))
-#else
-#define Py_DEPRECATED(VERSION_UNUSED)
-#endif
-
-#if defined(__clang__)
-#define _Py_COMP_DIAG_PUSH _Pragma("clang diagnostic push")
-#define _Py_COMP_DIAG_IGNORE_DEPR_DECLS \
- _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
-#define _Py_COMP_DIAG_POP _Pragma("clang diagnostic pop")
-#elif defined(__GNUC__) \
- && ((__GNUC__ >= 5) || (__GNUC__ == 4) && (__GNUC_MINOR__ >= 6))
-#define _Py_COMP_DIAG_PUSH _Pragma("GCC diagnostic push")
-#define _Py_COMP_DIAG_IGNORE_DEPR_DECLS \
- _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
-#define _Py_COMP_DIAG_POP _Pragma("GCC diagnostic pop")
-#elif defined(_MSC_VER)
-#define _Py_COMP_DIAG_PUSH __pragma(warning(push))
-#define _Py_COMP_DIAG_IGNORE_DEPR_DECLS __pragma(warning(disable: 4996))
-#define _Py_COMP_DIAG_POP __pragma(warning(pop))
-#else
-#define _Py_COMP_DIAG_PUSH
-#define _Py_COMP_DIAG_IGNORE_DEPR_DECLS
-#define _Py_COMP_DIAG_POP
-#endif
-
-/* _Py_HOT_FUNCTION
- * The hot attribute on a function is used to inform the compiler that the
- * function is a hot spot of the compiled program. The function is optimized
- * more aggressively and on many target it is placed into special subsection of
- * the text section so all hot functions appears close together improving
- * locality.
- *
- * Usage:
- * int _Py_HOT_FUNCTION x(void) { return 3; }
- *
- * Issue #28618: This attribute must not be abused, otherwise it can have a
- * negative effect on performance. Only the functions were Python spend most of
- * its time must use it. Use a profiler when running performance benchmark
- * suite to find these functions.
- */
-#if defined(__GNUC__) \
- && ((__GNUC__ >= 5) || (__GNUC__ == 4) && (__GNUC_MINOR__ >= 3))
-#define _Py_HOT_FUNCTION __attribute__((hot))
-#else
-#define _Py_HOT_FUNCTION
-#endif
-
-/* _Py_NO_INLINE
- * Disable inlining on a function. For example, it helps to reduce the C stack
- * consumption.
- *
- * Usage:
- * int _Py_NO_INLINE x(void) { return 3; }
- */
-#if defined(_MSC_VER)
-# define _Py_NO_INLINE __declspec(noinline)
-#elif defined(__GNUC__) || defined(__clang__)
-# define _Py_NO_INLINE __attribute__ ((noinline))
-#else
-# define _Py_NO_INLINE
-#endif
-
-/**************************************************************************
-Prototypes that are missing from the standard include files on some systems
-(and possibly only some versions of such systems.)
-
-Please be conservative with adding new ones, document them and enclose them
-in platform-specific #ifdefs.
-**************************************************************************/
-
-#ifdef SOLARIS
-/* Unchecked */
-extern int gethostname(char *, int);
-#endif
-
-#ifdef HAVE__GETPTY
-#include <sys/types.h> /* we need to import mode_t */
-extern char * _getpty(int *, int, mode_t, int);
-#endif
-
-/* On QNX 6, struct termio must be declared by including sys/termio.h
- if TCGETA, TCSETA, TCSETAW, or TCSETAF are used. sys/termio.h must
- be included before termios.h or it will generate an error. */
-#if defined(HAVE_SYS_TERMIO_H) && !defined(__hpux)
-#include <sys/termio.h>
-#endif
-
-
-/* On 4.4BSD-descendants, ctype functions serves the whole range of
- * wchar_t character set rather than single byte code points only.
- * This characteristic can break some operations of string object
- * including str.upper() and str.split() on UTF-8 locales. This
- * workaround was provided by Tim Robbins of FreeBSD project.
- */
-
-#if defined(__APPLE__)
-# define _PY_PORT_CTYPE_UTF8_ISSUE
-#endif
-
-#ifdef _PY_PORT_CTYPE_UTF8_ISSUE
-#ifndef __cplusplus
- /* The workaround below is unsafe in C++ because
- * the <locale> defines these symbols as real functions,
- * with a slightly different signature.
- * See issue #10910
- */
-#include <ctype.h>
-#include <wctype.h>
-#undef isalnum
-#define isalnum(c) iswalnum(btowc(c))
-#undef isalpha
-#define isalpha(c) iswalpha(btowc(c))
-#undef islower
-#define islower(c) iswlower(btowc(c))
-#undef isspace
-#define isspace(c) iswspace(btowc(c))
-#undef isupper
-#define isupper(c) iswupper(btowc(c))
-#undef tolower
-#define tolower(c) towlower(btowc(c))
-#undef toupper
-#define toupper(c) towupper(btowc(c))
-#endif
-#endif
-
-
-/* Declarations for symbol visibility.
-
- PyAPI_FUNC(type): Declares a public Python API function and return type
- PyAPI_DATA(type): Declares public Python data and its type
- PyMODINIT_FUNC: A Python module init function. If these functions are
- inside the Python core, they are private to the core.
- If in an extension module, it may be declared with
- external linkage depending on the platform.
-
- As a number of platforms support/require "__declspec(dllimport/dllexport)",
- we support a HAVE_DECLSPEC_DLL macro to save duplication.
-*/
-
-/*
- All windows ports, except cygwin, are handled in PC/pyconfig.h.
-
- Cygwin is the only other autoconf platform requiring special
- linkage handling and it uses __declspec().
-*/
-#if defined(__CYGWIN__)
-# define HAVE_DECLSPEC_DLL
-#endif
-
-#include "exports.h"
-
-/* only get special linkage if built as shared or platform is Cygwin */
-#if defined(Py_ENABLE_SHARED) || defined(__CYGWIN__)
-# if defined(HAVE_DECLSPEC_DLL)
-# if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
-# define PyAPI_FUNC(RTYPE) Py_EXPORTED_SYMBOL RTYPE
-# define PyAPI_DATA(RTYPE) extern Py_EXPORTED_SYMBOL RTYPE
- /* module init functions inside the core need no external linkage */
- /* except for Cygwin to handle embedding */
-# if defined(__CYGWIN__)
-# define PyMODINIT_FUNC Py_EXPORTED_SYMBOL PyObject*
-# else /* __CYGWIN__ */
-# define PyMODINIT_FUNC PyObject*
-# endif /* __CYGWIN__ */
-# else /* Py_BUILD_CORE */
- /* Building an extension module, or an embedded situation */
- /* public Python functions and data are imported */
- /* Under Cygwin, auto-import functions to prevent compilation */
- /* failures similar to those described at the bottom of 4.1: */
- /* http://docs.python.org/extending/windows.html#a-cookbook-approach */
-# if !defined(__CYGWIN__)
-# define PyAPI_FUNC(RTYPE) Py_IMPORTED_SYMBOL RTYPE
-# endif /* !__CYGWIN__ */
-# define PyAPI_DATA(RTYPE) extern Py_IMPORTED_SYMBOL RTYPE
- /* module init functions outside the core must be exported */
-# if defined(__cplusplus)
-# define PyMODINIT_FUNC extern "C" Py_EXPORTED_SYMBOL PyObject*
-# else /* __cplusplus */
-# define PyMODINIT_FUNC Py_EXPORTED_SYMBOL PyObject*
-# endif /* __cplusplus */
-# endif /* Py_BUILD_CORE */
-# endif /* HAVE_DECLSPEC_DLL */
-#endif /* Py_ENABLE_SHARED */
-
-/* If no external linkage macros defined by now, create defaults */
-#ifndef PyAPI_FUNC
-# define PyAPI_FUNC(RTYPE) Py_EXPORTED_SYMBOL RTYPE
-#endif
-#ifndef PyAPI_DATA
-# define PyAPI_DATA(RTYPE) extern Py_EXPORTED_SYMBOL RTYPE
-#endif
-#ifndef PyMODINIT_FUNC
-# if defined(__cplusplus)
-# define PyMODINIT_FUNC extern "C" Py_EXPORTED_SYMBOL PyObject*
-# else /* __cplusplus */
-# define PyMODINIT_FUNC Py_EXPORTED_SYMBOL PyObject*
-# endif /* __cplusplus */
-#endif
-
-/* limits.h constants that may be missing */
-
-#ifndef INT_MAX
-#define INT_MAX 2147483647
-#endif
-
-#ifndef LONG_MAX
-#if SIZEOF_LONG == 4
-#define LONG_MAX 0X7FFFFFFFL
-#elif SIZEOF_LONG == 8
-#define LONG_MAX 0X7FFFFFFFFFFFFFFFL
-#else
-#error "could not set LONG_MAX in pyport.h"
-#endif
-#endif
-
-#ifndef LONG_MIN
-#define LONG_MIN (-LONG_MAX-1)
-#endif
-
-#ifndef LONG_BIT
-#define LONG_BIT (8 * SIZEOF_LONG)
-#endif
-
-#if LONG_BIT != 8 * SIZEOF_LONG
-/* 04-Oct-2000 LONG_BIT is apparently (mis)defined as 64 on some recent
- * 32-bit platforms using gcc. We try to catch that here at compile-time
- * rather than waiting for integer multiplication to trigger bogus
- * overflows.
- */
-#error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)."
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-/*
- * Hide GCC attributes from compilers that don't support them.
- */
-#if (!defined(__GNUC__) || __GNUC__ < 2 || \
- (__GNUC__ == 2 && __GNUC_MINOR__ < 7) )
-#define Py_GCC_ATTRIBUTE(x)
-#else
-#define Py_GCC_ATTRIBUTE(x) __attribute__(x)
-#endif
-
-/*
- * Specify alignment on compilers that support it.
- */
-#if defined(__GNUC__) && __GNUC__ >= 3
-#define Py_ALIGNED(x) __attribute__((aligned(x)))
-#else
-#define Py_ALIGNED(x)
-#endif
-
-/* Eliminate end-of-loop code not reached warnings from SunPro C
- * when using do{...}while(0) macros
- */
-#ifdef __SUNPRO_C
-#pragma error_messages (off,E_END_OF_LOOP_CODE_NOT_REACHED)
-#endif
-
-#ifndef Py_LL
-#define Py_LL(x) x##LL
-#endif
-
-#ifndef Py_ULL
-#define Py_ULL(x) Py_LL(x##U)
-#endif
-
-#define Py_VA_COPY va_copy
-
-/*
- * Convenient macros to deal with endianness of the platform. WORDS_BIGENDIAN is
- * detected by configure and defined in pyconfig.h. The code in pyconfig.h
- * also takes care of Apple's universal builds.
- */
-
-#ifdef WORDS_BIGENDIAN
-# define PY_BIG_ENDIAN 1
-# define PY_LITTLE_ENDIAN 0
-#else
-# define PY_BIG_ENDIAN 0
-# define PY_LITTLE_ENDIAN 1
-#endif
-
-#ifdef Py_BUILD_CORE
-/*
- * Macros to protect CRT calls against instant termination when passed an
- * invalid parameter (issue23524).
- */
-#if defined _MSC_VER && _MSC_VER >= 1900
-
-extern _invalid_parameter_handler _Py_silent_invalid_parameter_handler;
-#define _Py_BEGIN_SUPPRESS_IPH { _invalid_parameter_handler _Py_old_handler = \
- _set_thread_local_invalid_parameter_handler(_Py_silent_invalid_parameter_handler);
-#define _Py_END_SUPPRESS_IPH _set_thread_local_invalid_parameter_handler(_Py_old_handler); }
-
-#else
-
-#define _Py_BEGIN_SUPPRESS_IPH
-#define _Py_END_SUPPRESS_IPH
-
-#endif /* _MSC_VER >= 1900 */
-#endif /* Py_BUILD_CORE */
-
-#ifdef __ANDROID__
- /* The Android langinfo.h header is not used. */
-# undef HAVE_LANGINFO_H
-# undef CODESET
-#endif
-
-/* Maximum value of the Windows DWORD type */
-#define PY_DWORD_MAX 4294967295U
-
-/* This macro used to tell whether Python was built with multithreading
- * enabled. Now multithreading is always enabled, but keep the macro
- * for compatibility.
- */
-#ifndef WITH_THREAD
-# define WITH_THREAD
-#endif
-
-/* Check that ALT_SOABI is consistent with Py_TRACE_REFS:
- ./configure --with-trace-refs should must be used to define Py_TRACE_REFS */
-#if defined(ALT_SOABI) && defined(Py_TRACE_REFS)
-# error "Py_TRACE_REFS ABI is not compatible with release and debug ABI"
-#endif
-
-#if defined(__ANDROID__) || defined(__VXWORKS__)
- // Use UTF-8 as the locale encoding, ignore the LC_CTYPE locale.
- // See _Py_GetLocaleEncoding(), PyUnicode_DecodeLocale()
- // and PyUnicode_EncodeLocale().
-# define _Py_FORCE_UTF8_LOCALE
-#endif
-
-#if defined(_Py_FORCE_UTF8_LOCALE) || defined(__APPLE__)
- // Use UTF-8 as the filesystem encoding.
- // See PyUnicode_DecodeFSDefaultAndSize(), PyUnicode_EncodeFSDefault(),
- // Py_DecodeLocale() and Py_EncodeLocale().
-# define _Py_FORCE_UTF8_FS_ENCODING
-#endif
-
-/* Mark a function which cannot return. Example:
- PyAPI_FUNC(void) _Py_NO_RETURN PyThread_exit_thread(void);
-
- XLC support is intentionally omitted due to bpo-40244 */
-#ifndef _Py_NO_RETURN
-#if defined(__clang__) || \
- (defined(__GNUC__) && \
- ((__GNUC__ >= 3) || \
- (__GNUC__ == 2) && (__GNUC_MINOR__ >= 5)))
-# define _Py_NO_RETURN __attribute__((__noreturn__))
-#elif defined(_MSC_VER)
-# define _Py_NO_RETURN __declspec(noreturn)
-#else
-# define _Py_NO_RETURN
-#endif
-#endif
-
-
-// Preprocessor check for a builtin preprocessor function. Always return 0
-// if __has_builtin() macro is not defined.
-//
-// __has_builtin() is available on clang and GCC 10.
-#ifdef __has_builtin
-# define _Py__has_builtin(x) __has_builtin(x)
-#else
-# define _Py__has_builtin(x) 0
-#endif
-
-
-#endif /* Py_PYPORT_H */
diff --git a/include/python3.10/pystate.h b/include/python3.10/pystate.h
deleted file mode 100644
index bae4407..0000000
--- a/include/python3.10/pystate.h
+++ /dev/null
@@ -1,150 +0,0 @@
-/* Thread and interpreter state structures and their interfaces */
-
-
-#ifndef Py_PYSTATE_H
-#define Py_PYSTATE_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* This limitation is for performance and simplicity. If needed it can be
-removed (with effort). */
-#define MAX_CO_EXTRA_USERS 255
-
-/* Forward declarations for PyFrameObject, PyThreadState
- and PyInterpreterState */
-struct _ts;
-struct _is;
-
-/* struct _ts is defined in cpython/pystate.h */
-typedef struct _ts PyThreadState;
-/* struct _is is defined in internal/pycore_interp.h */
-typedef struct _is PyInterpreterState;
-
-PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_New(void);
-PyAPI_FUNC(void) PyInterpreterState_Clear(PyInterpreterState *);
-PyAPI_FUNC(void) PyInterpreterState_Delete(PyInterpreterState *);
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03090000
-/* New in 3.9 */
-/* Get the current interpreter state.
-
- Issue a fatal error if there no current Python thread state or no current
- interpreter. It cannot return NULL.
-
- The caller must hold the GIL. */
-PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Get(void);
-#endif
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03080000
-/* New in 3.8 */
-PyAPI_FUNC(PyObject *) PyInterpreterState_GetDict(PyInterpreterState *);
-#endif
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03070000
-/* New in 3.7 */
-PyAPI_FUNC(int64_t) PyInterpreterState_GetID(PyInterpreterState *);
-#endif
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-
-/* State unique per thread */
-
-/* New in 3.3 */
-PyAPI_FUNC(int) PyState_AddModule(PyObject*, struct PyModuleDef*);
-PyAPI_FUNC(int) PyState_RemoveModule(struct PyModuleDef*);
-#endif
-PyAPI_FUNC(PyObject*) PyState_FindModule(struct PyModuleDef*);
-
-PyAPI_FUNC(PyThreadState *) PyThreadState_New(PyInterpreterState *);
-PyAPI_FUNC(void) PyThreadState_Clear(PyThreadState *);
-PyAPI_FUNC(void) PyThreadState_Delete(PyThreadState *);
-
-/* Get the current thread state.
-
- When the current thread state is NULL, this issues a fatal error (so that
- the caller needn't check for NULL).
-
- The caller must hold the GIL.
-
- See also PyThreadState_GET() and _PyThreadState_GET(). */
-PyAPI_FUNC(PyThreadState *) PyThreadState_Get(void);
-
-/* Get the current Python thread state.
-
- Macro using PyThreadState_Get() or _PyThreadState_GET() depending if
- pycore_pystate.h is included or not (this header redefines the macro).
-
- If PyThreadState_Get() is used, issue a fatal error if the current thread
- state is NULL.
-
- See also PyThreadState_Get() and _PyThreadState_GET(). */
-#define PyThreadState_GET() PyThreadState_Get()
-
-PyAPI_FUNC(PyThreadState *) PyThreadState_Swap(PyThreadState *);
-PyAPI_FUNC(PyObject *) PyThreadState_GetDict(void);
-PyAPI_FUNC(int) PyThreadState_SetAsyncExc(unsigned long, PyObject *);
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03090000
-/* New in 3.9 */
-PyAPI_FUNC(PyInterpreterState*) PyThreadState_GetInterpreter(PyThreadState *tstate);
-PyAPI_FUNC(PyFrameObject*) PyThreadState_GetFrame(PyThreadState *tstate);
-PyAPI_FUNC(uint64_t) PyThreadState_GetID(PyThreadState *tstate);
-#endif
-
-typedef
- enum {PyGILState_LOCKED, PyGILState_UNLOCKED}
- PyGILState_STATE;
-
-
-/* Ensure that the current thread is ready to call the Python
- C API, regardless of the current state of Python, or of its
- thread lock. This may be called as many times as desired
- by a thread so long as each call is matched with a call to
- PyGILState_Release(). In general, other thread-state APIs may
- be used between _Ensure() and _Release() calls, so long as the
- thread-state is restored to its previous state before the Release().
- For example, normal use of the Py_BEGIN_ALLOW_THREADS/
- Py_END_ALLOW_THREADS macros are acceptable.
-
- The return value is an opaque "handle" to the thread state when
- PyGILState_Ensure() was called, and must be passed to
- PyGILState_Release() to ensure Python is left in the same state. Even
- though recursive calls are allowed, these handles can *not* be shared -
- each unique call to PyGILState_Ensure must save the handle for its
- call to PyGILState_Release.
-
- When the function returns, the current thread will hold the GIL.
-
- Failure is a fatal error.
-*/
-PyAPI_FUNC(PyGILState_STATE) PyGILState_Ensure(void);
-
-/* Release any resources previously acquired. After this call, Python's
- state will be the same as it was prior to the corresponding
- PyGILState_Ensure() call (but generally this state will be unknown to
- the caller, hence the use of the GILState API.)
-
- Every call to PyGILState_Ensure must be matched by a call to
- PyGILState_Release on the same thread.
-*/
-PyAPI_FUNC(void) PyGILState_Release(PyGILState_STATE);
-
-/* Helper/diagnostic function - get the current thread state for
- this thread. May return NULL if no GILState API has been used
- on the current thread. Note that the main thread always has such a
- thread-state, even if no auto-thread-state call has been made
- on the main thread.
-*/
-PyAPI_FUNC(PyThreadState *) PyGILState_GetThisThreadState(void);
-
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_PYSTATE_H
-# include "cpython/pystate.h"
-# undef Py_CPYTHON_PYSTATE_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_PYSTATE_H */
diff --git a/include/python3.10/pystrhex.h b/include/python3.10/pystrhex.h
deleted file mode 100644
index a4f3630..0000000
--- a/include/python3.10/pystrhex.h
+++ /dev/null
@@ -1,22 +0,0 @@
-#ifndef Py_STRHEX_H
-#define Py_STRHEX_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_LIMITED_API
-/* Returns a str() containing the hex representation of argbuf. */
-PyAPI_FUNC(PyObject*) _Py_strhex(const char* argbuf, const Py_ssize_t arglen);
-/* Returns a bytes() containing the ASCII hex representation of argbuf. */
-PyAPI_FUNC(PyObject*) _Py_strhex_bytes(const char* argbuf, const Py_ssize_t arglen);
-/* These variants include support for a separator between every N bytes: */
-PyAPI_FUNC(PyObject*) _Py_strhex_with_sep(const char* argbuf, const Py_ssize_t arglen, const PyObject* sep, const int bytes_per_group);
-PyAPI_FUNC(PyObject*) _Py_strhex_bytes_with_sep(const char* argbuf, const Py_ssize_t arglen, const PyObject* sep, const int bytes_per_group);
-#endif /* !Py_LIMITED_API */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* !Py_STRHEX_H */
diff --git a/include/python3.10/pystrtod.h b/include/python3.10/pystrtod.h
deleted file mode 100644
index c1e84de..0000000
--- a/include/python3.10/pystrtod.h
+++ /dev/null
@@ -1,45 +0,0 @@
-#ifndef Py_STRTOD_H
-#define Py_STRTOD_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-PyAPI_FUNC(double) PyOS_string_to_double(const char *str,
- char **endptr,
- PyObject *overflow_exception);
-
-/* The caller is responsible for calling PyMem_Free to free the buffer
- that's is returned. */
-PyAPI_FUNC(char *) PyOS_double_to_string(double val,
- char format_code,
- int precision,
- int flags,
- int *type);
-
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(PyObject *) _Py_string_to_number_with_underscores(
- const char *str, Py_ssize_t len, const char *what, PyObject *obj, void *arg,
- PyObject *(*innerfunc)(const char *, Py_ssize_t, void *));
-
-PyAPI_FUNC(double) _Py_parse_inf_or_nan(const char *p, char **endptr);
-#endif
-
-
-/* PyOS_double_to_string's "flags" parameter can be set to 0 or more of: */
-#define Py_DTSF_SIGN 0x01 /* always add the sign */
-#define Py_DTSF_ADD_DOT_0 0x02 /* if the result is an integer add ".0" */
-#define Py_DTSF_ALT 0x04 /* "alternate" formatting. it's format_code
- specific */
-
-/* PyOS_double_to_string's "type", if non-NULL, will be set to one of: */
-#define Py_DTST_FINITE 0
-#define Py_DTST_INFINITE 1
-#define Py_DTST_NAN 2
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* !Py_STRTOD_H */
diff --git a/include/python3.10/pythonrun.h b/include/python3.10/pythonrun.h
deleted file mode 100644
index b0a2fc3..0000000
--- a/include/python3.10/pythonrun.h
+++ /dev/null
@@ -1,44 +0,0 @@
-
-/* Interfaces to parse and execute pieces of python code */
-
-#ifndef Py_PYTHONRUN_H
-#define Py_PYTHONRUN_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-PyAPI_FUNC(PyObject *) Py_CompileString(const char *, const char *, int);
-
-PyAPI_FUNC(void) PyErr_Print(void);
-PyAPI_FUNC(void) PyErr_PrintEx(int);
-PyAPI_FUNC(void) PyErr_Display(PyObject *, PyObject *, PyObject *);
-
-
-/* Stuff with no proper home (yet) */
-PyAPI_DATA(int) (*PyOS_InputHook)(void);
-
-/* Stack size, in "pointers" (so we get extra safety margins
- on 64-bit platforms). On a 32-bit platform, this translates
- to an 8k margin. */
-#define PYOS_STACK_MARGIN 2048
-
-#if defined(WIN32) && !defined(MS_WIN64) && !defined(_M_ARM) && defined(_MSC_VER) && _MSC_VER >= 1300
-/* Enable stack checking under Microsoft C */
-#define USE_STACKCHECK
-#endif
-
-#ifdef USE_STACKCHECK
-/* Check that we aren't overflowing our stack */
-PyAPI_FUNC(int) PyOS_CheckStack(void);
-#endif
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_PYTHONRUN_H
-# include "cpython/pythonrun.h"
-# undef Py_CPYTHON_PYTHONRUN_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_PYTHONRUN_H */
diff --git a/include/python3.10/pythread.h b/include/python3.10/pythread.h
deleted file mode 100644
index bb9d864..0000000
--- a/include/python3.10/pythread.h
+++ /dev/null
@@ -1,169 +0,0 @@
-
-#ifndef Py_PYTHREAD_H
-#define Py_PYTHREAD_H
-
-typedef void *PyThread_type_lock;
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Return status codes for Python lock acquisition. Chosen for maximum
- * backwards compatibility, ie failure -> 0, success -> 1. */
-typedef enum PyLockStatus {
- PY_LOCK_FAILURE = 0,
- PY_LOCK_ACQUIRED = 1,
- PY_LOCK_INTR
-} PyLockStatus;
-
-#ifndef Py_LIMITED_API
-#define PYTHREAD_INVALID_THREAD_ID ((unsigned long)-1)
-#endif
-
-PyAPI_FUNC(void) PyThread_init_thread(void);
-PyAPI_FUNC(unsigned long) PyThread_start_new_thread(void (*)(void *), void *);
-PyAPI_FUNC(void) _Py_NO_RETURN PyThread_exit_thread(void);
-PyAPI_FUNC(unsigned long) PyThread_get_thread_ident(void);
-
-#if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(_WIN32) || defined(_AIX)
-#define PY_HAVE_THREAD_NATIVE_ID
-PyAPI_FUNC(unsigned long) PyThread_get_thread_native_id(void);
-#endif
-
-PyAPI_FUNC(PyThread_type_lock) PyThread_allocate_lock(void);
-PyAPI_FUNC(void) PyThread_free_lock(PyThread_type_lock);
-PyAPI_FUNC(int) PyThread_acquire_lock(PyThread_type_lock, int);
-#define WAIT_LOCK 1
-#define NOWAIT_LOCK 0
-
-#ifndef Py_LIMITED_API
-#ifdef HAVE_FORK
-/* Private function to reinitialize a lock at fork in the child process.
- Reset the lock to the unlocked state.
- Return 0 on success, return -1 on error. */
-PyAPI_FUNC(int) _PyThread_at_fork_reinit(PyThread_type_lock *lock);
-#endif /* HAVE_FORK */
-#endif /* !Py_LIMITED_API */
-
-/* PY_TIMEOUT_T is the integral type used to specify timeouts when waiting
- on a lock (see PyThread_acquire_lock_timed() below).
- PY_TIMEOUT_MAX is the highest usable value (in microseconds) of that
- type, and depends on the system threading API.
-
- NOTE: this isn't the same value as `_thread.TIMEOUT_MAX`. The _thread
- module exposes a higher-level API, with timeouts expressed in seconds
- and floating-point numbers allowed.
-*/
-#define PY_TIMEOUT_T long long
-
-#if defined(_POSIX_THREADS)
- /* PyThread_acquire_lock_timed() uses _PyTime_FromNanoseconds(us * 1000),
- convert microseconds to nanoseconds. */
-# define PY_TIMEOUT_MAX (LLONG_MAX / 1000)
-#elif defined (NT_THREADS)
- /* In the NT API, the timeout is a DWORD and is expressed in milliseconds */
-# if 0xFFFFFFFFLL * 1000 < LLONG_MAX
-# define PY_TIMEOUT_MAX (0xFFFFFFFFLL * 1000)
-# else
-# define PY_TIMEOUT_MAX LLONG_MAX
-# endif
-#else
-# define PY_TIMEOUT_MAX LLONG_MAX
-#endif
-
-
-/* If microseconds == 0, the call is non-blocking: it returns immediately
- even when the lock can't be acquired.
- If microseconds > 0, the call waits up to the specified duration.
- If microseconds < 0, the call waits until success (or abnormal failure)
-
- microseconds must be less than PY_TIMEOUT_MAX. Behaviour otherwise is
- undefined.
-
- If intr_flag is true and the acquire is interrupted by a signal, then the
- call will return PY_LOCK_INTR. The caller may reattempt to acquire the
- lock.
-*/
-PyAPI_FUNC(PyLockStatus) PyThread_acquire_lock_timed(PyThread_type_lock,
- PY_TIMEOUT_T microseconds,
- int intr_flag);
-
-PyAPI_FUNC(void) PyThread_release_lock(PyThread_type_lock);
-
-PyAPI_FUNC(size_t) PyThread_get_stacksize(void);
-PyAPI_FUNC(int) PyThread_set_stacksize(size_t);
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-PyAPI_FUNC(PyObject*) PyThread_GetInfo(void);
-#endif
-
-
-/* Thread Local Storage (TLS) API
- TLS API is DEPRECATED. Use Thread Specific Storage (TSS) API.
-
- The existing TLS API has used int to represent TLS keys across all
- platforms, but it is not POSIX-compliant. Therefore, the new TSS API uses
- opaque data type to represent TSS keys to be compatible (see PEP 539).
-*/
-Py_DEPRECATED(3.7) PyAPI_FUNC(int) PyThread_create_key(void);
-Py_DEPRECATED(3.7) PyAPI_FUNC(void) PyThread_delete_key(int key);
-Py_DEPRECATED(3.7) PyAPI_FUNC(int) PyThread_set_key_value(int key,
- void *value);
-Py_DEPRECATED(3.7) PyAPI_FUNC(void *) PyThread_get_key_value(int key);
-Py_DEPRECATED(3.7) PyAPI_FUNC(void) PyThread_delete_key_value(int key);
-
-/* Cleanup after a fork */
-Py_DEPRECATED(3.7) PyAPI_FUNC(void) PyThread_ReInitTLS(void);
-
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03070000
-/* New in 3.7 */
-/* Thread Specific Storage (TSS) API */
-
-typedef struct _Py_tss_t Py_tss_t; /* opaque */
-
-#ifndef Py_LIMITED_API
-#if defined(_POSIX_THREADS)
- /* Darwin needs pthread.h to know type name the pthread_key_t. */
-# include <pthread.h>
-# define NATIVE_TSS_KEY_T pthread_key_t
-#elif defined(NT_THREADS)
- /* In Windows, native TSS key type is DWORD,
- but hardcode the unsigned long to avoid errors for include directive.
- */
-# define NATIVE_TSS_KEY_T unsigned long
-#else
-# error "Require native threads. See https://bugs.python.org/issue31370"
-#endif
-
-/* When Py_LIMITED_API is not defined, the type layout of Py_tss_t is
- exposed to allow static allocation in the API clients. Even in this case,
- you must handle TSS keys through API functions due to compatibility.
-*/
-struct _Py_tss_t {
- int _is_initialized;
- NATIVE_TSS_KEY_T _key;
-};
-
-#undef NATIVE_TSS_KEY_T
-
-/* When static allocation, you must initialize with Py_tss_NEEDS_INIT. */
-#define Py_tss_NEEDS_INIT {0}
-#endif /* !Py_LIMITED_API */
-
-PyAPI_FUNC(Py_tss_t *) PyThread_tss_alloc(void);
-PyAPI_FUNC(void) PyThread_tss_free(Py_tss_t *key);
-
-/* The parameter key must not be NULL. */
-PyAPI_FUNC(int) PyThread_tss_is_created(Py_tss_t *key);
-PyAPI_FUNC(int) PyThread_tss_create(Py_tss_t *key);
-PyAPI_FUNC(void) PyThread_tss_delete(Py_tss_t *key);
-PyAPI_FUNC(int) PyThread_tss_set(Py_tss_t *key, void *value);
-PyAPI_FUNC(void *) PyThread_tss_get(Py_tss_t *key);
-#endif /* New in 3.7 */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* !Py_PYTHREAD_H */
diff --git a/include/python3.10/setobject.h b/include/python3.10/setobject.h
deleted file mode 100644
index 62516be..0000000
--- a/include/python3.10/setobject.h
+++ /dev/null
@@ -1,110 +0,0 @@
-/* Set object interface */
-
-#ifndef Py_SETOBJECT_H
-#define Py_SETOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_LIMITED_API
-
-/* There are three kinds of entries in the table:
-
-1. Unused: key == NULL and hash == 0
-2. Dummy: key == dummy and hash == -1
-3. Active: key != NULL and key != dummy and hash != -1
-
-The hash field of Unused slots is always zero.
-
-The hash field of Dummy slots are set to -1
-meaning that dummy entries can be detected by
-either entry->key==dummy or by entry->hash==-1.
-*/
-
-#define PySet_MINSIZE 8
-
-typedef struct {
- PyObject *key;
- Py_hash_t hash; /* Cached hash code of the key */
-} setentry;
-
-/* The SetObject data structure is shared by set and frozenset objects.
-
-Invariant for sets:
- - hash is -1
-
-Invariants for frozensets:
- - data is immutable.
- - hash is the hash of the frozenset or -1 if not computed yet.
-
-*/
-
-typedef struct {
- PyObject_HEAD
-
- Py_ssize_t fill; /* Number active and dummy entries*/
- Py_ssize_t used; /* Number active entries */
-
- /* The table contains mask + 1 slots, and that's a power of 2.
- * We store the mask instead of the size because the mask is more
- * frequently needed.
- */
- Py_ssize_t mask;
-
- /* The table points to a fixed-size smalltable for small tables
- * or to additional malloc'ed memory for bigger tables.
- * The table pointer is never NULL which saves us from repeated
- * runtime null-tests.
- */
- setentry *table;
- Py_hash_t hash; /* Only used by frozenset objects */
- Py_ssize_t finger; /* Search finger for pop() */
-
- setentry smalltable[PySet_MINSIZE];
- PyObject *weakreflist; /* List of weak references */
-} PySetObject;
-
-#define PySet_GET_SIZE(so) (assert(PyAnySet_Check(so)),(((PySetObject *)(so))->used))
-
-PyAPI_DATA(PyObject *) _PySet_Dummy;
-
-PyAPI_FUNC(int) _PySet_NextEntry(PyObject *set, Py_ssize_t *pos, PyObject **key, Py_hash_t *hash);
-PyAPI_FUNC(int) _PySet_Update(PyObject *set, PyObject *iterable);
-
-#endif /* Section excluded by Py_LIMITED_API */
-
-PyAPI_DATA(PyTypeObject) PySet_Type;
-PyAPI_DATA(PyTypeObject) PyFrozenSet_Type;
-PyAPI_DATA(PyTypeObject) PySetIter_Type;
-
-PyAPI_FUNC(PyObject *) PySet_New(PyObject *);
-PyAPI_FUNC(PyObject *) PyFrozenSet_New(PyObject *);
-
-PyAPI_FUNC(int) PySet_Add(PyObject *set, PyObject *key);
-PyAPI_FUNC(int) PySet_Clear(PyObject *set);
-PyAPI_FUNC(int) PySet_Contains(PyObject *anyset, PyObject *key);
-PyAPI_FUNC(int) PySet_Discard(PyObject *set, PyObject *key);
-PyAPI_FUNC(PyObject *) PySet_Pop(PyObject *set);
-PyAPI_FUNC(Py_ssize_t) PySet_Size(PyObject *anyset);
-
-#define PyFrozenSet_CheckExact(ob) Py_IS_TYPE(ob, &PyFrozenSet_Type)
-#define PyFrozenSet_Check(ob) \
- (Py_IS_TYPE(ob, &PyFrozenSet_Type) || \
- PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type))
-
-#define PyAnySet_CheckExact(ob) \
- (Py_IS_TYPE(ob, &PySet_Type) || Py_IS_TYPE(ob, &PyFrozenSet_Type))
-#define PyAnySet_Check(ob) \
- (Py_IS_TYPE(ob, &PySet_Type) || Py_IS_TYPE(ob, &PyFrozenSet_Type) || \
- PyType_IsSubtype(Py_TYPE(ob), &PySet_Type) || \
- PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type))
-
-#define PySet_CheckExact(op) Py_IS_TYPE(op, &PySet_Type)
-#define PySet_Check(ob) \
- (Py_IS_TYPE(ob, &PySet_Type) || \
- PyType_IsSubtype(Py_TYPE(ob), &PySet_Type))
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_SETOBJECT_H */
diff --git a/include/python3.10/structmember.h b/include/python3.10/structmember.h
deleted file mode 100644
index 93b7aff..0000000
--- a/include/python3.10/structmember.h
+++ /dev/null
@@ -1,75 +0,0 @@
-#ifndef Py_STRUCTMEMBER_H
-#define Py_STRUCTMEMBER_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-/* Interface to map C struct members to Python object attributes */
-
-#include <stddef.h> /* For offsetof */
-
-/* An array of PyMemberDef structures defines the name, type and offset
- of selected members of a C structure. These can be read by
- PyMember_GetOne() and set by PyMember_SetOne() (except if their READONLY
- flag is set). The array must be terminated with an entry whose name
- pointer is NULL. */
-
-typedef struct PyMemberDef {
- const char *name;
- int type;
- Py_ssize_t offset;
- int flags;
- const char *doc;
-} PyMemberDef;
-
-/* Types */
-#define T_SHORT 0
-#define T_INT 1
-#define T_LONG 2
-#define T_FLOAT 3
-#define T_DOUBLE 4
-#define T_STRING 5
-#define T_OBJECT 6
-/* XXX the ordering here is weird for binary compatibility */
-#define T_CHAR 7 /* 1-character string */
-#define T_BYTE 8 /* 8-bit signed int */
-/* unsigned variants: */
-#define T_UBYTE 9
-#define T_USHORT 10
-#define T_UINT 11
-#define T_ULONG 12
-
-/* Added by Jack: strings contained in the structure */
-#define T_STRING_INPLACE 13
-
-/* Added by Lillo: bools contained in the structure (assumed char) */
-#define T_BOOL 14
-
-#define T_OBJECT_EX 16 /* Like T_OBJECT, but raises AttributeError
- when the value is NULL, instead of
- converting to None. */
-#define T_LONGLONG 17
-#define T_ULONGLONG 18
-
-#define T_PYSSIZET 19 /* Py_ssize_t */
-#define T_NONE 20 /* Value is always None */
-
-
-/* Flags */
-#define READONLY 1
-#define READ_RESTRICTED 2
-#define PY_WRITE_RESTRICTED 4
-#define RESTRICTED (READ_RESTRICTED | PY_WRITE_RESTRICTED)
-
-#define PY_AUDIT_READ READ_RESTRICTED
-
-/* Current API, use this */
-PyAPI_FUNC(PyObject *) PyMember_GetOne(const char *, struct PyMemberDef *);
-PyAPI_FUNC(int) PyMember_SetOne(char *, struct PyMemberDef *, PyObject *);
-
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_STRUCTMEMBER_H */
diff --git a/include/python3.10/structseq.h b/include/python3.10/structseq.h
deleted file mode 100644
index 8f51c89..0000000
--- a/include/python3.10/structseq.h
+++ /dev/null
@@ -1,49 +0,0 @@
-
-/* Named tuple object interface */
-
-#ifndef Py_STRUCTSEQ_H
-#define Py_STRUCTSEQ_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef struct PyStructSequence_Field {
- const char *name;
- const char *doc;
-} PyStructSequence_Field;
-
-typedef struct PyStructSequence_Desc {
- const char *name;
- const char *doc;
- struct PyStructSequence_Field *fields;
- int n_in_sequence;
-} PyStructSequence_Desc;
-
-extern const char * const PyStructSequence_UnnamedField;
-
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(void) PyStructSequence_InitType(PyTypeObject *type,
- PyStructSequence_Desc *desc);
-PyAPI_FUNC(int) PyStructSequence_InitType2(PyTypeObject *type,
- PyStructSequence_Desc *desc);
-#endif
-PyAPI_FUNC(PyTypeObject*) PyStructSequence_NewType(PyStructSequence_Desc *desc);
-
-PyAPI_FUNC(PyObject *) PyStructSequence_New(PyTypeObject* type);
-
-#ifndef Py_LIMITED_API
-typedef PyTupleObject PyStructSequence;
-
-/* Macro, *only* to be used to fill in brand new objects */
-#define PyStructSequence_SET_ITEM(op, i, v) PyTuple_SET_ITEM(op, i, v)
-
-#define PyStructSequence_GET_ITEM(op, i) PyTuple_GET_ITEM(op, i)
-#endif
-
-PyAPI_FUNC(void) PyStructSequence_SetItem(PyObject*, Py_ssize_t, PyObject*);
-PyAPI_FUNC(PyObject*) PyStructSequence_GetItem(PyObject*, Py_ssize_t);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_STRUCTSEQ_H */
diff --git a/include/python3.10/sysmodule.h b/include/python3.10/sysmodule.h
deleted file mode 100644
index 670e5d2..0000000
--- a/include/python3.10/sysmodule.h
+++ /dev/null
@@ -1,41 +0,0 @@
-
-/* System module interface */
-
-#ifndef Py_SYSMODULE_H
-#define Py_SYSMODULE_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-PyAPI_FUNC(PyObject *) PySys_GetObject(const char *);
-PyAPI_FUNC(int) PySys_SetObject(const char *, PyObject *);
-
-PyAPI_FUNC(void) PySys_SetArgv(int, wchar_t **);
-PyAPI_FUNC(void) PySys_SetArgvEx(int, wchar_t **, int);
-PyAPI_FUNC(void) PySys_SetPath(const wchar_t *);
-
-PyAPI_FUNC(void) PySys_WriteStdout(const char *format, ...)
- Py_GCC_ATTRIBUTE((format(printf, 1, 2)));
-PyAPI_FUNC(void) PySys_WriteStderr(const char *format, ...)
- Py_GCC_ATTRIBUTE((format(printf, 1, 2)));
-PyAPI_FUNC(void) PySys_FormatStdout(const char *format, ...);
-PyAPI_FUNC(void) PySys_FormatStderr(const char *format, ...);
-
-PyAPI_FUNC(void) PySys_ResetWarnOptions(void);
-PyAPI_FUNC(void) PySys_AddWarnOption(const wchar_t *);
-PyAPI_FUNC(void) PySys_AddWarnOptionUnicode(PyObject *);
-PyAPI_FUNC(int) PySys_HasWarnOptions(void);
-
-PyAPI_FUNC(void) PySys_AddXOption(const wchar_t *);
-PyAPI_FUNC(PyObject *) PySys_GetXOptions(void);
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_SYSMODULE_H
-# include "cpython/sysmodule.h"
-# undef Py_CPYTHON_SYSMODULE_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_SYSMODULE_H */
diff --git a/include/python3.10/traceback.h b/include/python3.10/traceback.h
deleted file mode 100644
index 781e5a6..0000000
--- a/include/python3.10/traceback.h
+++ /dev/null
@@ -1,26 +0,0 @@
-#ifndef Py_TRACEBACK_H
-#define Py_TRACEBACK_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Traceback interface */
-
-PyAPI_FUNC(int) PyTraceBack_Here(PyFrameObject *);
-PyAPI_FUNC(int) PyTraceBack_Print(PyObject *, PyObject *);
-
-/* Reveal traceback type so we can typecheck traceback objects */
-PyAPI_DATA(PyTypeObject) PyTraceBack_Type;
-#define PyTraceBack_Check(v) Py_IS_TYPE(v, &PyTraceBack_Type)
-
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_TRACEBACK_H
-# include "cpython/traceback.h"
-# undef Py_CPYTHON_TRACEBACK_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_TRACEBACK_H */
diff --git a/include/python3.10/tupleobject.h b/include/python3.10/tupleobject.h
deleted file mode 100644
index e796a32..0000000
--- a/include/python3.10/tupleobject.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/* Tuple object interface */
-
-#ifndef Py_TUPLEOBJECT_H
-#define Py_TUPLEOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
-Another generally useful object type is a tuple of object pointers.
-For Python, this is an immutable type. C code can change the tuple items
-(but not their number), and even use tuples as general-purpose arrays of
-object references, but in general only brand new tuples should be mutated,
-not ones that might already have been exposed to Python code.
-
-*** WARNING *** PyTuple_SetItem does not increment the new item's reference
-count, but does decrement the reference count of the item it replaces,
-if not nil. It does *decrement* the reference count if it is *not*
-inserted in the tuple. Similarly, PyTuple_GetItem does not increment the
-returned item's reference count.
-*/
-
-PyAPI_DATA(PyTypeObject) PyTuple_Type;
-PyAPI_DATA(PyTypeObject) PyTupleIter_Type;
-
-#define PyTuple_Check(op) \
- PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TUPLE_SUBCLASS)
-#define PyTuple_CheckExact(op) Py_IS_TYPE(op, &PyTuple_Type)
-
-PyAPI_FUNC(PyObject *) PyTuple_New(Py_ssize_t size);
-PyAPI_FUNC(Py_ssize_t) PyTuple_Size(PyObject *);
-PyAPI_FUNC(PyObject *) PyTuple_GetItem(PyObject *, Py_ssize_t);
-PyAPI_FUNC(int) PyTuple_SetItem(PyObject *, Py_ssize_t, PyObject *);
-PyAPI_FUNC(PyObject *) PyTuple_GetSlice(PyObject *, Py_ssize_t, Py_ssize_t);
-PyAPI_FUNC(PyObject *) PyTuple_Pack(Py_ssize_t, ...);
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_TUPLEOBJECT_H
-# include "cpython/tupleobject.h"
-# undef Py_CPYTHON_TUPLEOBJECT_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_TUPLEOBJECT_H */
diff --git a/include/python3.10/typeslots.h b/include/python3.10/typeslots.h
deleted file mode 100644
index 5800d01..0000000
--- a/include/python3.10/typeslots.h
+++ /dev/null
@@ -1,94 +0,0 @@
-/* Do not renumber the file; these numbers are part of the stable ABI. */
-#if defined(Py_LIMITED_API)
-/* Disabled, see #10181 */
-#undef Py_bf_getbuffer
-#undef Py_bf_releasebuffer
-#else
-#define Py_bf_getbuffer 1
-#define Py_bf_releasebuffer 2
-#endif
-#define Py_mp_ass_subscript 3
-#define Py_mp_length 4
-#define Py_mp_subscript 5
-#define Py_nb_absolute 6
-#define Py_nb_add 7
-#define Py_nb_and 8
-#define Py_nb_bool 9
-#define Py_nb_divmod 10
-#define Py_nb_float 11
-#define Py_nb_floor_divide 12
-#define Py_nb_index 13
-#define Py_nb_inplace_add 14
-#define Py_nb_inplace_and 15
-#define Py_nb_inplace_floor_divide 16
-#define Py_nb_inplace_lshift 17
-#define Py_nb_inplace_multiply 18
-#define Py_nb_inplace_or 19
-#define Py_nb_inplace_power 20
-#define Py_nb_inplace_remainder 21
-#define Py_nb_inplace_rshift 22
-#define Py_nb_inplace_subtract 23
-#define Py_nb_inplace_true_divide 24
-#define Py_nb_inplace_xor 25
-#define Py_nb_int 26
-#define Py_nb_invert 27
-#define Py_nb_lshift 28
-#define Py_nb_multiply 29
-#define Py_nb_negative 30
-#define Py_nb_or 31
-#define Py_nb_positive 32
-#define Py_nb_power 33
-#define Py_nb_remainder 34
-#define Py_nb_rshift 35
-#define Py_nb_subtract 36
-#define Py_nb_true_divide 37
-#define Py_nb_xor 38
-#define Py_sq_ass_item 39
-#define Py_sq_concat 40
-#define Py_sq_contains 41
-#define Py_sq_inplace_concat 42
-#define Py_sq_inplace_repeat 43
-#define Py_sq_item 44
-#define Py_sq_length 45
-#define Py_sq_repeat 46
-#define Py_tp_alloc 47
-#define Py_tp_base 48
-#define Py_tp_bases 49
-#define Py_tp_call 50
-#define Py_tp_clear 51
-#define Py_tp_dealloc 52
-#define Py_tp_del 53
-#define Py_tp_descr_get 54
-#define Py_tp_descr_set 55
-#define Py_tp_doc 56
-#define Py_tp_getattr 57
-#define Py_tp_getattro 58
-#define Py_tp_hash 59
-#define Py_tp_init 60
-#define Py_tp_is_gc 61
-#define Py_tp_iter 62
-#define Py_tp_iternext 63
-#define Py_tp_methods 64
-#define Py_tp_new 65
-#define Py_tp_repr 66
-#define Py_tp_richcompare 67
-#define Py_tp_setattr 68
-#define Py_tp_setattro 69
-#define Py_tp_str 70
-#define Py_tp_traverse 71
-#define Py_tp_members 72
-#define Py_tp_getset 73
-#define Py_tp_free 74
-#define Py_nb_matrix_multiply 75
-#define Py_nb_inplace_matrix_multiply 76
-#define Py_am_await 77
-#define Py_am_aiter 78
-#define Py_am_anext 79
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
-/* New in 3.5 */
-#define Py_tp_finalize 80
-#endif
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000
-/* New in 3.10 */
-#define Py_am_send 81
-#endif
diff --git a/include/python3.10/unicodeobject.h b/include/python3.10/unicodeobject.h
deleted file mode 100644
index b0ac086..0000000
--- a/include/python3.10/unicodeobject.h
+++ /dev/null
@@ -1,1053 +0,0 @@
-#ifndef Py_UNICODEOBJECT_H
-#define Py_UNICODEOBJECT_H
-
-#include <stdarg.h>
-
-/*
-
-Unicode implementation based on original code by Fredrik Lundh,
-modified by Marc-Andre Lemburg (mal@lemburg.com) according to the
-Unicode Integration Proposal. (See
-http://www.egenix.com/files/python/unicode-proposal.txt).
-
-Copyright (c) Corporation for National Research Initiatives.
-
-
- Original header:
- --------------------------------------------------------------------
-
- * Yet another Unicode string type for Python. This type supports the
- * 16-bit Basic Multilingual Plane (BMP) only.
- *
- * Written by Fredrik Lundh, January 1999.
- *
- * Copyright (c) 1999 by Secret Labs AB.
- * Copyright (c) 1999 by Fredrik Lundh.
- *
- * fredrik@pythonware.com
- * http://www.pythonware.com
- *
- * --------------------------------------------------------------------
- * This Unicode String Type 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.
- * -------------------------------------------------------------------- */
-
-#include <ctype.h>
-
-/* === Internal API ======================================================= */
-
-/* --- Internal Unicode Format -------------------------------------------- */
-
-/* Python 3.x requires unicode */
-#define Py_USING_UNICODE
-
-#ifndef SIZEOF_WCHAR_T
-#error Must define SIZEOF_WCHAR_T
-#endif
-
-#define Py_UNICODE_SIZE SIZEOF_WCHAR_T
-
-/* If wchar_t can be used for UCS-4 storage, set Py_UNICODE_WIDE.
- Otherwise, Unicode strings are stored as UCS-2 (with limited support
- for UTF-16) */
-
-#if Py_UNICODE_SIZE >= 4
-#define Py_UNICODE_WIDE
-#endif
-
-/* Set these flags if the platform has "wchar.h" and the
- wchar_t type is a 16-bit unsigned type */
-/* #define HAVE_WCHAR_H */
-/* #define HAVE_USABLE_WCHAR_T */
-
-/* If the compiler provides a wchar_t type we try to support it
- through the interface functions PyUnicode_FromWideChar(),
- PyUnicode_AsWideChar() and PyUnicode_AsWideCharString(). */
-
-#ifdef HAVE_USABLE_WCHAR_T
-# ifndef HAVE_WCHAR_H
-# define HAVE_WCHAR_H
-# endif
-#endif
-
-#ifdef HAVE_WCHAR_H
-# include <wchar.h>
-#endif
-
-/* Py_UCS4 and Py_UCS2 are typedefs for the respective
- unicode representations. */
-typedef uint32_t Py_UCS4;
-typedef uint16_t Py_UCS2;
-typedef uint8_t Py_UCS1;
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-PyAPI_DATA(PyTypeObject) PyUnicode_Type;
-PyAPI_DATA(PyTypeObject) PyUnicodeIter_Type;
-
-#define PyUnicode_Check(op) \
- PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_UNICODE_SUBCLASS)
-#define PyUnicode_CheckExact(op) Py_IS_TYPE(op, &PyUnicode_Type)
-
-/* --- Constants ---------------------------------------------------------- */
-
-/* This Unicode character will be used as replacement character during
- decoding if the errors argument is set to "replace". Note: the
- Unicode character U+FFFD is the official REPLACEMENT CHARACTER in
- Unicode 3.0. */
-
-#define Py_UNICODE_REPLACEMENT_CHARACTER ((Py_UCS4) 0xFFFD)
-
-/* === Public API ========================================================= */
-
-/* Similar to PyUnicode_FromUnicode(), but u points to UTF-8 encoded bytes */
-PyAPI_FUNC(PyObject*) PyUnicode_FromStringAndSize(
- const char *u, /* UTF-8 encoded string */
- Py_ssize_t size /* size of buffer */
- );
-
-/* Similar to PyUnicode_FromUnicode(), but u points to null-terminated
- UTF-8 encoded bytes. The size is determined with strlen(). */
-PyAPI_FUNC(PyObject*) PyUnicode_FromString(
- const char *u /* UTF-8 encoded string */
- );
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-PyAPI_FUNC(PyObject*) PyUnicode_Substring(
- PyObject *str,
- Py_ssize_t start,
- Py_ssize_t end);
-#endif
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-/* Copy the string into a UCS4 buffer including the null character if copy_null
- is set. Return NULL and raise an exception on error. Raise a SystemError if
- the buffer is smaller than the string. Return buffer on success.
-
- buflen is the length of the buffer in (Py_UCS4) characters. */
-PyAPI_FUNC(Py_UCS4*) PyUnicode_AsUCS4(
- PyObject *unicode,
- Py_UCS4* buffer,
- Py_ssize_t buflen,
- int copy_null);
-
-/* Copy the string into a UCS4 buffer. A new buffer is allocated using
- * PyMem_Malloc; if this fails, NULL is returned with a memory error
- exception set. */
-PyAPI_FUNC(Py_UCS4*) PyUnicode_AsUCS4Copy(PyObject *unicode);
-#endif
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-/* Get the length of the Unicode object. */
-
-PyAPI_FUNC(Py_ssize_t) PyUnicode_GetLength(
- PyObject *unicode
-);
-#endif
-
-/* Get the number of Py_UNICODE units in the
- string representation. */
-
-Py_DEPRECATED(3.3) PyAPI_FUNC(Py_ssize_t) PyUnicode_GetSize(
- PyObject *unicode /* Unicode object */
- );
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-/* Read a character from the string. */
-
-PyAPI_FUNC(Py_UCS4) PyUnicode_ReadChar(
- PyObject *unicode,
- Py_ssize_t index
- );
-
-/* Write a character to the string. The string must have been created through
- PyUnicode_New, must not be shared, and must not have been hashed yet.
-
- Return 0 on success, -1 on error. */
-
-PyAPI_FUNC(int) PyUnicode_WriteChar(
- PyObject *unicode,
- Py_ssize_t index,
- Py_UCS4 character
- );
-#endif
-
-/* Resize a Unicode object. The length is the number of characters, except
- if the kind of the string is PyUnicode_WCHAR_KIND: in this case, the length
- is the number of Py_UNICODE characters.
-
- *unicode is modified to point to the new (resized) object and 0
- returned on success.
-
- Try to resize the string in place (which is usually faster than allocating
- a new string and copy characters), or create a new string.
-
- Error handling is implemented as follows: an exception is set, -1
- is returned and *unicode left untouched.
-
- WARNING: The function doesn't check string content, the result may not be a
- string in canonical representation. */
-
-PyAPI_FUNC(int) PyUnicode_Resize(
- PyObject **unicode, /* Pointer to the Unicode object */
- Py_ssize_t length /* New length */
- );
-
-/* Decode obj to a Unicode object.
-
- bytes, bytearray and other bytes-like objects are decoded according to the
- given encoding and error handler. The encoding and error handler can be
- NULL to have the interface use UTF-8 and "strict".
-
- All other objects (including Unicode objects) raise an exception.
-
- The API returns NULL in case of an error. The caller is responsible
- for decref'ing the returned objects.
-
-*/
-
-PyAPI_FUNC(PyObject*) PyUnicode_FromEncodedObject(
- PyObject *obj, /* Object */
- const char *encoding, /* encoding */
- const char *errors /* error handling */
- );
-
-/* Copy an instance of a Unicode subtype to a new true Unicode object if
- necessary. If obj is already a true Unicode object (not a subtype), return
- the reference with *incremented* refcount.
-
- The API returns NULL in case of an error. The caller is responsible
- for decref'ing the returned objects.
-
-*/
-
-PyAPI_FUNC(PyObject*) PyUnicode_FromObject(
- PyObject *obj /* Object */
- );
-
-PyAPI_FUNC(PyObject *) PyUnicode_FromFormatV(
- const char *format, /* ASCII-encoded string */
- va_list vargs
- );
-PyAPI_FUNC(PyObject *) PyUnicode_FromFormat(
- const char *format, /* ASCII-encoded string */
- ...
- );
-
-PyAPI_FUNC(void) PyUnicode_InternInPlace(PyObject **);
-PyAPI_FUNC(PyObject *) PyUnicode_InternFromString(
- const char *u /* UTF-8 encoded string */
- );
-
-// PyUnicode_InternImmortal() is deprecated since Python 3.10
-// and will be removed in Python 3.12. Use PyUnicode_InternInPlace() instead.
-Py_DEPRECATED(3.10) PyAPI_FUNC(void) PyUnicode_InternImmortal(PyObject **);
-
-/* Use only if you know it's a string */
-#define PyUnicode_CHECK_INTERNED(op) \
- (((PyASCIIObject *)(op))->state.interned)
-
-/* --- wchar_t support for platforms which support it --------------------- */
-
-#ifdef HAVE_WCHAR_H
-
-/* Create a Unicode Object from the wchar_t buffer w of the given
- size.
-
- The buffer is copied into the new object. */
-
-PyAPI_FUNC(PyObject*) PyUnicode_FromWideChar(
- const wchar_t *w, /* wchar_t buffer */
- Py_ssize_t size /* size of buffer */
- );
-
-/* Copies the Unicode Object contents into the wchar_t buffer w. At
- most size wchar_t characters are copied.
-
- Note that the resulting wchar_t string may or may not be
- 0-terminated. It is the responsibility of the caller to make sure
- that the wchar_t string is 0-terminated in case this is required by
- the application.
-
- Returns the number of wchar_t characters copied (excluding a
- possibly trailing 0-termination character) or -1 in case of an
- error. */
-
-PyAPI_FUNC(Py_ssize_t) PyUnicode_AsWideChar(
- PyObject *unicode, /* Unicode object */
- wchar_t *w, /* wchar_t buffer */
- Py_ssize_t size /* size of buffer */
- );
-
-/* Convert the Unicode object to a wide character string. The output string
- always ends with a nul character. If size is not NULL, write the number of
- wide characters (excluding the null character) into *size.
-
- Returns a buffer allocated by PyMem_Malloc() (use PyMem_Free() to free it)
- on success. On error, returns NULL, *size is undefined and raises a
- MemoryError. */
-
-PyAPI_FUNC(wchar_t*) PyUnicode_AsWideCharString(
- PyObject *unicode, /* Unicode object */
- Py_ssize_t *size /* number of characters of the result */
- );
-
-#endif
-
-/* --- Unicode ordinals --------------------------------------------------- */
-
-/* Create a Unicode Object from the given Unicode code point ordinal.
-
- The ordinal must be in range(0x110000). A ValueError is
- raised in case it is not.
-
-*/
-
-PyAPI_FUNC(PyObject*) PyUnicode_FromOrdinal(int ordinal);
-
-/* === Builtin Codecs =====================================================
-
- Many of these APIs take two arguments encoding and errors. These
- parameters encoding and errors have the same semantics as the ones
- of the builtin str() API.
-
- Setting encoding to NULL causes the default encoding (UTF-8) to be used.
-
- Error handling is set by errors which may also be set to NULL
- meaning to use the default handling defined for the codec. Default
- error handling for all builtin codecs is "strict" (ValueErrors are
- raised).
-
- The codecs all use a similar interface. Only deviation from the
- generic ones are documented.
-
-*/
-
-/* --- Manage the default encoding ---------------------------------------- */
-
-/* Returns "utf-8". */
-PyAPI_FUNC(const char*) PyUnicode_GetDefaultEncoding(void);
-
-/* --- Generic Codecs ----------------------------------------------------- */
-
-/* Create a Unicode object by decoding the encoded string s of the
- given size. */
-
-PyAPI_FUNC(PyObject*) PyUnicode_Decode(
- const char *s, /* encoded string */
- Py_ssize_t size, /* size of buffer */
- const char *encoding, /* encoding */
- const char *errors /* error handling */
- );
-
-/* Decode a Unicode object unicode and return the result as Python
- object.
-
- This API is DEPRECATED. The only supported standard encoding is rot13.
- Use PyCodec_Decode() to decode with rot13 and non-standard codecs
- that decode from str. */
-
-Py_DEPRECATED(3.6) PyAPI_FUNC(PyObject*) PyUnicode_AsDecodedObject(
- PyObject *unicode, /* Unicode object */
- const char *encoding, /* encoding */
- const char *errors /* error handling */
- );
-
-/* Decode a Unicode object unicode and return the result as Unicode
- object.
-
- This API is DEPRECATED. The only supported standard encoding is rot13.
- Use PyCodec_Decode() to decode with rot13 and non-standard codecs
- that decode from str to str. */
-
-Py_DEPRECATED(3.6) PyAPI_FUNC(PyObject*) PyUnicode_AsDecodedUnicode(
- PyObject *unicode, /* Unicode object */
- const char *encoding, /* encoding */
- const char *errors /* error handling */
- );
-
-/* Encodes a Unicode object and returns the result as Python
- object.
-
- This API is DEPRECATED. It is superseded by PyUnicode_AsEncodedString()
- since all standard encodings (except rot13) encode str to bytes.
- Use PyCodec_Encode() for encoding with rot13 and non-standard codecs
- that encode form str to non-bytes. */
-
-Py_DEPRECATED(3.6) PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedObject(
- PyObject *unicode, /* Unicode object */
- const char *encoding, /* encoding */
- const char *errors /* error handling */
- );
-
-/* Encodes a Unicode object and returns the result as Python string
- object. */
-
-PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedString(
- PyObject *unicode, /* Unicode object */
- const char *encoding, /* encoding */
- const char *errors /* error handling */
- );
-
-/* Encodes a Unicode object and returns the result as Unicode
- object.
-
- This API is DEPRECATED. The only supported standard encodings is rot13.
- Use PyCodec_Encode() to encode with rot13 and non-standard codecs
- that encode from str to str. */
-
-Py_DEPRECATED(3.6) PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedUnicode(
- PyObject *unicode, /* Unicode object */
- const char *encoding, /* encoding */
- const char *errors /* error handling */
- );
-
-/* Build an encoding map. */
-
-PyAPI_FUNC(PyObject*) PyUnicode_BuildEncodingMap(
- PyObject* string /* 256 character map */
- );
-
-/* --- UTF-7 Codecs ------------------------------------------------------- */
-
-PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF7(
- const char *string, /* UTF-7 encoded string */
- Py_ssize_t length, /* size of string */
- const char *errors /* error handling */
- );
-
-PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF7Stateful(
- const char *string, /* UTF-7 encoded string */
- Py_ssize_t length, /* size of string */
- const char *errors, /* error handling */
- Py_ssize_t *consumed /* bytes consumed */
- );
-
-/* --- UTF-8 Codecs ------------------------------------------------------- */
-
-PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF8(
- const char *string, /* UTF-8 encoded string */
- Py_ssize_t length, /* size of string */
- const char *errors /* error handling */
- );
-
-PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF8Stateful(
- const char *string, /* UTF-8 encoded string */
- Py_ssize_t length, /* size of string */
- const char *errors, /* error handling */
- Py_ssize_t *consumed /* bytes consumed */
- );
-
-PyAPI_FUNC(PyObject*) PyUnicode_AsUTF8String(
- PyObject *unicode /* Unicode object */
- );
-
-/* Returns a pointer to the default encoding (UTF-8) of the
- Unicode object unicode and the size of the encoded representation
- in bytes stored in *size.
-
- In case of an error, no *size is set.
-
- This function caches the UTF-8 encoded string in the unicodeobject
- and subsequent calls will return the same string. The memory is released
- when the unicodeobject is deallocated.
-*/
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000
-PyAPI_FUNC(const char *) PyUnicode_AsUTF8AndSize(
- PyObject *unicode,
- Py_ssize_t *size);
-#endif
-
-/* --- UTF-32 Codecs ------------------------------------------------------ */
-
-/* Decodes length bytes from a UTF-32 encoded buffer string and returns
- the corresponding Unicode object.
-
- errors (if non-NULL) defines the error handling. It defaults
- to "strict".
-
- If byteorder is non-NULL, the decoder starts decoding using the
- given byte order:
-
- *byteorder == -1: little endian
- *byteorder == 0: native order
- *byteorder == 1: big endian
-
- In native mode, the first four bytes of the stream are checked for a
- BOM mark. If found, the BOM mark is analysed, the byte order
- adjusted and the BOM skipped. In the other modes, no BOM mark
- interpretation is done. After completion, *byteorder is set to the
- current byte order at the end of input data.
-
- If byteorder is NULL, the codec starts in native order mode.
-
-*/
-
-PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF32(
- const char *string, /* UTF-32 encoded string */
- Py_ssize_t length, /* size of string */
- const char *errors, /* error handling */
- int *byteorder /* pointer to byteorder to use
- 0=native;-1=LE,1=BE; updated on
- exit */
- );
-
-PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF32Stateful(
- const char *string, /* UTF-32 encoded string */
- Py_ssize_t length, /* size of string */
- const char *errors, /* error handling */
- int *byteorder, /* pointer to byteorder to use
- 0=native;-1=LE,1=BE; updated on
- exit */
- Py_ssize_t *consumed /* bytes consumed */
- );
-
-/* Returns a Python string using the UTF-32 encoding in native byte
- order. The string always starts with a BOM mark. */
-
-PyAPI_FUNC(PyObject*) PyUnicode_AsUTF32String(
- PyObject *unicode /* Unicode object */
- );
-
-/* Returns a Python string object holding the UTF-32 encoded value of
- the Unicode data.
-
- If byteorder is not 0, output is written according to the following
- byte order:
-
- byteorder == -1: little endian
- byteorder == 0: native byte order (writes a BOM mark)
- byteorder == 1: big endian
-
- If byteorder is 0, the output string will always start with the
- Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is
- prepended.
-
-*/
-
-/* --- UTF-16 Codecs ------------------------------------------------------ */
-
-/* Decodes length bytes from a UTF-16 encoded buffer string and returns
- the corresponding Unicode object.
-
- errors (if non-NULL) defines the error handling. It defaults
- to "strict".
-
- If byteorder is non-NULL, the decoder starts decoding using the
- given byte order:
-
- *byteorder == -1: little endian
- *byteorder == 0: native order
- *byteorder == 1: big endian
-
- In native mode, the first two bytes of the stream are checked for a
- BOM mark. If found, the BOM mark is analysed, the byte order
- adjusted and the BOM skipped. In the other modes, no BOM mark
- interpretation is done. After completion, *byteorder is set to the
- current byte order at the end of input data.
-
- If byteorder is NULL, the codec starts in native order mode.
-
-*/
-
-PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF16(
- const char *string, /* UTF-16 encoded string */
- Py_ssize_t length, /* size of string */
- const char *errors, /* error handling */
- int *byteorder /* pointer to byteorder to use
- 0=native;-1=LE,1=BE; updated on
- exit */
- );
-
-PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF16Stateful(
- const char *string, /* UTF-16 encoded string */
- Py_ssize_t length, /* size of string */
- const char *errors, /* error handling */
- int *byteorder, /* pointer to byteorder to use
- 0=native;-1=LE,1=BE; updated on
- exit */
- Py_ssize_t *consumed /* bytes consumed */
- );
-
-/* Returns a Python string using the UTF-16 encoding in native byte
- order. The string always starts with a BOM mark. */
-
-PyAPI_FUNC(PyObject*) PyUnicode_AsUTF16String(
- PyObject *unicode /* Unicode object */
- );
-
-/* --- Unicode-Escape Codecs ---------------------------------------------- */
-
-PyAPI_FUNC(PyObject*) PyUnicode_DecodeUnicodeEscape(
- const char *string, /* Unicode-Escape encoded string */
- Py_ssize_t length, /* size of string */
- const char *errors /* error handling */
- );
-
-PyAPI_FUNC(PyObject*) PyUnicode_AsUnicodeEscapeString(
- PyObject *unicode /* Unicode object */
- );
-
-/* --- Raw-Unicode-Escape Codecs ------------------------------------------ */
-
-PyAPI_FUNC(PyObject*) PyUnicode_DecodeRawUnicodeEscape(
- const char *string, /* Raw-Unicode-Escape encoded string */
- Py_ssize_t length, /* size of string */
- const char *errors /* error handling */
- );
-
-PyAPI_FUNC(PyObject*) PyUnicode_AsRawUnicodeEscapeString(
- PyObject *unicode /* Unicode object */
- );
-
-/* --- Latin-1 Codecs -----------------------------------------------------
-
- Note: Latin-1 corresponds to the first 256 Unicode ordinals. */
-
-PyAPI_FUNC(PyObject*) PyUnicode_DecodeLatin1(
- const char *string, /* Latin-1 encoded string */
- Py_ssize_t length, /* size of string */
- const char *errors /* error handling */
- );
-
-PyAPI_FUNC(PyObject*) PyUnicode_AsLatin1String(
- PyObject *unicode /* Unicode object */
- );
-
-/* --- ASCII Codecs -------------------------------------------------------
-
- Only 7-bit ASCII data is excepted. All other codes generate errors.
-
-*/
-
-PyAPI_FUNC(PyObject*) PyUnicode_DecodeASCII(
- const char *string, /* ASCII encoded string */
- Py_ssize_t length, /* size of string */
- const char *errors /* error handling */
- );
-
-PyAPI_FUNC(PyObject*) PyUnicode_AsASCIIString(
- PyObject *unicode /* Unicode object */
- );
-
-/* --- Character Map Codecs -----------------------------------------------
-
- This codec uses mappings to encode and decode characters.
-
- Decoding mappings must map byte ordinals (integers in the range from 0 to
- 255) to Unicode strings, integers (which are then interpreted as Unicode
- ordinals) or None. Unmapped data bytes (ones which cause a LookupError)
- as well as mapped to None, 0xFFFE or '\ufffe' are treated as "undefined
- mapping" and cause an error.
-
- Encoding mappings must map Unicode ordinal integers to bytes objects,
- integers in the range from 0 to 255 or None. Unmapped character
- ordinals (ones which cause a LookupError) as well as mapped to
- None are treated as "undefined mapping" and cause an error.
-
-*/
-
-PyAPI_FUNC(PyObject*) PyUnicode_DecodeCharmap(
- const char *string, /* Encoded string */
- Py_ssize_t length, /* size of string */
- PyObject *mapping, /* decoding mapping */
- const char *errors /* error handling */
- );
-
-PyAPI_FUNC(PyObject*) PyUnicode_AsCharmapString(
- PyObject *unicode, /* Unicode object */
- PyObject *mapping /* encoding mapping */
- );
-
-/* --- MBCS codecs for Windows -------------------------------------------- */
-
-#ifdef MS_WINDOWS
-PyAPI_FUNC(PyObject*) PyUnicode_DecodeMBCS(
- const char *string, /* MBCS encoded string */
- Py_ssize_t length, /* size of string */
- const char *errors /* error handling */
- );
-
-PyAPI_FUNC(PyObject*) PyUnicode_DecodeMBCSStateful(
- const char *string, /* MBCS encoded string */
- Py_ssize_t length, /* size of string */
- const char *errors, /* error handling */
- Py_ssize_t *consumed /* bytes consumed */
- );
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-PyAPI_FUNC(PyObject*) PyUnicode_DecodeCodePageStateful(
- int code_page, /* code page number */
- const char *string, /* encoded string */
- Py_ssize_t length, /* size of string */
- const char *errors, /* error handling */
- Py_ssize_t *consumed /* bytes consumed */
- );
-#endif
-
-PyAPI_FUNC(PyObject*) PyUnicode_AsMBCSString(
- PyObject *unicode /* Unicode object */
- );
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-PyAPI_FUNC(PyObject*) PyUnicode_EncodeCodePage(
- int code_page, /* code page number */
- PyObject *unicode, /* Unicode object */
- const char *errors /* error handling */
- );
-#endif
-
-#endif /* MS_WINDOWS */
-
-/* --- Locale encoding --------------------------------------------------- */
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-/* Decode a string from the current locale encoding. The decoder is strict if
- *surrogateescape* is equal to zero, otherwise it uses the 'surrogateescape'
- error handler (PEP 383) to escape undecodable bytes. If a byte sequence can
- be decoded as a surrogate character and *surrogateescape* is not equal to
- zero, the byte sequence is escaped using the 'surrogateescape' error handler
- instead of being decoded. *str* must end with a null character but cannot
- contain embedded null characters. */
-
-PyAPI_FUNC(PyObject*) PyUnicode_DecodeLocaleAndSize(
- const char *str,
- Py_ssize_t len,
- const char *errors);
-
-/* Similar to PyUnicode_DecodeLocaleAndSize(), but compute the string
- length using strlen(). */
-
-PyAPI_FUNC(PyObject*) PyUnicode_DecodeLocale(
- const char *str,
- const char *errors);
-
-/* Encode a Unicode object to the current locale encoding. The encoder is
- strict is *surrogateescape* is equal to zero, otherwise the
- "surrogateescape" error handler is used. Return a bytes object. The string
- cannot contain embedded null characters. */
-
-PyAPI_FUNC(PyObject*) PyUnicode_EncodeLocale(
- PyObject *unicode,
- const char *errors
- );
-#endif
-
-/* --- File system encoding ---------------------------------------------- */
-
-/* ParseTuple converter: encode str objects to bytes using
- PyUnicode_EncodeFSDefault(); bytes objects are output as-is. */
-
-PyAPI_FUNC(int) PyUnicode_FSConverter(PyObject*, void*);
-
-/* ParseTuple converter: decode bytes objects to unicode using
- PyUnicode_DecodeFSDefaultAndSize(); str objects are output as-is. */
-
-PyAPI_FUNC(int) PyUnicode_FSDecoder(PyObject*, void*);
-
-/* Decode a null-terminated string using Py_FileSystemDefaultEncoding
- and the "surrogateescape" error handler.
-
- If Py_FileSystemDefaultEncoding is not set, fall back to the locale
- encoding.
-
- Use PyUnicode_DecodeFSDefaultAndSize() if the string length is known.
-*/
-
-PyAPI_FUNC(PyObject*) PyUnicode_DecodeFSDefault(
- const char *s /* encoded string */
- );
-
-/* Decode a string using Py_FileSystemDefaultEncoding
- and the "surrogateescape" error handler.
-
- If Py_FileSystemDefaultEncoding is not set, fall back to the locale
- encoding.
-*/
-
-PyAPI_FUNC(PyObject*) PyUnicode_DecodeFSDefaultAndSize(
- const char *s, /* encoded string */
- Py_ssize_t size /* size */
- );
-
-/* Encode a Unicode object to Py_FileSystemDefaultEncoding with the
- "surrogateescape" error handler, and return bytes.
-
- If Py_FileSystemDefaultEncoding is not set, fall back to the locale
- encoding.
-*/
-
-PyAPI_FUNC(PyObject*) PyUnicode_EncodeFSDefault(
- PyObject *unicode
- );
-
-/* --- Methods & Slots ----------------------------------------------------
-
- These are capable of handling Unicode objects and strings on input
- (we refer to them as strings in the descriptions) and return
- Unicode objects or integers as appropriate. */
-
-/* Concat two strings giving a new Unicode string. */
-
-PyAPI_FUNC(PyObject*) PyUnicode_Concat(
- PyObject *left, /* Left string */
- PyObject *right /* Right string */
- );
-
-/* Concat two strings and put the result in *pleft
- (sets *pleft to NULL on error) */
-
-PyAPI_FUNC(void) PyUnicode_Append(
- PyObject **pleft, /* Pointer to left string */
- PyObject *right /* Right string */
- );
-
-/* Concat two strings, put the result in *pleft and drop the right object
- (sets *pleft to NULL on error) */
-
-PyAPI_FUNC(void) PyUnicode_AppendAndDel(
- PyObject **pleft, /* Pointer to left string */
- PyObject *right /* Right string */
- );
-
-/* Split a string giving a list of Unicode strings.
-
- If sep is NULL, splitting will be done at all whitespace
- substrings. Otherwise, splits occur at the given separator.
-
- At most maxsplit splits will be done. If negative, no limit is set.
-
- Separators are not included in the resulting list.
-
-*/
-
-PyAPI_FUNC(PyObject*) PyUnicode_Split(
- PyObject *s, /* String to split */
- PyObject *sep, /* String separator */
- Py_ssize_t maxsplit /* Maxsplit count */
- );
-
-/* Dito, but split at line breaks.
-
- CRLF is considered to be one line break. Line breaks are not
- included in the resulting list. */
-
-PyAPI_FUNC(PyObject*) PyUnicode_Splitlines(
- PyObject *s, /* String to split */
- int keepends /* If true, line end markers are included */
- );
-
-/* Partition a string using a given separator. */
-
-PyAPI_FUNC(PyObject*) PyUnicode_Partition(
- PyObject *s, /* String to partition */
- PyObject *sep /* String separator */
- );
-
-/* Partition a string using a given separator, searching from the end of the
- string. */
-
-PyAPI_FUNC(PyObject*) PyUnicode_RPartition(
- PyObject *s, /* String to partition */
- PyObject *sep /* String separator */
- );
-
-/* Split a string giving a list of Unicode strings.
-
- If sep is NULL, splitting will be done at all whitespace
- substrings. Otherwise, splits occur at the given separator.
-
- At most maxsplit splits will be done. But unlike PyUnicode_Split
- PyUnicode_RSplit splits from the end of the string. If negative,
- no limit is set.
-
- Separators are not included in the resulting list.
-
-*/
-
-PyAPI_FUNC(PyObject*) PyUnicode_RSplit(
- PyObject *s, /* String to split */
- PyObject *sep, /* String separator */
- Py_ssize_t maxsplit /* Maxsplit count */
- );
-
-/* Translate a string by applying a character mapping table to it and
- return the resulting Unicode object.
-
- The mapping table must map Unicode ordinal integers to Unicode strings,
- Unicode ordinal integers or None (causing deletion of the character).
-
- Mapping tables may be dictionaries or sequences. Unmapped character
- ordinals (ones which cause a LookupError) are left untouched and
- are copied as-is.
-
-*/
-
-PyAPI_FUNC(PyObject *) PyUnicode_Translate(
- PyObject *str, /* String */
- PyObject *table, /* Translate table */
- const char *errors /* error handling */
- );
-
-/* Join a sequence of strings using the given separator and return
- the resulting Unicode string. */
-
-PyAPI_FUNC(PyObject*) PyUnicode_Join(
- PyObject *separator, /* Separator string */
- PyObject *seq /* Sequence object */
- );
-
-/* Return 1 if substr matches str[start:end] at the given tail end, 0
- otherwise. */
-
-PyAPI_FUNC(Py_ssize_t) PyUnicode_Tailmatch(
- PyObject *str, /* String */
- PyObject *substr, /* Prefix or Suffix string */
- Py_ssize_t start, /* Start index */
- Py_ssize_t end, /* Stop index */
- int direction /* Tail end: -1 prefix, +1 suffix */
- );
-
-/* Return the first position of substr in str[start:end] using the
- given search direction or -1 if not found. -2 is returned in case
- an error occurred and an exception is set. */
-
-PyAPI_FUNC(Py_ssize_t) PyUnicode_Find(
- PyObject *str, /* String */
- PyObject *substr, /* Substring to find */
- Py_ssize_t start, /* Start index */
- Py_ssize_t end, /* Stop index */
- int direction /* Find direction: +1 forward, -1 backward */
- );
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-/* Like PyUnicode_Find, but search for single character only. */
-PyAPI_FUNC(Py_ssize_t) PyUnicode_FindChar(
- PyObject *str,
- Py_UCS4 ch,
- Py_ssize_t start,
- Py_ssize_t end,
- int direction
- );
-#endif
-
-/* Count the number of occurrences of substr in str[start:end]. */
-
-PyAPI_FUNC(Py_ssize_t) PyUnicode_Count(
- PyObject *str, /* String */
- PyObject *substr, /* Substring to count */
- Py_ssize_t start, /* Start index */
- Py_ssize_t end /* Stop index */
- );
-
-/* Replace at most maxcount occurrences of substr in str with replstr
- and return the resulting Unicode object. */
-
-PyAPI_FUNC(PyObject *) PyUnicode_Replace(
- PyObject *str, /* String */
- PyObject *substr, /* Substring to find */
- PyObject *replstr, /* Substring to replace */
- Py_ssize_t maxcount /* Max. number of replacements to apply;
- -1 = all */
- );
-
-/* Compare two strings and return -1, 0, 1 for less than, equal,
- greater than resp.
- Raise an exception and return -1 on error. */
-
-PyAPI_FUNC(int) PyUnicode_Compare(
- PyObject *left, /* Left string */
- PyObject *right /* Right string */
- );
-
-/* Compare a Unicode object with C string and return -1, 0, 1 for less than,
- equal, and greater than, respectively. It is best to pass only
- ASCII-encoded strings, but the function interprets the input string as
- ISO-8859-1 if it contains non-ASCII characters.
- This function does not raise exceptions. */
-
-PyAPI_FUNC(int) PyUnicode_CompareWithASCIIString(
- PyObject *left,
- const char *right /* ASCII-encoded string */
- );
-
-/* Rich compare two strings and return one of the following:
-
- - NULL in case an exception was raised
- - Py_True or Py_False for successful comparisons
- - Py_NotImplemented in case the type combination is unknown
-
- Possible values for op:
-
- Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE
-
-*/
-
-PyAPI_FUNC(PyObject *) PyUnicode_RichCompare(
- PyObject *left, /* Left string */
- PyObject *right, /* Right string */
- int op /* Operation: Py_EQ, Py_NE, Py_GT, etc. */
- );
-
-/* Apply an argument tuple or dictionary to a format string and return
- the resulting Unicode string. */
-
-PyAPI_FUNC(PyObject *) PyUnicode_Format(
- PyObject *format, /* Format string */
- PyObject *args /* Argument tuple or dictionary */
- );
-
-/* Checks whether element is contained in container and return 1/0
- accordingly.
-
- element has to coerce to a one element Unicode string. -1 is
- returned in case of an error. */
-
-PyAPI_FUNC(int) PyUnicode_Contains(
- PyObject *container, /* Container string */
- PyObject *element /* Element string */
- );
-
-/* Checks whether argument is a valid identifier. */
-
-PyAPI_FUNC(int) PyUnicode_IsIdentifier(PyObject *s);
-
-/* === Characters Type APIs =============================================== */
-
-#ifndef Py_LIMITED_API
-# define Py_CPYTHON_UNICODEOBJECT_H
-# include "cpython/unicodeobject.h"
-# undef Py_CPYTHON_UNICODEOBJECT_H
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_UNICODEOBJECT_H */
diff --git a/include/python3.10/warnings.h b/include/python3.10/warnings.h
deleted file mode 100644
index a675bb5..0000000
--- a/include/python3.10/warnings.h
+++ /dev/null
@@ -1,67 +0,0 @@
-#ifndef Py_WARNINGS_H
-#define Py_WARNINGS_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(PyObject*) _PyWarnings_Init(void);
-#endif
-
-PyAPI_FUNC(int) PyErr_WarnEx(
- PyObject *category,
- const char *message, /* UTF-8 encoded string */
- Py_ssize_t stack_level);
-PyAPI_FUNC(int) PyErr_WarnFormat(
- PyObject *category,
- Py_ssize_t stack_level,
- const char *format, /* ASCII-encoded string */
- ...);
-
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000
-/* Emit a ResourceWarning warning */
-PyAPI_FUNC(int) PyErr_ResourceWarning(
- PyObject *source,
- Py_ssize_t stack_level,
- const char *format, /* ASCII-encoded string */
- ...);
-#endif
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(int) PyErr_WarnExplicitObject(
- PyObject *category,
- PyObject *message,
- PyObject *filename,
- int lineno,
- PyObject *module,
- PyObject *registry);
-#endif
-PyAPI_FUNC(int) PyErr_WarnExplicit(
- PyObject *category,
- const char *message, /* UTF-8 encoded string */
- const char *filename, /* decoded from the filesystem encoding */
- int lineno,
- const char *module, /* UTF-8 encoded string */
- PyObject *registry);
-
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(int)
-PyErr_WarnExplicitFormat(PyObject *category,
- const char *filename, int lineno,
- const char *module, PyObject *registry,
- const char *format, ...);
-#endif
-
-/* DEPRECATED: Use PyErr_WarnEx() instead. */
-#ifndef Py_LIMITED_API
-#define PyErr_Warn(category, msg) PyErr_WarnEx(category, msg, 1)
-#endif
-
-#ifndef Py_LIMITED_API
-void _PyErr_WarnUnawaitedCoroutine(PyObject *coro);
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_WARNINGS_H */
-
diff --git a/include/python3.10/weakrefobject.h b/include/python3.10/weakrefobject.h
deleted file mode 100644
index ac4b482..0000000
--- a/include/python3.10/weakrefobject.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/* Weak references objects for Python. */
-
-#ifndef Py_WEAKREFOBJECT_H
-#define Py_WEAKREFOBJECT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-typedef struct _PyWeakReference PyWeakReference;
-
-/* PyWeakReference is the base struct for the Python ReferenceType, ProxyType,
- * and CallableProxyType.
- */
-#ifndef Py_LIMITED_API
-struct _PyWeakReference {
- PyObject_HEAD
-
- /* The object to which this is a weak reference, or Py_None if none.
- * Note that this is a stealth reference: wr_object's refcount is
- * not incremented to reflect this pointer.
- */
- PyObject *wr_object;
-
- /* A callable to invoke when wr_object dies, or NULL if none. */
- PyObject *wr_callback;
-
- /* A cache for wr_object's hash code. As usual for hashes, this is -1
- * if the hash code isn't known yet.
- */
- Py_hash_t hash;
-
- /* If wr_object is weakly referenced, wr_object has a doubly-linked NULL-
- * terminated list of weak references to it. These are the list pointers.
- * If wr_object goes away, wr_object is set to Py_None, and these pointers
- * have no meaning then.
- */
- PyWeakReference *wr_prev;
- PyWeakReference *wr_next;
-};
-#endif
-
-PyAPI_DATA(PyTypeObject) _PyWeakref_RefType;
-PyAPI_DATA(PyTypeObject) _PyWeakref_ProxyType;
-PyAPI_DATA(PyTypeObject) _PyWeakref_CallableProxyType;
-
-#define PyWeakref_CheckRef(op) PyObject_TypeCheck(op, &_PyWeakref_RefType)
-#define PyWeakref_CheckRefExact(op) \
- Py_IS_TYPE(op, &_PyWeakref_RefType)
-#define PyWeakref_CheckProxy(op) \
- (Py_IS_TYPE(op, &_PyWeakref_ProxyType) || \
- Py_IS_TYPE(op, &_PyWeakref_CallableProxyType))
-
-#define PyWeakref_Check(op) \
- (PyWeakref_CheckRef(op) || PyWeakref_CheckProxy(op))
-
-
-PyAPI_FUNC(PyObject *) PyWeakref_NewRef(PyObject *ob,
- PyObject *callback);
-PyAPI_FUNC(PyObject *) PyWeakref_NewProxy(PyObject *ob,
- PyObject *callback);
-PyAPI_FUNC(PyObject *) PyWeakref_GetObject(PyObject *ref);
-
-#ifndef Py_LIMITED_API
-PyAPI_FUNC(Py_ssize_t) _PyWeakref_GetWeakrefCount(PyWeakReference *head);
-
-PyAPI_FUNC(void) _PyWeakref_ClearRef(PyWeakReference *self);
-#endif
-
-/* Explanation for the Py_REFCNT() check: when a weakref's target is part
- of a long chain of deallocations which triggers the trashcan mechanism,
- clearing the weakrefs can be delayed long after the target's refcount
- has dropped to zero. In the meantime, code accessing the weakref will
- be able to "see" the target object even though it is supposed to be
- unreachable. See issue #16602. */
-
-#define PyWeakref_GET_OBJECT(ref) \
- (Py_REFCNT(((PyWeakReference *)(ref))->wr_object) > 0 \
- ? ((PyWeakReference *)(ref))->wr_object \
- : Py_None)
-
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_WEAKREFOBJECT_H */
diff --git a/include/python3.11/Python.h b/include/python3.11/Python.h
new file mode 100644
index 0000000..52a7aac
--- /dev/null
+++ b/include/python3.11/Python.h
@@ -0,0 +1,109 @@
+// Entry point of the Python C API.
+// C extensions should only #include <Python.h>, and not include directly
+// the other Python header files included by <Python.h>.
+
+#ifndef Py_PYTHON_H
+#define Py_PYTHON_H
+
+// Since this is a "meta-include" file, no #ifdef __cplusplus / extern "C" {
+
+// Include Python header files
+#include "patchlevel.h"
+#include "pyconfig.h"
+#include "pymacconfig.h"
+
+#if defined(__sgi) && !defined(_SGI_MP_SOURCE)
+# define _SGI_MP_SOURCE
+#endif
+
+// stdlib.h, stdio.h, errno.h and string.h headers are not used by Python
+// headers, but kept for backward compatibility. They are excluded from the
+// limited C API of Python 3.11.
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# include <stdlib.h>
+# include <stdio.h> // FILE*
+# include <errno.h> // errno
+# include <string.h> // memcpy()
+#endif
+#ifndef MS_WINDOWS
+# include <unistd.h>
+#endif
+#ifdef HAVE_STDDEF_H
+# include <stddef.h> // size_t
+#endif
+
+#include <assert.h> // assert()
+#include <wchar.h> // wchar_t
+
+#include "pyport.h"
+#include "pymacro.h"
+#include "pymath.h"
+#include "pymem.h"
+#include "pytypedefs.h"
+#include "pybuffer.h"
+#include "object.h"
+#include "objimpl.h"
+#include "typeslots.h"
+#include "pyhash.h"
+#include "cpython/pydebug.h"
+#include "bytearrayobject.h"
+#include "bytesobject.h"
+#include "unicodeobject.h"
+#include "longobject.h"
+#include "cpython/longintrepr.h"
+#include "boolobject.h"
+#include "floatobject.h"
+#include "complexobject.h"
+#include "rangeobject.h"
+#include "memoryobject.h"
+#include "tupleobject.h"
+#include "listobject.h"
+#include "dictobject.h"
+#include "cpython/odictobject.h"
+#include "enumobject.h"
+#include "setobject.h"
+#include "methodobject.h"
+#include "moduleobject.h"
+#include "cpython/funcobject.h"
+#include "cpython/classobject.h"
+#include "fileobject.h"
+#include "pycapsule.h"
+#include "cpython/code.h"
+#include "pyframe.h"
+#include "traceback.h"
+#include "sliceobject.h"
+#include "cpython/cellobject.h"
+#include "iterobject.h"
+#include "cpython/initconfig.h"
+#include "pystate.h"
+#include "cpython/genobject.h"
+#include "descrobject.h"
+#include "genericaliasobject.h"
+#include "warnings.h"
+#include "weakrefobject.h"
+#include "structseq.h"
+#include "cpython/picklebufobject.h"
+#include "cpython/pytime.h"
+#include "codecs.h"
+#include "pyerrors.h"
+#include "pythread.h"
+#include "cpython/context.h"
+#include "modsupport.h"
+#include "compile.h"
+#include "pythonrun.h"
+#include "pylifecycle.h"
+#include "ceval.h"
+#include "sysmodule.h"
+#include "osmodule.h"
+#include "intrcheck.h"
+#include "import.h"
+#include "abstract.h"
+#include "bltinmodule.h"
+#include "cpython/pyctype.h"
+#include "pystrtod.h"
+#include "pystrcmp.h"
+#include "fileutils.h"
+#include "cpython/pyfpe.h"
+#include "tracemalloc.h"
+
+#endif /* !Py_PYTHON_H */
diff --git a/include/python3.11/abstract.h b/include/python3.11/abstract.h
new file mode 100644
index 0000000..9e06fbb
--- /dev/null
+++ b/include/python3.11/abstract.h
@@ -0,0 +1,873 @@
+/* Abstract Object Interface (many thanks to Jim Fulton) */
+
+#ifndef Py_ABSTRACTOBJECT_H
+#define Py_ABSTRACTOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* === Object Protocol ================================================== */
+
+/* Implemented elsewhere:
+
+ int PyObject_Print(PyObject *o, FILE *fp, int flags);
+
+ Print an object 'o' on file 'fp'. Returns -1 on error. The flags argument
+ is used to enable certain printing options. The only option currently
+ supported is Py_Print_RAW.
+
+ (What should be said about Py_Print_RAW?). */
+
+
+/* Implemented elsewhere:
+
+ int PyObject_HasAttrString(PyObject *o, const char *attr_name);
+
+ Returns 1 if object 'o' has the attribute attr_name, and 0 otherwise.
+
+ This is equivalent to the Python expression: hasattr(o,attr_name).
+
+ This function always succeeds. */
+
+
+/* Implemented elsewhere:
+
+ PyObject* PyObject_GetAttrString(PyObject *o, const char *attr_name);
+
+ Retrieve an attributed named attr_name form object o.
+ Returns the attribute value on success, or NULL on failure.
+
+ This is the equivalent of the Python expression: o.attr_name. */
+
+
+/* Implemented elsewhere:
+
+ int PyObject_HasAttr(PyObject *o, PyObject *attr_name);
+
+ Returns 1 if o has the attribute attr_name, and 0 otherwise.
+
+ This is equivalent to the Python expression: hasattr(o,attr_name).
+
+ This function always succeeds. */
+
+/* Implemented elsewhere:
+
+ PyObject* PyObject_GetAttr(PyObject *o, PyObject *attr_name);
+
+ Retrieve an attributed named 'attr_name' form object 'o'.
+ Returns the attribute value on success, or NULL on failure.
+
+ This is the equivalent of the Python expression: o.attr_name. */
+
+
+/* Implemented elsewhere:
+
+ int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v);
+
+ Set the value of the attribute named attr_name, for object 'o',
+ to the value 'v'. Raise an exception and return -1 on failure; return 0 on
+ success.
+
+ This is the equivalent of the Python statement o.attr_name=v. */
+
+
+/* Implemented elsewhere:
+
+ int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v);
+
+ Set the value of the attribute named attr_name, for object 'o', to the value
+ 'v'. an exception and return -1 on failure; return 0 on success.
+
+ This is the equivalent of the Python statement o.attr_name=v. */
+
+/* Implemented as a macro:
+
+ int PyObject_DelAttrString(PyObject *o, const char *attr_name);
+
+ Delete attribute named attr_name, for object o. Returns
+ -1 on failure.
+
+ This is the equivalent of the Python statement: del o.attr_name. */
+#define PyObject_DelAttrString(O,A) PyObject_SetAttrString((O),(A), NULL)
+
+
+/* Implemented as a macro:
+
+ int PyObject_DelAttr(PyObject *o, PyObject *attr_name);
+
+ Delete attribute named attr_name, for object o. Returns -1
+ on failure. This is the equivalent of the Python
+ statement: del o.attr_name. */
+#define PyObject_DelAttr(O,A) PyObject_SetAttr((O),(A), NULL)
+
+
+/* Implemented elsewhere:
+
+ PyObject *PyObject_Repr(PyObject *o);
+
+ Compute the string representation of object 'o'. Returns the
+ string representation on success, NULL on failure.
+
+ This is the equivalent of the Python expression: repr(o).
+
+ Called by the repr() built-in function. */
+
+
+/* Implemented elsewhere:
+
+ PyObject *PyObject_Str(PyObject *o);
+
+ Compute the string representation of object, o. Returns the
+ string representation on success, NULL on failure.
+
+ This is the equivalent of the Python expression: str(o).
+
+ Called by the str() and print() built-in functions. */
+
+
+/* Declared elsewhere
+
+ PyAPI_FUNC(int) PyCallable_Check(PyObject *o);
+
+ Determine if the object, o, is callable. Return 1 if the object is callable
+ and 0 otherwise.
+
+ This function always succeeds. */
+
+
+#ifdef PY_SSIZE_T_CLEAN
+# define PyObject_CallFunction _PyObject_CallFunction_SizeT
+# define PyObject_CallMethod _PyObject_CallMethod_SizeT
+#endif
+
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03090000
+/* Call a callable Python object without any arguments */
+PyAPI_FUNC(PyObject *) PyObject_CallNoArgs(PyObject *func);
+#endif
+
+
+/* Call a callable Python object 'callable' with arguments given by the
+ tuple 'args' and keywords arguments given by the dictionary 'kwargs'.
+
+ 'args' must not be NULL, use an empty tuple if no arguments are
+ needed. If no named arguments are needed, 'kwargs' can be NULL.
+
+ This is the equivalent of the Python expression:
+ callable(*args, **kwargs). */
+PyAPI_FUNC(PyObject *) PyObject_Call(PyObject *callable,
+ PyObject *args, PyObject *kwargs);
+
+
+/* Call a callable Python object 'callable', with arguments given by the
+ tuple 'args'. If no arguments are needed, then 'args' can be NULL.
+
+ Returns the result of the call on success, or NULL on failure.
+
+ This is the equivalent of the Python expression:
+ callable(*args). */
+PyAPI_FUNC(PyObject *) PyObject_CallObject(PyObject *callable,
+ PyObject *args);
+
+/* Call a callable Python object, callable, with a variable number of C
+ arguments. The C arguments are described using a mkvalue-style format
+ string.
+
+ The format may be NULL, indicating that no arguments are provided.
+
+ Returns the result of the call on success, or NULL on failure.
+
+ This is the equivalent of the Python expression:
+ callable(arg1, arg2, ...). */
+PyAPI_FUNC(PyObject *) PyObject_CallFunction(PyObject *callable,
+ const char *format, ...);
+
+/* Call the method named 'name' of object 'obj' with a variable number of
+ C arguments. The C arguments are described by a mkvalue format string.
+
+ The format can be NULL, indicating that no arguments are provided.
+
+ Returns the result of the call on success, or NULL on failure.
+
+ This is the equivalent of the Python expression:
+ obj.name(arg1, arg2, ...). */
+PyAPI_FUNC(PyObject *) PyObject_CallMethod(PyObject *obj,
+ const char *name,
+ const char *format, ...);
+
+PyAPI_FUNC(PyObject *) _PyObject_CallFunction_SizeT(PyObject *callable,
+ const char *format,
+ ...);
+
+PyAPI_FUNC(PyObject *) _PyObject_CallMethod_SizeT(PyObject *obj,
+ const char *name,
+ const char *format,
+ ...);
+
+/* Call a callable Python object 'callable' with a variable number of C
+ arguments. The C arguments are provided as PyObject* values, terminated
+ by a NULL.
+
+ Returns the result of the call on success, or NULL on failure.
+
+ This is the equivalent of the Python expression:
+ callable(arg1, arg2, ...). */
+PyAPI_FUNC(PyObject *) PyObject_CallFunctionObjArgs(PyObject *callable,
+ ...);
+
+/* Call the method named 'name' of object 'obj' with a variable number of
+ C arguments. The C arguments are provided as PyObject* values, terminated
+ by NULL.
+
+ Returns the result of the call on success, or NULL on failure.
+
+ This is the equivalent of the Python expression: obj.name(*args). */
+
+PyAPI_FUNC(PyObject *) PyObject_CallMethodObjArgs(
+ PyObject *obj,
+ PyObject *name,
+ ...);
+
+
+/* Implemented elsewhere:
+
+ Py_hash_t PyObject_Hash(PyObject *o);
+
+ Compute and return the hash, hash_value, of an object, o. On
+ failure, return -1.
+
+ This is the equivalent of the Python expression: hash(o). */
+
+
+/* Implemented elsewhere:
+
+ int PyObject_IsTrue(PyObject *o);
+
+ Returns 1 if the object, o, is considered to be true, 0 if o is
+ considered to be false and -1 on failure.
+
+ This is equivalent to the Python expression: not not o. */
+
+
+/* Implemented elsewhere:
+
+ int PyObject_Not(PyObject *o);
+
+ Returns 0 if the object, o, is considered to be true, 1 if o is
+ considered to be false and -1 on failure.
+
+ This is equivalent to the Python expression: not o. */
+
+
+/* Get the type of an object.
+
+ On success, returns a type object corresponding to the object type of object
+ 'o'. On failure, returns NULL.
+
+ This is equivalent to the Python expression: type(o) */
+PyAPI_FUNC(PyObject *) PyObject_Type(PyObject *o);
+
+
+/* Return the size of object 'o'. If the object 'o' provides both sequence and
+ mapping protocols, the sequence size is returned.
+
+ On error, -1 is returned.
+
+ This is the equivalent to the Python expression: len(o) */
+PyAPI_FUNC(Py_ssize_t) PyObject_Size(PyObject *o);
+
+
+/* For DLL compatibility */
+#undef PyObject_Length
+PyAPI_FUNC(Py_ssize_t) PyObject_Length(PyObject *o);
+#define PyObject_Length PyObject_Size
+
+/* Return element of 'o' corresponding to the object 'key'. Return NULL
+ on failure.
+
+ This is the equivalent of the Python expression: o[key] */
+PyAPI_FUNC(PyObject *) PyObject_GetItem(PyObject *o, PyObject *key);
+
+
+/* Map the object 'key' to the value 'v' into 'o'.
+
+ Raise an exception and return -1 on failure; return 0 on success.
+
+ This is the equivalent of the Python statement: o[key]=v. */
+PyAPI_FUNC(int) PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v);
+
+/* Remove the mapping for the string 'key' from the object 'o'.
+ Returns -1 on failure.
+
+ This is equivalent to the Python statement: del o[key]. */
+PyAPI_FUNC(int) PyObject_DelItemString(PyObject *o, const char *key);
+
+/* Delete the mapping for the object 'key' from the object 'o'.
+ Returns -1 on failure.
+
+ This is the equivalent of the Python statement: del o[key]. */
+PyAPI_FUNC(int) PyObject_DelItem(PyObject *o, PyObject *key);
+
+
+/* === Old Buffer API ============================================ */
+
+/* FIXME: usage of these should all be replaced in Python itself
+ but for backwards compatibility we will implement them.
+ Their usage without a corresponding "unlock" mechanism
+ may create issues (but they would already be there). */
+
+/* Takes an arbitrary object which must support the (character, single segment)
+ buffer interface and returns a pointer to a read-only memory location
+ usable as character based input for subsequent processing.
+
+ Return 0 on success. buffer and buffer_len are only set in case no error
+ occurs. Otherwise, -1 is returned and an exception set. */
+Py_DEPRECATED(3.0)
+PyAPI_FUNC(int) PyObject_AsCharBuffer(PyObject *obj,
+ const char **buffer,
+ Py_ssize_t *buffer_len);
+
+/* Checks whether an arbitrary object supports the (character, single segment)
+ buffer interface.
+
+ Returns 1 on success, 0 on failure. */
+Py_DEPRECATED(3.0) PyAPI_FUNC(int) PyObject_CheckReadBuffer(PyObject *obj);
+
+/* Same as PyObject_AsCharBuffer() except that this API expects (readable,
+ single segment) buffer interface and returns a pointer to a read-only memory
+ location which can contain arbitrary data.
+
+ 0 is returned on success. buffer and buffer_len are only set in case no
+ error occurs. Otherwise, -1 is returned and an exception set. */
+Py_DEPRECATED(3.0)
+PyAPI_FUNC(int) PyObject_AsReadBuffer(PyObject *obj,
+ const void **buffer,
+ Py_ssize_t *buffer_len);
+
+/* Takes an arbitrary object which must support the (writable, single segment)
+ buffer interface and returns a pointer to a writable memory location in
+ buffer of size 'buffer_len'.
+
+ Return 0 on success. buffer and buffer_len are only set in case no error
+ occurs. Otherwise, -1 is returned and an exception set. */
+Py_DEPRECATED(3.0)
+PyAPI_FUNC(int) PyObject_AsWriteBuffer(PyObject *obj,
+ void **buffer,
+ Py_ssize_t *buffer_len);
+
+
+/* === New Buffer API ============================================ */
+
+/* Takes an arbitrary object and returns the result of calling
+ obj.__format__(format_spec). */
+PyAPI_FUNC(PyObject *) PyObject_Format(PyObject *obj,
+ PyObject *format_spec);
+
+
+/* ==== Iterators ================================================ */
+
+/* Takes an object and returns an iterator for it.
+ This is typically a new iterator but if the argument is an iterator, this
+ returns itself. */
+PyAPI_FUNC(PyObject *) PyObject_GetIter(PyObject *);
+
+/* Takes an AsyncIterable object and returns an AsyncIterator for it.
+ This is typically a new iterator but if the argument is an AsyncIterator,
+ this returns itself. */
+PyAPI_FUNC(PyObject *) PyObject_GetAIter(PyObject *);
+
+/* Returns non-zero if the object 'obj' provides iterator protocols, and 0 otherwise.
+
+ This function always succeeds. */
+PyAPI_FUNC(int) PyIter_Check(PyObject *);
+
+/* Returns non-zero if the object 'obj' provides AsyncIterator protocols, and 0 otherwise.
+
+ This function always succeeds. */
+PyAPI_FUNC(int) PyAIter_Check(PyObject *);
+
+/* Takes an iterator object and calls its tp_iternext slot,
+ returning the next value.
+
+ If the iterator is exhausted, this returns NULL without setting an
+ exception.
+
+ NULL with an exception means an error occurred. */
+PyAPI_FUNC(PyObject *) PyIter_Next(PyObject *);
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000
+
+/* Takes generator, coroutine or iterator object and sends the value into it.
+ Returns:
+ - PYGEN_RETURN (0) if generator has returned.
+ 'result' parameter is filled with return value
+ - PYGEN_ERROR (-1) if exception was raised.
+ 'result' parameter is NULL
+ - PYGEN_NEXT (1) if generator has yielded.
+ 'result' parameter is filled with yielded value. */
+PyAPI_FUNC(PySendResult) PyIter_Send(PyObject *, PyObject *, PyObject **);
+#endif
+
+
+/* === Number Protocol ================================================== */
+
+/* Returns 1 if the object 'o' provides numeric protocols, and 0 otherwise.
+
+ This function always succeeds. */
+PyAPI_FUNC(int) PyNumber_Check(PyObject *o);
+
+/* Returns the result of adding o1 and o2, or NULL on failure.
+
+ This is the equivalent of the Python expression: o1 + o2. */
+PyAPI_FUNC(PyObject *) PyNumber_Add(PyObject *o1, PyObject *o2);
+
+/* Returns the result of subtracting o2 from o1, or NULL on failure.
+
+ This is the equivalent of the Python expression: o1 - o2. */
+PyAPI_FUNC(PyObject *) PyNumber_Subtract(PyObject *o1, PyObject *o2);
+
+/* Returns the result of multiplying o1 and o2, or NULL on failure.
+
+ This is the equivalent of the Python expression: o1 * o2. */
+PyAPI_FUNC(PyObject *) PyNumber_Multiply(PyObject *o1, PyObject *o2);
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
+/* This is the equivalent of the Python expression: o1 @ o2. */
+PyAPI_FUNC(PyObject *) PyNumber_MatrixMultiply(PyObject *o1, PyObject *o2);
+#endif
+
+/* Returns the result of dividing o1 by o2 giving an integral result,
+ or NULL on failure.
+
+ This is the equivalent of the Python expression: o1 // o2. */
+PyAPI_FUNC(PyObject *) PyNumber_FloorDivide(PyObject *o1, PyObject *o2);
+
+/* Returns the result of dividing o1 by o2 giving a float result, or NULL on
+ failure.
+
+ This is the equivalent of the Python expression: o1 / o2. */
+PyAPI_FUNC(PyObject *) PyNumber_TrueDivide(PyObject *o1, PyObject *o2);
+
+/* Returns the remainder of dividing o1 by o2, or NULL on failure.
+
+ This is the equivalent of the Python expression: o1 % o2. */
+PyAPI_FUNC(PyObject *) PyNumber_Remainder(PyObject *o1, PyObject *o2);
+
+/* See the built-in function divmod.
+
+ Returns NULL on failure.
+
+ This is the equivalent of the Python expression: divmod(o1, o2). */
+PyAPI_FUNC(PyObject *) PyNumber_Divmod(PyObject *o1, PyObject *o2);
+
+/* See the built-in function pow. Returns NULL on failure.
+
+ This is the equivalent of the Python expression: pow(o1, o2, o3),
+ where o3 is optional. */
+PyAPI_FUNC(PyObject *) PyNumber_Power(PyObject *o1, PyObject *o2,
+ PyObject *o3);
+
+/* Returns the negation of o on success, or NULL on failure.
+
+ This is the equivalent of the Python expression: -o. */
+PyAPI_FUNC(PyObject *) PyNumber_Negative(PyObject *o);
+
+/* Returns the positive of o on success, or NULL on failure.
+
+ This is the equivalent of the Python expression: +o. */
+PyAPI_FUNC(PyObject *) PyNumber_Positive(PyObject *o);
+
+/* Returns the absolute value of 'o', or NULL on failure.
+
+ This is the equivalent of the Python expression: abs(o). */
+PyAPI_FUNC(PyObject *) PyNumber_Absolute(PyObject *o);
+
+/* Returns the bitwise negation of 'o' on success, or NULL on failure.
+
+ This is the equivalent of the Python expression: ~o. */
+PyAPI_FUNC(PyObject *) PyNumber_Invert(PyObject *o);
+
+/* Returns the result of left shifting o1 by o2 on success, or NULL on failure.
+
+ This is the equivalent of the Python expression: o1 << o2. */
+PyAPI_FUNC(PyObject *) PyNumber_Lshift(PyObject *o1, PyObject *o2);
+
+/* Returns the result of right shifting o1 by o2 on success, or NULL on
+ failure.
+
+ This is the equivalent of the Python expression: o1 >> o2. */
+PyAPI_FUNC(PyObject *) PyNumber_Rshift(PyObject *o1, PyObject *o2);
+
+/* Returns the result of bitwise and of o1 and o2 on success, or NULL on
+ failure.
+
+ This is the equivalent of the Python expression: o1 & o2. */
+PyAPI_FUNC(PyObject *) PyNumber_And(PyObject *o1, PyObject *o2);
+
+/* Returns the bitwise exclusive or of o1 by o2 on success, or NULL on failure.
+
+ This is the equivalent of the Python expression: o1 ^ o2. */
+PyAPI_FUNC(PyObject *) PyNumber_Xor(PyObject *o1, PyObject *o2);
+
+/* Returns the result of bitwise or on o1 and o2 on success, or NULL on
+ failure.
+
+ This is the equivalent of the Python expression: o1 | o2. */
+PyAPI_FUNC(PyObject *) PyNumber_Or(PyObject *o1, PyObject *o2);
+
+/* Returns 1 if obj is an index integer (has the nb_index slot of the
+ tp_as_number structure filled in), and 0 otherwise. */
+PyAPI_FUNC(int) PyIndex_Check(PyObject *);
+
+/* Returns the object 'o' converted to a Python int, or NULL with an exception
+ raised on failure. */
+PyAPI_FUNC(PyObject *) PyNumber_Index(PyObject *o);
+
+/* Returns the object 'o' converted to Py_ssize_t by going through
+ PyNumber_Index() first.
+
+ If an overflow error occurs while converting the int to Py_ssize_t, then the
+ second argument 'exc' is the error-type to return. If it is NULL, then the
+ overflow error is cleared and the value is clipped. */
+PyAPI_FUNC(Py_ssize_t) PyNumber_AsSsize_t(PyObject *o, PyObject *exc);
+
+/* Returns the object 'o' converted to an integer object on success, or NULL
+ on failure.
+
+ This is the equivalent of the Python expression: int(o). */
+PyAPI_FUNC(PyObject *) PyNumber_Long(PyObject *o);
+
+/* Returns the object 'o' converted to a float object on success, or NULL
+ on failure.
+
+ This is the equivalent of the Python expression: float(o). */
+PyAPI_FUNC(PyObject *) PyNumber_Float(PyObject *o);
+
+
+/* --- In-place variants of (some of) the above number protocol functions -- */
+
+/* Returns the result of adding o2 to o1, possibly in-place, or NULL
+ on failure.
+
+ This is the equivalent of the Python expression: o1 += o2. */
+PyAPI_FUNC(PyObject *) PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2);
+
+/* Returns the result of subtracting o2 from o1, possibly in-place or
+ NULL on failure.
+
+ This is the equivalent of the Python expression: o1 -= o2. */
+PyAPI_FUNC(PyObject *) PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2);
+
+/* Returns the result of multiplying o1 by o2, possibly in-place, or NULL on
+ failure.
+
+ This is the equivalent of the Python expression: o1 *= o2. */
+PyAPI_FUNC(PyObject *) PyNumber_InPlaceMultiply(PyObject *o1, PyObject *o2);
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
+/* This is the equivalent of the Python expression: o1 @= o2. */
+PyAPI_FUNC(PyObject *) PyNumber_InPlaceMatrixMultiply(PyObject *o1, PyObject *o2);
+#endif
+
+/* Returns the result of dividing o1 by o2 giving an integral result, possibly
+ in-place, or NULL on failure.
+
+ This is the equivalent of the Python expression: o1 /= o2. */
+PyAPI_FUNC(PyObject *) PyNumber_InPlaceFloorDivide(PyObject *o1,
+ PyObject *o2);
+
+/* Returns the result of dividing o1 by o2 giving a float result, possibly
+ in-place, or null on failure.
+
+ This is the equivalent of the Python expression: o1 /= o2. */
+PyAPI_FUNC(PyObject *) PyNumber_InPlaceTrueDivide(PyObject *o1,
+ PyObject *o2);
+
+/* Returns the remainder of dividing o1 by o2, possibly in-place, or NULL on
+ failure.
+
+ This is the equivalent of the Python expression: o1 %= o2. */
+PyAPI_FUNC(PyObject *) PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2);
+
+/* Returns the result of raising o1 to the power of o2, possibly in-place,
+ or NULL on failure.
+
+ This is the equivalent of the Python expression: o1 **= o2,
+ or o1 = pow(o1, o2, o3) if o3 is present. */
+PyAPI_FUNC(PyObject *) PyNumber_InPlacePower(PyObject *o1, PyObject *o2,
+ PyObject *o3);
+
+/* Returns the result of left shifting o1 by o2, possibly in-place, or NULL
+ on failure.
+
+ This is the equivalent of the Python expression: o1 <<= o2. */
+PyAPI_FUNC(PyObject *) PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2);
+
+/* Returns the result of right shifting o1 by o2, possibly in-place or NULL
+ on failure.
+
+ This is the equivalent of the Python expression: o1 >>= o2. */
+PyAPI_FUNC(PyObject *) PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2);
+
+/* Returns the result of bitwise and of o1 and o2, possibly in-place, or NULL
+ on failure.
+
+ This is the equivalent of the Python expression: o1 &= o2. */
+PyAPI_FUNC(PyObject *) PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2);
+
+/* Returns the bitwise exclusive or of o1 by o2, possibly in-place, or NULL
+ on failure.
+
+ This is the equivalent of the Python expression: o1 ^= o2. */
+PyAPI_FUNC(PyObject *) PyNumber_InPlaceXor(PyObject *o1, PyObject *o2);
+
+/* Returns the result of bitwise or of o1 and o2, possibly in-place,
+ or NULL on failure.
+
+ This is the equivalent of the Python expression: o1 |= o2. */
+PyAPI_FUNC(PyObject *) PyNumber_InPlaceOr(PyObject *o1, PyObject *o2);
+
+/* Returns the integer n converted to a string with a base, with a base
+ marker of 0b, 0o or 0x prefixed if applicable.
+
+ If n is not an int object, it is converted with PyNumber_Index first. */
+PyAPI_FUNC(PyObject *) PyNumber_ToBase(PyObject *n, int base);
+
+
+/* === Sequence protocol ================================================ */
+
+/* Return 1 if the object provides sequence protocol, and zero
+ otherwise.
+
+ This function always succeeds. */
+PyAPI_FUNC(int) PySequence_Check(PyObject *o);
+
+/* Return the size of sequence object o, or -1 on failure. */
+PyAPI_FUNC(Py_ssize_t) PySequence_Size(PyObject *o);
+
+/* For DLL compatibility */
+#undef PySequence_Length
+PyAPI_FUNC(Py_ssize_t) PySequence_Length(PyObject *o);
+#define PySequence_Length PySequence_Size
+
+
+/* Return the concatenation of o1 and o2 on success, and NULL on failure.
+
+ This is the equivalent of the Python expression: o1 + o2. */
+PyAPI_FUNC(PyObject *) PySequence_Concat(PyObject *o1, PyObject *o2);
+
+/* Return the result of repeating sequence object 'o' 'count' times,
+ or NULL on failure.
+
+ This is the equivalent of the Python expression: o * count. */
+PyAPI_FUNC(PyObject *) PySequence_Repeat(PyObject *o, Py_ssize_t count);
+
+/* Return the ith element of o, or NULL on failure.
+
+ This is the equivalent of the Python expression: o[i]. */
+PyAPI_FUNC(PyObject *) PySequence_GetItem(PyObject *o, Py_ssize_t i);
+
+/* Return the slice of sequence object o between i1 and i2, or NULL on failure.
+
+ This is the equivalent of the Python expression: o[i1:i2]. */
+PyAPI_FUNC(PyObject *) PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2);
+
+/* Assign object 'v' to the ith element of the sequence 'o'. Raise an exception
+ and return -1 on failure; return 0 on success.
+
+ This is the equivalent of the Python statement o[i] = v. */
+PyAPI_FUNC(int) PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v);
+
+/* Delete the 'i'-th element of the sequence 'v'. Returns -1 on failure.
+
+ This is the equivalent of the Python statement: del o[i]. */
+PyAPI_FUNC(int) PySequence_DelItem(PyObject *o, Py_ssize_t i);
+
+/* Assign the sequence object 'v' to the slice in sequence object 'o',
+ from 'i1' to 'i2'. Returns -1 on failure.
+
+ This is the equivalent of the Python statement: o[i1:i2] = v. */
+PyAPI_FUNC(int) PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2,
+ PyObject *v);
+
+/* Delete the slice in sequence object 'o' from 'i1' to 'i2'.
+ Returns -1 on failure.
+
+ This is the equivalent of the Python statement: del o[i1:i2]. */
+PyAPI_FUNC(int) PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2);
+
+/* Returns the sequence 'o' as a tuple on success, and NULL on failure.
+
+ This is equivalent to the Python expression: tuple(o). */
+PyAPI_FUNC(PyObject *) PySequence_Tuple(PyObject *o);
+
+/* Returns the sequence 'o' as a list on success, and NULL on failure.
+ This is equivalent to the Python expression: list(o) */
+PyAPI_FUNC(PyObject *) PySequence_List(PyObject *o);
+
+/* Return the sequence 'o' as a list, unless it's already a tuple or list.
+
+ Use PySequence_Fast_GET_ITEM to access the members of this list, and
+ PySequence_Fast_GET_SIZE to get its length.
+
+ Returns NULL on failure. If the object does not support iteration, raises a
+ TypeError exception with 'm' as the message text. */
+PyAPI_FUNC(PyObject *) PySequence_Fast(PyObject *o, const char* m);
+
+/* Return the size of the sequence 'o', assuming that 'o' was returned by
+ PySequence_Fast and is not NULL. */
+#define PySequence_Fast_GET_SIZE(o) \
+ (PyList_Check(o) ? PyList_GET_SIZE(o) : PyTuple_GET_SIZE(o))
+
+/* Return the 'i'-th element of the sequence 'o', assuming that o was returned
+ by PySequence_Fast, and that i is within bounds. */
+#define PySequence_Fast_GET_ITEM(o, i)\
+ (PyList_Check(o) ? PyList_GET_ITEM(o, i) : PyTuple_GET_ITEM(o, i))
+
+/* Return a pointer to the underlying item array for
+ an object returned by PySequence_Fast */
+#define PySequence_Fast_ITEMS(sf) \
+ (PyList_Check(sf) ? ((PyListObject *)(sf))->ob_item \
+ : ((PyTupleObject *)(sf))->ob_item)
+
+/* Return the number of occurrences on value on 'o', that is, return
+ the number of keys for which o[key] == value.
+
+ On failure, return -1. This is equivalent to the Python expression:
+ o.count(value). */
+PyAPI_FUNC(Py_ssize_t) PySequence_Count(PyObject *o, PyObject *value);
+
+/* Return 1 if 'ob' is in the sequence 'seq'; 0 if 'ob' is not in the sequence
+ 'seq'; -1 on error.
+
+ Use __contains__ if possible, else _PySequence_IterSearch(). */
+PyAPI_FUNC(int) PySequence_Contains(PyObject *seq, PyObject *ob);
+
+/* For DLL-level backwards compatibility */
+#undef PySequence_In
+/* Determine if the sequence 'o' contains 'value'. If an item in 'o' is equal
+ to 'value', return 1, otherwise return 0. On error, return -1.
+
+ This is equivalent to the Python expression: value in o. */
+PyAPI_FUNC(int) PySequence_In(PyObject *o, PyObject *value);
+
+/* For source-level backwards compatibility */
+#define PySequence_In PySequence_Contains
+
+
+/* Return the first index for which o[i] == value.
+ On error, return -1.
+
+ This is equivalent to the Python expression: o.index(value). */
+PyAPI_FUNC(Py_ssize_t) PySequence_Index(PyObject *o, PyObject *value);
+
+
+/* --- In-place versions of some of the above Sequence functions --- */
+
+/* Append sequence 'o2' to sequence 'o1', in-place when possible. Return the
+ resulting object, which could be 'o1', or NULL on failure.
+
+ This is the equivalent of the Python expression: o1 += o2. */
+PyAPI_FUNC(PyObject *) PySequence_InPlaceConcat(PyObject *o1, PyObject *o2);
+
+/* Repeat sequence 'o' by 'count', in-place when possible. Return the resulting
+ object, which could be 'o', or NULL on failure.
+
+ This is the equivalent of the Python expression: o1 *= count. */
+PyAPI_FUNC(PyObject *) PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count);
+
+
+/* === Mapping protocol ================================================= */
+
+/* Return 1 if the object provides mapping protocol, and 0 otherwise.
+
+ This function always succeeds. */
+PyAPI_FUNC(int) PyMapping_Check(PyObject *o);
+
+/* Returns the number of keys in mapping object 'o' on success, and -1 on
+ failure. This is equivalent to the Python expression: len(o). */
+PyAPI_FUNC(Py_ssize_t) PyMapping_Size(PyObject *o);
+
+/* For DLL compatibility */
+#undef PyMapping_Length
+PyAPI_FUNC(Py_ssize_t) PyMapping_Length(PyObject *o);
+#define PyMapping_Length PyMapping_Size
+
+
+/* Implemented as a macro:
+
+ int PyMapping_DelItemString(PyObject *o, const char *key);
+
+ Remove the mapping for the string 'key' from the mapping 'o'. Returns -1 on
+ failure.
+
+ This is equivalent to the Python statement: del o[key]. */
+#define PyMapping_DelItemString(O,K) PyObject_DelItemString((O),(K))
+
+/* Implemented as a macro:
+
+ int PyMapping_DelItem(PyObject *o, PyObject *key);
+
+ Remove the mapping for the object 'key' from the mapping object 'o'.
+ Returns -1 on failure.
+
+ This is equivalent to the Python statement: del o[key]. */
+#define PyMapping_DelItem(O,K) PyObject_DelItem((O),(K))
+
+/* On success, return 1 if the mapping object 'o' has the key 'key',
+ and 0 otherwise.
+
+ This is equivalent to the Python expression: key in o.
+
+ This function always succeeds. */
+PyAPI_FUNC(int) PyMapping_HasKeyString(PyObject *o, const char *key);
+
+/* Return 1 if the mapping object has the key 'key', and 0 otherwise.
+
+ This is equivalent to the Python expression: key in o.
+
+ This function always succeeds. */
+PyAPI_FUNC(int) PyMapping_HasKey(PyObject *o, PyObject *key);
+
+/* On success, return a list or tuple of the keys in mapping object 'o'.
+ On failure, return NULL. */
+PyAPI_FUNC(PyObject *) PyMapping_Keys(PyObject *o);
+
+/* On success, return a list or tuple of the values in mapping object 'o'.
+ On failure, return NULL. */
+PyAPI_FUNC(PyObject *) PyMapping_Values(PyObject *o);
+
+/* On success, return a list or tuple of the items in mapping object 'o',
+ where each item is a tuple containing a key-value pair. On failure, return
+ NULL. */
+PyAPI_FUNC(PyObject *) PyMapping_Items(PyObject *o);
+
+/* Return element of 'o' corresponding to the string 'key' or NULL on failure.
+
+ This is the equivalent of the Python expression: o[key]. */
+PyAPI_FUNC(PyObject *) PyMapping_GetItemString(PyObject *o,
+ const char *key);
+
+/* Map the string 'key' to the value 'v' in the mapping 'o'.
+ Returns -1 on failure.
+
+ This is the equivalent of the Python statement: o[key]=v. */
+PyAPI_FUNC(int) PyMapping_SetItemString(PyObject *o, const char *key,
+ PyObject *value);
+
+/* isinstance(object, typeorclass) */
+PyAPI_FUNC(int) PyObject_IsInstance(PyObject *object, PyObject *typeorclass);
+
+/* issubclass(object, typeorclass) */
+PyAPI_FUNC(int) PyObject_IsSubclass(PyObject *object, PyObject *typeorclass);
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_ABSTRACTOBJECT_H
+# include "cpython/abstract.h"
+# undef Py_CPYTHON_ABSTRACTOBJECT_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* Py_ABSTRACTOBJECT_H */
diff --git a/include/python3.10/bltinmodule.h b/include/python3.11/bltinmodule.h
similarity index 100%
rename from include/python3.10/bltinmodule.h
rename to include/python3.11/bltinmodule.h
diff --git a/include/python3.11/boolobject.h b/include/python3.11/boolobject.h
new file mode 100644
index 0000000..28068d1
--- /dev/null
+++ b/include/python3.11/boolobject.h
@@ -0,0 +1,43 @@
+/* Boolean object interface */
+
+#ifndef Py_BOOLOBJECT_H
+#define Py_BOOLOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+PyAPI_DATA(PyTypeObject) PyBool_Type;
+
+#define PyBool_Check(x) Py_IS_TYPE(x, &PyBool_Type)
+
+/* Py_False and Py_True are the only two bools in existence.
+Don't forget to apply Py_INCREF() when returning either!!! */
+
+/* Don't use these directly */
+PyAPI_DATA(PyLongObject) _Py_FalseStruct;
+PyAPI_DATA(PyLongObject) _Py_TrueStruct;
+
+/* Use these macros */
+#define Py_False ((PyObject *) &_Py_FalseStruct)
+#define Py_True ((PyObject *) &_Py_TrueStruct)
+
+// Test if an object is the True singleton, the same as "x is True" in Python.
+PyAPI_FUNC(int) Py_IsTrue(PyObject *x);
+#define Py_IsTrue(x) Py_Is((x), Py_True)
+
+// Test if an object is the False singleton, the same as "x is False" in Python.
+PyAPI_FUNC(int) Py_IsFalse(PyObject *x);
+#define Py_IsFalse(x) Py_Is((x), Py_False)
+
+/* Macros for returning Py_True or Py_False, respectively */
+#define Py_RETURN_TRUE return Py_NewRef(Py_True)
+#define Py_RETURN_FALSE return Py_NewRef(Py_False)
+
+/* Function to return a bool from a C long */
+PyAPI_FUNC(PyObject *) PyBool_FromLong(long);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_BOOLOBJECT_H */
diff --git a/include/python3.11/bytearrayobject.h b/include/python3.11/bytearrayobject.h
new file mode 100644
index 0000000..ae2bde1
--- /dev/null
+++ b/include/python3.11/bytearrayobject.h
@@ -0,0 +1,44 @@
+/* ByteArray object interface */
+
+#ifndef Py_BYTEARRAYOBJECT_H
+#define Py_BYTEARRAYOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Type PyByteArrayObject represents a mutable array of bytes.
+ * The Python API is that of a sequence;
+ * the bytes are mapped to ints in [0, 256).
+ * Bytes are not characters; they may be used to encode characters.
+ * The only way to go between bytes and str/unicode is via encoding
+ * and decoding.
+ * For the convenience of C programmers, the bytes type is considered
+ * to contain a char pointer, not an unsigned char pointer.
+ */
+
+/* Type object */
+PyAPI_DATA(PyTypeObject) PyByteArray_Type;
+PyAPI_DATA(PyTypeObject) PyByteArrayIter_Type;
+
+/* Type check macros */
+#define PyByteArray_Check(self) PyObject_TypeCheck(self, &PyByteArray_Type)
+#define PyByteArray_CheckExact(self) Py_IS_TYPE(self, &PyByteArray_Type)
+
+/* Direct API functions */
+PyAPI_FUNC(PyObject *) PyByteArray_FromObject(PyObject *);
+PyAPI_FUNC(PyObject *) PyByteArray_Concat(PyObject *, PyObject *);
+PyAPI_FUNC(PyObject *) PyByteArray_FromStringAndSize(const char *, Py_ssize_t);
+PyAPI_FUNC(Py_ssize_t) PyByteArray_Size(PyObject *);
+PyAPI_FUNC(char *) PyByteArray_AsString(PyObject *);
+PyAPI_FUNC(int) PyByteArray_Resize(PyObject *, Py_ssize_t);
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_BYTEARRAYOBJECT_H
+# include "cpython/bytearrayobject.h"
+# undef Py_CPYTHON_BYTEARRAYOBJECT_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_BYTEARRAYOBJECT_H */
diff --git a/include/python3.11/bytesobject.h b/include/python3.11/bytesobject.h
new file mode 100644
index 0000000..4c4dc40
--- /dev/null
+++ b/include/python3.11/bytesobject.h
@@ -0,0 +1,69 @@
+
+/* Bytes object interface */
+
+#ifndef Py_BYTESOBJECT_H
+#define Py_BYTESOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdarg.h> // va_list
+
+/*
+Type PyBytesObject represents a byte string. An extra zero byte is
+reserved at the end to ensure it is zero-terminated, but a size is
+present so strings with null bytes in them can be represented. This
+is an immutable object type.
+
+There are functions to create new bytes objects, to test
+an object for bytes-ness, and to get the
+byte string value. The latter function returns a null pointer
+if the object is not of the proper type.
+There is a variant that takes an explicit size as well as a
+variant that assumes a zero-terminated string. Note that none of the
+functions should be applied to NULL pointer.
+*/
+
+PyAPI_DATA(PyTypeObject) PyBytes_Type;
+PyAPI_DATA(PyTypeObject) PyBytesIter_Type;
+
+#define PyBytes_Check(op) \
+ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_BYTES_SUBCLASS)
+#define PyBytes_CheckExact(op) Py_IS_TYPE(op, &PyBytes_Type)
+
+PyAPI_FUNC(PyObject *) PyBytes_FromStringAndSize(const char *, Py_ssize_t);
+PyAPI_FUNC(PyObject *) PyBytes_FromString(const char *);
+PyAPI_FUNC(PyObject *) PyBytes_FromObject(PyObject *);
+PyAPI_FUNC(PyObject *) PyBytes_FromFormatV(const char*, va_list)
+ Py_GCC_ATTRIBUTE((format(printf, 1, 0)));
+PyAPI_FUNC(PyObject *) PyBytes_FromFormat(const char*, ...)
+ Py_GCC_ATTRIBUTE((format(printf, 1, 2)));
+PyAPI_FUNC(Py_ssize_t) PyBytes_Size(PyObject *);
+PyAPI_FUNC(char *) PyBytes_AsString(PyObject *);
+PyAPI_FUNC(PyObject *) PyBytes_Repr(PyObject *, int);
+PyAPI_FUNC(void) PyBytes_Concat(PyObject **, PyObject *);
+PyAPI_FUNC(void) PyBytes_ConcatAndDel(PyObject **, PyObject *);
+PyAPI_FUNC(PyObject *) PyBytes_DecodeEscape(const char *, Py_ssize_t,
+ const char *, Py_ssize_t,
+ const char *);
+
+/* Provides access to the internal data buffer and size of a bytes object.
+ Passing NULL as len parameter will force the string buffer to be
+ 0-terminated (passing a string with embedded NUL characters will
+ cause an exception). */
+PyAPI_FUNC(int) PyBytes_AsStringAndSize(
+ PyObject *obj, /* bytes object */
+ char **s, /* pointer to buffer variable */
+ Py_ssize_t *len /* pointer to length variable or NULL */
+ );
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_BYTESOBJECT_H
+# include "cpython/bytesobject.h"
+# undef Py_CPYTHON_BYTESOBJECT_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_BYTESOBJECT_H */
diff --git a/include/python3.11/ceval.h b/include/python3.11/ceval.h
new file mode 100644
index 0000000..1b57f6e
--- /dev/null
+++ b/include/python3.11/ceval.h
@@ -0,0 +1,168 @@
+/* Interface to random parts in ceval.c */
+
+#ifndef Py_CEVAL_H
+#define Py_CEVAL_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+PyAPI_FUNC(PyObject *) PyEval_EvalCode(PyObject *, PyObject *, PyObject *);
+
+PyAPI_FUNC(PyObject *) PyEval_EvalCodeEx(PyObject *co,
+ PyObject *globals,
+ PyObject *locals,
+ PyObject *const *args, int argc,
+ PyObject *const *kwds, int kwdc,
+ PyObject *const *defs, int defc,
+ PyObject *kwdefs, PyObject *closure);
+
+/* PyEval_CallObjectWithKeywords(), PyEval_CallObject(), PyEval_CallFunction
+ * and PyEval_CallMethod are deprecated. Since they are officially part of the
+ * stable ABI (PEP 384), they must be kept for backward compatibility.
+ * PyObject_Call(), PyObject_CallFunction() and PyObject_CallMethod() are
+ * recommended to call a callable object.
+ */
+
+Py_DEPRECATED(3.9) PyAPI_FUNC(PyObject *) PyEval_CallObjectWithKeywords(
+ PyObject *callable,
+ PyObject *args,
+ PyObject *kwargs);
+
+/* Deprecated since PyEval_CallObjectWithKeywords is deprecated */
+#define PyEval_CallObject(callable, arg) \
+ PyEval_CallObjectWithKeywords(callable, arg, (PyObject *)NULL)
+
+Py_DEPRECATED(3.9) PyAPI_FUNC(PyObject *) PyEval_CallFunction(
+ PyObject *callable, const char *format, ...);
+Py_DEPRECATED(3.9) PyAPI_FUNC(PyObject *) PyEval_CallMethod(
+ PyObject *obj, const char *name, const char *format, ...);
+
+PyAPI_FUNC(PyObject *) PyEval_GetBuiltins(void);
+PyAPI_FUNC(PyObject *) PyEval_GetGlobals(void);
+PyAPI_FUNC(PyObject *) PyEval_GetLocals(void);
+PyAPI_FUNC(PyFrameObject *) PyEval_GetFrame(void);
+
+PyAPI_FUNC(int) Py_AddPendingCall(int (*func)(void *), void *arg);
+PyAPI_FUNC(int) Py_MakePendingCalls(void);
+
+/* Protection against deeply nested recursive calls
+
+ In Python 3.0, this protection has two levels:
+ * normal anti-recursion protection is triggered when the recursion level
+ exceeds the current recursion limit. It raises a RecursionError, and sets
+ the "overflowed" flag in the thread state structure. This flag
+ temporarily *disables* the normal protection; this allows cleanup code
+ to potentially outgrow the recursion limit while processing the
+ RecursionError.
+ * "last chance" anti-recursion protection is triggered when the recursion
+ level exceeds "current recursion limit + 50". By construction, this
+ protection can only be triggered when the "overflowed" flag is set. It
+ means the cleanup code has itself gone into an infinite loop, or the
+ RecursionError has been mistakingly ignored. When this protection is
+ triggered, the interpreter aborts with a Fatal Error.
+
+ In addition, the "overflowed" flag is automatically reset when the
+ recursion level drops below "current recursion limit - 50". This heuristic
+ is meant to ensure that the normal anti-recursion protection doesn't get
+ disabled too long.
+
+ Please note: this scheme has its own limitations. See:
+ http://mail.python.org/pipermail/python-dev/2008-August/082106.html
+ for some observations.
+*/
+PyAPI_FUNC(void) Py_SetRecursionLimit(int);
+PyAPI_FUNC(int) Py_GetRecursionLimit(void);
+
+PyAPI_FUNC(int) Py_EnterRecursiveCall(const char *where);
+PyAPI_FUNC(void) Py_LeaveRecursiveCall(void);
+
+PyAPI_FUNC(const char *) PyEval_GetFuncName(PyObject *);
+PyAPI_FUNC(const char *) PyEval_GetFuncDesc(PyObject *);
+
+PyAPI_FUNC(PyObject *) PyEval_EvalFrame(PyFrameObject *);
+PyAPI_FUNC(PyObject *) PyEval_EvalFrameEx(PyFrameObject *f, int exc);
+
+/* Interface for threads.
+
+ A module that plans to do a blocking system call (or something else
+ that lasts a long time and doesn't touch Python data) can allow other
+ threads to run as follows:
+
+ ...preparations here...
+ Py_BEGIN_ALLOW_THREADS
+ ...blocking system call here...
+ Py_END_ALLOW_THREADS
+ ...interpret result here...
+
+ The Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS pair expands to a
+ {}-surrounded block.
+ To leave the block in the middle (e.g., with return), you must insert
+ a line containing Py_BLOCK_THREADS before the return, e.g.
+
+ if (...premature_exit...) {
+ Py_BLOCK_THREADS
+ PyErr_SetFromErrno(PyExc_OSError);
+ return NULL;
+ }
+
+ An alternative is:
+
+ Py_BLOCK_THREADS
+ if (...premature_exit...) {
+ PyErr_SetFromErrno(PyExc_OSError);
+ return NULL;
+ }
+ Py_UNBLOCK_THREADS
+
+ For convenience, that the value of 'errno' is restored across
+ Py_END_ALLOW_THREADS and Py_BLOCK_THREADS.
+
+ WARNING: NEVER NEST CALLS TO Py_BEGIN_ALLOW_THREADS AND
+ Py_END_ALLOW_THREADS!!!
+
+ Note that not yet all candidates have been converted to use this
+ mechanism!
+*/
+
+PyAPI_FUNC(PyThreadState *) PyEval_SaveThread(void);
+PyAPI_FUNC(void) PyEval_RestoreThread(PyThreadState *);
+
+Py_DEPRECATED(3.9) PyAPI_FUNC(int) PyEval_ThreadsInitialized(void);
+Py_DEPRECATED(3.9) PyAPI_FUNC(void) PyEval_InitThreads(void);
+/* PyEval_AcquireLock() and PyEval_ReleaseLock() are part of stable ABI.
+ * They will be removed from this header file in the future version.
+ * But they will be remained in ABI until Python 4.0.
+ */
+Py_DEPRECATED(3.2) PyAPI_FUNC(void) PyEval_AcquireLock(void);
+Py_DEPRECATED(3.2) PyAPI_FUNC(void) PyEval_ReleaseLock(void);
+PyAPI_FUNC(void) PyEval_AcquireThread(PyThreadState *tstate);
+PyAPI_FUNC(void) PyEval_ReleaseThread(PyThreadState *tstate);
+
+#define Py_BEGIN_ALLOW_THREADS { \
+ PyThreadState *_save; \
+ _save = PyEval_SaveThread();
+#define Py_BLOCK_THREADS PyEval_RestoreThread(_save);
+#define Py_UNBLOCK_THREADS _save = PyEval_SaveThread();
+#define Py_END_ALLOW_THREADS PyEval_RestoreThread(_save); \
+ }
+
+/* Masks and values used by FORMAT_VALUE opcode. */
+#define FVC_MASK 0x3
+#define FVC_NONE 0x0
+#define FVC_STR 0x1
+#define FVC_REPR 0x2
+#define FVC_ASCII 0x3
+#define FVS_MASK 0x4
+#define FVS_HAVE_SPEC 0x4
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_CEVAL_H
+# include "cpython/ceval.h"
+# undef Py_CPYTHON_CEVAL_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_CEVAL_H */
diff --git a/include/python3.10/codecs.h b/include/python3.11/codecs.h
similarity index 100%
rename from include/python3.10/codecs.h
rename to include/python3.11/codecs.h
diff --git a/include/python3.10/compile.h b/include/python3.11/compile.h
similarity index 100%
rename from include/python3.10/compile.h
rename to include/python3.11/compile.h
diff --git a/include/python3.11/complexobject.h b/include/python3.11/complexobject.h
new file mode 100644
index 0000000..c7764e4
--- /dev/null
+++ b/include/python3.11/complexobject.h
@@ -0,0 +1,30 @@
+/* Complex number structure */
+
+#ifndef Py_COMPLEXOBJECT_H
+#define Py_COMPLEXOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Complex object interface */
+
+PyAPI_DATA(PyTypeObject) PyComplex_Type;
+
+#define PyComplex_Check(op) PyObject_TypeCheck(op, &PyComplex_Type)
+#define PyComplex_CheckExact(op) Py_IS_TYPE(op, &PyComplex_Type)
+
+PyAPI_FUNC(PyObject *) PyComplex_FromDoubles(double real, double imag);
+
+PyAPI_FUNC(double) PyComplex_RealAsDouble(PyObject *op);
+PyAPI_FUNC(double) PyComplex_ImagAsDouble(PyObject *op);
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_COMPLEXOBJECT_H
+# include "cpython/complexobject.h"
+# undef Py_CPYTHON_COMPLEXOBJECT_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_COMPLEXOBJECT_H */
diff --git a/include/python3.11/cpython/abstract.h b/include/python3.11/cpython/abstract.h
new file mode 100644
index 0000000..d276669
--- /dev/null
+++ b/include/python3.11/cpython/abstract.h
@@ -0,0 +1,219 @@
+#ifndef Py_CPYTHON_ABSTRACTOBJECT_H
+# error "this header file must not be included directly"
+#endif
+
+/* === Object Protocol ================================================== */
+
+#ifdef PY_SSIZE_T_CLEAN
+# define _PyObject_CallMethodId _PyObject_CallMethodId_SizeT
+#endif
+
+/* Convert keyword arguments from the FASTCALL (stack: C array, kwnames: tuple)
+ format to a Python dictionary ("kwargs" dict).
+
+ The type of kwnames keys is not checked. The final function getting
+ arguments is responsible to check if all keys are strings, for example using
+ PyArg_ParseTupleAndKeywords() or PyArg_ValidateKeywordArguments().
+
+ Duplicate keys are merged using the last value. If duplicate keys must raise
+ an exception, the caller is responsible to implement an explicit keys on
+ kwnames. */
+PyAPI_FUNC(PyObject *) _PyStack_AsDict(
+ PyObject *const *values,
+ PyObject *kwnames);
+
+/* Suggested size (number of positional arguments) for arrays of PyObject*
+ allocated on a C stack to avoid allocating memory on the heap memory. Such
+ array is used to pass positional arguments to call functions of the
+ PyObject_Vectorcall() family.
+
+ The size is chosen to not abuse the C stack and so limit the risk of stack
+ overflow. The size is also chosen to allow using the small stack for most
+ function calls of the Python standard library. On 64-bit CPU, it allocates
+ 40 bytes on the stack. */
+#define _PY_FASTCALL_SMALL_STACK 5
+
+PyAPI_FUNC(PyObject *) _Py_CheckFunctionResult(
+ PyThreadState *tstate,
+ PyObject *callable,
+ PyObject *result,
+ const char *where);
+
+/* === Vectorcall protocol (PEP 590) ============================= */
+
+/* Call callable using tp_call. Arguments are like PyObject_Vectorcall()
+ or PyObject_FastCallDict() (both forms are supported),
+ except that nargs is plainly the number of arguments without flags. */
+PyAPI_FUNC(PyObject *) _PyObject_MakeTpCall(
+ PyThreadState *tstate,
+ PyObject *callable,
+ PyObject *const *args, Py_ssize_t nargs,
+ PyObject *keywords);
+
+#define PY_VECTORCALL_ARGUMENTS_OFFSET \
+ (_Py_STATIC_CAST(size_t, 1) << (8 * sizeof(size_t) - 1))
+
+static inline Py_ssize_t
+PyVectorcall_NARGS(size_t n)
+{
+ return n & ~PY_VECTORCALL_ARGUMENTS_OFFSET;
+}
+
+PyAPI_FUNC(vectorcallfunc) PyVectorcall_Function(PyObject *callable);
+
+PyAPI_FUNC(PyObject *) PyObject_Vectorcall(
+ PyObject *callable,
+ PyObject *const *args,
+ size_t nargsf,
+ PyObject *kwnames);
+
+// Backwards compatibility aliases for API that was provisional in Python 3.8
+#define _PyObject_Vectorcall PyObject_Vectorcall
+#define _PyObject_VectorcallMethod PyObject_VectorcallMethod
+#define _PyObject_FastCallDict PyObject_VectorcallDict
+#define _PyVectorcall_Function PyVectorcall_Function
+#define _PyObject_CallOneArg PyObject_CallOneArg
+#define _PyObject_CallMethodNoArgs PyObject_CallMethodNoArgs
+#define _PyObject_CallMethodOneArg PyObject_CallMethodOneArg
+
+/* Same as PyObject_Vectorcall except that keyword arguments are passed as
+ dict, which may be NULL if there are no keyword arguments. */
+PyAPI_FUNC(PyObject *) PyObject_VectorcallDict(
+ PyObject *callable,
+ PyObject *const *args,
+ size_t nargsf,
+ PyObject *kwargs);
+
+/* Call "callable" (which must support vectorcall) with positional arguments
+ "tuple" and keyword arguments "dict". "dict" may also be NULL */
+PyAPI_FUNC(PyObject *) PyVectorcall_Call(PyObject *callable, PyObject *tuple, PyObject *dict);
+
+// Same as PyObject_Vectorcall(), except without keyword arguments
+PyAPI_FUNC(PyObject *) _PyObject_FastCall(
+ PyObject *func,
+ PyObject *const *args,
+ Py_ssize_t nargs);
+
+PyAPI_FUNC(PyObject *) PyObject_CallOneArg(PyObject *func, PyObject *arg);
+
+PyAPI_FUNC(PyObject *) PyObject_VectorcallMethod(
+ PyObject *name, PyObject *const *args,
+ size_t nargsf, PyObject *kwnames);
+
+static inline PyObject *
+PyObject_CallMethodNoArgs(PyObject *self, PyObject *name)
+{
+ size_t nargsf = 1 | PY_VECTORCALL_ARGUMENTS_OFFSET;
+ return PyObject_VectorcallMethod(name, &self, nargsf, _Py_NULL);
+}
+
+static inline PyObject *
+PyObject_CallMethodOneArg(PyObject *self, PyObject *name, PyObject *arg)
+{
+ PyObject *args[2] = {self, arg};
+ size_t nargsf = 2 | PY_VECTORCALL_ARGUMENTS_OFFSET;
+ assert(arg != NULL);
+ return PyObject_VectorcallMethod(name, args, nargsf, _Py_NULL);
+}
+
+PyAPI_FUNC(PyObject *) _PyObject_CallMethod(PyObject *obj,
+ PyObject *name,
+ const char *format, ...);
+
+/* Like PyObject_CallMethod(), but expect a _Py_Identifier*
+ as the method name. */
+PyAPI_FUNC(PyObject *) _PyObject_CallMethodId(PyObject *obj,
+ _Py_Identifier *name,
+ const char *format, ...);
+
+PyAPI_FUNC(PyObject *) _PyObject_CallMethodId_SizeT(PyObject *obj,
+ _Py_Identifier *name,
+ const char *format,
+ ...);
+
+PyAPI_FUNC(PyObject *) _PyObject_CallMethodIdObjArgs(
+ PyObject *obj,
+ _Py_Identifier *name,
+ ...);
+
+static inline PyObject *
+_PyObject_VectorcallMethodId(
+ _Py_Identifier *name, PyObject *const *args,
+ size_t nargsf, PyObject *kwnames)
+{
+ PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
+ if (!oname) {
+ return _Py_NULL;
+ }
+ return PyObject_VectorcallMethod(oname, args, nargsf, kwnames);
+}
+
+static inline PyObject *
+_PyObject_CallMethodIdNoArgs(PyObject *self, _Py_Identifier *name)
+{
+ size_t nargsf = 1 | PY_VECTORCALL_ARGUMENTS_OFFSET;
+ return _PyObject_VectorcallMethodId(name, &self, nargsf, _Py_NULL);
+}
+
+static inline PyObject *
+_PyObject_CallMethodIdOneArg(PyObject *self, _Py_Identifier *name, PyObject *arg)
+{
+ PyObject *args[2] = {self, arg};
+ size_t nargsf = 2 | PY_VECTORCALL_ARGUMENTS_OFFSET;
+ assert(arg != NULL);
+ return _PyObject_VectorcallMethodId(name, args, nargsf, _Py_NULL);
+}
+
+PyAPI_FUNC(int) _PyObject_HasLen(PyObject *o);
+
+/* Guess the size of object 'o' using len(o) or o.__length_hint__().
+ If neither of those return a non-negative value, then return the default
+ value. If one of the calls fails, this function returns -1. */
+PyAPI_FUNC(Py_ssize_t) PyObject_LengthHint(PyObject *o, Py_ssize_t);
+
+/* === Sequence protocol ================================================ */
+
+/* Assume tp_as_sequence and sq_item exist and that 'i' does not
+ need to be corrected for a negative index. */
+#define PySequence_ITEM(o, i)\
+ ( Py_TYPE(o)->tp_as_sequence->sq_item(o, i) )
+
+#define PY_ITERSEARCH_COUNT 1
+#define PY_ITERSEARCH_INDEX 2
+#define PY_ITERSEARCH_CONTAINS 3
+
+/* Iterate over seq.
+
+ Result depends on the operation:
+
+ PY_ITERSEARCH_COUNT: return # of times obj appears in seq; -1 if
+ error.
+ PY_ITERSEARCH_INDEX: return 0-based index of first occurrence of
+ obj in seq; set ValueError and return -1 if none found;
+ also return -1 on error.
+ PY_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on
+ error. */
+PyAPI_FUNC(Py_ssize_t) _PySequence_IterSearch(PyObject *seq,
+ PyObject *obj, int operation);
+
+/* === Mapping protocol ================================================= */
+
+PyAPI_FUNC(int) _PyObject_RealIsInstance(PyObject *inst, PyObject *cls);
+
+PyAPI_FUNC(int) _PyObject_RealIsSubclass(PyObject *derived, PyObject *cls);
+
+PyAPI_FUNC(char *const *) _PySequence_BytesToCharpArray(PyObject* self);
+
+PyAPI_FUNC(void) _Py_FreeCharPArray(char *const array[]);
+
+/* For internal use by buffer API functions */
+PyAPI_FUNC(void) _Py_add_one_to_index_F(int nd, Py_ssize_t *index,
+ const Py_ssize_t *shape);
+PyAPI_FUNC(void) _Py_add_one_to_index_C(int nd, Py_ssize_t *index,
+ const Py_ssize_t *shape);
+
+/* Convert Python int to Py_ssize_t. Do nothing if the argument is None. */
+PyAPI_FUNC(int) _Py_convert_optional_to_ssize_t(PyObject *, void *);
+
+/* Same as PyNumber_Index but can return an instance of a subclass of int. */
+PyAPI_FUNC(PyObject *) _PyNumber_Index(PyObject *o);
diff --git a/include/python3.11/cpython/bytearrayobject.h b/include/python3.11/cpython/bytearrayobject.h
new file mode 100644
index 0000000..5114169
--- /dev/null
+++ b/include/python3.11/cpython/bytearrayobject.h
@@ -0,0 +1,38 @@
+#ifndef Py_CPYTHON_BYTEARRAYOBJECT_H
+# error "this header file must not be included directly"
+#endif
+
+/* Object layout */
+typedef struct {
+ PyObject_VAR_HEAD
+ Py_ssize_t ob_alloc; /* How many bytes allocated in ob_bytes */
+ char *ob_bytes; /* Physical backing buffer */
+ char *ob_start; /* Logical start inside ob_bytes */
+ Py_ssize_t ob_exports; /* How many buffer exports */
+} PyByteArrayObject;
+
+PyAPI_DATA(char) _PyByteArray_empty_string[];
+
+/* Macros and static inline functions, trading safety for speed */
+#define _PyByteArray_CAST(op) \
+ (assert(PyByteArray_Check(op)), _Py_CAST(PyByteArrayObject*, op))
+
+static inline char* PyByteArray_AS_STRING(PyObject *op)
+{
+ PyByteArrayObject *self = _PyByteArray_CAST(op);
+ if (Py_SIZE(self)) {
+ return self->ob_start;
+ }
+ return _PyByteArray_empty_string;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyByteArray_AS_STRING(self) PyByteArray_AS_STRING(_PyObject_CAST(self))
+#endif
+
+static inline Py_ssize_t PyByteArray_GET_SIZE(PyObject *op) {
+ PyByteArrayObject *self = _PyByteArray_CAST(op);
+ return Py_SIZE(self);
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyByteArray_GET_SIZE(self) PyByteArray_GET_SIZE(_PyObject_CAST(self))
+#endif
diff --git a/include/python3.11/cpython/bytesobject.h b/include/python3.11/cpython/bytesobject.h
new file mode 100644
index 0000000..5334366
--- /dev/null
+++ b/include/python3.11/cpython/bytesobject.h
@@ -0,0 +1,133 @@
+#ifndef Py_CPYTHON_BYTESOBJECT_H
+# error "this header file must not be included directly"
+#endif
+
+typedef struct {
+ PyObject_VAR_HEAD
+ Py_DEPRECATED(3.11) Py_hash_t ob_shash;
+ char ob_sval[1];
+
+ /* Invariants:
+ * ob_sval contains space for 'ob_size+1' elements.
+ * ob_sval[ob_size] == 0.
+ * ob_shash is the hash of the byte string or -1 if not computed yet.
+ */
+} PyBytesObject;
+
+PyAPI_FUNC(int) _PyBytes_Resize(PyObject **, Py_ssize_t);
+PyAPI_FUNC(PyObject*) _PyBytes_FormatEx(
+ const char *format,
+ Py_ssize_t format_len,
+ PyObject *args,
+ int use_bytearray);
+PyAPI_FUNC(PyObject*) _PyBytes_FromHex(
+ PyObject *string,
+ int use_bytearray);
+
+/* Helper for PyBytes_DecodeEscape that detects invalid escape chars. */
+PyAPI_FUNC(PyObject *) _PyBytes_DecodeEscape(const char *, Py_ssize_t,
+ const char *, const char **);
+
+/* Macros and static inline functions, trading safety for speed */
+#define _PyBytes_CAST(op) \
+ (assert(PyBytes_Check(op)), _Py_CAST(PyBytesObject*, op))
+
+static inline char* PyBytes_AS_STRING(PyObject *op)
+{
+ return _PyBytes_CAST(op)->ob_sval;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyBytes_AS_STRING(op) PyBytes_AS_STRING(_PyObject_CAST(op))
+#endif
+
+static inline Py_ssize_t PyBytes_GET_SIZE(PyObject *op) {
+ PyBytesObject *self = _PyBytes_CAST(op);
+ return Py_SIZE(self);
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyBytes_GET_SIZE(self) PyBytes_GET_SIZE(_PyObject_CAST(self))
+#endif
+
+/* _PyBytes_Join(sep, x) is like sep.join(x). sep must be PyBytesObject*,
+ x must be an iterable object. */
+PyAPI_FUNC(PyObject *) _PyBytes_Join(PyObject *sep, PyObject *x);
+
+
+/* The _PyBytesWriter structure is big: it contains an embedded "stack buffer".
+ A _PyBytesWriter variable must be declared at the end of variables in a
+ function to optimize the memory allocation on the stack. */
+typedef struct {
+ /* bytes, bytearray or NULL (when the small buffer is used) */
+ PyObject *buffer;
+
+ /* Number of allocated size. */
+ Py_ssize_t allocated;
+
+ /* Minimum number of allocated bytes,
+ incremented by _PyBytesWriter_Prepare() */
+ Py_ssize_t min_size;
+
+ /* If non-zero, use a bytearray instead of a bytes object for buffer. */
+ int use_bytearray;
+
+ /* If non-zero, overallocate the buffer (default: 0).
+ This flag must be zero if use_bytearray is non-zero. */
+ int overallocate;
+
+ /* Stack buffer */
+ int use_small_buffer;
+ char small_buffer[512];
+} _PyBytesWriter;
+
+/* Initialize a bytes writer
+
+ By default, the overallocation is disabled. Set the overallocate attribute
+ to control the allocation of the buffer. */
+PyAPI_FUNC(void) _PyBytesWriter_Init(_PyBytesWriter *writer);
+
+/* Get the buffer content and reset the writer.
+ Return a bytes object, or a bytearray object if use_bytearray is non-zero.
+ Raise an exception and return NULL on error. */
+PyAPI_FUNC(PyObject *) _PyBytesWriter_Finish(_PyBytesWriter *writer,
+ void *str);
+
+/* Deallocate memory of a writer (clear its internal buffer). */
+PyAPI_FUNC(void) _PyBytesWriter_Dealloc(_PyBytesWriter *writer);
+
+/* Allocate the buffer to write size bytes.
+ Return the pointer to the beginning of buffer data.
+ Raise an exception and return NULL on error. */
+PyAPI_FUNC(void*) _PyBytesWriter_Alloc(_PyBytesWriter *writer,
+ Py_ssize_t size);
+
+/* Ensure that the buffer is large enough to write *size* bytes.
+ Add size to the writer minimum size (min_size attribute).
+
+ str is the current pointer inside the buffer.
+ Return the updated current pointer inside the buffer.
+ Raise an exception and return NULL on error. */
+PyAPI_FUNC(void*) _PyBytesWriter_Prepare(_PyBytesWriter *writer,
+ void *str,
+ Py_ssize_t size);
+
+/* Resize the buffer to make it larger.
+ The new buffer may be larger than size bytes because of overallocation.
+ Return the updated current pointer inside the buffer.
+ Raise an exception and return NULL on error.
+
+ Note: size must be greater than the number of allocated bytes in the writer.
+
+ This function doesn't use the writer minimum size (min_size attribute).
+
+ See also _PyBytesWriter_Prepare().
+ */
+PyAPI_FUNC(void*) _PyBytesWriter_Resize(_PyBytesWriter *writer,
+ void *str,
+ Py_ssize_t size);
+
+/* Write bytes.
+ Raise an exception and return NULL on error. */
+PyAPI_FUNC(void*) _PyBytesWriter_WriteBytes(_PyBytesWriter *writer,
+ void *str,
+ const void *bytes,
+ Py_ssize_t size);
diff --git a/include/python3.11/cpython/cellobject.h b/include/python3.11/cpython/cellobject.h
new file mode 100644
index 0000000..e07f9d1
--- /dev/null
+++ b/include/python3.11/cpython/cellobject.h
@@ -0,0 +1,31 @@
+/* Cell object interface */
+
+#ifndef Py_LIMITED_API
+#ifndef Py_CELLOBJECT_H
+#define Py_CELLOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct {
+ PyObject_HEAD
+ /* Content of the cell or NULL when empty */
+ PyObject *ob_ref;
+} PyCellObject;
+
+PyAPI_DATA(PyTypeObject) PyCell_Type;
+
+#define PyCell_Check(op) Py_IS_TYPE(op, &PyCell_Type)
+
+PyAPI_FUNC(PyObject *) PyCell_New(PyObject *);
+PyAPI_FUNC(PyObject *) PyCell_Get(PyObject *);
+PyAPI_FUNC(int) PyCell_Set(PyObject *, PyObject *);
+
+#define PyCell_GET(op) (((PyCellObject *)(op))->ob_ref)
+#define PyCell_SET(op, v) _Py_RVALUE(((PyCellObject *)(op))->ob_ref = (v))
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_TUPLEOBJECT_H */
+#endif /* Py_LIMITED_API */
diff --git a/include/python3.11/cpython/ceval.h b/include/python3.11/cpython/ceval.h
new file mode 100644
index 0000000..9d4eeaf
--- /dev/null
+++ b/include/python3.11/cpython/ceval.h
@@ -0,0 +1,26 @@
+#ifndef Py_CPYTHON_CEVAL_H
+# error "this header file must not be included directly"
+#endif
+
+PyAPI_FUNC(void) PyEval_SetProfile(Py_tracefunc, PyObject *);
+PyAPI_DATA(int) _PyEval_SetProfile(PyThreadState *tstate, Py_tracefunc func, PyObject *arg);
+PyAPI_FUNC(void) PyEval_SetTrace(Py_tracefunc, PyObject *);
+PyAPI_FUNC(int) _PyEval_SetTrace(PyThreadState *tstate, Py_tracefunc func, PyObject *arg);
+
+/* Helper to look up a builtin object */
+PyAPI_FUNC(PyObject *) _PyEval_GetBuiltin(PyObject *);
+PyAPI_FUNC(PyObject *) _PyEval_GetBuiltinId(_Py_Identifier *);
+/* Look at the current frame's (if any) code's co_flags, and turn on
+ the corresponding compiler flags in cf->cf_flags. Return 1 if any
+ flag was set, else return 0. */
+PyAPI_FUNC(int) PyEval_MergeCompilerFlags(PyCompilerFlags *cf);
+
+PyAPI_FUNC(PyObject *) _PyEval_EvalFrameDefault(PyThreadState *tstate, struct _PyInterpreterFrame *f, int exc);
+
+PyAPI_FUNC(void) _PyEval_SetSwitchInterval(unsigned long microseconds);
+PyAPI_FUNC(unsigned long) _PyEval_GetSwitchInterval(void);
+
+PyAPI_FUNC(Py_ssize_t) _PyEval_RequestCodeExtraIndex(freefunc);
+
+PyAPI_FUNC(int) _PyEval_SliceIndex(PyObject *, Py_ssize_t *);
+PyAPI_FUNC(int) _PyEval_SliceIndexNotNone(PyObject *, Py_ssize_t *);
diff --git a/include/python3.11/cpython/classobject.h b/include/python3.11/cpython/classobject.h
new file mode 100644
index 0000000..80df884
--- /dev/null
+++ b/include/python3.11/cpython/classobject.h
@@ -0,0 +1,57 @@
+/* Former class object interface -- now only bound methods are here */
+
+/* Revealing some structures (not for general use) */
+
+#ifndef Py_LIMITED_API
+#ifndef Py_CLASSOBJECT_H
+#define Py_CLASSOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct {
+ PyObject_HEAD
+ PyObject *im_func; /* The callable object implementing the method */
+ PyObject *im_self; /* The instance it is bound to */
+ PyObject *im_weakreflist; /* List of weak references */
+ vectorcallfunc vectorcall;
+} PyMethodObject;
+
+PyAPI_DATA(PyTypeObject) PyMethod_Type;
+
+#define PyMethod_Check(op) Py_IS_TYPE(op, &PyMethod_Type)
+
+PyAPI_FUNC(PyObject *) PyMethod_New(PyObject *, PyObject *);
+
+PyAPI_FUNC(PyObject *) PyMethod_Function(PyObject *);
+PyAPI_FUNC(PyObject *) PyMethod_Self(PyObject *);
+
+/* Macros for direct access to these values. Type checks are *not*
+ done, so use with care. */
+#define PyMethod_GET_FUNCTION(meth) \
+ (((PyMethodObject *)meth) -> im_func)
+#define PyMethod_GET_SELF(meth) \
+ (((PyMethodObject *)meth) -> im_self)
+
+typedef struct {
+ PyObject_HEAD
+ PyObject *func;
+} PyInstanceMethodObject;
+
+PyAPI_DATA(PyTypeObject) PyInstanceMethod_Type;
+
+#define PyInstanceMethod_Check(op) Py_IS_TYPE(op, &PyInstanceMethod_Type)
+
+PyAPI_FUNC(PyObject *) PyInstanceMethod_New(PyObject *);
+PyAPI_FUNC(PyObject *) PyInstanceMethod_Function(PyObject *);
+
+/* Macros for direct access to these values. Type checks are *not*
+ done, so use with care. */
+#define PyInstanceMethod_GET_FUNCTION(meth) \
+ (((PyInstanceMethodObject *)meth) -> func)
+
+#ifdef __cplusplus
+}
+#endif
+#endif // !Py_CLASSOBJECT_H
+#endif // !Py_LIMITED_API
diff --git a/include/python3.11/cpython/code.h b/include/python3.11/cpython/code.h
new file mode 100644
index 0000000..7006060
--- /dev/null
+++ b/include/python3.11/cpython/code.h
@@ -0,0 +1,236 @@
+/* Definitions for bytecode */
+
+#ifndef Py_LIMITED_API
+#ifndef Py_CODE_H
+#define Py_CODE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Each instruction in a code object is a fixed-width value,
+ * currently 2 bytes: 1-byte opcode + 1-byte oparg. The EXTENDED_ARG
+ * opcode allows for larger values but the current limit is 3 uses
+ * of EXTENDED_ARG (see Python/compile.c), for a maximum
+ * 32-bit value. This aligns with the note in Python/compile.c
+ * (compiler_addop_i_line) indicating that the max oparg value is
+ * 2**32 - 1, rather than INT_MAX.
+ */
+
+typedef uint16_t _Py_CODEUNIT;
+
+#ifdef WORDS_BIGENDIAN
+# define _Py_OPCODE(word) ((word) >> 8)
+# define _Py_OPARG(word) ((word) & 255)
+# define _Py_MAKECODEUNIT(opcode, oparg) (((opcode)<<8)|(oparg))
+#else
+# define _Py_OPCODE(word) ((word) & 255)
+# define _Py_OPARG(word) ((word) >> 8)
+# define _Py_MAKECODEUNIT(opcode, oparg) ((opcode)|((oparg)<<8))
+#endif
+
+// Use "unsigned char" instead of "uint8_t" here to avoid illegal aliasing:
+#define _Py_SET_OPCODE(word, opcode) (((unsigned char *)&(word))[0] = (opcode))
+
+// To avoid repeating ourselves in deepfreeze.py, all PyCodeObject members are
+// defined in this macro:
+#define _PyCode_DEF(SIZE) { \
+ PyObject_VAR_HEAD \
+ \
+ /* Note only the following fields are used in hash and/or comparisons \
+ * \
+ * - co_name \
+ * - co_argcount \
+ * - co_posonlyargcount \
+ * - co_kwonlyargcount \
+ * - co_nlocals \
+ * - co_stacksize \
+ * - co_flags \
+ * - co_firstlineno \
+ * - co_consts \
+ * - co_names \
+ * - co_localsplusnames \
+ * This is done to preserve the name and line number for tracebacks \
+ * and debuggers; otherwise, constant de-duplication would collapse \
+ * identical functions/lambdas defined on different lines. \
+ */ \
+ \
+ /* These fields are set with provided values on new code objects. */ \
+ \
+ /* The hottest fields (in the eval loop) are grouped here at the top. */ \
+ PyObject *co_consts; /* list (constants used) */ \
+ PyObject *co_names; /* list of strings (names used) */ \
+ PyObject *co_exceptiontable; /* Byte string encoding exception handling \
+ table */ \
+ int co_flags; /* CO_..., see below */ \
+ short co_warmup; /* Warmup counter for quickening */ \
+ short _co_linearray_entry_size; /* Size of each entry in _co_linearray */ \
+ \
+ /* The rest are not so impactful on performance. */ \
+ int co_argcount; /* #arguments, except *args */ \
+ int co_posonlyargcount; /* #positional only arguments */ \
+ int co_kwonlyargcount; /* #keyword only arguments */ \
+ int co_stacksize; /* #entries needed for evaluation stack */ \
+ int co_firstlineno; /* first source line number */ \
+ \
+ /* redundant values (derived from co_localsplusnames and \
+ co_localspluskinds) */ \
+ int co_nlocalsplus; /* number of local + cell + free variables \
+ */ \
+ int co_nlocals; /* number of local variables */ \
+ int co_nplaincellvars; /* number of non-arg cell variables */ \
+ int co_ncellvars; /* total number of cell variables */ \
+ int co_nfreevars; /* number of free variables */ \
+ \
+ PyObject *co_localsplusnames; /* tuple mapping offsets to names */ \
+ PyObject *co_localspluskinds; /* Bytes mapping to local kinds (one byte \
+ per variable) */ \
+ PyObject *co_filename; /* unicode (where it was loaded from) */ \
+ PyObject *co_name; /* unicode (name, for reference) */ \
+ PyObject *co_qualname; /* unicode (qualname, for reference) */ \
+ PyObject *co_linetable; /* bytes object that holds location info */ \
+ PyObject *co_weakreflist; /* to support weakrefs to code objects */ \
+ PyObject *_co_code; /* cached co_code object/attribute */ \
+ char *_co_linearray; /* array of line offsets */ \
+ int _co_firsttraceable; /* index of first traceable instruction */ \
+ /* Scratch space for extra data relating to the code object. \
+ Type is a void* to keep the format private in codeobject.c to force \
+ people to go through the proper APIs. */ \
+ void *co_extra; \
+ char co_code_adaptive[(SIZE)]; \
+}
+
+/* Bytecode object */
+struct PyCodeObject _PyCode_DEF(1);
+
+/* Masks for co_flags above */
+#define CO_OPTIMIZED 0x0001
+#define CO_NEWLOCALS 0x0002
+#define CO_VARARGS 0x0004
+#define CO_VARKEYWORDS 0x0008
+#define CO_NESTED 0x0010
+#define CO_GENERATOR 0x0020
+
+/* The CO_COROUTINE flag is set for coroutine functions (defined with
+ ``async def`` keywords) */
+#define CO_COROUTINE 0x0080
+#define CO_ITERABLE_COROUTINE 0x0100
+#define CO_ASYNC_GENERATOR 0x0200
+
+/* bpo-39562: These constant values are changed in Python 3.9
+ to prevent collision with compiler flags. CO_FUTURE_ and PyCF_
+ constants must be kept unique. PyCF_ constants can use bits from
+ 0x0100 to 0x10000. CO_FUTURE_ constants use bits starting at 0x20000. */
+#define CO_FUTURE_DIVISION 0x20000
+#define CO_FUTURE_ABSOLUTE_IMPORT 0x40000 /* do absolute imports by default */
+#define CO_FUTURE_WITH_STATEMENT 0x80000
+#define CO_FUTURE_PRINT_FUNCTION 0x100000
+#define CO_FUTURE_UNICODE_LITERALS 0x200000
+
+#define CO_FUTURE_BARRY_AS_BDFL 0x400000
+#define CO_FUTURE_GENERATOR_STOP 0x800000
+#define CO_FUTURE_ANNOTATIONS 0x1000000
+
+/* This should be defined if a future statement modifies the syntax.
+ For example, when a keyword is added.
+*/
+#define PY_PARSER_REQUIRES_FUTURE_KEYWORD
+
+#define CO_MAXBLOCKS 20 /* Max static block nesting within a function */
+
+PyAPI_DATA(PyTypeObject) PyCode_Type;
+
+#define PyCode_Check(op) Py_IS_TYPE(op, &PyCode_Type)
+#define PyCode_GetNumFree(op) ((op)->co_nfreevars)
+#define _PyCode_CODE(CO) ((_Py_CODEUNIT *)(CO)->co_code_adaptive)
+#define _PyCode_NBYTES(CO) (Py_SIZE(CO) * (Py_ssize_t)sizeof(_Py_CODEUNIT))
+
+/* Public interface */
+PyAPI_FUNC(PyCodeObject *) PyCode_New(
+ int, int, int, int, int, PyObject *, PyObject *,
+ PyObject *, PyObject *, PyObject *, PyObject *,
+ PyObject *, PyObject *, PyObject *, int, PyObject *,
+ PyObject *);
+
+PyAPI_FUNC(PyCodeObject *) PyCode_NewWithPosOnlyArgs(
+ int, int, int, int, int, int, PyObject *, PyObject *,
+ PyObject *, PyObject *, PyObject *, PyObject *,
+ PyObject *, PyObject *, PyObject *, int, PyObject *,
+ PyObject *);
+ /* same as struct above */
+
+/* Creates a new empty code object with the specified source location. */
+PyAPI_FUNC(PyCodeObject *)
+PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno);
+
+/* Return the line number associated with the specified bytecode index
+ in this code object. If you just need the line number of a frame,
+ use PyFrame_GetLineNumber() instead. */
+PyAPI_FUNC(int) PyCode_Addr2Line(PyCodeObject *, int);
+
+PyAPI_FUNC(int) PyCode_Addr2Location(PyCodeObject *, int, int *, int *, int *, int *);
+
+/* for internal use only */
+struct _opaque {
+ int computed_line;
+ const uint8_t *lo_next;
+ const uint8_t *limit;
+};
+
+typedef struct _line_offsets {
+ int ar_start;
+ int ar_end;
+ int ar_line;
+ struct _opaque opaque;
+} PyCodeAddressRange;
+
+/* Update *bounds to describe the first and one-past-the-last instructions in the
+ same line as lasti. Return the number of that line.
+*/
+PyAPI_FUNC(int) _PyCode_CheckLineNumber(int lasti, PyCodeAddressRange *bounds);
+
+/* Create a comparable key used to compare constants taking in account the
+ * object type. It is used to make sure types are not coerced (e.g., float and
+ * complex) _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms
+ *
+ * Return (type(obj), obj, ...): a tuple with variable size (at least 2 items)
+ * depending on the type and the value. The type is the first item to not
+ * compare bytes and str which can raise a BytesWarning exception. */
+PyAPI_FUNC(PyObject*) _PyCode_ConstantKey(PyObject *obj);
+
+PyAPI_FUNC(PyObject*) PyCode_Optimize(PyObject *code, PyObject* consts,
+ PyObject *names, PyObject *lnotab);
+
+
+PyAPI_FUNC(int) _PyCode_GetExtra(PyObject *code, Py_ssize_t index,
+ void **extra);
+PyAPI_FUNC(int) _PyCode_SetExtra(PyObject *code, Py_ssize_t index,
+ void *extra);
+
+/* Equivalent to getattr(code, 'co_code') in Python.
+ Returns a strong reference to a bytes object. */
+PyAPI_FUNC(PyObject *) PyCode_GetCode(PyCodeObject *code);
+/* Equivalent to getattr(code, 'co_varnames') in Python. */
+PyAPI_FUNC(PyObject *) PyCode_GetVarnames(PyCodeObject *code);
+/* Equivalent to getattr(code, 'co_cellvars') in Python. */
+PyAPI_FUNC(PyObject *) PyCode_GetCellvars(PyCodeObject *code);
+/* Equivalent to getattr(code, 'co_freevars') in Python. */
+PyAPI_FUNC(PyObject *) PyCode_GetFreevars(PyCodeObject *code);
+
+typedef enum _PyCodeLocationInfoKind {
+ /* short forms are 0 to 9 */
+ PY_CODE_LOCATION_INFO_SHORT0 = 0,
+ /* one lineforms are 10 to 12 */
+ PY_CODE_LOCATION_INFO_ONE_LINE0 = 10,
+ PY_CODE_LOCATION_INFO_ONE_LINE1 = 11,
+ PY_CODE_LOCATION_INFO_ONE_LINE2 = 12,
+
+ PY_CODE_LOCATION_INFO_NO_COLUMNS = 13,
+ PY_CODE_LOCATION_INFO_LONG = 14,
+ PY_CODE_LOCATION_INFO_NONE = 15
+} _PyCodeLocationInfoKind;
+
+#ifdef __cplusplus
+}
+#endif
+#endif // !Py_CODE_H
+#endif // !Py_LIMITED_API
diff --git a/include/python3.10/cpython/compile.h b/include/python3.11/cpython/compile.h
similarity index 100%
rename from include/python3.10/cpython/compile.h
rename to include/python3.11/cpython/compile.h
diff --git a/include/python3.11/cpython/complexobject.h b/include/python3.11/cpython/complexobject.h
new file mode 100644
index 0000000..b7d7283
--- /dev/null
+++ b/include/python3.11/cpython/complexobject.h
@@ -0,0 +1,44 @@
+#ifndef Py_CPYTHON_COMPLEXOBJECT_H
+# error "this header file must not be included directly"
+#endif
+
+typedef struct {
+ double real;
+ double imag;
+} Py_complex;
+
+/* Operations on complex numbers from complexmodule.c */
+
+PyAPI_FUNC(Py_complex) _Py_c_sum(Py_complex, Py_complex);
+PyAPI_FUNC(Py_complex) _Py_c_diff(Py_complex, Py_complex);
+PyAPI_FUNC(Py_complex) _Py_c_neg(Py_complex);
+PyAPI_FUNC(Py_complex) _Py_c_prod(Py_complex, Py_complex);
+PyAPI_FUNC(Py_complex) _Py_c_quot(Py_complex, Py_complex);
+PyAPI_FUNC(Py_complex) _Py_c_pow(Py_complex, Py_complex);
+PyAPI_FUNC(double) _Py_c_abs(Py_complex);
+
+/* Complex object interface */
+
+/*
+PyComplexObject represents a complex number with double-precision
+real and imaginary parts.
+*/
+typedef struct {
+ PyObject_HEAD
+ Py_complex cval;
+} PyComplexObject;
+
+PyAPI_FUNC(PyObject *) PyComplex_FromCComplex(Py_complex);
+
+PyAPI_FUNC(Py_complex) PyComplex_AsCComplex(PyObject *op);
+
+#ifdef Py_BUILD_CORE
+/* Format the object based on the format_spec, as defined in PEP 3101
+ (Advanced String Formatting). */
+extern int _PyComplex_FormatAdvancedWriter(
+ _PyUnicodeWriter *writer,
+ PyObject *obj,
+ PyObject *format_spec,
+ Py_ssize_t start,
+ Py_ssize_t end);
+#endif // Py_BUILD_CORE
diff --git a/include/python3.11/cpython/context.h b/include/python3.11/cpython/context.h
new file mode 100644
index 0000000..4db079f
--- /dev/null
+++ b/include/python3.11/cpython/context.h
@@ -0,0 +1,78 @@
+#ifndef Py_LIMITED_API
+#ifndef Py_CONTEXT_H
+#define Py_CONTEXT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_DATA(PyTypeObject) PyContext_Type;
+typedef struct _pycontextobject PyContext;
+
+PyAPI_DATA(PyTypeObject) PyContextVar_Type;
+typedef struct _pycontextvarobject PyContextVar;
+
+PyAPI_DATA(PyTypeObject) PyContextToken_Type;
+typedef struct _pycontexttokenobject PyContextToken;
+
+
+#define PyContext_CheckExact(o) Py_IS_TYPE(o, &PyContext_Type)
+#define PyContextVar_CheckExact(o) Py_IS_TYPE(o, &PyContextVar_Type)
+#define PyContextToken_CheckExact(o) Py_IS_TYPE(o, &PyContextToken_Type)
+
+
+PyAPI_FUNC(PyObject *) PyContext_New(void);
+PyAPI_FUNC(PyObject *) PyContext_Copy(PyObject *);
+PyAPI_FUNC(PyObject *) PyContext_CopyCurrent(void);
+
+PyAPI_FUNC(int) PyContext_Enter(PyObject *);
+PyAPI_FUNC(int) PyContext_Exit(PyObject *);
+
+
+/* Create a new context variable.
+
+ default_value can be NULL.
+*/
+PyAPI_FUNC(PyObject *) PyContextVar_New(
+ const char *name, PyObject *default_value);
+
+
+/* Get a value for the variable.
+
+ Returns -1 if an error occurred during lookup.
+
+ Returns 0 if value either was or was not found.
+
+ If value was found, *value will point to it.
+ If not, it will point to:
+
+ - default_value, if not NULL;
+ - the default value of "var", if not NULL;
+ - NULL.
+
+ '*value' will be a new ref, if not NULL.
+*/
+PyAPI_FUNC(int) PyContextVar_Get(
+ PyObject *var, PyObject *default_value, PyObject **value);
+
+
+/* Set a new value for the variable.
+ Returns NULL if an error occurs.
+*/
+PyAPI_FUNC(PyObject *) PyContextVar_Set(PyObject *var, PyObject *value);
+
+
+/* Reset a variable to its previous value.
+ Returns 0 on success, -1 on error.
+*/
+PyAPI_FUNC(int) PyContextVar_Reset(PyObject *var, PyObject *token);
+
+
+/* This method is exposed only for CPython tests. Don not use it. */
+PyAPI_FUNC(PyObject *) _PyContext_NewHamtForTests(void);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_CONTEXT_H */
+#endif /* !Py_LIMITED_API */
diff --git a/include/python3.11/cpython/descrobject.h b/include/python3.11/cpython/descrobject.h
new file mode 100644
index 0000000..e2ea1b9
--- /dev/null
+++ b/include/python3.11/cpython/descrobject.h
@@ -0,0 +1,64 @@
+#ifndef Py_CPYTHON_DESCROBJECT_H
+# error "this header file must not be included directly"
+#endif
+
+typedef PyObject *(*wrapperfunc)(PyObject *self, PyObject *args,
+ void *wrapped);
+
+typedef PyObject *(*wrapperfunc_kwds)(PyObject *self, PyObject *args,
+ void *wrapped, PyObject *kwds);
+
+struct wrapperbase {
+ const char *name;
+ int offset;
+ void *function;
+ wrapperfunc wrapper;
+ const char *doc;
+ int flags;
+ PyObject *name_strobj;
+};
+
+/* Flags for above struct */
+#define PyWrapperFlag_KEYWORDS 1 /* wrapper function takes keyword args */
+
+/* Various kinds of descriptor objects */
+
+typedef struct {
+ PyObject_HEAD
+ PyTypeObject *d_type;
+ PyObject *d_name;
+ PyObject *d_qualname;
+} PyDescrObject;
+
+#define PyDescr_COMMON PyDescrObject d_common
+
+#define PyDescr_TYPE(x) (((PyDescrObject *)(x))->d_type)
+#define PyDescr_NAME(x) (((PyDescrObject *)(x))->d_name)
+
+typedef struct {
+ PyDescr_COMMON;
+ PyMethodDef *d_method;
+ vectorcallfunc vectorcall;
+} PyMethodDescrObject;
+
+typedef struct {
+ PyDescr_COMMON;
+ PyMemberDef *d_member;
+} PyMemberDescrObject;
+
+typedef struct {
+ PyDescr_COMMON;
+ PyGetSetDef *d_getset;
+} PyGetSetDescrObject;
+
+typedef struct {
+ PyDescr_COMMON;
+ struct wrapperbase *d_base;
+ void *d_wrapped; /* This can be any function pointer */
+} PyWrapperDescrObject;
+
+PyAPI_DATA(PyTypeObject) _PyMethodWrapper_Type;
+
+PyAPI_FUNC(PyObject *) PyDescr_NewWrapper(PyTypeObject *,
+ struct wrapperbase *, void *);
+PyAPI_FUNC(int) PyDescr_IsData(PyObject *);
diff --git a/include/python3.11/cpython/dictobject.h b/include/python3.11/cpython/dictobject.h
new file mode 100644
index 0000000..033eaeb
--- /dev/null
+++ b/include/python3.11/cpython/dictobject.h
@@ -0,0 +1,78 @@
+#ifndef Py_CPYTHON_DICTOBJECT_H
+# error "this header file must not be included directly"
+#endif
+
+typedef struct _dictkeysobject PyDictKeysObject;
+typedef struct _dictvalues PyDictValues;
+
+/* The ma_values pointer is NULL for a combined table
+ * or points to an array of PyObject* for a split table
+ */
+typedef struct {
+ PyObject_HEAD
+
+ /* Number of items in the dictionary */
+ Py_ssize_t ma_used;
+
+ /* Dictionary version: globally unique, value change each time
+ the dictionary is modified */
+ uint64_t ma_version_tag;
+
+ PyDictKeysObject *ma_keys;
+
+ /* If ma_values is NULL, the table is "combined": keys and values
+ are stored in ma_keys.
+
+ If ma_values is not NULL, the table is split:
+ keys are stored in ma_keys and values are stored in ma_values */
+ PyDictValues *ma_values;
+} PyDictObject;
+
+PyAPI_FUNC(PyObject *) _PyDict_GetItem_KnownHash(PyObject *mp, PyObject *key,
+ Py_hash_t hash);
+PyAPI_FUNC(PyObject *) _PyDict_GetItemWithError(PyObject *dp, PyObject *key);
+PyAPI_FUNC(PyObject *) _PyDict_GetItemIdWithError(PyObject *dp,
+ _Py_Identifier *key);
+PyAPI_FUNC(PyObject *) _PyDict_GetItemStringWithError(PyObject *, const char *);
+PyAPI_FUNC(PyObject *) PyDict_SetDefault(
+ PyObject *mp, PyObject *key, PyObject *defaultobj);
+PyAPI_FUNC(int) _PyDict_SetItem_KnownHash(PyObject *mp, PyObject *key,
+ PyObject *item, Py_hash_t hash);
+PyAPI_FUNC(int) _PyDict_DelItem_KnownHash(PyObject *mp, PyObject *key,
+ Py_hash_t hash);
+PyAPI_FUNC(int) _PyDict_DelItemIf(PyObject *mp, PyObject *key,
+ int (*predicate)(PyObject *value));
+PyAPI_FUNC(int) _PyDict_Next(
+ PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, Py_hash_t *hash);
+
+/* Get the number of items of a dictionary. */
+#define PyDict_GET_SIZE(mp) (assert(PyDict_Check(mp)),((PyDictObject *)mp)->ma_used)
+PyAPI_FUNC(int) _PyDict_Contains_KnownHash(PyObject *, PyObject *, Py_hash_t);
+PyAPI_FUNC(int) _PyDict_ContainsId(PyObject *, _Py_Identifier *);
+PyAPI_FUNC(PyObject *) _PyDict_NewPresized(Py_ssize_t minused);
+PyAPI_FUNC(void) _PyDict_MaybeUntrack(PyObject *mp);
+PyAPI_FUNC(int) _PyDict_HasOnlyStringKeys(PyObject *mp);
+PyAPI_FUNC(Py_ssize_t) _PyDict_SizeOf(PyDictObject *);
+PyAPI_FUNC(PyObject *) _PyDict_Pop(PyObject *, PyObject *, PyObject *);
+#define _PyDict_HasSplitTable(d) ((d)->ma_values != NULL)
+
+/* Like PyDict_Merge, but override can be 0, 1 or 2. If override is 0,
+ the first occurrence of a key wins, if override is 1, the last occurrence
+ of a key wins, if override is 2, a KeyError with conflicting key as
+ argument is raised.
+*/
+PyAPI_FUNC(int) _PyDict_MergeEx(PyObject *mp, PyObject *other, int override);
+PyAPI_FUNC(int) _PyDict_SetItemId(PyObject *dp, _Py_Identifier *key, PyObject *item);
+
+PyAPI_FUNC(int) _PyDict_DelItemId(PyObject *mp, _Py_Identifier *key);
+PyAPI_FUNC(void) _PyDict_DebugMallocStats(FILE *out);
+
+/* _PyDictView */
+
+typedef struct {
+ PyObject_HEAD
+ PyDictObject *dv_dict;
+} _PyDictViewObject;
+
+PyAPI_FUNC(PyObject *) _PyDictView_New(PyObject *, PyTypeObject *);
+PyAPI_FUNC(PyObject *) _PyDictView_Intersect(PyObject* self, PyObject *other);
diff --git a/include/python3.11/cpython/fileobject.h b/include/python3.11/cpython/fileobject.h
new file mode 100644
index 0000000..b70ec31
--- /dev/null
+++ b/include/python3.11/cpython/fileobject.h
@@ -0,0 +1,19 @@
+#ifndef Py_CPYTHON_FILEOBJECT_H
+# error "this header file must not be included directly"
+#endif
+
+PyAPI_FUNC(char *) Py_UniversalNewlineFgets(char *, int, FILE*, PyObject *);
+PyAPI_FUNC(char *) _Py_UniversalNewlineFgetsWithSize(char *, int, FILE*, PyObject *, size_t*);
+
+/* The std printer acts as a preliminary sys.stderr until the new io
+ infrastructure is in place. */
+PyAPI_FUNC(PyObject *) PyFile_NewStdPrinter(int);
+PyAPI_DATA(PyTypeObject) PyStdPrinter_Type;
+
+typedef PyObject * (*Py_OpenCodeHookFunction)(PyObject *, void *);
+
+PyAPI_FUNC(PyObject *) PyFile_OpenCode(const char *utf8path);
+PyAPI_FUNC(PyObject *) PyFile_OpenCodeObject(PyObject *path);
+PyAPI_FUNC(int) PyFile_SetOpenCodeHook(Py_OpenCodeHookFunction hook, void *userData);
+
+PyAPI_FUNC(int) _PyLong_FileDescriptor_Converter(PyObject *, void *);
diff --git a/include/python3.11/cpython/fileutils.h b/include/python3.11/cpython/fileutils.h
new file mode 100644
index 0000000..b386ad1
--- /dev/null
+++ b/include/python3.11/cpython/fileutils.h
@@ -0,0 +1,8 @@
+#ifndef Py_CPYTHON_FILEUTILS_H
+# error "this header file must not be included directly"
+#endif
+
+// Used by _testcapi which must not use the internal C API
+PyAPI_FUNC(FILE*) _Py_fopen_obj(
+ PyObject *path,
+ const char *mode);
diff --git a/include/python3.11/cpython/floatobject.h b/include/python3.11/cpython/floatobject.h
new file mode 100644
index 0000000..7795d9f
--- /dev/null
+++ b/include/python3.11/cpython/floatobject.h
@@ -0,0 +1,21 @@
+#ifndef Py_CPYTHON_FLOATOBJECT_H
+# error "this header file must not be included directly"
+#endif
+
+typedef struct {
+ PyObject_HEAD
+ double ob_fval;
+} PyFloatObject;
+
+// Macro version of PyFloat_AsDouble() trading safety for speed.
+// It doesn't check if op is a double object.
+#define PyFloat_AS_DOUBLE(op) (((PyFloatObject *)(op))->ob_fval)
+
+
+PyAPI_FUNC(int) PyFloat_Pack2(double x, char *p, int le);
+PyAPI_FUNC(int) PyFloat_Pack4(double x, char *p, int le);
+PyAPI_FUNC(int) PyFloat_Pack8(double x, char *p, int le);
+
+PyAPI_FUNC(double) PyFloat_Unpack2(const char *p, int le);
+PyAPI_FUNC(double) PyFloat_Unpack4(const char *p, int le);
+PyAPI_FUNC(double) PyFloat_Unpack8(const char *p, int le);
diff --git a/include/python3.11/cpython/frameobject.h b/include/python3.11/cpython/frameobject.h
new file mode 100644
index 0000000..4e19535
--- /dev/null
+++ b/include/python3.11/cpython/frameobject.h
@@ -0,0 +1,29 @@
+/* Frame object interface */
+
+#ifndef Py_CPYTHON_FRAMEOBJECT_H
+# error "this header file must not be included directly"
+#endif
+
+/* Standard object interface */
+
+PyAPI_FUNC(PyFrameObject *) PyFrame_New(PyThreadState *, PyCodeObject *,
+ PyObject *, PyObject *);
+
+/* The rest of the interface is specific for frame objects */
+
+/* Conversions between "fast locals" and locals in dictionary */
+
+PyAPI_FUNC(void) PyFrame_LocalsToFast(PyFrameObject *, int);
+
+/* -- Caveat emptor --
+ * The concept of entry frames is an implementation detail of the CPython
+ * interpreter. This API is considered unstable and is provided for the
+ * convenience of debuggers, profilers and state-inspecting tools. Notice that
+ * this API can be changed in future minor versions if the underlying frame
+ * mechanism change or the concept of an 'entry frame' or its semantics becomes
+ * obsolete or outdated. */
+
+PyAPI_FUNC(int) _PyFrame_IsEntryFrame(PyFrameObject *frame);
+
+PyAPI_FUNC(int) PyFrame_FastToLocalsWithError(PyFrameObject *f);
+PyAPI_FUNC(void) PyFrame_FastToLocals(PyFrameObject *);
diff --git a/include/python3.11/cpython/funcobject.h b/include/python3.11/cpython/funcobject.h
new file mode 100644
index 0000000..99ac600
--- /dev/null
+++ b/include/python3.11/cpython/funcobject.h
@@ -0,0 +1,113 @@
+/* Function object interface */
+
+#ifndef Py_LIMITED_API
+#ifndef Py_FUNCOBJECT_H
+#define Py_FUNCOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+#define COMMON_FIELDS(PREFIX) \
+ PyObject *PREFIX ## globals; \
+ PyObject *PREFIX ## builtins; \
+ PyObject *PREFIX ## name; \
+ PyObject *PREFIX ## qualname; \
+ PyObject *PREFIX ## code; /* A code object, the __code__ attribute */ \
+ PyObject *PREFIX ## defaults; /* NULL or a tuple */ \
+ PyObject *PREFIX ## kwdefaults; /* NULL or a dict */ \
+ PyObject *PREFIX ## closure; /* NULL or a tuple of cell objects */
+
+typedef struct {
+ COMMON_FIELDS(fc_)
+} PyFrameConstructor;
+
+/* Function objects and code objects should not be confused with each other:
+ *
+ * Function objects are created by the execution of the 'def' statement.
+ * They reference a code object in their __code__ attribute, which is a
+ * purely syntactic object, i.e. nothing more than a compiled version of some
+ * source code lines. There is one code object per source code "fragment",
+ * but each code object can be referenced by zero or many function objects
+ * depending only on how many times the 'def' statement in the source was
+ * executed so far.
+ */
+
+typedef struct {
+ PyObject_HEAD
+ COMMON_FIELDS(func_)
+ PyObject *func_doc; /* The __doc__ attribute, can be anything */
+ PyObject *func_dict; /* The __dict__ attribute, a dict or NULL */
+ PyObject *func_weakreflist; /* List of weak references */
+ PyObject *func_module; /* The __module__ attribute, can be anything */
+ PyObject *func_annotations; /* Annotations, a dict or NULL */
+ vectorcallfunc vectorcall;
+ /* Version number for use by specializer.
+ * Can set to non-zero when we want to specialize.
+ * Will be set to zero if any of these change:
+ * defaults
+ * kwdefaults (only if the object changes, not the contents of the dict)
+ * code
+ * annotations */
+ uint32_t func_version;
+
+ /* Invariant:
+ * func_closure contains the bindings for func_code->co_freevars, so
+ * PyTuple_Size(func_closure) == PyCode_GetNumFree(func_code)
+ * (func_closure may be NULL if PyCode_GetNumFree(func_code) == 0).
+ */
+} PyFunctionObject;
+
+PyAPI_DATA(PyTypeObject) PyFunction_Type;
+
+#define PyFunction_Check(op) Py_IS_TYPE(op, &PyFunction_Type)
+
+PyAPI_FUNC(PyObject *) PyFunction_New(PyObject *, PyObject *);
+PyAPI_FUNC(PyObject *) PyFunction_NewWithQualName(PyObject *, PyObject *, PyObject *);
+PyAPI_FUNC(PyObject *) PyFunction_GetCode(PyObject *);
+PyAPI_FUNC(PyObject *) PyFunction_GetGlobals(PyObject *);
+PyAPI_FUNC(PyObject *) PyFunction_GetModule(PyObject *);
+PyAPI_FUNC(PyObject *) PyFunction_GetDefaults(PyObject *);
+PyAPI_FUNC(int) PyFunction_SetDefaults(PyObject *, PyObject *);
+PyAPI_FUNC(PyObject *) PyFunction_GetKwDefaults(PyObject *);
+PyAPI_FUNC(int) PyFunction_SetKwDefaults(PyObject *, PyObject *);
+PyAPI_FUNC(PyObject *) PyFunction_GetClosure(PyObject *);
+PyAPI_FUNC(int) PyFunction_SetClosure(PyObject *, PyObject *);
+PyAPI_FUNC(PyObject *) PyFunction_GetAnnotations(PyObject *);
+PyAPI_FUNC(int) PyFunction_SetAnnotations(PyObject *, PyObject *);
+
+PyAPI_FUNC(PyObject *) _PyFunction_Vectorcall(
+ PyObject *func,
+ PyObject *const *stack,
+ size_t nargsf,
+ PyObject *kwnames);
+
+/* Macros for direct access to these values. Type checks are *not*
+ done, so use with care. */
+#define PyFunction_GET_CODE(func) \
+ (((PyFunctionObject *)func) -> func_code)
+#define PyFunction_GET_GLOBALS(func) \
+ (((PyFunctionObject *)func) -> func_globals)
+#define PyFunction_GET_MODULE(func) \
+ (((PyFunctionObject *)func) -> func_module)
+#define PyFunction_GET_DEFAULTS(func) \
+ (((PyFunctionObject *)func) -> func_defaults)
+#define PyFunction_GET_KW_DEFAULTS(func) \
+ (((PyFunctionObject *)func) -> func_kwdefaults)
+#define PyFunction_GET_CLOSURE(func) \
+ (((PyFunctionObject *)func) -> func_closure)
+#define PyFunction_GET_ANNOTATIONS(func) \
+ (((PyFunctionObject *)func) -> func_annotations)
+
+/* The classmethod and staticmethod types lives here, too */
+PyAPI_DATA(PyTypeObject) PyClassMethod_Type;
+PyAPI_DATA(PyTypeObject) PyStaticMethod_Type;
+
+PyAPI_FUNC(PyObject *) PyClassMethod_New(PyObject *);
+PyAPI_FUNC(PyObject *) PyStaticMethod_New(PyObject *);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_FUNCOBJECT_H */
+#endif /* Py_LIMITED_API */
diff --git a/include/python3.11/cpython/genobject.h b/include/python3.11/cpython/genobject.h
new file mode 100644
index 0000000..40eaa19
--- /dev/null
+++ b/include/python3.11/cpython/genobject.h
@@ -0,0 +1,88 @@
+/* Generator object interface */
+
+#ifndef Py_LIMITED_API
+#ifndef Py_GENOBJECT_H
+#define Py_GENOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* --- Generators --------------------------------------------------------- */
+
+/* _PyGenObject_HEAD defines the initial segment of generator
+ and coroutine objects. */
+#define _PyGenObject_HEAD(prefix) \
+ PyObject_HEAD \
+ /* The code object backing the generator */ \
+ PyCodeObject *prefix##_code; \
+ /* List of weak reference. */ \
+ PyObject *prefix##_weakreflist; \
+ /* Name of the generator. */ \
+ PyObject *prefix##_name; \
+ /* Qualified name of the generator. */ \
+ PyObject *prefix##_qualname; \
+ _PyErr_StackItem prefix##_exc_state; \
+ PyObject *prefix##_origin_or_finalizer; \
+ char prefix##_hooks_inited; \
+ char prefix##_closed; \
+ char prefix##_running_async; \
+ /* The frame */ \
+ int8_t prefix##_frame_state; \
+ PyObject *prefix##_iframe[1];
+
+typedef struct {
+ /* The gi_ prefix is intended to remind of generator-iterator. */
+ _PyGenObject_HEAD(gi)
+} PyGenObject;
+
+PyAPI_DATA(PyTypeObject) PyGen_Type;
+
+#define PyGen_Check(op) PyObject_TypeCheck(op, &PyGen_Type)
+#define PyGen_CheckExact(op) Py_IS_TYPE(op, &PyGen_Type)
+
+PyAPI_FUNC(PyObject *) PyGen_New(PyFrameObject *);
+PyAPI_FUNC(PyObject *) PyGen_NewWithQualName(PyFrameObject *,
+ PyObject *name, PyObject *qualname);
+PyAPI_FUNC(int) _PyGen_SetStopIterationValue(PyObject *);
+PyAPI_FUNC(int) _PyGen_FetchStopIterationValue(PyObject **);
+PyAPI_FUNC(void) _PyGen_Finalize(PyObject *self);
+
+
+/* --- PyCoroObject ------------------------------------------------------- */
+
+typedef struct {
+ _PyGenObject_HEAD(cr)
+} PyCoroObject;
+
+PyAPI_DATA(PyTypeObject) PyCoro_Type;
+PyAPI_DATA(PyTypeObject) _PyCoroWrapper_Type;
+
+#define PyCoro_CheckExact(op) Py_IS_TYPE(op, &PyCoro_Type)
+PyAPI_FUNC(PyObject *) PyCoro_New(PyFrameObject *,
+ PyObject *name, PyObject *qualname);
+
+
+/* --- Asynchronous Generators -------------------------------------------- */
+
+typedef struct {
+ _PyGenObject_HEAD(ag)
+} PyAsyncGenObject;
+
+PyAPI_DATA(PyTypeObject) PyAsyncGen_Type;
+PyAPI_DATA(PyTypeObject) _PyAsyncGenASend_Type;
+PyAPI_DATA(PyTypeObject) _PyAsyncGenWrappedValue_Type;
+PyAPI_DATA(PyTypeObject) _PyAsyncGenAThrow_Type;
+
+PyAPI_FUNC(PyObject *) PyAsyncGen_New(PyFrameObject *,
+ PyObject *name, PyObject *qualname);
+
+#define PyAsyncGen_CheckExact(op) Py_IS_TYPE(op, &PyAsyncGen_Type)
+
+
+#undef _PyGenObject_HEAD
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_GENOBJECT_H */
+#endif /* Py_LIMITED_API */
diff --git a/include/python3.11/cpython/import.h b/include/python3.11/cpython/import.h
new file mode 100644
index 0000000..a69b4f3
--- /dev/null
+++ b/include/python3.11/cpython/import.h
@@ -0,0 +1,45 @@
+#ifndef Py_CPYTHON_IMPORT_H
+# error "this header file must not be included directly"
+#endif
+
+PyMODINIT_FUNC PyInit__imp(void);
+
+PyAPI_FUNC(int) _PyImport_IsInitialized(PyInterpreterState *);
+
+PyAPI_FUNC(PyObject *) _PyImport_GetModuleId(_Py_Identifier *name);
+PyAPI_FUNC(int) _PyImport_SetModule(PyObject *name, PyObject *module);
+PyAPI_FUNC(int) _PyImport_SetModuleString(const char *name, PyObject* module);
+
+PyAPI_FUNC(void) _PyImport_AcquireLock(void);
+PyAPI_FUNC(int) _PyImport_ReleaseLock(void);
+
+PyAPI_FUNC(int) _PyImport_FixupBuiltin(
+ PyObject *mod,
+ const char *name, /* UTF-8 encoded string */
+ PyObject *modules
+ );
+PyAPI_FUNC(int) _PyImport_FixupExtensionObject(PyObject*, PyObject *,
+ PyObject *, PyObject *);
+
+struct _inittab {
+ const char *name; /* ASCII encoded string */
+ PyObject* (*initfunc)(void);
+};
+PyAPI_DATA(struct _inittab *) PyImport_Inittab;
+PyAPI_FUNC(int) PyImport_ExtendInittab(struct _inittab *newtab);
+
+struct _frozen {
+ const char *name; /* ASCII encoded string */
+ const unsigned char *code;
+ int size;
+ int is_package;
+ PyObject *(*get_code)(void);
+};
+
+/* Embedding apps may change this pointer to point to their favorite
+ collection of frozen modules: */
+
+PyAPI_DATA(const struct _frozen *) PyImport_FrozenModules;
+
+PyAPI_DATA(PyObject *) _PyImport_GetModuleAttr(PyObject *, PyObject *);
+PyAPI_DATA(PyObject *) _PyImport_GetModuleAttrString(const char *, const char *);
diff --git a/include/python3.11/cpython/initconfig.h b/include/python3.11/cpython/initconfig.h
new file mode 100644
index 0000000..3b6d593
--- /dev/null
+++ b/include/python3.11/cpython/initconfig.h
@@ -0,0 +1,257 @@
+#ifndef Py_PYCORECONFIG_H
+#define Py_PYCORECONFIG_H
+#ifndef Py_LIMITED_API
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* --- PyStatus ----------------------------------------------- */
+
+typedef struct {
+ enum {
+ _PyStatus_TYPE_OK=0,
+ _PyStatus_TYPE_ERROR=1,
+ _PyStatus_TYPE_EXIT=2
+ } _type;
+ const char *func;
+ const char *err_msg;
+ int exitcode;
+} PyStatus;
+
+PyAPI_FUNC(PyStatus) PyStatus_Ok(void);
+PyAPI_FUNC(PyStatus) PyStatus_Error(const char *err_msg);
+PyAPI_FUNC(PyStatus) PyStatus_NoMemory(void);
+PyAPI_FUNC(PyStatus) PyStatus_Exit(int exitcode);
+PyAPI_FUNC(int) PyStatus_IsError(PyStatus err);
+PyAPI_FUNC(int) PyStatus_IsExit(PyStatus err);
+PyAPI_FUNC(int) PyStatus_Exception(PyStatus err);
+
+/* --- PyWideStringList ------------------------------------------------ */
+
+typedef struct {
+ /* If length is greater than zero, items must be non-NULL
+ and all items strings must be non-NULL */
+ Py_ssize_t length;
+ wchar_t **items;
+} PyWideStringList;
+
+PyAPI_FUNC(PyStatus) PyWideStringList_Append(PyWideStringList *list,
+ const wchar_t *item);
+PyAPI_FUNC(PyStatus) PyWideStringList_Insert(PyWideStringList *list,
+ Py_ssize_t index,
+ const wchar_t *item);
+
+
+/* --- PyPreConfig ----------------------------------------------- */
+
+typedef struct PyPreConfig {
+ int _config_init; /* _PyConfigInitEnum value */
+
+ /* Parse Py_PreInitializeFromBytesArgs() arguments?
+ See PyConfig.parse_argv */
+ int parse_argv;
+
+ /* If greater than 0, enable isolated mode: sys.path contains
+ neither the script's directory nor the user's site-packages directory.
+
+ Set to 1 by the -I command line option. If set to -1 (default), inherit
+ Py_IsolatedFlag value. */
+ int isolated;
+
+ /* If greater than 0: use environment variables.
+ Set to 0 by -E command line option. If set to -1 (default), it is
+ set to !Py_IgnoreEnvironmentFlag. */
+ int use_environment;
+
+ /* Set the LC_CTYPE locale to the user preferred locale? If equals to 0,
+ set coerce_c_locale and coerce_c_locale_warn to 0. */
+ int configure_locale;
+
+ /* Coerce the LC_CTYPE locale if it's equal to "C"? (PEP 538)
+
+ Set to 0 by PYTHONCOERCECLOCALE=0. Set to 1 by PYTHONCOERCECLOCALE=1.
+ Set to 2 if the user preferred LC_CTYPE locale is "C".
+
+ If it is equal to 1, LC_CTYPE locale is read to decide if it should be
+ coerced or not (ex: PYTHONCOERCECLOCALE=1). Internally, it is set to 2
+ if the LC_CTYPE locale must be coerced.
+
+ Disable by default (set to 0). Set it to -1 to let Python decide if it
+ should be enabled or not. */
+ int coerce_c_locale;
+
+ /* Emit a warning if the LC_CTYPE locale is coerced?
+
+ Set to 1 by PYTHONCOERCECLOCALE=warn.
+
+ Disable by default (set to 0). Set it to -1 to let Python decide if it
+ should be enabled or not. */
+ int coerce_c_locale_warn;
+
+#ifdef MS_WINDOWS
+ /* If greater than 1, use the "mbcs" encoding instead of the UTF-8
+ encoding for the filesystem encoding.
+
+ Set to 1 if the PYTHONLEGACYWINDOWSFSENCODING environment variable is
+ set to a non-empty string. If set to -1 (default), inherit
+ Py_LegacyWindowsFSEncodingFlag value.
+
+ See PEP 529 for more details. */
+ int legacy_windows_fs_encoding;
+#endif
+
+ /* Enable UTF-8 mode? (PEP 540)
+
+ Disabled by default (equals to 0).
+
+ Set to 1 by "-X utf8" and "-X utf8=1" command line options.
+ Set to 1 by PYTHONUTF8=1 environment variable.
+
+ Set to 0 by "-X utf8=0" and PYTHONUTF8=0.
+
+ If equals to -1, it is set to 1 if the LC_CTYPE locale is "C" or
+ "POSIX", otherwise it is set to 0. Inherit Py_UTF8Mode value value. */
+ int utf8_mode;
+
+ /* If non-zero, enable the Python Development Mode.
+
+ Set to 1 by the -X dev command line option. Set by the PYTHONDEVMODE
+ environment variable. */
+ int dev_mode;
+
+ /* Memory allocator: PYTHONMALLOC env var.
+ See PyMemAllocatorName for valid values. */
+ int allocator;
+} PyPreConfig;
+
+PyAPI_FUNC(void) PyPreConfig_InitPythonConfig(PyPreConfig *config);
+PyAPI_FUNC(void) PyPreConfig_InitIsolatedConfig(PyPreConfig *config);
+
+
+/* --- PyConfig ---------------------------------------------- */
+
+/* This structure is best documented in the Doc/c-api/init_config.rst file. */
+typedef struct PyConfig {
+ int _config_init; /* _PyConfigInitEnum value */
+
+ int isolated;
+ int use_environment;
+ int dev_mode;
+ int install_signal_handlers;
+ int use_hash_seed;
+ unsigned long hash_seed;
+ int faulthandler;
+ int tracemalloc;
+ int import_time;
+ int code_debug_ranges;
+ int show_ref_count;
+ int dump_refs;
+ wchar_t *dump_refs_file;
+ int malloc_stats;
+ wchar_t *filesystem_encoding;
+ wchar_t *filesystem_errors;
+ wchar_t *pycache_prefix;
+ int parse_argv;
+ PyWideStringList orig_argv;
+ PyWideStringList argv;
+ PyWideStringList xoptions;
+ PyWideStringList warnoptions;
+ int site_import;
+ int bytes_warning;
+ int warn_default_encoding;
+ int inspect;
+ int interactive;
+ int optimization_level;
+ int parser_debug;
+ int write_bytecode;
+ int verbose;
+ int quiet;
+ int user_site_directory;
+ int configure_c_stdio;
+ int buffered_stdio;
+ wchar_t *stdio_encoding;
+ wchar_t *stdio_errors;
+#ifdef MS_WINDOWS
+ int legacy_windows_stdio;
+#endif
+ wchar_t *check_hash_pycs_mode;
+ int use_frozen_modules;
+ int safe_path;
+
+ /* --- Path configuration inputs ------------ */
+ int pathconfig_warnings;
+ wchar_t *program_name;
+ wchar_t *pythonpath_env;
+ wchar_t *home;
+ wchar_t *platlibdir;
+
+ /* --- Path configuration outputs ----------- */
+ int module_search_paths_set;
+ PyWideStringList module_search_paths;
+ wchar_t *stdlib_dir;
+ wchar_t *executable;
+ wchar_t *base_executable;
+ wchar_t *prefix;
+ wchar_t *base_prefix;
+ wchar_t *exec_prefix;
+ wchar_t *base_exec_prefix;
+
+ /* --- Parameter only used by Py_Main() ---------- */
+ int skip_source_first_line;
+ wchar_t *run_command;
+ wchar_t *run_module;
+ wchar_t *run_filename;
+
+ /* --- Private fields ---------------------------- */
+
+ // Install importlib? If equals to 0, importlib is not initialized at all.
+ // Needed by freeze_importlib.
+ int _install_importlib;
+
+ // If equal to 0, stop Python initialization before the "main" phase.
+ int _init_main;
+
+ // If non-zero, disallow threads, subprocesses, and fork.
+ // Default: 0.
+ int _isolated_interpreter;
+
+ // If non-zero, we believe we're running from a source tree.
+ int _is_python_build;
+} PyConfig;
+
+PyAPI_FUNC(void) PyConfig_InitPythonConfig(PyConfig *config);
+PyAPI_FUNC(void) PyConfig_InitIsolatedConfig(PyConfig *config);
+PyAPI_FUNC(void) PyConfig_Clear(PyConfig *);
+PyAPI_FUNC(PyStatus) PyConfig_SetString(
+ PyConfig *config,
+ wchar_t **config_str,
+ const wchar_t *str);
+PyAPI_FUNC(PyStatus) PyConfig_SetBytesString(
+ PyConfig *config,
+ wchar_t **config_str,
+ const char *str);
+PyAPI_FUNC(PyStatus) PyConfig_Read(PyConfig *config);
+PyAPI_FUNC(PyStatus) PyConfig_SetBytesArgv(
+ PyConfig *config,
+ Py_ssize_t argc,
+ char * const *argv);
+PyAPI_FUNC(PyStatus) PyConfig_SetArgv(PyConfig *config,
+ Py_ssize_t argc,
+ wchar_t * const *argv);
+PyAPI_FUNC(PyStatus) PyConfig_SetWideStringList(PyConfig *config,
+ PyWideStringList *list,
+ Py_ssize_t length, wchar_t **items);
+
+
+/* --- Helper functions --------------------------------------- */
+
+/* Get the original command line arguments, before Python modified them.
+
+ See also PyConfig.orig_argv. */
+PyAPI_FUNC(void) Py_GetArgcArgv(int *argc, wchar_t ***argv);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_LIMITED_API */
+#endif /* !Py_PYCORECONFIG_H */
diff --git a/include/python3.11/cpython/listobject.h b/include/python3.11/cpython/listobject.h
new file mode 100644
index 0000000..1add821
--- /dev/null
+++ b/include/python3.11/cpython/listobject.h
@@ -0,0 +1,51 @@
+#ifndef Py_CPYTHON_LISTOBJECT_H
+# error "this header file must not be included directly"
+#endif
+
+typedef struct {
+ PyObject_VAR_HEAD
+ /* Vector of pointers to list elements. list[0] is ob_item[0], etc. */
+ PyObject **ob_item;
+
+ /* ob_item contains space for 'allocated' elements. The number
+ * currently in use is ob_size.
+ * Invariants:
+ * 0 <= ob_size <= allocated
+ * len(list) == ob_size
+ * ob_item == NULL implies ob_size == allocated == 0
+ * list.sort() temporarily sets allocated to -1 to detect mutations.
+ *
+ * Items must normally not be NULL, except during construction when
+ * the list is not yet visible outside the function that builds it.
+ */
+ Py_ssize_t allocated;
+} PyListObject;
+
+PyAPI_FUNC(PyObject *) _PyList_Extend(PyListObject *, PyObject *);
+PyAPI_FUNC(void) _PyList_DebugMallocStats(FILE *out);
+
+/* Cast argument to PyListObject* type. */
+#define _PyList_CAST(op) \
+ (assert(PyList_Check(op)), _Py_CAST(PyListObject*, (op)))
+
+// Macros and static inline functions, trading safety for speed
+
+static inline Py_ssize_t PyList_GET_SIZE(PyObject *op) {
+ PyListObject *list = _PyList_CAST(op);
+ return Py_SIZE(list);
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyList_GET_SIZE(op) PyList_GET_SIZE(_PyObject_CAST(op))
+#endif
+
+#define PyList_GET_ITEM(op, index) (_PyList_CAST(op)->ob_item[index])
+
+static inline void
+PyList_SET_ITEM(PyObject *op, Py_ssize_t index, PyObject *value) {
+ PyListObject *list = _PyList_CAST(op);
+ list->ob_item[index] = value;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+#define PyList_SET_ITEM(op, index, value) \
+ PyList_SET_ITEM(_PyObject_CAST(op), index, _PyObject_CAST(value))
+#endif
diff --git a/include/python3.11/cpython/longintrepr.h b/include/python3.11/cpython/longintrepr.h
new file mode 100644
index 0000000..6d52427
--- /dev/null
+++ b/include/python3.11/cpython/longintrepr.h
@@ -0,0 +1,96 @@
+#ifndef Py_LIMITED_API
+#ifndef Py_LONGINTREPR_H
+#define Py_LONGINTREPR_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* This is published for the benefit of "friends" marshal.c and _decimal.c. */
+
+/* Parameters of the integer representation. There are two different
+ sets of parameters: one set for 30-bit digits, stored in an unsigned 32-bit
+ integer type, and one set for 15-bit digits with each digit stored in an
+ unsigned short. The value of PYLONG_BITS_IN_DIGIT, defined either at
+ configure time or in pyport.h, is used to decide which digit size to use.
+
+ Type 'digit' should be able to hold 2*PyLong_BASE-1, and type 'twodigits'
+ should be an unsigned integer type able to hold all integers up to
+ PyLong_BASE*PyLong_BASE-1. x_sub assumes that 'digit' is an unsigned type,
+ and that overflow is handled by taking the result modulo 2**N for some N >
+ PyLong_SHIFT. The majority of the code doesn't care about the precise
+ value of PyLong_SHIFT, but there are some notable exceptions:
+
+ - PyLong_{As,From}ByteArray require that PyLong_SHIFT be at least 8
+
+ - long_hash() requires that PyLong_SHIFT is *strictly* less than the number
+ of bits in an unsigned long, as do the PyLong <-> long (or unsigned long)
+ conversion functions
+
+ - the Python int <-> size_t/Py_ssize_t conversion functions expect that
+ PyLong_SHIFT is strictly less than the number of bits in a size_t
+
+ - the marshal code currently expects that PyLong_SHIFT is a multiple of 15
+
+ - NSMALLNEGINTS and NSMALLPOSINTS should be small enough to fit in a single
+ digit; with the current values this forces PyLong_SHIFT >= 9
+
+ The values 15 and 30 should fit all of the above requirements, on any
+ platform.
+*/
+
+#if PYLONG_BITS_IN_DIGIT == 30
+typedef uint32_t digit;
+typedef int32_t sdigit; /* signed variant of digit */
+typedef uint64_t twodigits;
+typedef int64_t stwodigits; /* signed variant of twodigits */
+#define PyLong_SHIFT 30
+#define _PyLong_DECIMAL_SHIFT 9 /* max(e such that 10**e fits in a digit) */
+#define _PyLong_DECIMAL_BASE ((digit)1000000000) /* 10 ** DECIMAL_SHIFT */
+#elif PYLONG_BITS_IN_DIGIT == 15
+typedef unsigned short digit;
+typedef short sdigit; /* signed variant of digit */
+typedef unsigned long twodigits;
+typedef long stwodigits; /* signed variant of twodigits */
+#define PyLong_SHIFT 15
+#define _PyLong_DECIMAL_SHIFT 4 /* max(e such that 10**e fits in a digit) */
+#define _PyLong_DECIMAL_BASE ((digit)10000) /* 10 ** DECIMAL_SHIFT */
+#else
+#error "PYLONG_BITS_IN_DIGIT should be 15 or 30"
+#endif
+#define PyLong_BASE ((digit)1 << PyLong_SHIFT)
+#define PyLong_MASK ((digit)(PyLong_BASE - 1))
+
+/* Long integer representation.
+ The absolute value of a number is equal to
+ SUM(for i=0 through abs(ob_size)-1) ob_digit[i] * 2**(SHIFT*i)
+ Negative numbers are represented with ob_size < 0;
+ zero is represented by ob_size == 0.
+ In a normalized number, ob_digit[abs(ob_size)-1] (the most significant
+ digit) is never zero. Also, in all cases, for all valid i,
+ 0 <= ob_digit[i] <= MASK.
+ The allocation function takes care of allocating extra memory
+ so that ob_digit[0] ... ob_digit[abs(ob_size)-1] are actually available.
+ We always allocate memory for at least one digit, so accessing ob_digit[0]
+ is always safe. However, in the case ob_size == 0, the contents of
+ ob_digit[0] may be undefined.
+
+ CAUTION: Generic code manipulating subtypes of PyVarObject has to
+ aware that ints abuse ob_size's sign bit.
+*/
+
+struct _longobject {
+ PyObject_VAR_HEAD
+ digit ob_digit[1];
+};
+
+PyAPI_FUNC(PyLongObject *) _PyLong_New(Py_ssize_t);
+
+/* Return a copy of src. */
+PyAPI_FUNC(PyObject *) _PyLong_Copy(PyLongObject *src);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_LONGINTREPR_H */
+#endif /* Py_LIMITED_API */
diff --git a/include/python3.11/cpython/longobject.h b/include/python3.11/cpython/longobject.h
new file mode 100644
index 0000000..1a73799
--- /dev/null
+++ b/include/python3.11/cpython/longobject.h
@@ -0,0 +1,95 @@
+#ifndef Py_CPYTHON_LONGOBJECT_H
+# error "this header file must not be included directly"
+#endif
+
+PyAPI_FUNC(int) _PyLong_AsInt(PyObject *);
+
+PyAPI_FUNC(int) _PyLong_UnsignedShort_Converter(PyObject *, void *);
+PyAPI_FUNC(int) _PyLong_UnsignedInt_Converter(PyObject *, void *);
+PyAPI_FUNC(int) _PyLong_UnsignedLong_Converter(PyObject *, void *);
+PyAPI_FUNC(int) _PyLong_UnsignedLongLong_Converter(PyObject *, void *);
+PyAPI_FUNC(int) _PyLong_Size_t_Converter(PyObject *, void *);
+
+/* _PyLong_Frexp returns a double x and an exponent e such that the
+ true value is approximately equal to x * 2**e. e is >= 0. x is
+ 0.0 if and only if the input is 0 (in which case, e and x are both
+ zeroes); otherwise, 0.5 <= abs(x) < 1.0. On overflow, which is
+ possible if the number of bits doesn't fit into a Py_ssize_t, sets
+ OverflowError and returns -1.0 for x, 0 for e. */
+PyAPI_FUNC(double) _PyLong_Frexp(PyLongObject *a, Py_ssize_t *e);
+
+PyAPI_FUNC(PyObject *) PyLong_FromUnicodeObject(PyObject *u, int base);
+PyAPI_FUNC(PyObject *) _PyLong_FromBytes(const char *, Py_ssize_t, int);
+
+/* _PyLong_Sign. Return 0 if v is 0, -1 if v < 0, +1 if v > 0.
+ v must not be NULL, and must be a normalized long.
+ There are no error cases.
+*/
+PyAPI_FUNC(int) _PyLong_Sign(PyObject *v);
+
+/* _PyLong_NumBits. Return the number of bits needed to represent the
+ absolute value of a long. For example, this returns 1 for 1 and -1, 2
+ for 2 and -2, and 2 for 3 and -3. It returns 0 for 0.
+ v must not be NULL, and must be a normalized long.
+ (size_t)-1 is returned and OverflowError set if the true result doesn't
+ fit in a size_t.
+*/
+PyAPI_FUNC(size_t) _PyLong_NumBits(PyObject *v);
+
+/* _PyLong_DivmodNear. Given integers a and b, compute the nearest
+ integer q to the exact quotient a / b, rounding to the nearest even integer
+ in the case of a tie. Return (q, r), where r = a - q*b. The remainder r
+ will satisfy abs(r) <= abs(b)/2, with equality possible only if q is
+ even.
+*/
+PyAPI_FUNC(PyObject *) _PyLong_DivmodNear(PyObject *, PyObject *);
+
+/* _PyLong_FromByteArray: View the n unsigned bytes as a binary integer in
+ base 256, and return a Python int with the same numeric value.
+ If n is 0, the integer is 0. Else:
+ If little_endian is 1/true, bytes[n-1] is the MSB and bytes[0] the LSB;
+ else (little_endian is 0/false) bytes[0] is the MSB and bytes[n-1] the
+ LSB.
+ If is_signed is 0/false, view the bytes as a non-negative integer.
+ If is_signed is 1/true, view the bytes as a 2's-complement integer,
+ non-negative if bit 0x80 of the MSB is clear, negative if set.
+ Error returns:
+ + Return NULL with the appropriate exception set if there's not
+ enough memory to create the Python int.
+*/
+PyAPI_FUNC(PyObject *) _PyLong_FromByteArray(
+ const unsigned char* bytes, size_t n,
+ int little_endian, int is_signed);
+
+/* _PyLong_AsByteArray: Convert the least-significant 8*n bits of long
+ v to a base-256 integer, stored in array bytes. Normally return 0,
+ return -1 on error.
+ If little_endian is 1/true, store the MSB at bytes[n-1] and the LSB at
+ bytes[0]; else (little_endian is 0/false) store the MSB at bytes[0] and
+ the LSB at bytes[n-1].
+ If is_signed is 0/false, it's an error if v < 0; else (v >= 0) n bytes
+ are filled and there's nothing special about bit 0x80 of the MSB.
+ If is_signed is 1/true, bytes is filled with the 2's-complement
+ representation of v's value. Bit 0x80 of the MSB is the sign bit.
+ Error returns (-1):
+ + is_signed is 0 and v < 0. TypeError is set in this case, and bytes
+ isn't altered.
+ + n isn't big enough to hold the full mathematical value of v. For
+ example, if is_signed is 0 and there are more digits in the v than
+ fit in n; or if is_signed is 1, v < 0, and n is just 1 bit shy of
+ being large enough to hold a sign bit. OverflowError is set in this
+ case, but bytes holds the least-significant n bytes of the true value.
+*/
+PyAPI_FUNC(int) _PyLong_AsByteArray(PyLongObject* v,
+ unsigned char* bytes, size_t n,
+ int little_endian, int is_signed);
+
+/* _PyLong_Format: Convert the long to a string object with given base,
+ appending a base prefix of 0[box] if base is 2, 8 or 16. */
+PyAPI_FUNC(PyObject *) _PyLong_Format(PyObject *obj, int base);
+
+/* For use by the gcd function in mathmodule.c */
+PyAPI_FUNC(PyObject *) _PyLong_GCD(PyObject *, PyObject *);
+
+PyAPI_FUNC(PyObject *) _PyLong_Rshift(PyObject *, size_t);
+PyAPI_FUNC(PyObject *) _PyLong_Lshift(PyObject *, size_t);
diff --git a/include/python3.11/cpython/methodobject.h b/include/python3.11/cpython/methodobject.h
new file mode 100644
index 0000000..54a61cf
--- /dev/null
+++ b/include/python3.11/cpython/methodobject.h
@@ -0,0 +1,74 @@
+#ifndef Py_CPYTHON_METHODOBJECT_H
+# error "this header file must not be included directly"
+#endif
+
+// PyCFunctionObject structure
+
+typedef struct {
+ PyObject_HEAD
+ PyMethodDef *m_ml; /* Description of the C function to call */
+ PyObject *m_self; /* Passed as 'self' arg to the C func, can be NULL */
+ PyObject *m_module; /* The __module__ attribute, can be anything */
+ PyObject *m_weakreflist; /* List of weak references */
+ vectorcallfunc vectorcall;
+} PyCFunctionObject;
+
+#define _PyCFunctionObject_CAST(func) \
+ (assert(PyCFunction_Check(func)), \
+ _Py_CAST(PyCFunctionObject*, (func)))
+
+
+// PyCMethodObject structure
+
+typedef struct {
+ PyCFunctionObject func;
+ PyTypeObject *mm_class; /* Class that defines this method */
+} PyCMethodObject;
+
+#define _PyCMethodObject_CAST(func) \
+ (assert(PyCMethod_Check(func)), \
+ _Py_CAST(PyCMethodObject*, (func)))
+
+PyAPI_DATA(PyTypeObject) PyCMethod_Type;
+
+#define PyCMethod_CheckExact(op) Py_IS_TYPE(op, &PyCMethod_Type)
+#define PyCMethod_Check(op) PyObject_TypeCheck(op, &PyCMethod_Type)
+
+
+/* Static inline functions for direct access to these values.
+ Type checks are *not* done, so use with care. */
+static inline PyCFunction PyCFunction_GET_FUNCTION(PyObject *func) {
+ return _PyCFunctionObject_CAST(func)->m_ml->ml_meth;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyCFunction_GET_FUNCTION(func) PyCFunction_GET_FUNCTION(_PyObject_CAST(func))
+#endif
+
+static inline PyObject* PyCFunction_GET_SELF(PyObject *func_obj) {
+ PyCFunctionObject *func = _PyCFunctionObject_CAST(func_obj);
+ if (func->m_ml->ml_flags & METH_STATIC) {
+ return _Py_NULL;
+ }
+ return func->m_self;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyCFunction_GET_SELF(func) PyCFunction_GET_SELF(_PyObject_CAST(func))
+#endif
+
+static inline int PyCFunction_GET_FLAGS(PyObject *func) {
+ return _PyCFunctionObject_CAST(func)->m_ml->ml_flags;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyCFunction_GET_FLAGS(func) PyCFunction_GET_FLAGS(_PyObject_CAST(func))
+#endif
+
+static inline PyTypeObject* PyCFunction_GET_CLASS(PyObject *func_obj) {
+ PyCFunctionObject *func = _PyCFunctionObject_CAST(func_obj);
+ if (func->m_ml->ml_flags & METH_METHOD) {
+ return _PyCMethodObject_CAST(func)->mm_class;
+ }
+ return _Py_NULL;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyCFunction_GET_CLASS(func) PyCFunction_GET_CLASS(_PyObject_CAST(func))
+#endif
diff --git a/include/python3.11/cpython/modsupport.h b/include/python3.11/cpython/modsupport.h
new file mode 100644
index 0000000..769eb52
--- /dev/null
+++ b/include/python3.11/cpython/modsupport.h
@@ -0,0 +1,107 @@
+#ifndef Py_CPYTHON_MODSUPPORT_H
+# error "this header file must not be included directly"
+#endif
+
+/* If PY_SSIZE_T_CLEAN is defined, each functions treats #-specifier
+ to mean Py_ssize_t */
+#ifdef PY_SSIZE_T_CLEAN
+#define _Py_VaBuildStack _Py_VaBuildStack_SizeT
+#else
+PyAPI_FUNC(PyObject *) _Py_VaBuildValue_SizeT(const char *, va_list);
+PyAPI_FUNC(PyObject **) _Py_VaBuildStack_SizeT(
+ PyObject **small_stack,
+ Py_ssize_t small_stack_len,
+ const char *format,
+ va_list va,
+ Py_ssize_t *p_nargs);
+#endif
+
+PyAPI_FUNC(int) _PyArg_UnpackStack(
+ PyObject *const *args,
+ Py_ssize_t nargs,
+ const char *name,
+ Py_ssize_t min,
+ Py_ssize_t max,
+ ...);
+
+PyAPI_FUNC(int) _PyArg_NoKeywords(const char *funcname, PyObject *kwargs);
+PyAPI_FUNC(int) _PyArg_NoKwnames(const char *funcname, PyObject *kwnames);
+PyAPI_FUNC(int) _PyArg_NoPositional(const char *funcname, PyObject *args);
+#define _PyArg_NoKeywords(funcname, kwargs) \
+ ((kwargs) == NULL || _PyArg_NoKeywords((funcname), (kwargs)))
+#define _PyArg_NoKwnames(funcname, kwnames) \
+ ((kwnames) == NULL || _PyArg_NoKwnames((funcname), (kwnames)))
+#define _PyArg_NoPositional(funcname, args) \
+ ((args) == NULL || _PyArg_NoPositional((funcname), (args)))
+
+PyAPI_FUNC(void) _PyArg_BadArgument(const char *, const char *, const char *, PyObject *);
+PyAPI_FUNC(int) _PyArg_CheckPositional(const char *, Py_ssize_t,
+ Py_ssize_t, Py_ssize_t);
+#define _PyArg_CheckPositional(funcname, nargs, min, max) \
+ ((!ANY_VARARGS(max) && (min) <= (nargs) && (nargs) <= (max)) \
+ || _PyArg_CheckPositional((funcname), (nargs), (min), (max)))
+
+PyAPI_FUNC(PyObject **) _Py_VaBuildStack(
+ PyObject **small_stack,
+ Py_ssize_t small_stack_len,
+ const char *format,
+ va_list va,
+ Py_ssize_t *p_nargs);
+
+typedef struct _PyArg_Parser {
+ const char *format;
+ const char * const *keywords;
+ const char *fname;
+ const char *custom_msg;
+ int pos; /* number of positional-only arguments */
+ int min; /* minimal number of arguments */
+ int max; /* maximal number of positional arguments */
+ PyObject *kwtuple; /* tuple of keyword parameter names */
+ struct _PyArg_Parser *next;
+} _PyArg_Parser;
+
+#ifdef PY_SSIZE_T_CLEAN
+#define _PyArg_ParseTupleAndKeywordsFast _PyArg_ParseTupleAndKeywordsFast_SizeT
+#define _PyArg_ParseStack _PyArg_ParseStack_SizeT
+#define _PyArg_ParseStackAndKeywords _PyArg_ParseStackAndKeywords_SizeT
+#define _PyArg_VaParseTupleAndKeywordsFast _PyArg_VaParseTupleAndKeywordsFast_SizeT
+#endif
+
+PyAPI_FUNC(int) _PyArg_ParseTupleAndKeywordsFast(PyObject *, PyObject *,
+ struct _PyArg_Parser *, ...);
+PyAPI_FUNC(int) _PyArg_ParseStack(
+ PyObject *const *args,
+ Py_ssize_t nargs,
+ const char *format,
+ ...);
+PyAPI_FUNC(int) _PyArg_ParseStackAndKeywords(
+ PyObject *const *args,
+ Py_ssize_t nargs,
+ PyObject *kwnames,
+ struct _PyArg_Parser *,
+ ...);
+PyAPI_FUNC(int) _PyArg_VaParseTupleAndKeywordsFast(PyObject *, PyObject *,
+ struct _PyArg_Parser *, va_list);
+PyAPI_FUNC(PyObject * const *) _PyArg_UnpackKeywords(
+ PyObject *const *args, Py_ssize_t nargs,
+ PyObject *kwargs, PyObject *kwnames,
+ struct _PyArg_Parser *parser,
+ int minpos, int maxpos, int minkw,
+ PyObject **buf);
+
+PyAPI_FUNC(PyObject * const *) _PyArg_UnpackKeywordsWithVararg(
+ PyObject *const *args, Py_ssize_t nargs,
+ PyObject *kwargs, PyObject *kwnames,
+ struct _PyArg_Parser *parser,
+ int minpos, int maxpos, int minkw,
+ int vararg, PyObject **buf);
+
+#define _PyArg_UnpackKeywords(args, nargs, kwargs, kwnames, parser, minpos, maxpos, minkw, buf) \
+ (((minkw) == 0 && (kwargs) == NULL && (kwnames) == NULL && \
+ (minpos) <= (nargs) && (nargs) <= (maxpos) && args != NULL) ? (args) : \
+ _PyArg_UnpackKeywords((args), (nargs), (kwargs), (kwnames), (parser), \
+ (minpos), (maxpos), (minkw), (buf)))
+
+PyAPI_FUNC(PyObject *) _PyModule_CreateInitialized(PyModuleDef*, int apiver);
+
+PyAPI_DATA(const char *) _Py_PackageContext;
diff --git a/include/python3.11/cpython/object.h b/include/python3.11/cpython/object.h
new file mode 100644
index 0000000..b018dab
--- /dev/null
+++ b/include/python3.11/cpython/object.h
@@ -0,0 +1,511 @@
+#ifndef Py_CPYTHON_OBJECT_H
+# error "this header file must not be included directly"
+#endif
+
+PyAPI_FUNC(void) _Py_NewReference(PyObject *op);
+
+#ifdef Py_TRACE_REFS
+/* Py_TRACE_REFS is such major surgery that we call external routines. */
+PyAPI_FUNC(void) _Py_ForgetReference(PyObject *);
+#endif
+
+#ifdef Py_REF_DEBUG
+PyAPI_FUNC(Py_ssize_t) _Py_GetRefTotal(void);
+#endif
+
+
+/********************* String Literals ****************************************/
+/* This structure helps managing static strings. The basic usage goes like this:
+ Instead of doing
+
+ r = PyObject_CallMethod(o, "foo", "args", ...);
+
+ do
+
+ _Py_IDENTIFIER(foo);
+ ...
+ r = _PyObject_CallMethodId(o, &PyId_foo, "args", ...);
+
+ PyId_foo is a static variable, either on block level or file level. On first
+ usage, the string "foo" is interned, and the structures are linked. On interpreter
+ shutdown, all strings are released.
+
+ Alternatively, _Py_static_string allows choosing the variable name.
+ _PyUnicode_FromId returns a borrowed reference to the interned string.
+ _PyObject_{Get,Set,Has}AttrId are __getattr__ versions using _Py_Identifier*.
+*/
+typedef struct _Py_Identifier {
+ const char* string;
+ // Index in PyInterpreterState.unicode.ids.array. It is process-wide
+ // unique and must be initialized to -1.
+ Py_ssize_t index;
+} _Py_Identifier;
+
+#if defined(NEEDS_PY_IDENTIFIER) || !defined(Py_BUILD_CORE)
+// For now we are keeping _Py_IDENTIFIER for continued use
+// in non-builtin extensions (and naughty PyPI modules).
+
+#define _Py_static_string_init(value) { .string = value, .index = -1 }
+#define _Py_static_string(varname, value) static _Py_Identifier varname = _Py_static_string_init(value)
+#define _Py_IDENTIFIER(varname) _Py_static_string(PyId_##varname, #varname)
+
+#endif /* NEEDS_PY_IDENTIFIER */
+
+typedef int (*getbufferproc)(PyObject *, Py_buffer *, int);
+typedef void (*releasebufferproc)(PyObject *, Py_buffer *);
+
+typedef PyObject *(*vectorcallfunc)(PyObject *callable, PyObject *const *args,
+ size_t nargsf, PyObject *kwnames);
+
+
+typedef struct {
+ /* Number implementations must check *both*
+ arguments for proper type and implement the necessary conversions
+ in the slot functions themselves. */
+
+ binaryfunc nb_add;
+ binaryfunc nb_subtract;
+ binaryfunc nb_multiply;
+ binaryfunc nb_remainder;
+ binaryfunc nb_divmod;
+ ternaryfunc nb_power;
+ unaryfunc nb_negative;
+ unaryfunc nb_positive;
+ unaryfunc nb_absolute;
+ inquiry nb_bool;
+ unaryfunc nb_invert;
+ binaryfunc nb_lshift;
+ binaryfunc nb_rshift;
+ binaryfunc nb_and;
+ binaryfunc nb_xor;
+ binaryfunc nb_or;
+ unaryfunc nb_int;
+ void *nb_reserved; /* the slot formerly known as nb_long */
+ unaryfunc nb_float;
+
+ binaryfunc nb_inplace_add;
+ binaryfunc nb_inplace_subtract;
+ binaryfunc nb_inplace_multiply;
+ binaryfunc nb_inplace_remainder;
+ ternaryfunc nb_inplace_power;
+ binaryfunc nb_inplace_lshift;
+ binaryfunc nb_inplace_rshift;
+ binaryfunc nb_inplace_and;
+ binaryfunc nb_inplace_xor;
+ binaryfunc nb_inplace_or;
+
+ binaryfunc nb_floor_divide;
+ binaryfunc nb_true_divide;
+ binaryfunc nb_inplace_floor_divide;
+ binaryfunc nb_inplace_true_divide;
+
+ unaryfunc nb_index;
+
+ binaryfunc nb_matrix_multiply;
+ binaryfunc nb_inplace_matrix_multiply;
+} PyNumberMethods;
+
+typedef struct {
+ lenfunc sq_length;
+ binaryfunc sq_concat;
+ ssizeargfunc sq_repeat;
+ ssizeargfunc sq_item;
+ void *was_sq_slice;
+ ssizeobjargproc sq_ass_item;
+ void *was_sq_ass_slice;
+ objobjproc sq_contains;
+
+ binaryfunc sq_inplace_concat;
+ ssizeargfunc sq_inplace_repeat;
+} PySequenceMethods;
+
+typedef struct {
+ lenfunc mp_length;
+ binaryfunc mp_subscript;
+ objobjargproc mp_ass_subscript;
+} PyMappingMethods;
+
+typedef PySendResult (*sendfunc)(PyObject *iter, PyObject *value, PyObject **result);
+
+typedef struct {
+ unaryfunc am_await;
+ unaryfunc am_aiter;
+ unaryfunc am_anext;
+ sendfunc am_send;
+} PyAsyncMethods;
+
+typedef struct {
+ getbufferproc bf_getbuffer;
+ releasebufferproc bf_releasebuffer;
+} PyBufferProcs;
+
+/* Allow printfunc in the tp_vectorcall_offset slot for
+ * backwards-compatibility */
+typedef Py_ssize_t printfunc;
+
+// If this structure is modified, Doc/includes/typestruct.h should be updated
+// as well.
+struct _typeobject {
+ PyObject_VAR_HEAD
+ const char *tp_name; /* For printing, in format "<module>.<name>" */
+ Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */
+
+ /* Methods to implement standard operations */
+
+ destructor tp_dealloc;
+ Py_ssize_t tp_vectorcall_offset;
+ getattrfunc tp_getattr;
+ setattrfunc tp_setattr;
+ PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
+ or tp_reserved (Python 3) */
+ reprfunc tp_repr;
+
+ /* Method suites for standard classes */
+
+ PyNumberMethods *tp_as_number;
+ PySequenceMethods *tp_as_sequence;
+ PyMappingMethods *tp_as_mapping;
+
+ /* More standard operations (here for binary compatibility) */
+
+ hashfunc tp_hash;
+ ternaryfunc tp_call;
+ reprfunc tp_str;
+ getattrofunc tp_getattro;
+ setattrofunc tp_setattro;
+
+ /* Functions to access object as input/output buffer */
+ PyBufferProcs *tp_as_buffer;
+
+ /* Flags to define presence of optional/expanded features */
+ unsigned long tp_flags;
+
+ const char *tp_doc; /* Documentation string */
+
+ /* Assigned meaning in release 2.0 */
+ /* call function for all accessible objects */
+ traverseproc tp_traverse;
+
+ /* delete references to contained objects */
+ inquiry tp_clear;
+
+ /* Assigned meaning in release 2.1 */
+ /* rich comparisons */
+ richcmpfunc tp_richcompare;
+
+ /* weak reference enabler */
+ Py_ssize_t tp_weaklistoffset;
+
+ /* Iterators */
+ getiterfunc tp_iter;
+ iternextfunc tp_iternext;
+
+ /* Attribute descriptor and subclassing stuff */
+ PyMethodDef *tp_methods;
+ PyMemberDef *tp_members;
+ PyGetSetDef *tp_getset;
+ // Strong reference on a heap type, borrowed reference on a static type
+ PyTypeObject *tp_base;
+ PyObject *tp_dict;
+ descrgetfunc tp_descr_get;
+ descrsetfunc tp_descr_set;
+ Py_ssize_t tp_dictoffset;
+ initproc tp_init;
+ allocfunc tp_alloc;
+ newfunc tp_new;
+ freefunc tp_free; /* Low-level free-memory routine */
+ inquiry tp_is_gc; /* For PyObject_IS_GC */
+ PyObject *tp_bases;
+ PyObject *tp_mro; /* method resolution order */
+ PyObject *tp_cache;
+ PyObject *tp_subclasses;
+ PyObject *tp_weaklist;
+ destructor tp_del;
+
+ /* Type attribute cache version tag. Added in version 2.6 */
+ unsigned int tp_version_tag;
+
+ destructor tp_finalize;
+ vectorcallfunc tp_vectorcall;
+};
+
+/* This struct is used by the specializer
+ * It should should be treated as an opaque blob
+ * by code other than the specializer and interpreter. */
+struct _specialization_cache {
+ PyObject *getitem;
+};
+
+/* The *real* layout of a type object when allocated on the heap */
+typedef struct _heaptypeobject {
+ /* Note: there's a dependency on the order of these members
+ in slotptr() in typeobject.c . */
+ PyTypeObject ht_type;
+ PyAsyncMethods as_async;
+ PyNumberMethods as_number;
+ PyMappingMethods as_mapping;
+ PySequenceMethods as_sequence; /* as_sequence comes after as_mapping,
+ so that the mapping wins when both
+ the mapping and the sequence define
+ a given operator (e.g. __getitem__).
+ see add_operators() in typeobject.c . */
+ PyBufferProcs as_buffer;
+ PyObject *ht_name, *ht_slots, *ht_qualname;
+ struct _dictkeysobject *ht_cached_keys;
+ PyObject *ht_module;
+ char *_ht_tpname; // Storage for "tp_name"; see PyType_FromModuleAndSpec
+ struct _specialization_cache _spec_cache; // For use by the specializer.
+ /* here are optional user slots, followed by the members. */
+} PyHeapTypeObject;
+
+PyAPI_FUNC(const char *) _PyType_Name(PyTypeObject *);
+PyAPI_FUNC(PyObject *) _PyType_Lookup(PyTypeObject *, PyObject *);
+PyAPI_FUNC(PyObject *) _PyType_LookupId(PyTypeObject *, _Py_Identifier *);
+PyAPI_FUNC(PyObject *) _PyObject_LookupSpecialId(PyObject *, _Py_Identifier *);
+#ifndef Py_BUILD_CORE
+// Backward compatibility for 3rd-party extensions
+// that may be using the old name.
+#define _PyObject_LookupSpecial _PyObject_LookupSpecialId
+#endif
+PyAPI_FUNC(PyTypeObject *) _PyType_CalculateMetaclass(PyTypeObject *, PyObject *);
+PyAPI_FUNC(PyObject *) _PyType_GetDocFromInternalDoc(const char *, const char *);
+PyAPI_FUNC(PyObject *) _PyType_GetTextSignatureFromInternalDoc(const char *, const char *);
+PyAPI_FUNC(PyObject *) PyType_GetModuleByDef(PyTypeObject *, PyModuleDef *);
+
+PyAPI_FUNC(int) PyObject_Print(PyObject *, FILE *, int);
+PyAPI_FUNC(void) _Py_BreakPoint(void);
+PyAPI_FUNC(void) _PyObject_Dump(PyObject *);
+PyAPI_FUNC(int) _PyObject_IsFreed(PyObject *);
+
+PyAPI_FUNC(int) _PyObject_IsAbstract(PyObject *);
+PyAPI_FUNC(PyObject *) _PyObject_GetAttrId(PyObject *, _Py_Identifier *);
+PyAPI_FUNC(int) _PyObject_SetAttrId(PyObject *, _Py_Identifier *, PyObject *);
+/* Replacements of PyObject_GetAttr() and _PyObject_GetAttrId() which
+ don't raise AttributeError.
+
+ Return 1 and set *result != NULL if an attribute is found.
+ Return 0 and set *result == NULL if an attribute is not found;
+ an AttributeError is silenced.
+ Return -1 and set *result == NULL if an error other than AttributeError
+ is raised.
+*/
+PyAPI_FUNC(int) _PyObject_LookupAttr(PyObject *, PyObject *, PyObject **);
+PyAPI_FUNC(int) _PyObject_LookupAttrId(PyObject *, _Py_Identifier *, PyObject **);
+
+PyAPI_FUNC(int) _PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method);
+
+PyAPI_FUNC(PyObject **) _PyObject_GetDictPtr(PyObject *);
+PyAPI_FUNC(PyObject *) _PyObject_NextNotImplemented(PyObject *);
+PyAPI_FUNC(void) PyObject_CallFinalizer(PyObject *);
+PyAPI_FUNC(int) PyObject_CallFinalizerFromDealloc(PyObject *);
+
+/* Same as PyObject_Generic{Get,Set}Attr, but passing the attributes
+ dict as the last parameter. */
+PyAPI_FUNC(PyObject *)
+_PyObject_GenericGetAttrWithDict(PyObject *, PyObject *, PyObject *, int);
+PyAPI_FUNC(int)
+_PyObject_GenericSetAttrWithDict(PyObject *, PyObject *,
+ PyObject *, PyObject *);
+
+PyAPI_FUNC(PyObject *) _PyObject_FunctionStr(PyObject *);
+
+/* Safely decref `op` and set `op` to `op2`.
+ *
+ * As in case of Py_CLEAR "the obvious" code can be deadly:
+ *
+ * Py_DECREF(op);
+ * op = op2;
+ *
+ * The safe way is:
+ *
+ * Py_SETREF(op, op2);
+ *
+ * That arranges to set `op` to `op2` _before_ decref'ing, so that any code
+ * triggered as a side-effect of `op` getting torn down no longer believes
+ * `op` points to a valid object.
+ *
+ * Py_XSETREF is a variant of Py_SETREF that uses Py_XDECREF instead of
+ * Py_DECREF.
+ */
+
+#define Py_SETREF(op, op2) \
+ do { \
+ PyObject *_py_tmp = _PyObject_CAST(op); \
+ (op) = (op2); \
+ Py_DECREF(_py_tmp); \
+ } while (0)
+
+#define Py_XSETREF(op, op2) \
+ do { \
+ PyObject *_py_tmp = _PyObject_CAST(op); \
+ (op) = (op2); \
+ Py_XDECREF(_py_tmp); \
+ } while (0)
+
+
+PyAPI_DATA(PyTypeObject) _PyNone_Type;
+PyAPI_DATA(PyTypeObject) _PyNotImplemented_Type;
+
+/* Maps Py_LT to Py_GT, ..., Py_GE to Py_LE.
+ * Defined in object.c.
+ */
+PyAPI_DATA(int) _Py_SwappedOp[];
+
+PyAPI_FUNC(void)
+_PyDebugAllocatorStats(FILE *out, const char *block_name, int num_blocks,
+ size_t sizeof_block);
+PyAPI_FUNC(void)
+_PyObject_DebugTypeStats(FILE *out);
+
+/* Define a pair of assertion macros:
+ _PyObject_ASSERT_FROM(), _PyObject_ASSERT_WITH_MSG() and _PyObject_ASSERT().
+
+ These work like the regular C assert(), in that they will abort the
+ process with a message on stderr if the given condition fails to hold,
+ but compile away to nothing if NDEBUG is defined.
+
+ However, before aborting, Python will also try to call _PyObject_Dump() on
+ the given object. This may be of use when investigating bugs in which a
+ particular object is corrupt (e.g. buggy a tp_visit method in an extension
+ module breaking the garbage collector), to help locate the broken objects.
+
+ The WITH_MSG variant allows you to supply an additional message that Python
+ will attempt to print to stderr, after the object dump. */
+#ifdef NDEBUG
+ /* No debugging: compile away the assertions: */
+# define _PyObject_ASSERT_FROM(obj, expr, msg, filename, lineno, func) \
+ ((void)0)
+#else
+ /* With debugging: generate checks: */
+# define _PyObject_ASSERT_FROM(obj, expr, msg, filename, lineno, func) \
+ ((expr) \
+ ? (void)(0) \
+ : _PyObject_AssertFailed((obj), Py_STRINGIFY(expr), \
+ (msg), (filename), (lineno), (func)))
+#endif
+
+#define _PyObject_ASSERT_WITH_MSG(obj, expr, msg) \
+ _PyObject_ASSERT_FROM(obj, expr, msg, __FILE__, __LINE__, __func__)
+#define _PyObject_ASSERT(obj, expr) \
+ _PyObject_ASSERT_WITH_MSG(obj, expr, NULL)
+
+#define _PyObject_ASSERT_FAILED_MSG(obj, msg) \
+ _PyObject_AssertFailed((obj), NULL, (msg), __FILE__, __LINE__, __func__)
+
+/* Declare and define _PyObject_AssertFailed() even when NDEBUG is defined,
+ to avoid causing compiler/linker errors when building extensions without
+ NDEBUG against a Python built with NDEBUG defined.
+
+ msg, expr and function can be NULL. */
+PyAPI_FUNC(void) _Py_NO_RETURN _PyObject_AssertFailed(
+ PyObject *obj,
+ const char *expr,
+ const char *msg,
+ const char *file,
+ int line,
+ const char *function);
+
+/* Check if an object is consistent. For example, ensure that the reference
+ counter is greater than or equal to 1, and ensure that ob_type is not NULL.
+
+ Call _PyObject_AssertFailed() if the object is inconsistent.
+
+ If check_content is zero, only check header fields: reduce the overhead.
+
+ The function always return 1. The return value is just here to be able to
+ write:
+
+ assert(_PyObject_CheckConsistency(obj, 1)); */
+PyAPI_FUNC(int) _PyObject_CheckConsistency(
+ PyObject *op,
+ int check_content);
+
+
+/* Trashcan mechanism, thanks to Christian Tismer.
+
+When deallocating a container object, it's possible to trigger an unbounded
+chain of deallocations, as each Py_DECREF in turn drops the refcount on "the
+next" object in the chain to 0. This can easily lead to stack overflows,
+especially in threads (which typically have less stack space to work with).
+
+A container object can avoid this by bracketing the body of its tp_dealloc
+function with a pair of macros:
+
+static void
+mytype_dealloc(mytype *p)
+{
+ ... declarations go here ...
+
+ PyObject_GC_UnTrack(p); // must untrack first
+ Py_TRASHCAN_BEGIN(p, mytype_dealloc)
+ ... The body of the deallocator goes here, including all calls ...
+ ... to Py_DECREF on contained objects. ...
+ Py_TRASHCAN_END // there should be no code after this
+}
+
+CAUTION: Never return from the middle of the body! If the body needs to
+"get out early", put a label immediately before the Py_TRASHCAN_END
+call, and goto it. Else the call-depth counter (see below) will stay
+above 0 forever, and the trashcan will never get emptied.
+
+How it works: The BEGIN macro increments a call-depth counter. So long
+as this counter is small, the body of the deallocator is run directly without
+further ado. But if the counter gets large, it instead adds p to a list of
+objects to be deallocated later, skips the body of the deallocator, and
+resumes execution after the END macro. The tp_dealloc routine then returns
+without deallocating anything (and so unbounded call-stack depth is avoided).
+
+When the call stack finishes unwinding again, code generated by the END macro
+notices this, and calls another routine to deallocate all the objects that
+may have been added to the list of deferred deallocations. In effect, a
+chain of N deallocations is broken into (N-1)/(_PyTrash_UNWIND_LEVEL-1) pieces,
+with the call stack never exceeding a depth of _PyTrash_UNWIND_LEVEL.
+
+Since the tp_dealloc of a subclass typically calls the tp_dealloc of the base
+class, we need to ensure that the trashcan is only triggered on the tp_dealloc
+of the actual class being deallocated. Otherwise we might end up with a
+partially-deallocated object. To check this, the tp_dealloc function must be
+passed as second argument to Py_TRASHCAN_BEGIN().
+*/
+
+/* Python 3.9 private API, invoked by the macros below. */
+PyAPI_FUNC(int) _PyTrash_begin(PyThreadState *tstate, PyObject *op);
+PyAPI_FUNC(void) _PyTrash_end(PyThreadState *tstate);
+/* Python 3.10 private API, invoked by the Py_TRASHCAN_BEGIN(). */
+PyAPI_FUNC(int) _PyTrash_cond(PyObject *op, destructor dealloc);
+
+#define Py_TRASHCAN_BEGIN_CONDITION(op, cond) \
+ do { \
+ PyThreadState *_tstate = NULL; \
+ /* If "cond" is false, then _tstate remains NULL and the deallocator \
+ * is run normally without involving the trashcan */ \
+ if (cond) { \
+ _tstate = PyThreadState_Get(); \
+ if (_PyTrash_begin(_tstate, _PyObject_CAST(op))) { \
+ break; \
+ } \
+ }
+ /* The body of the deallocator is here. */
+#define Py_TRASHCAN_END \
+ if (_tstate) { \
+ _PyTrash_end(_tstate); \
+ } \
+ } while (0);
+
+#define Py_TRASHCAN_BEGIN(op, dealloc) \
+ Py_TRASHCAN_BEGIN_CONDITION(op, \
+ _PyTrash_cond(_PyObject_CAST(op), (destructor)dealloc))
+
+/* The following two macros, Py_TRASHCAN_SAFE_BEGIN and
+ * Py_TRASHCAN_SAFE_END, are deprecated since version 3.11 and
+ * will be removed in the future.
+ * Use Py_TRASHCAN_BEGIN and Py_TRASHCAN_END instead.
+ */
+Py_DEPRECATED(3.11) typedef int UsingDeprecatedTrashcanMacro;
+#define Py_TRASHCAN_SAFE_BEGIN(op) \
+ do { \
+ UsingDeprecatedTrashcanMacro cond=1; \
+ Py_TRASHCAN_BEGIN_CONDITION(op, cond);
+#define Py_TRASHCAN_SAFE_END(op) \
+ Py_TRASHCAN_END; \
+ } while(0);
diff --git a/include/python3.11/cpython/objimpl.h b/include/python3.11/cpython/objimpl.h
new file mode 100644
index 0000000..d7c76ea
--- /dev/null
+++ b/include/python3.11/cpython/objimpl.h
@@ -0,0 +1,89 @@
+#ifndef Py_CPYTHON_OBJIMPL_H
+# error "this header file must not be included directly"
+#endif
+
+#define _PyObject_SIZE(typeobj) ( (typeobj)->tp_basicsize )
+
+/* _PyObject_VAR_SIZE returns the number of bytes (as size_t) allocated for a
+ vrbl-size object with nitems items, exclusive of gc overhead (if any). The
+ value is rounded up to the closest multiple of sizeof(void *), in order to
+ ensure that pointer fields at the end of the object are correctly aligned
+ for the platform (this is of special importance for subclasses of, e.g.,
+ str or int, so that pointers can be stored after the embedded data).
+
+ Note that there's no memory wastage in doing this, as malloc has to
+ return (at worst) pointer-aligned memory anyway.
+*/
+#if ((SIZEOF_VOID_P - 1) & SIZEOF_VOID_P) != 0
+# error "_PyObject_VAR_SIZE requires SIZEOF_VOID_P be a power of 2"
+#endif
+
+#define _PyObject_VAR_SIZE(typeobj, nitems) \
+ _Py_SIZE_ROUND_UP((typeobj)->tp_basicsize + \
+ (nitems)*(typeobj)->tp_itemsize, \
+ SIZEOF_VOID_P)
+
+
+/* This example code implements an object constructor with a custom
+ allocator, where PyObject_New is inlined, and shows the important
+ distinction between two steps (at least):
+ 1) the actual allocation of the object storage;
+ 2) the initialization of the Python specific fields
+ in this storage with PyObject_{Init, InitVar}.
+
+ PyObject *
+ YourObject_New(...)
+ {
+ PyObject *op;
+
+ op = (PyObject *) Your_Allocator(_PyObject_SIZE(YourTypeStruct));
+ if (op == NULL) {
+ return PyErr_NoMemory();
+ }
+
+ PyObject_Init(op, &YourTypeStruct);
+
+ op->ob_field = value;
+ ...
+ return op;
+ }
+
+ Note that in C++, the use of the new operator usually implies that
+ the 1st step is performed automatically for you, so in a C++ class
+ constructor you would start directly with PyObject_Init/InitVar. */
+
+
+typedef struct {
+ /* user context passed as the first argument to the 2 functions */
+ void *ctx;
+
+ /* allocate an arena of size bytes */
+ void* (*alloc) (void *ctx, size_t size);
+
+ /* free an arena */
+ void (*free) (void *ctx, void *ptr, size_t size);
+} PyObjectArenaAllocator;
+
+/* Get the arena allocator. */
+PyAPI_FUNC(void) PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator);
+
+/* Set the arena allocator. */
+PyAPI_FUNC(void) PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator);
+
+
+/* Test if an object implements the garbage collector protocol */
+PyAPI_FUNC(int) PyObject_IS_GC(PyObject *obj);
+
+
+/* Code built with Py_BUILD_CORE must include pycore_gc.h instead which
+ defines a different _PyGC_FINALIZED() macro. */
+#ifndef Py_BUILD_CORE
+ // Kept for backward compatibility with Python 3.8
+# define _PyGC_FINALIZED(o) PyObject_GC_IsFinalized(o)
+#endif
+
+
+// Test if a type supports weak references
+PyAPI_FUNC(int) PyType_SUPPORTS_WEAKREFS(PyTypeObject *type);
+
+PyAPI_FUNC(PyObject **) PyObject_GET_WEAKREFS_LISTPTR(PyObject *op);
diff --git a/include/python3.10/cpython/odictobject.h b/include/python3.11/cpython/odictobject.h
similarity index 100%
rename from include/python3.10/cpython/odictobject.h
rename to include/python3.11/cpython/odictobject.h
diff --git a/include/python3.10/cpython/picklebufobject.h b/include/python3.11/cpython/picklebufobject.h
similarity index 100%
rename from include/python3.10/cpython/picklebufobject.h
rename to include/python3.11/cpython/picklebufobject.h
diff --git a/include/python3.11/cpython/pthread_stubs.h b/include/python3.11/cpython/pthread_stubs.h
new file mode 100644
index 0000000..d95ee03
--- /dev/null
+++ b/include/python3.11/cpython/pthread_stubs.h
@@ -0,0 +1,88 @@
+#ifndef Py_CPYTHON_PTRHEAD_STUBS_H
+#define Py_CPYTHON_PTRHEAD_STUBS_H
+
+#if !defined(HAVE_PTHREAD_STUBS)
+# error "this header file requires stubbed pthreads."
+#endif
+
+#ifndef _POSIX_THREADS
+# define _POSIX_THREADS 1
+#endif
+
+/* Minimal pthread stubs for CPython.
+ *
+ * The stubs implement the minimum pthread API for CPython.
+ * - pthread_create() fails.
+ * - pthread_exit() calls exit(0).
+ * - pthread_key_*() functions implement minimal TSS without destructor.
+ * - all other functions do nothing and return 0.
+ */
+
+#ifdef __wasi__
+// WASI's bits/alltypes.h provides type definitions when __NEED_ is set.
+// The header file can be included multiple times.
+# define __NEED_pthread_cond_t 1
+# define __NEED_pthread_condattr_t 1
+# define __NEED_pthread_mutex_t 1
+# define __NEED_pthread_mutexattr_t 1
+# define __NEED_pthread_key_t 1
+# define __NEED_pthread_t 1
+# define __NEED_pthread_attr_t 1
+# include <bits/alltypes.h>
+#else
+typedef struct { void *__x; } pthread_cond_t;
+typedef struct { unsigned __attr; } pthread_condattr_t;
+typedef struct { void *__x; } pthread_mutex_t;
+typedef struct { unsigned __attr; } pthread_mutexattr_t;
+typedef unsigned pthread_key_t;
+typedef unsigned pthread_t;
+typedef struct { unsigned __attr; } pthread_attr_t;
+#endif
+
+// mutex
+PyAPI_FUNC(int) pthread_mutex_init(pthread_mutex_t *restrict mutex,
+ const pthread_mutexattr_t *restrict attr);
+PyAPI_FUNC(int) pthread_mutex_destroy(pthread_mutex_t *mutex);
+PyAPI_FUNC(int) pthread_mutex_trylock(pthread_mutex_t *mutex);
+PyAPI_FUNC(int) pthread_mutex_lock(pthread_mutex_t *mutex);
+PyAPI_FUNC(int) pthread_mutex_unlock(pthread_mutex_t *mutex);
+
+// condition
+PyAPI_FUNC(int) pthread_cond_init(pthread_cond_t *restrict cond,
+ const pthread_condattr_t *restrict attr);
+PyAPI_FUNC(int) pthread_cond_destroy(pthread_cond_t *cond);
+PyAPI_FUNC(int) pthread_cond_wait(pthread_cond_t *restrict cond,
+ pthread_mutex_t *restrict mutex);
+PyAPI_FUNC(int) pthread_cond_timedwait(pthread_cond_t *restrict cond,
+ pthread_mutex_t *restrict mutex,
+ const struct timespec *restrict abstime);
+PyAPI_FUNC(int) pthread_cond_signal(pthread_cond_t *cond);
+PyAPI_FUNC(int) pthread_condattr_init(pthread_condattr_t *attr);
+PyAPI_FUNC(int) pthread_condattr_setclock(
+ pthread_condattr_t *attr, clockid_t clock_id);
+
+// pthread
+PyAPI_FUNC(int) pthread_create(pthread_t *restrict thread,
+ const pthread_attr_t *restrict attr,
+ void *(*start_routine)(void *),
+ void *restrict arg);
+PyAPI_FUNC(int) pthread_detach(pthread_t thread);
+PyAPI_FUNC(pthread_t) pthread_self(void);
+PyAPI_FUNC(int) pthread_exit(void *retval) __attribute__ ((__noreturn__));
+PyAPI_FUNC(int) pthread_attr_init(pthread_attr_t *attr);
+PyAPI_FUNC(int) pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize);
+PyAPI_FUNC(int) pthread_attr_destroy(pthread_attr_t *attr);
+
+
+// pthread_key
+#ifndef PTHREAD_KEYS_MAX
+# define PTHREAD_KEYS_MAX 128
+#endif
+
+PyAPI_FUNC(int) pthread_key_create(pthread_key_t *key,
+ void (*destr_function)(void *));
+PyAPI_FUNC(int) pthread_key_delete(pthread_key_t key);
+PyAPI_FUNC(void *) pthread_getspecific(pthread_key_t key);
+PyAPI_FUNC(int) pthread_setspecific(pthread_key_t key, const void *value);
+
+#endif // Py_CPYTHON_PTRHEAD_STUBS_H
diff --git a/include/python3.10/cpython/pyctype.h b/include/python3.11/cpython/pyctype.h
similarity index 100%
rename from include/python3.10/cpython/pyctype.h
rename to include/python3.11/cpython/pyctype.h
diff --git a/include/python3.11/cpython/pydebug.h b/include/python3.11/cpython/pydebug.h
new file mode 100644
index 0000000..cab799f
--- /dev/null
+++ b/include/python3.11/cpython/pydebug.h
@@ -0,0 +1,38 @@
+#ifndef Py_LIMITED_API
+#ifndef Py_PYDEBUG_H
+#define Py_PYDEBUG_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_DATA(int) Py_DebugFlag;
+PyAPI_DATA(int) Py_VerboseFlag;
+PyAPI_DATA(int) Py_QuietFlag;
+PyAPI_DATA(int) Py_InteractiveFlag;
+PyAPI_DATA(int) Py_InspectFlag;
+PyAPI_DATA(int) Py_OptimizeFlag;
+PyAPI_DATA(int) Py_NoSiteFlag;
+PyAPI_DATA(int) Py_BytesWarningFlag;
+PyAPI_DATA(int) Py_FrozenFlag;
+PyAPI_DATA(int) Py_IgnoreEnvironmentFlag;
+PyAPI_DATA(int) Py_DontWriteBytecodeFlag;
+PyAPI_DATA(int) Py_NoUserSiteDirectory;
+PyAPI_DATA(int) Py_UnbufferedStdioFlag;
+PyAPI_DATA(int) Py_HashRandomizationFlag;
+PyAPI_DATA(int) Py_IsolatedFlag;
+
+#ifdef MS_WINDOWS
+PyAPI_DATA(int) Py_LegacyWindowsFSEncodingFlag;
+PyAPI_DATA(int) Py_LegacyWindowsStdioFlag;
+#endif
+
+/* this is a wrapper around getenv() that pays attention to
+ Py_IgnoreEnvironmentFlag. It should be used for getting variables like
+ PYTHONPATH and PYTHONHOME from the environment */
+PyAPI_DATA(char*) Py_GETENV(const char *name);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_PYDEBUG_H */
+#endif /* Py_LIMITED_API */
diff --git a/include/python3.11/cpython/pyerrors.h b/include/python3.11/cpython/pyerrors.h
new file mode 100644
index 0000000..47d80e3
--- /dev/null
+++ b/include/python3.11/cpython/pyerrors.h
@@ -0,0 +1,179 @@
+#ifndef Py_CPYTHON_ERRORS_H
+# error "this header file must not be included directly"
+#endif
+
+/* Error objects */
+
+/* PyException_HEAD defines the initial segment of every exception class. */
+#define PyException_HEAD PyObject_HEAD PyObject *dict;\
+ PyObject *args; PyObject *notes; PyObject *traceback;\
+ PyObject *context; PyObject *cause;\
+ char suppress_context;
+
+typedef struct {
+ PyException_HEAD
+} PyBaseExceptionObject;
+
+typedef struct {
+ PyException_HEAD
+ PyObject *msg;
+ PyObject *excs;
+} PyBaseExceptionGroupObject;
+
+typedef struct {
+ PyException_HEAD
+ PyObject *msg;
+ PyObject *filename;
+ PyObject *lineno;
+ PyObject *offset;
+ PyObject *end_lineno;
+ PyObject *end_offset;
+ PyObject *text;
+ PyObject *print_file_and_line;
+} PySyntaxErrorObject;
+
+typedef struct {
+ PyException_HEAD
+ PyObject *msg;
+ PyObject *name;
+ PyObject *path;
+} PyImportErrorObject;
+
+typedef struct {
+ PyException_HEAD
+ PyObject *encoding;
+ PyObject *object;
+ Py_ssize_t start;
+ Py_ssize_t end;
+ PyObject *reason;
+} PyUnicodeErrorObject;
+
+typedef struct {
+ PyException_HEAD
+ PyObject *code;
+} PySystemExitObject;
+
+typedef struct {
+ PyException_HEAD
+ PyObject *myerrno;
+ PyObject *strerror;
+ PyObject *filename;
+ PyObject *filename2;
+#ifdef MS_WINDOWS
+ PyObject *winerror;
+#endif
+ Py_ssize_t written; /* only for BlockingIOError, -1 otherwise */
+} PyOSErrorObject;
+
+typedef struct {
+ PyException_HEAD
+ PyObject *value;
+} PyStopIterationObject;
+
+typedef struct {
+ PyException_HEAD
+ PyObject *name;
+} PyNameErrorObject;
+
+typedef struct {
+ PyException_HEAD
+ PyObject *obj;
+ PyObject *name;
+} PyAttributeErrorObject;
+
+/* Compatibility typedefs */
+typedef PyOSErrorObject PyEnvironmentErrorObject;
+#ifdef MS_WINDOWS
+typedef PyOSErrorObject PyWindowsErrorObject;
+#endif
+
+/* Error handling definitions */
+
+PyAPI_FUNC(void) _PyErr_SetKeyError(PyObject *);
+PyAPI_FUNC(_PyErr_StackItem*) _PyErr_GetTopmostException(PyThreadState *tstate);
+PyAPI_FUNC(PyObject*) _PyErr_GetHandledException(PyThreadState *);
+PyAPI_FUNC(void) _PyErr_SetHandledException(PyThreadState *, PyObject *);
+PyAPI_FUNC(void) _PyErr_GetExcInfo(PyThreadState *, PyObject **, PyObject **, PyObject **);
+
+/* Context manipulation (PEP 3134) */
+
+PyAPI_FUNC(void) _PyErr_ChainExceptions(PyObject *, PyObject *, PyObject *);
+
+/* Like PyErr_Format(), but saves current exception as __context__ and
+ __cause__.
+ */
+PyAPI_FUNC(PyObject *) _PyErr_FormatFromCause(
+ PyObject *exception,
+ const char *format, /* ASCII-encoded string */
+ ...
+ );
+
+/* In exceptions.c */
+
+/* Helper that attempts to replace the current exception with one of the
+ * same type but with a prefix added to the exception text. The resulting
+ * exception description looks like:
+ *
+ * prefix (exc_type: original_exc_str)
+ *
+ * Only some exceptions can be safely replaced. If the function determines
+ * it isn't safe to perform the replacement, it will leave the original
+ * unmodified exception in place.
+ *
+ * Returns a borrowed reference to the new exception (if any), NULL if the
+ * existing exception was left in place.
+ */
+PyAPI_FUNC(PyObject *) _PyErr_TrySetFromCause(
+ const char *prefix_format, /* ASCII-encoded string */
+ ...
+ );
+
+/* In signalmodule.c */
+
+int PySignal_SetWakeupFd(int fd);
+PyAPI_FUNC(int) _PyErr_CheckSignals(void);
+
+/* Support for adding program text to SyntaxErrors */
+
+PyAPI_FUNC(void) PyErr_SyntaxLocationObject(
+ PyObject *filename,
+ int lineno,
+ int col_offset);
+
+PyAPI_FUNC(void) PyErr_RangedSyntaxLocationObject(
+ PyObject *filename,
+ int lineno,
+ int col_offset,
+ int end_lineno,
+ int end_col_offset);
+
+PyAPI_FUNC(PyObject *) PyErr_ProgramTextObject(
+ PyObject *filename,
+ int lineno);
+
+PyAPI_FUNC(PyObject *) _PyErr_ProgramDecodedTextObject(
+ PyObject *filename,
+ int lineno,
+ const char* encoding);
+
+PyAPI_FUNC(PyObject *) _PyUnicodeTranslateError_Create(
+ PyObject *object,
+ Py_ssize_t start,
+ Py_ssize_t end,
+ const char *reason /* UTF-8 encoded string */
+ );
+
+PyAPI_FUNC(void) _PyErr_WriteUnraisableMsg(
+ const char *err_msg,
+ PyObject *obj);
+
+PyAPI_FUNC(void) _Py_NO_RETURN _Py_FatalErrorFunc(
+ const char *func,
+ const char *message);
+
+PyAPI_FUNC(void) _Py_NO_RETURN _Py_FatalErrorFormat(
+ const char *func,
+ const char *format,
+ ...);
+
+#define Py_FatalError(message) _Py_FatalErrorFunc(__func__, message)
diff --git a/include/python3.10/cpython/pyfpe.h b/include/python3.11/cpython/pyfpe.h
similarity index 100%
rename from include/python3.10/cpython/pyfpe.h
rename to include/python3.11/cpython/pyfpe.h
diff --git a/include/python3.11/cpython/pyframe.h b/include/python3.11/cpython/pyframe.h
new file mode 100644
index 0000000..1dc634c
--- /dev/null
+++ b/include/python3.11/cpython/pyframe.h
@@ -0,0 +1,17 @@
+#ifndef Py_CPYTHON_PYFRAME_H
+# error "this header file must not be included directly"
+#endif
+
+PyAPI_DATA(PyTypeObject) PyFrame_Type;
+
+#define PyFrame_Check(op) Py_IS_TYPE((op), &PyFrame_Type)
+
+PyAPI_FUNC(PyFrameObject *) PyFrame_GetBack(PyFrameObject *frame);
+PyAPI_FUNC(PyObject *) PyFrame_GetLocals(PyFrameObject *frame);
+
+PyAPI_FUNC(PyObject *) PyFrame_GetGlobals(PyFrameObject *frame);
+PyAPI_FUNC(PyObject *) PyFrame_GetBuiltins(PyFrameObject *frame);
+
+PyAPI_FUNC(PyObject *) PyFrame_GetGenerator(PyFrameObject *frame);
+PyAPI_FUNC(int) PyFrame_GetLasti(PyFrameObject *frame);
+
diff --git a/include/python3.11/cpython/pylifecycle.h b/include/python3.11/cpython/pylifecycle.h
new file mode 100644
index 0000000..bb5b07e
--- /dev/null
+++ b/include/python3.11/cpython/pylifecycle.h
@@ -0,0 +1,65 @@
+#ifndef Py_CPYTHON_PYLIFECYCLE_H
+# error "this header file must not be included directly"
+#endif
+
+/* Py_FrozenMain is kept out of the Limited API until documented and present
+ in all builds of Python */
+PyAPI_FUNC(int) Py_FrozenMain(int argc, char **argv);
+
+/* Only used by applications that embed the interpreter and need to
+ * override the standard encoding determination mechanism
+ */
+Py_DEPRECATED(3.11) PyAPI_FUNC(int) Py_SetStandardStreamEncoding(
+ const char *encoding,
+ const char *errors);
+
+/* PEP 432 Multi-phase initialization API (Private while provisional!) */
+
+PyAPI_FUNC(PyStatus) Py_PreInitialize(
+ const PyPreConfig *src_config);
+PyAPI_FUNC(PyStatus) Py_PreInitializeFromBytesArgs(
+ const PyPreConfig *src_config,
+ Py_ssize_t argc,
+ char **argv);
+PyAPI_FUNC(PyStatus) Py_PreInitializeFromArgs(
+ const PyPreConfig *src_config,
+ Py_ssize_t argc,
+ wchar_t **argv);
+
+PyAPI_FUNC(int) _Py_IsCoreInitialized(void);
+
+
+/* Initialization and finalization */
+
+PyAPI_FUNC(PyStatus) Py_InitializeFromConfig(
+ const PyConfig *config);
+PyAPI_FUNC(PyStatus) _Py_InitializeMain(void);
+
+PyAPI_FUNC(int) Py_RunMain(void);
+
+
+PyAPI_FUNC(void) _Py_NO_RETURN Py_ExitStatusException(PyStatus err);
+
+/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL. */
+PyAPI_FUNC(void) _Py_RestoreSignals(void);
+
+PyAPI_FUNC(int) Py_FdIsInteractive(FILE *, const char *);
+PyAPI_FUNC(int) _Py_FdIsInteractive(FILE *fp, PyObject *filename);
+
+Py_DEPRECATED(3.11) PyAPI_FUNC(void) _Py_SetProgramFullPath(const wchar_t *);
+
+PyAPI_FUNC(const char *) _Py_gitidentifier(void);
+PyAPI_FUNC(const char *) _Py_gitversion(void);
+
+PyAPI_FUNC(int) _Py_IsFinalizing(void);
+
+/* Random */
+PyAPI_FUNC(int) _PyOS_URandom(void *buffer, Py_ssize_t size);
+PyAPI_FUNC(int) _PyOS_URandomNonblock(void *buffer, Py_ssize_t size);
+
+/* Legacy locale support */
+PyAPI_FUNC(int) _Py_CoerceLegacyLocale(int warn);
+PyAPI_FUNC(int) _Py_LegacyLocaleDetected(int warn);
+PyAPI_FUNC(char *) _Py_SetLocaleFromEnv(int category);
+
+PyAPI_FUNC(PyThreadState *) _Py_NewInterpreter(int isolated_subinterpreter);
diff --git a/include/python3.10/cpython/pymem.h b/include/python3.11/cpython/pymem.h
similarity index 100%
rename from include/python3.10/cpython/pymem.h
rename to include/python3.11/cpython/pymem.h
diff --git a/include/python3.11/cpython/pystate.h b/include/python3.11/cpython/pystate.h
new file mode 100644
index 0000000..2bd4606
--- /dev/null
+++ b/include/python3.11/cpython/pystate.h
@@ -0,0 +1,366 @@
+#ifndef Py_CPYTHON_PYSTATE_H
+# error "this header file must not be included directly"
+#endif
+
+
+PyAPI_FUNC(int) _PyInterpreterState_RequiresIDRef(PyInterpreterState *);
+PyAPI_FUNC(void) _PyInterpreterState_RequireIDRef(PyInterpreterState *, int);
+
+PyAPI_FUNC(PyObject *) _PyInterpreterState_GetMainModule(PyInterpreterState *);
+
+/* State unique per thread */
+
+/* Py_tracefunc return -1 when raising an exception, or 0 for success. */
+typedef int (*Py_tracefunc)(PyObject *, PyFrameObject *, int, PyObject *);
+
+/* The following values are used for 'what' for tracefunc functions
+ *
+ * To add a new kind of trace event, also update "trace_init" in
+ * Python/sysmodule.c to define the Python level event name
+ */
+#define PyTrace_CALL 0
+#define PyTrace_EXCEPTION 1
+#define PyTrace_LINE 2
+#define PyTrace_RETURN 3
+#define PyTrace_C_CALL 4
+#define PyTrace_C_EXCEPTION 5
+#define PyTrace_C_RETURN 6
+#define PyTrace_OPCODE 7
+
+
+typedef struct {
+ PyCodeObject *code; // The code object for the bounds. May be NULL.
+ PyCodeAddressRange bounds; // Only valid if code != NULL.
+} PyTraceInfo;
+
+// Internal structure: you should not use it directly, but use public functions
+// like PyThreadState_EnterTracing() and PyThreadState_LeaveTracing().
+typedef struct _PyCFrame {
+ /* This struct will be threaded through the C stack
+ * allowing fast access to per-thread state that needs
+ * to be accessed quickly by the interpreter, but can
+ * be modified outside of the interpreter.
+ *
+ * WARNING: This makes data on the C stack accessible from
+ * heap objects. Care must be taken to maintain stack
+ * discipline and make sure that instances of this struct cannot
+ * accessed outside of their lifetime.
+ */
+ uint8_t use_tracing; // 0 or 255 (or'ed into opcode, hence 8-bit type)
+ /* Pointer to the currently executing frame (it can be NULL) */
+ struct _PyInterpreterFrame *current_frame;
+ struct _PyCFrame *previous;
+} _PyCFrame;
+
+typedef struct _err_stackitem {
+ /* This struct represents a single execution context where we might
+ * be currently handling an exception. It is a per-coroutine state
+ * (coroutine in the computer science sense, including the thread
+ * and generators).
+ *
+ * This is used as an entry on the exception stack, where each
+ * entry indicates if it is currently handling an exception.
+ * This ensures that the exception state is not impacted
+ * by "yields" from an except handler. The thread
+ * always has an entry (the bottom-most one).
+ */
+
+ /* The exception currently being handled in this context, if any. */
+ PyObject *exc_value;
+
+ struct _err_stackitem *previous_item;
+
+} _PyErr_StackItem;
+
+typedef struct _stack_chunk {
+ struct _stack_chunk *previous;
+ size_t size;
+ size_t top;
+ PyObject * data[1]; /* Variable sized */
+} _PyStackChunk;
+
+struct _ts {
+ /* See Python/ceval.c for comments explaining most fields */
+
+ PyThreadState *prev;
+ PyThreadState *next;
+ PyInterpreterState *interp;
+
+ /* Has been initialized to a safe state.
+
+ In order to be effective, this must be set to 0 during or right
+ after allocation. */
+ int _initialized;
+
+ /* Was this thread state statically allocated? */
+ int _static;
+
+ int recursion_remaining;
+ int recursion_limit;
+ int recursion_headroom; /* Allow 50 more calls to handle any errors. */
+
+ /* 'tracing' keeps track of the execution depth when tracing/profiling.
+ This is to prevent the actual trace/profile code from being recorded in
+ the trace/profile. */
+ int tracing;
+ int tracing_what; /* The event currently being traced, if any. */
+
+ /* Pointer to current _PyCFrame in the C stack frame of the currently,
+ * or most recently, executing _PyEval_EvalFrameDefault. */
+ _PyCFrame *cframe;
+
+ Py_tracefunc c_profilefunc;
+ Py_tracefunc c_tracefunc;
+ PyObject *c_profileobj;
+ PyObject *c_traceobj;
+
+ /* The exception currently being raised */
+ PyObject *curexc_type;
+ PyObject *curexc_value;
+ PyObject *curexc_traceback;
+
+ /* Pointer to the top of the exception stack for the exceptions
+ * we may be currently handling. (See _PyErr_StackItem above.)
+ * This is never NULL. */
+ _PyErr_StackItem *exc_info;
+
+ PyObject *dict; /* Stores per-thread state */
+
+ int gilstate_counter;
+
+ PyObject *async_exc; /* Asynchronous exception to raise */
+ unsigned long thread_id; /* Thread id where this tstate was created */
+
+ /* Native thread id where this tstate was created. This will be 0 except on
+ * those platforms that have the notion of native thread id, for which the
+ * macro PY_HAVE_THREAD_NATIVE_ID is then defined.
+ */
+ unsigned long native_thread_id;
+
+ int trash_delete_nesting;
+ PyObject *trash_delete_later;
+
+ /* Called when a thread state is deleted normally, but not when it
+ * is destroyed after fork().
+ * Pain: to prevent rare but fatal shutdown errors (issue 18808),
+ * Thread.join() must wait for the join'ed thread's tstate to be unlinked
+ * from the tstate chain. That happens at the end of a thread's life,
+ * in pystate.c.
+ * The obvious way doesn't quite work: create a lock which the tstate
+ * unlinking code releases, and have Thread.join() wait to acquire that
+ * lock. The problem is that we _are_ at the end of the thread's life:
+ * if the thread holds the last reference to the lock, decref'ing the
+ * lock will delete the lock, and that may trigger arbitrary Python code
+ * if there's a weakref, with a callback, to the lock. But by this time
+ * _PyRuntime.gilstate.tstate_current is already NULL, so only the simplest
+ * of C code can be allowed to run (in particular it must not be possible to
+ * release the GIL).
+ * So instead of holding the lock directly, the tstate holds a weakref to
+ * the lock: that's the value of on_delete_data below. Decref'ing a
+ * weakref is harmless.
+ * on_delete points to _threadmodule.c's static release_sentinel() function.
+ * After the tstate is unlinked, release_sentinel is called with the
+ * weakref-to-lock (on_delete_data) argument, and release_sentinel releases
+ * the indirectly held lock.
+ */
+ void (*on_delete)(void *);
+ void *on_delete_data;
+
+ int coroutine_origin_tracking_depth;
+
+ PyObject *async_gen_firstiter;
+ PyObject *async_gen_finalizer;
+
+ PyObject *context;
+ uint64_t context_ver;
+
+ /* Unique thread state id. */
+ uint64_t id;
+
+ PyTraceInfo trace_info;
+
+ _PyStackChunk *datastack_chunk;
+ PyObject **datastack_top;
+ PyObject **datastack_limit;
+ /* XXX signal handlers should also be here */
+
+ /* The following fields are here to avoid allocation during init.
+ The data is exposed through PyThreadState pointer fields.
+ These fields should not be accessed directly outside of init.
+ This is indicated by an underscore prefix on the field names.
+
+ All other PyInterpreterState pointer fields are populated when
+ needed and default to NULL.
+ */
+ // Note some fields do not have a leading underscore for backward
+ // compatibility. See https://bugs.python.org/issue45953#msg412046.
+
+ /* The thread's exception stack entry. (Always the last entry.) */
+ _PyErr_StackItem exc_state;
+
+ /* The bottom-most frame on the stack. */
+ _PyCFrame root_cframe;
+};
+
+
+/* other API */
+
+// Alias for backward compatibility with Python 3.8
+#define _PyInterpreterState_Get PyInterpreterState_Get
+
+PyAPI_FUNC(PyThreadState *) _PyThreadState_Prealloc(PyInterpreterState *);
+
+/* Similar to PyThreadState_Get(), but don't issue a fatal error
+ * if it is NULL. */
+PyAPI_FUNC(PyThreadState *) _PyThreadState_UncheckedGet(void);
+
+PyAPI_FUNC(PyObject *) _PyThreadState_GetDict(PyThreadState *tstate);
+
+// Disable tracing and profiling.
+PyAPI_FUNC(void) PyThreadState_EnterTracing(PyThreadState *tstate);
+
+// Reset tracing and profiling: enable them if a trace function or a profile
+// function is set, otherwise disable them.
+PyAPI_FUNC(void) PyThreadState_LeaveTracing(PyThreadState *tstate);
+
+/* PyGILState */
+
+/* Helper/diagnostic function - return 1 if the current thread
+ currently holds the GIL, 0 otherwise.
+
+ The function returns 1 if _PyGILState_check_enabled is non-zero. */
+PyAPI_FUNC(int) PyGILState_Check(void);
+
+/* Get the single PyInterpreterState used by this process' GILState
+ implementation.
+
+ This function doesn't check for error. Return NULL before _PyGILState_Init()
+ is called and after _PyGILState_Fini() is called.
+
+ See also _PyInterpreterState_Get() and _PyInterpreterState_GET(). */
+PyAPI_FUNC(PyInterpreterState *) _PyGILState_GetInterpreterStateUnsafe(void);
+
+/* The implementation of sys._current_frames() Returns a dict mapping
+ thread id to that thread's current frame.
+*/
+PyAPI_FUNC(PyObject *) _PyThread_CurrentFrames(void);
+
+/* The implementation of sys._current_exceptions() Returns a dict mapping
+ thread id to that thread's current exception.
+*/
+PyAPI_FUNC(PyObject *) _PyThread_CurrentExceptions(void);
+
+/* Routines for advanced debuggers, requested by David Beazley.
+ Don't use unless you know what you are doing! */
+PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Main(void);
+PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Head(void);
+PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Next(PyInterpreterState *);
+PyAPI_FUNC(PyThreadState *) PyInterpreterState_ThreadHead(PyInterpreterState *);
+PyAPI_FUNC(PyThreadState *) PyThreadState_Next(PyThreadState *);
+PyAPI_FUNC(void) PyThreadState_DeleteCurrent(void);
+
+/* Frame evaluation API */
+
+typedef PyObject* (*_PyFrameEvalFunction)(PyThreadState *tstate, struct _PyInterpreterFrame *, int);
+
+PyAPI_FUNC(_PyFrameEvalFunction) _PyInterpreterState_GetEvalFrameFunc(
+ PyInterpreterState *interp);
+PyAPI_FUNC(void) _PyInterpreterState_SetEvalFrameFunc(
+ PyInterpreterState *interp,
+ _PyFrameEvalFunction eval_frame);
+
+PyAPI_FUNC(const PyConfig*) _PyInterpreterState_GetConfig(PyInterpreterState *interp);
+
+/* Get a copy of the current interpreter configuration.
+
+ Return 0 on success. Raise an exception and return -1 on error.
+
+ The caller must initialize 'config', using PyConfig_InitPythonConfig()
+ for example.
+
+ Python must be preinitialized to call this method.
+ The caller must hold the GIL. */
+PyAPI_FUNC(int) _PyInterpreterState_GetConfigCopy(
+ struct PyConfig *config);
+
+/* Set the configuration of the current interpreter.
+
+ This function should be called during or just after the Python
+ initialization.
+
+ Update the sys module with the new configuration. If the sys module was
+ modified directly after the Python initialization, these changes are lost.
+
+ Some configuration like faulthandler or warnoptions can be updated in the
+ configuration, but don't reconfigure Python (don't enable/disable
+ faulthandler and don't reconfigure warnings filters).
+
+ Return 0 on success. Raise an exception and return -1 on error.
+
+ The configuration should come from _PyInterpreterState_GetConfigCopy(). */
+PyAPI_FUNC(int) _PyInterpreterState_SetConfig(
+ const struct PyConfig *config);
+
+// Get the configuration of the current interpreter.
+// The caller must hold the GIL.
+PyAPI_FUNC(const PyConfig*) _Py_GetConfig(void);
+
+
+/* cross-interpreter data */
+
+// _PyCrossInterpreterData is similar to Py_buffer as an effectively
+// opaque struct that holds data outside the object machinery. This
+// is necessary to pass safely between interpreters in the same process.
+typedef struct _xid _PyCrossInterpreterData;
+
+struct _xid {
+ // data is the cross-interpreter-safe derivation of a Python object
+ // (see _PyObject_GetCrossInterpreterData). It will be NULL if the
+ // new_object func (below) encodes the data.
+ void *data;
+ // obj is the Python object from which the data was derived. This
+ // is non-NULL only if the data remains bound to the object in some
+ // way, such that the object must be "released" (via a decref) when
+ // the data is released. In that case the code that sets the field,
+ // likely a registered "crossinterpdatafunc", is responsible for
+ // ensuring it owns the reference (i.e. incref).
+ PyObject *obj;
+ // interp is the ID of the owning interpreter of the original
+ // object. It corresponds to the active interpreter when
+ // _PyObject_GetCrossInterpreterData() was called. This should only
+ // be set by the cross-interpreter machinery.
+ //
+ // We use the ID rather than the PyInterpreterState to avoid issues
+ // with deleted interpreters. Note that IDs are never re-used, so
+ // each one will always correspond to a specific interpreter
+ // (whether still alive or not).
+ int64_t interp;
+ // new_object is a function that returns a new object in the current
+ // interpreter given the data. The resulting object (a new
+ // reference) will be equivalent to the original object. This field
+ // is required.
+ PyObject *(*new_object)(_PyCrossInterpreterData *);
+ // free is called when the data is released. If it is NULL then
+ // nothing will be done to free the data. For some types this is
+ // okay (e.g. bytes) and for those types this field should be set
+ // to NULL. However, for most the data was allocated just for
+ // cross-interpreter use, so it must be freed when
+ // _PyCrossInterpreterData_Release is called or the memory will
+ // leak. In that case, at the very least this field should be set
+ // to PyMem_RawFree (the default if not explicitly set to NULL).
+ // The call will happen with the original interpreter activated.
+ void (*free)(void *);
+};
+
+PyAPI_FUNC(int) _PyObject_GetCrossInterpreterData(PyObject *, _PyCrossInterpreterData *);
+PyAPI_FUNC(PyObject *) _PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *);
+PyAPI_FUNC(void) _PyCrossInterpreterData_Release(_PyCrossInterpreterData *);
+
+PyAPI_FUNC(int) _PyObject_CheckCrossInterpreterData(PyObject *);
+
+/* cross-interpreter data registry */
+
+typedef int (*crossinterpdatafunc)(PyObject *, _PyCrossInterpreterData *);
+
+PyAPI_FUNC(int) _PyCrossInterpreterData_RegisterClass(PyTypeObject *, crossinterpdatafunc);
+PyAPI_FUNC(crossinterpdatafunc) _PyCrossInterpreterData_Lookup(PyObject *);
diff --git a/include/python3.10/cpython/pythonrun.h b/include/python3.11/cpython/pythonrun.h
similarity index 100%
rename from include/python3.10/cpython/pythonrun.h
rename to include/python3.11/cpython/pythonrun.h
diff --git a/include/python3.11/cpython/pythread.h b/include/python3.11/cpython/pythread.h
new file mode 100644
index 0000000..ce4ec8f
--- /dev/null
+++ b/include/python3.11/cpython/pythread.h
@@ -0,0 +1,42 @@
+#ifndef Py_CPYTHON_PYTHREAD_H
+# error "this header file must not be included directly"
+#endif
+
+#define PYTHREAD_INVALID_THREAD_ID ((unsigned long)-1)
+
+#ifdef HAVE_FORK
+/* Private function to reinitialize a lock at fork in the child process.
+ Reset the lock to the unlocked state.
+ Return 0 on success, return -1 on error. */
+PyAPI_FUNC(int) _PyThread_at_fork_reinit(PyThread_type_lock *lock);
+#endif /* HAVE_FORK */
+
+#ifdef HAVE_PTHREAD_H
+ /* Darwin needs pthread.h to know type name the pthread_key_t. */
+# include <pthread.h>
+# define NATIVE_TSS_KEY_T pthread_key_t
+#elif defined(NT_THREADS)
+ /* In Windows, native TSS key type is DWORD,
+ but hardcode the unsigned long to avoid errors for include directive.
+ */
+# define NATIVE_TSS_KEY_T unsigned long
+#elif defined(HAVE_PTHREAD_STUBS)
+# include "cpython/pthread_stubs.h"
+# define NATIVE_TSS_KEY_T pthread_key_t
+#else
+# error "Require native threads. See https://bugs.python.org/issue31370"
+#endif
+
+/* When Py_LIMITED_API is not defined, the type layout of Py_tss_t is
+ exposed to allow static allocation in the API clients. Even in this case,
+ you must handle TSS keys through API functions due to compatibility.
+*/
+struct _Py_tss_t {
+ int _is_initialized;
+ NATIVE_TSS_KEY_T _key;
+};
+
+#undef NATIVE_TSS_KEY_T
+
+/* When static allocation, you must initialize with Py_tss_NEEDS_INIT. */
+#define Py_tss_NEEDS_INIT {0}
diff --git a/include/python3.11/cpython/pytime.h b/include/python3.11/cpython/pytime.h
new file mode 100644
index 0000000..23d4f16
--- /dev/null
+++ b/include/python3.11/cpython/pytime.h
@@ -0,0 +1,323 @@
+// The _PyTime_t API is written to use timestamp and timeout values stored in
+// various formats and to read clocks.
+//
+// The _PyTime_t type is an integer to support directly common arithmetic
+// operations like t1 + t2.
+//
+// The _PyTime_t API supports a resolution of 1 nanosecond. The _PyTime_t type
+// is signed to support negative timestamps. The supported range is around
+// [-292.3 years; +292.3 years]. Using the Unix epoch (January 1st, 1970), the
+// supported date range is around [1677-09-21; 2262-04-11].
+//
+// Formats:
+//
+// * seconds
+// * seconds as a floating pointer number (C double)
+// * milliseconds (10^-3 seconds)
+// * microseconds (10^-6 seconds)
+// * 100 nanoseconds (10^-7 seconds)
+// * nanoseconds (10^-9 seconds)
+// * timeval structure, 1 microsecond resolution (10^-6 seconds)
+// * timespec structure, 1 nanosecond resolution (10^-9 seconds)
+//
+// Integer overflows are detected and raise OverflowError. Conversion to a
+// resolution worse than 1 nanosecond is rounded correctly with the requested
+// rounding mode. There are 4 rounding modes: floor (towards -inf), ceiling
+// (towards +inf), half even and up (away from zero).
+//
+// Some functions clamp the result in the range [_PyTime_MIN; _PyTime_MAX], so
+// the caller doesn't have to handle errors and doesn't need to hold the GIL.
+// For example, _PyTime_Add(t1, t2) computes t1+t2 and clamp the result on
+// overflow.
+//
+// Clocks:
+//
+// * System clock
+// * Monotonic clock
+// * Performance counter
+//
+// Operations like (t * k / q) with integers are implemented in a way to reduce
+// the risk of integer overflow. Such operation is used to convert a clock
+// value expressed in ticks with a frequency to _PyTime_t, like
+// QueryPerformanceCounter() with QueryPerformanceFrequency().
+
+#ifndef Py_LIMITED_API
+#ifndef Py_PYTIME_H
+#define Py_PYTIME_H
+
+/**************************************************************************
+Symbols and macros to supply platform-independent interfaces to time related
+functions and constants
+**************************************************************************/
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* _PyTime_t: Python timestamp with subsecond precision. It can be used to
+ store a duration, and so indirectly a date (related to another date, like
+ UNIX epoch). */
+typedef int64_t _PyTime_t;
+// _PyTime_MIN nanoseconds is around -292.3 years
+#define _PyTime_MIN INT64_MIN
+// _PyTime_MAX nanoseconds is around +292.3 years
+#define _PyTime_MAX INT64_MAX
+#define _SIZEOF_PYTIME_T 8
+
+typedef enum {
+ /* Round towards minus infinity (-inf).
+ For example, used to read a clock. */
+ _PyTime_ROUND_FLOOR=0,
+ /* Round towards infinity (+inf).
+ For example, used for timeout to wait "at least" N seconds. */
+ _PyTime_ROUND_CEILING=1,
+ /* Round to nearest with ties going to nearest even integer.
+ For example, used to round from a Python float. */
+ _PyTime_ROUND_HALF_EVEN=2,
+ /* Round away from zero
+ For example, used for timeout. _PyTime_ROUND_CEILING rounds
+ -1e-9 to 0 milliseconds which causes bpo-31786 issue.
+ _PyTime_ROUND_UP rounds -1e-9 to -1 millisecond which keeps
+ the timeout sign as expected. select.poll(timeout) must block
+ for negative values." */
+ _PyTime_ROUND_UP=3,
+ /* _PyTime_ROUND_TIMEOUT (an alias for _PyTime_ROUND_UP) should be
+ used for timeouts. */
+ _PyTime_ROUND_TIMEOUT = _PyTime_ROUND_UP
+} _PyTime_round_t;
+
+
+/* Convert a time_t to a PyLong. */
+PyAPI_FUNC(PyObject *) _PyLong_FromTime_t(
+ time_t sec);
+
+/* Convert a PyLong to a time_t. */
+PyAPI_FUNC(time_t) _PyLong_AsTime_t(
+ PyObject *obj);
+
+/* Convert a number of seconds, int or float, to time_t. */
+PyAPI_FUNC(int) _PyTime_ObjectToTime_t(
+ PyObject *obj,
+ time_t *sec,
+ _PyTime_round_t);
+
+/* Convert a number of seconds, int or float, to a timeval structure.
+ usec is in the range [0; 999999] and rounded towards zero.
+ For example, -1.2 is converted to (-2, 800000). */
+PyAPI_FUNC(int) _PyTime_ObjectToTimeval(
+ PyObject *obj,
+ time_t *sec,
+ long *usec,
+ _PyTime_round_t);
+
+/* Convert a number of seconds, int or float, to a timespec structure.
+ nsec is in the range [0; 999999999] and rounded towards zero.
+ For example, -1.2 is converted to (-2, 800000000). */
+PyAPI_FUNC(int) _PyTime_ObjectToTimespec(
+ PyObject *obj,
+ time_t *sec,
+ long *nsec,
+ _PyTime_round_t);
+
+
+/* Create a timestamp from a number of seconds. */
+PyAPI_FUNC(_PyTime_t) _PyTime_FromSeconds(int seconds);
+
+/* Macro to create a timestamp from a number of seconds, no integer overflow.
+ Only use the macro for small values, prefer _PyTime_FromSeconds(). */
+#define _PYTIME_FROMSECONDS(seconds) \
+ ((_PyTime_t)(seconds) * (1000 * 1000 * 1000))
+
+/* Create a timestamp from a number of nanoseconds. */
+PyAPI_FUNC(_PyTime_t) _PyTime_FromNanoseconds(_PyTime_t ns);
+
+/* Create a timestamp from nanoseconds (Python int). */
+PyAPI_FUNC(int) _PyTime_FromNanosecondsObject(_PyTime_t *t,
+ PyObject *obj);
+
+/* Convert a number of seconds (Python float or int) to a timestamp.
+ Raise an exception and return -1 on error, return 0 on success. */
+PyAPI_FUNC(int) _PyTime_FromSecondsObject(_PyTime_t *t,
+ PyObject *obj,
+ _PyTime_round_t round);
+
+/* Convert a number of milliseconds (Python float or int, 10^-3) to a timestamp.
+ Raise an exception and return -1 on error, return 0 on success. */
+PyAPI_FUNC(int) _PyTime_FromMillisecondsObject(_PyTime_t *t,
+ PyObject *obj,
+ _PyTime_round_t round);
+
+/* Convert a timestamp to a number of seconds as a C double. */
+PyAPI_FUNC(double) _PyTime_AsSecondsDouble(_PyTime_t t);
+
+/* Convert timestamp to a number of milliseconds (10^-3 seconds). */
+PyAPI_FUNC(_PyTime_t) _PyTime_AsMilliseconds(_PyTime_t t,
+ _PyTime_round_t round);
+
+/* Convert timestamp to a number of microseconds (10^-6 seconds). */
+PyAPI_FUNC(_PyTime_t) _PyTime_AsMicroseconds(_PyTime_t t,
+ _PyTime_round_t round);
+
+/* Convert timestamp to a number of nanoseconds (10^-9 seconds). */
+PyAPI_FUNC(_PyTime_t) _PyTime_AsNanoseconds(_PyTime_t t);
+
+#ifdef MS_WINDOWS
+// Convert timestamp to a number of 100 nanoseconds (10^-7 seconds).
+PyAPI_FUNC(_PyTime_t) _PyTime_As100Nanoseconds(_PyTime_t t,
+ _PyTime_round_t round);
+#endif
+
+/* Convert timestamp to a number of nanoseconds (10^-9 seconds) as a Python int
+ object. */
+PyAPI_FUNC(PyObject *) _PyTime_AsNanosecondsObject(_PyTime_t t);
+
+#ifndef MS_WINDOWS
+/* Create a timestamp from a timeval structure.
+ Raise an exception and return -1 on overflow, return 0 on success. */
+PyAPI_FUNC(int) _PyTime_FromTimeval(_PyTime_t *tp, struct timeval *tv);
+#endif
+
+/* Convert a timestamp to a timeval structure (microsecond resolution).
+ tv_usec is always positive.
+ Raise an exception and return -1 if the conversion overflowed,
+ return 0 on success. */
+PyAPI_FUNC(int) _PyTime_AsTimeval(_PyTime_t t,
+ struct timeval *tv,
+ _PyTime_round_t round);
+
+/* Similar to _PyTime_AsTimeval() but don't raise an exception on overflow.
+ On overflow, clamp tv_sec to _PyTime_t min/max. */
+PyAPI_FUNC(void) _PyTime_AsTimeval_clamp(_PyTime_t t,
+ struct timeval *tv,
+ _PyTime_round_t round);
+
+/* Convert a timestamp to a number of seconds (secs) and microseconds (us).
+ us is always positive. This function is similar to _PyTime_AsTimeval()
+ except that secs is always a time_t type, whereas the timeval structure
+ uses a C long for tv_sec on Windows.
+ Raise an exception and return -1 if the conversion overflowed,
+ return 0 on success. */
+PyAPI_FUNC(int) _PyTime_AsTimevalTime_t(
+ _PyTime_t t,
+ time_t *secs,
+ int *us,
+ _PyTime_round_t round);
+
+#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_KQUEUE)
+/* Create a timestamp from a timespec structure.
+ Raise an exception and return -1 on overflow, return 0 on success. */
+PyAPI_FUNC(int) _PyTime_FromTimespec(_PyTime_t *tp, struct timespec *ts);
+
+/* Convert a timestamp to a timespec structure (nanosecond resolution).
+ tv_nsec is always positive.
+ Raise an exception and return -1 on error, return 0 on success. */
+PyAPI_FUNC(int) _PyTime_AsTimespec(_PyTime_t t, struct timespec *ts);
+
+/* Similar to _PyTime_AsTimespec() but don't raise an exception on overflow.
+ On overflow, clamp tv_sec to _PyTime_t min/max. */
+PyAPI_FUNC(void) _PyTime_AsTimespec_clamp(_PyTime_t t, struct timespec *ts);
+#endif
+
+
+// Compute t1 + t2. Clamp to [_PyTime_MIN; _PyTime_MAX] on overflow.
+PyAPI_FUNC(_PyTime_t) _PyTime_Add(_PyTime_t t1, _PyTime_t t2);
+
+/* Compute ticks * mul / div.
+ Clamp to [_PyTime_MIN; _PyTime_MAX] on overflow.
+ The caller must ensure that ((div - 1) * mul) cannot overflow. */
+PyAPI_FUNC(_PyTime_t) _PyTime_MulDiv(_PyTime_t ticks,
+ _PyTime_t mul,
+ _PyTime_t div);
+
+/* Structure used by time.get_clock_info() */
+typedef struct {
+ const char *implementation;
+ int monotonic;
+ int adjustable;
+ double resolution;
+} _Py_clock_info_t;
+
+/* Get the current time from the system clock.
+
+ If the internal clock fails, silently ignore the error and return 0.
+ On integer overflow, silently ignore the overflow and clamp the clock to
+ [_PyTime_MIN; _PyTime_MAX].
+
+ Use _PyTime_GetSystemClockWithInfo() to check for failure. */
+PyAPI_FUNC(_PyTime_t) _PyTime_GetSystemClock(void);
+
+/* Get the current time from the system clock.
+ * On success, set *t and *info (if not NULL), and return 0.
+ * On error, raise an exception and return -1.
+ */
+PyAPI_FUNC(int) _PyTime_GetSystemClockWithInfo(
+ _PyTime_t *t,
+ _Py_clock_info_t *info);
+
+/* Get the time of a monotonic clock, i.e. a clock that cannot go backwards.
+ The clock is not affected by system clock updates. The reference point of
+ the returned value is undefined, so that only the difference between the
+ results of consecutive calls is valid.
+
+ If the internal clock fails, silently ignore the error and return 0.
+ On integer overflow, silently ignore the overflow and clamp the clock to
+ [_PyTime_MIN; _PyTime_MAX].
+
+ Use _PyTime_GetMonotonicClockWithInfo() to check for failure. */
+PyAPI_FUNC(_PyTime_t) _PyTime_GetMonotonicClock(void);
+
+/* Get the time of a monotonic clock, i.e. a clock that cannot go backwards.
+ The clock is not affected by system clock updates. The reference point of
+ the returned value is undefined, so that only the difference between the
+ results of consecutive calls is valid.
+
+ Fill info (if set) with information of the function used to get the time.
+
+ Return 0 on success, raise an exception and return -1 on error. */
+PyAPI_FUNC(int) _PyTime_GetMonotonicClockWithInfo(
+ _PyTime_t *t,
+ _Py_clock_info_t *info);
+
+
+/* Converts a timestamp to the Gregorian time, using the local time zone.
+ Return 0 on success, raise an exception and return -1 on error. */
+PyAPI_FUNC(int) _PyTime_localtime(time_t t, struct tm *tm);
+
+/* Converts a timestamp to the Gregorian time, assuming UTC.
+ Return 0 on success, raise an exception and return -1 on error. */
+PyAPI_FUNC(int) _PyTime_gmtime(time_t t, struct tm *tm);
+
+/* Get the performance counter: clock with the highest available resolution to
+ measure a short duration.
+
+ If the internal clock fails, silently ignore the error and return 0.
+ On integer overflow, silently ignore the overflow and clamp the clock to
+ [_PyTime_MIN; _PyTime_MAX].
+
+ Use _PyTime_GetPerfCounterWithInfo() to check for failure. */
+PyAPI_FUNC(_PyTime_t) _PyTime_GetPerfCounter(void);
+
+/* Get the performance counter: clock with the highest available resolution to
+ measure a short duration.
+
+ Fill info (if set) with information of the function used to get the time.
+
+ Return 0 on success, raise an exception and return -1 on error. */
+PyAPI_FUNC(int) _PyTime_GetPerfCounterWithInfo(
+ _PyTime_t *t,
+ _Py_clock_info_t *info);
+
+
+// Create a deadline.
+// Pseudo code: _PyTime_GetMonotonicClock() + timeout.
+PyAPI_FUNC(_PyTime_t) _PyDeadline_Init(_PyTime_t timeout);
+
+// Get remaining time from a deadline.
+// Pseudo code: deadline - _PyTime_GetMonotonicClock().
+PyAPI_FUNC(_PyTime_t) _PyDeadline_Get(_PyTime_t deadline);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* Py_PYTIME_H */
+#endif /* Py_LIMITED_API */
diff --git a/include/python3.11/cpython/setobject.h b/include/python3.11/cpython/setobject.h
new file mode 100644
index 0000000..b4443a6
--- /dev/null
+++ b/include/python3.11/cpython/setobject.h
@@ -0,0 +1,67 @@
+#ifndef Py_CPYTHON_SETOBJECT_H
+# error "this header file must not be included directly"
+#endif
+
+/* There are three kinds of entries in the table:
+
+1. Unused: key == NULL and hash == 0
+2. Dummy: key == dummy and hash == -1
+3. Active: key != NULL and key != dummy and hash != -1
+
+The hash field of Unused slots is always zero.
+
+The hash field of Dummy slots are set to -1
+meaning that dummy entries can be detected by
+either entry->key==dummy or by entry->hash==-1.
+*/
+
+#define PySet_MINSIZE 8
+
+typedef struct {
+ PyObject *key;
+ Py_hash_t hash; /* Cached hash code of the key */
+} setentry;
+
+/* The SetObject data structure is shared by set and frozenset objects.
+
+Invariant for sets:
+ - hash is -1
+
+Invariants for frozensets:
+ - data is immutable.
+ - hash is the hash of the frozenset or -1 if not computed yet.
+
+*/
+
+typedef struct {
+ PyObject_HEAD
+
+ Py_ssize_t fill; /* Number active and dummy entries*/
+ Py_ssize_t used; /* Number active entries */
+
+ /* The table contains mask + 1 slots, and that's a power of 2.
+ * We store the mask instead of the size because the mask is more
+ * frequently needed.
+ */
+ Py_ssize_t mask;
+
+ /* The table points to a fixed-size smalltable for small tables
+ * or to additional malloc'ed memory for bigger tables.
+ * The table pointer is never NULL which saves us from repeated
+ * runtime null-tests.
+ */
+ setentry *table;
+ Py_hash_t hash; /* Only used by frozenset objects */
+ Py_ssize_t finger; /* Search finger for pop() */
+
+ setentry smalltable[PySet_MINSIZE];
+ PyObject *weakreflist; /* List of weak references */
+} PySetObject;
+
+#define PySet_GET_SIZE(so) \
+ (assert(PyAnySet_Check(so)), (((PySetObject *)(so))->used))
+
+PyAPI_DATA(PyObject *) _PySet_Dummy;
+
+PyAPI_FUNC(int) _PySet_NextEntry(PyObject *set, Py_ssize_t *pos, PyObject **key, Py_hash_t *hash);
+PyAPI_FUNC(int) _PySet_Update(PyObject *set, PyObject *iterable);
diff --git a/include/python3.11/cpython/sysmodule.h b/include/python3.11/cpython/sysmodule.h
new file mode 100644
index 0000000..19d9ddd
--- /dev/null
+++ b/include/python3.11/cpython/sysmodule.h
@@ -0,0 +1,16 @@
+#ifndef Py_CPYTHON_SYSMODULE_H
+# error "this header file must not be included directly"
+#endif
+
+PyAPI_FUNC(PyObject *) _PySys_GetAttr(PyThreadState *tstate,
+ PyObject *name);
+
+PyAPI_FUNC(size_t) _PySys_GetSizeOf(PyObject *);
+
+typedef int(*Py_AuditHookFunction)(const char *, PyObject *, void *);
+
+PyAPI_FUNC(int) PySys_Audit(
+ const char *event,
+ const char *argFormat,
+ ...);
+PyAPI_FUNC(int) PySys_AddAuditHook(Py_AuditHookFunction, void*);
diff --git a/include/python3.11/cpython/traceback.h b/include/python3.11/cpython/traceback.h
new file mode 100644
index 0000000..a4e087b
--- /dev/null
+++ b/include/python3.11/cpython/traceback.h
@@ -0,0 +1,16 @@
+#ifndef Py_CPYTHON_TRACEBACK_H
+# error "this header file must not be included directly"
+#endif
+
+typedef struct _traceback PyTracebackObject;
+
+struct _traceback {
+ PyObject_HEAD
+ PyTracebackObject *tb_next;
+ PyFrameObject *tb_frame;
+ int tb_lasti;
+ int tb_lineno;
+};
+
+PyAPI_FUNC(int) _Py_DisplaySourceLine(PyObject *, PyObject *, int, int, int *, PyObject **);
+PyAPI_FUNC(void) _PyTraceback_Add(const char *, const char *, int);
diff --git a/include/python3.11/cpython/tupleobject.h b/include/python3.11/cpython/tupleobject.h
new file mode 100644
index 0000000..3d9c1af
--- /dev/null
+++ b/include/python3.11/cpython/tupleobject.h
@@ -0,0 +1,43 @@
+#ifndef Py_CPYTHON_TUPLEOBJECT_H
+# error "this header file must not be included directly"
+#endif
+
+typedef struct {
+ PyObject_VAR_HEAD
+ /* ob_item contains space for 'ob_size' elements.
+ Items must normally not be NULL, except during construction when
+ the tuple is not yet visible outside the function that builds it. */
+ PyObject *ob_item[1];
+} PyTupleObject;
+
+PyAPI_FUNC(int) _PyTuple_Resize(PyObject **, Py_ssize_t);
+PyAPI_FUNC(void) _PyTuple_MaybeUntrack(PyObject *);
+
+/* Cast argument to PyTupleObject* type. */
+#define _PyTuple_CAST(op) \
+ (assert(PyTuple_Check(op)), _Py_CAST(PyTupleObject*, (op)))
+
+// Macros and static inline functions, trading safety for speed
+
+static inline Py_ssize_t PyTuple_GET_SIZE(PyObject *op) {
+ PyTupleObject *tuple = _PyTuple_CAST(op);
+ return Py_SIZE(tuple);
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyTuple_GET_SIZE(op) PyTuple_GET_SIZE(_PyObject_CAST(op))
+#endif
+
+#define PyTuple_GET_ITEM(op, index) (_PyTuple_CAST(op)->ob_item[index])
+
+/* Function *only* to be used to fill in brand new tuples */
+static inline void
+PyTuple_SET_ITEM(PyObject *op, Py_ssize_t index, PyObject *value) {
+ PyTupleObject *tuple = _PyTuple_CAST(op);
+ tuple->ob_item[index] = value;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+#define PyTuple_SET_ITEM(op, index, value) \
+ PyTuple_SET_ITEM(_PyObject_CAST(op), index, _PyObject_CAST(value))
+#endif
+
+PyAPI_FUNC(void) _PyTuple_DebugMallocStats(FILE *out);
diff --git a/include/python3.11/cpython/unicodeobject.h b/include/python3.11/cpython/unicodeobject.h
new file mode 100644
index 0000000..84307d1
--- /dev/null
+++ b/include/python3.11/cpython/unicodeobject.h
@@ -0,0 +1,1153 @@
+#ifndef Py_CPYTHON_UNICODEOBJECT_H
+# error "this header file must not be included directly"
+#endif
+
+/* Py_UNICODE was the native Unicode storage format (code unit) used by
+ Python and represents a single Unicode element in the Unicode type.
+ With PEP 393, Py_UNICODE is deprecated and replaced with a
+ typedef to wchar_t. */
+#define PY_UNICODE_TYPE wchar_t
+/* Py_DEPRECATED(3.3) */ typedef wchar_t Py_UNICODE;
+
+/* --- Internal Unicode Operations ---------------------------------------- */
+
+#ifndef USE_UNICODE_WCHAR_CACHE
+# define USE_UNICODE_WCHAR_CACHE 1
+#endif /* USE_UNICODE_WCHAR_CACHE */
+
+/* Since splitting on whitespace is an important use case, and
+ whitespace in most situations is solely ASCII whitespace, we
+ optimize for the common case by using a quick look-up table
+ _Py_ascii_whitespace (see below) with an inlined check.
+
+ */
+#define Py_UNICODE_ISSPACE(ch) \
+ ((Py_UCS4)(ch) < 128U ? _Py_ascii_whitespace[(ch)] : _PyUnicode_IsWhitespace(ch))
+
+#define Py_UNICODE_ISLOWER(ch) _PyUnicode_IsLowercase(ch)
+#define Py_UNICODE_ISUPPER(ch) _PyUnicode_IsUppercase(ch)
+#define Py_UNICODE_ISTITLE(ch) _PyUnicode_IsTitlecase(ch)
+#define Py_UNICODE_ISLINEBREAK(ch) _PyUnicode_IsLinebreak(ch)
+
+#define Py_UNICODE_TOLOWER(ch) _PyUnicode_ToLowercase(ch)
+#define Py_UNICODE_TOUPPER(ch) _PyUnicode_ToUppercase(ch)
+#define Py_UNICODE_TOTITLE(ch) _PyUnicode_ToTitlecase(ch)
+
+#define Py_UNICODE_ISDECIMAL(ch) _PyUnicode_IsDecimalDigit(ch)
+#define Py_UNICODE_ISDIGIT(ch) _PyUnicode_IsDigit(ch)
+#define Py_UNICODE_ISNUMERIC(ch) _PyUnicode_IsNumeric(ch)
+#define Py_UNICODE_ISPRINTABLE(ch) _PyUnicode_IsPrintable(ch)
+
+#define Py_UNICODE_TODECIMAL(ch) _PyUnicode_ToDecimalDigit(ch)
+#define Py_UNICODE_TODIGIT(ch) _PyUnicode_ToDigit(ch)
+#define Py_UNICODE_TONUMERIC(ch) _PyUnicode_ToNumeric(ch)
+
+#define Py_UNICODE_ISALPHA(ch) _PyUnicode_IsAlpha(ch)
+
+#define Py_UNICODE_ISALNUM(ch) \
+ (Py_UNICODE_ISALPHA(ch) || \
+ Py_UNICODE_ISDECIMAL(ch) || \
+ Py_UNICODE_ISDIGIT(ch) || \
+ Py_UNICODE_ISNUMERIC(ch))
+
+/* macros to work with surrogates */
+#define Py_UNICODE_IS_SURROGATE(ch) (0xD800 <= (ch) && (ch) <= 0xDFFF)
+#define Py_UNICODE_IS_HIGH_SURROGATE(ch) (0xD800 <= (ch) && (ch) <= 0xDBFF)
+#define Py_UNICODE_IS_LOW_SURROGATE(ch) (0xDC00 <= (ch) && (ch) <= 0xDFFF)
+/* Join two surrogate characters and return a single Py_UCS4 value. */
+#define Py_UNICODE_JOIN_SURROGATES(high, low) \
+ (((((Py_UCS4)(high) & 0x03FF) << 10) | \
+ ((Py_UCS4)(low) & 0x03FF)) + 0x10000)
+/* high surrogate = top 10 bits added to D800 */
+#define Py_UNICODE_HIGH_SURROGATE(ch) (0xD800 - (0x10000 >> 10) + ((ch) >> 10))
+/* low surrogate = bottom 10 bits added to DC00 */
+#define Py_UNICODE_LOW_SURROGATE(ch) (0xDC00 + ((ch) & 0x3FF))
+
+/* --- Unicode Type ------------------------------------------------------- */
+
+/* ASCII-only strings created through PyUnicode_New use the PyASCIIObject
+ structure. state.ascii and state.compact are set, and the data
+ immediately follow the structure. utf8_length and wstr_length can be found
+ in the length field; the utf8 pointer is equal to the data pointer. */
+typedef struct {
+ /* There are 4 forms of Unicode strings:
+
+ - compact ascii:
+
+ * structure = PyASCIIObject
+ * test: PyUnicode_IS_COMPACT_ASCII(op)
+ * kind = PyUnicode_1BYTE_KIND
+ * compact = 1
+ * ascii = 1
+ * ready = 1
+ * (length is the length of the utf8 and wstr strings)
+ * (data starts just after the structure)
+ * (since ASCII is decoded from UTF-8, the utf8 string are the data)
+
+ - compact:
+
+ * structure = PyCompactUnicodeObject
+ * test: PyUnicode_IS_COMPACT(op) && !PyUnicode_IS_ASCII(op)
+ * kind = PyUnicode_1BYTE_KIND, PyUnicode_2BYTE_KIND or
+ PyUnicode_4BYTE_KIND
+ * compact = 1
+ * ready = 1
+ * ascii = 0
+ * utf8 is not shared with data
+ * utf8_length = 0 if utf8 is NULL
+ * wstr is shared with data and wstr_length=length
+ if kind=PyUnicode_2BYTE_KIND and sizeof(wchar_t)=2
+ or if kind=PyUnicode_4BYTE_KIND and sizeof(wchar_t)=4
+ * wstr_length = 0 if wstr is NULL
+ * (data starts just after the structure)
+
+ - legacy string, not ready:
+
+ * structure = PyUnicodeObject
+ * test: kind == PyUnicode_WCHAR_KIND
+ * length = 0 (use wstr_length)
+ * hash = -1
+ * kind = PyUnicode_WCHAR_KIND
+ * compact = 0
+ * ascii = 0
+ * ready = 0
+ * interned = SSTATE_NOT_INTERNED
+ * wstr is not NULL
+ * data.any is NULL
+ * utf8 is NULL
+ * utf8_length = 0
+
+ - legacy string, ready:
+
+ * structure = PyUnicodeObject structure
+ * test: !PyUnicode_IS_COMPACT(op) && kind != PyUnicode_WCHAR_KIND
+ * kind = PyUnicode_1BYTE_KIND, PyUnicode_2BYTE_KIND or
+ PyUnicode_4BYTE_KIND
+ * compact = 0
+ * ready = 1
+ * data.any is not NULL
+ * utf8 is shared and utf8_length = length with data.any if ascii = 1
+ * utf8_length = 0 if utf8 is NULL
+ * wstr is shared with data.any and wstr_length = length
+ if kind=PyUnicode_2BYTE_KIND and sizeof(wchar_t)=2
+ or if kind=PyUnicode_4BYTE_KIND and sizeof(wchar_4)=4
+ * wstr_length = 0 if wstr is NULL
+
+ Compact strings use only one memory block (structure + characters),
+ whereas legacy strings use one block for the structure and one block
+ for characters.
+
+ Legacy strings are created by PyUnicode_FromUnicode() and
+ PyUnicode_FromStringAndSize(NULL, size) functions. They become ready
+ when PyUnicode_READY() is called.
+
+ See also _PyUnicode_CheckConsistency().
+ */
+ PyObject_HEAD
+ Py_ssize_t length; /* Number of code points in the string */
+ Py_hash_t hash; /* Hash value; -1 if not set */
+ struct {
+ /*
+ SSTATE_NOT_INTERNED (0)
+ SSTATE_INTERNED_MORTAL (1)
+ SSTATE_INTERNED_IMMORTAL (2)
+
+ If interned != SSTATE_NOT_INTERNED, the two references from the
+ dictionary to this object are *not* counted in ob_refcnt.
+ */
+ unsigned int interned:2;
+ /* Character size:
+
+ - PyUnicode_WCHAR_KIND (0):
+
+ * character type = wchar_t (16 or 32 bits, depending on the
+ platform)
+
+ - PyUnicode_1BYTE_KIND (1):
+
+ * character type = Py_UCS1 (8 bits, unsigned)
+ * all characters are in the range U+0000-U+00FF (latin1)
+ * if ascii is set, all characters are in the range U+0000-U+007F
+ (ASCII), otherwise at least one character is in the range
+ U+0080-U+00FF
+
+ - PyUnicode_2BYTE_KIND (2):
+
+ * character type = Py_UCS2 (16 bits, unsigned)
+ * all characters are in the range U+0000-U+FFFF (BMP)
+ * at least one character is in the range U+0100-U+FFFF
+
+ - PyUnicode_4BYTE_KIND (4):
+
+ * character type = Py_UCS4 (32 bits, unsigned)
+ * all characters are in the range U+0000-U+10FFFF
+ * at least one character is in the range U+10000-U+10FFFF
+ */
+ unsigned int kind:3;
+ /* Compact is with respect to the allocation scheme. Compact unicode
+ objects only require one memory block while non-compact objects use
+ one block for the PyUnicodeObject struct and another for its data
+ buffer. */
+ unsigned int compact:1;
+ /* The string only contains characters in the range U+0000-U+007F (ASCII)
+ and the kind is PyUnicode_1BYTE_KIND. If ascii is set and compact is
+ set, use the PyASCIIObject structure. */
+ unsigned int ascii:1;
+ /* The ready flag indicates whether the object layout is initialized
+ completely. This means that this is either a compact object, or
+ the data pointer is filled out. The bit is redundant, and helps
+ to minimize the test in PyUnicode_IS_READY(). */
+ unsigned int ready:1;
+ /* Padding to ensure that PyUnicode_DATA() is always aligned to
+ 4 bytes (see issue #19537 on m68k). */
+ unsigned int :24;
+ } state;
+ wchar_t *wstr; /* wchar_t representation (null-terminated) */
+} PyASCIIObject;
+
+/* Non-ASCII strings allocated through PyUnicode_New use the
+ PyCompactUnicodeObject structure. state.compact is set, and the data
+ immediately follow the structure. */
+typedef struct {
+ PyASCIIObject _base;
+ Py_ssize_t utf8_length; /* Number of bytes in utf8, excluding the
+ * terminating \0. */
+ char *utf8; /* UTF-8 representation (null-terminated) */
+ Py_ssize_t wstr_length; /* Number of code points in wstr, possible
+ * surrogates count as two code points. */
+} PyCompactUnicodeObject;
+
+/* Strings allocated through PyUnicode_FromUnicode(NULL, len) use the
+ PyUnicodeObject structure. The actual string data is initially in the wstr
+ block, and copied into the data block using _PyUnicode_Ready. */
+typedef struct {
+ PyCompactUnicodeObject _base;
+ union {
+ void *any;
+ Py_UCS1 *latin1;
+ Py_UCS2 *ucs2;
+ Py_UCS4 *ucs4;
+ } data; /* Canonical, smallest-form Unicode buffer */
+} PyUnicodeObject;
+
+PyAPI_FUNC(int) _PyUnicode_CheckConsistency(
+ PyObject *op,
+ int check_content);
+
+
+#define _PyASCIIObject_CAST(op) \
+ (assert(PyUnicode_Check(op)), \
+ _Py_CAST(PyASCIIObject*, (op)))
+#define _PyCompactUnicodeObject_CAST(op) \
+ (assert(PyUnicode_Check(op)), \
+ _Py_CAST(PyCompactUnicodeObject*, (op)))
+#define _PyUnicodeObject_CAST(op) \
+ (assert(PyUnicode_Check(op)), \
+ _Py_CAST(PyUnicodeObject*, (op)))
+
+
+/* --- Flexible String Representation Helper Macros (PEP 393) -------------- */
+
+/* Values for PyASCIIObject.state: */
+
+/* Interning state. */
+#define SSTATE_NOT_INTERNED 0
+#define SSTATE_INTERNED_MORTAL 1
+#define SSTATE_INTERNED_IMMORTAL 2
+
+/* Use only if you know it's a string */
+static inline unsigned int PyUnicode_CHECK_INTERNED(PyObject *op) {
+ return _PyASCIIObject_CAST(op)->state.interned;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyUnicode_CHECK_INTERNED(op) PyUnicode_CHECK_INTERNED(_PyObject_CAST(op))
+#endif
+
+/* Fast check to determine whether an object is ready. Equivalent to:
+ PyUnicode_IS_COMPACT(op) || _PyUnicodeObject_CAST(op)->data.any */
+static inline unsigned int PyUnicode_IS_READY(PyObject *op) {
+ return _PyASCIIObject_CAST(op)->state.ready;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyUnicode_IS_READY(op) PyUnicode_IS_READY(_PyObject_CAST(op))
+#endif
+
+/* Return true if the string contains only ASCII characters, or 0 if not. The
+ string may be compact (PyUnicode_IS_COMPACT_ASCII) or not, but must be
+ ready. */
+static inline unsigned int PyUnicode_IS_ASCII(PyObject *op) {
+ assert(PyUnicode_IS_READY(op));
+ return _PyASCIIObject_CAST(op)->state.ascii;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyUnicode_IS_ASCII(op) PyUnicode_IS_ASCII(_PyObject_CAST(op))
+#endif
+
+/* Return true if the string is compact or 0 if not.
+ No type checks or Ready calls are performed. */
+static inline unsigned int PyUnicode_IS_COMPACT(PyObject *op) {
+ return _PyASCIIObject_CAST(op)->state.compact;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyUnicode_IS_COMPACT(op) PyUnicode_IS_COMPACT(_PyObject_CAST(op))
+#endif
+
+/* Return true if the string is a compact ASCII string (use PyASCIIObject
+ structure), or 0 if not. No type checks or Ready calls are performed. */
+static inline int PyUnicode_IS_COMPACT_ASCII(PyObject *op) {
+ return (_PyASCIIObject_CAST(op)->state.ascii && PyUnicode_IS_COMPACT(op));
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyUnicode_IS_COMPACT_ASCII(op) PyUnicode_IS_COMPACT_ASCII(_PyObject_CAST(op))
+#endif
+
+enum PyUnicode_Kind {
+/* String contains only wstr byte characters. This is only possible
+ when the string was created with a legacy API and _PyUnicode_Ready()
+ has not been called yet. */
+ PyUnicode_WCHAR_KIND = 0,
+/* Return values of the PyUnicode_KIND() function: */
+ PyUnicode_1BYTE_KIND = 1,
+ PyUnicode_2BYTE_KIND = 2,
+ PyUnicode_4BYTE_KIND = 4
+};
+
+/* Return one of the PyUnicode_*_KIND values defined above. */
+#define PyUnicode_KIND(op) \
+ (assert(PyUnicode_IS_READY(op)), \
+ _PyASCIIObject_CAST(op)->state.kind)
+
+/* Return a void pointer to the raw unicode buffer. */
+static inline void* _PyUnicode_COMPACT_DATA(PyObject *op) {
+ if (PyUnicode_IS_ASCII(op)) {
+ return _Py_STATIC_CAST(void*, (_PyASCIIObject_CAST(op) + 1));
+ }
+ return _Py_STATIC_CAST(void*, (_PyCompactUnicodeObject_CAST(op) + 1));
+}
+
+static inline void* _PyUnicode_NONCOMPACT_DATA(PyObject *op) {
+ void *data;
+ assert(!PyUnicode_IS_COMPACT(op));
+ data = _PyUnicodeObject_CAST(op)->data.any;
+ assert(data != NULL);
+ return data;
+}
+
+static inline void* PyUnicode_DATA(PyObject *op) {
+ if (PyUnicode_IS_COMPACT(op)) {
+ return _PyUnicode_COMPACT_DATA(op);
+ }
+ return _PyUnicode_NONCOMPACT_DATA(op);
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyUnicode_DATA(op) PyUnicode_DATA(_PyObject_CAST(op))
+#endif
+
+/* Return pointers to the canonical representation cast to unsigned char,
+ Py_UCS2, or Py_UCS4 for direct character access.
+ No checks are performed, use PyUnicode_KIND() before to ensure
+ these will work correctly. */
+
+#define PyUnicode_1BYTE_DATA(op) _Py_STATIC_CAST(Py_UCS1*, PyUnicode_DATA(op))
+#define PyUnicode_2BYTE_DATA(op) _Py_STATIC_CAST(Py_UCS2*, PyUnicode_DATA(op))
+#define PyUnicode_4BYTE_DATA(op) _Py_STATIC_CAST(Py_UCS4*, PyUnicode_DATA(op))
+
+/* Returns the length of the unicode string. The caller has to make sure that
+ the string has it's canonical representation set before calling
+ this function. Call PyUnicode_(FAST_)Ready to ensure that. */
+static inline Py_ssize_t PyUnicode_GET_LENGTH(PyObject *op) {
+ assert(PyUnicode_IS_READY(op));
+ return _PyASCIIObject_CAST(op)->length;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyUnicode_GET_LENGTH(op) PyUnicode_GET_LENGTH(_PyObject_CAST(op))
+#endif
+
+/* Write into the canonical representation, this function does not do any sanity
+ checks and is intended for usage in loops. The caller should cache the
+ kind and data pointers obtained from other function calls.
+ index is the index in the string (starts at 0) and value is the new
+ code point value which should be written to that location. */
+static inline void PyUnicode_WRITE(int kind, void *data,
+ Py_ssize_t index, Py_UCS4 value)
+{
+ if (kind == PyUnicode_1BYTE_KIND) {
+ assert(value <= 0xffU);
+ _Py_STATIC_CAST(Py_UCS1*, data)[index] = _Py_STATIC_CAST(Py_UCS1, value);
+ }
+ else if (kind == PyUnicode_2BYTE_KIND) {
+ assert(value <= 0xffffU);
+ _Py_STATIC_CAST(Py_UCS2*, data)[index] = _Py_STATIC_CAST(Py_UCS2, value);
+ }
+ else {
+ assert(kind == PyUnicode_4BYTE_KIND);
+ assert(value <= 0x10ffffU);
+ _Py_STATIC_CAST(Py_UCS4*, data)[index] = value;
+ }
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+#define PyUnicode_WRITE(kind, data, index, value) \
+ PyUnicode_WRITE(_Py_STATIC_CAST(int, kind), _Py_CAST(void*, data), \
+ (index), _Py_STATIC_CAST(Py_UCS4, value))
+#endif
+
+/* Read a code point from the string's canonical representation. No checks
+ or ready calls are performed. */
+static inline Py_UCS4 PyUnicode_READ(int kind,
+ const void *data, Py_ssize_t index)
+{
+ if (kind == PyUnicode_1BYTE_KIND) {
+ return _Py_STATIC_CAST(const Py_UCS1*, data)[index];
+ }
+ if (kind == PyUnicode_2BYTE_KIND) {
+ return _Py_STATIC_CAST(const Py_UCS2*, data)[index];
+ }
+ assert(kind == PyUnicode_4BYTE_KIND);
+ return _Py_STATIC_CAST(const Py_UCS4*, data)[index];
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+#define PyUnicode_READ(kind, data, index) \
+ PyUnicode_READ(_Py_STATIC_CAST(int, kind), \
+ _Py_STATIC_CAST(const void*, data), \
+ (index))
+#endif
+
+/* PyUnicode_READ_CHAR() is less efficient than PyUnicode_READ() because it
+ calls PyUnicode_KIND() and might call it twice. For single reads, use
+ PyUnicode_READ_CHAR, for multiple consecutive reads callers should
+ cache kind and use PyUnicode_READ instead. */
+static inline Py_UCS4 PyUnicode_READ_CHAR(PyObject *unicode, Py_ssize_t index)
+{
+ int kind;
+ assert(PyUnicode_IS_READY(unicode));
+ kind = PyUnicode_KIND(unicode);
+ if (kind == PyUnicode_1BYTE_KIND) {
+ return PyUnicode_1BYTE_DATA(unicode)[index];
+ }
+ if (kind == PyUnicode_2BYTE_KIND) {
+ return PyUnicode_2BYTE_DATA(unicode)[index];
+ }
+ assert(kind == PyUnicode_4BYTE_KIND);
+ return PyUnicode_4BYTE_DATA(unicode)[index];
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyUnicode_READ_CHAR(unicode, index) \
+ PyUnicode_READ_CHAR(_PyObject_CAST(unicode), (index))
+#endif
+
+/* Return a maximum character value which is suitable for creating another
+ string based on op. This is always an approximation but more efficient
+ than iterating over the string. */
+static inline Py_UCS4 PyUnicode_MAX_CHAR_VALUE(PyObject *op)
+{
+ int kind;
+
+ assert(PyUnicode_IS_READY(op));
+ if (PyUnicode_IS_ASCII(op)) {
+ return 0x7fU;
+ }
+
+ kind = PyUnicode_KIND(op);
+ if (kind == PyUnicode_1BYTE_KIND) {
+ return 0xffU;
+ }
+ if (kind == PyUnicode_2BYTE_KIND) {
+ return 0xffffU;
+ }
+ assert(kind == PyUnicode_4BYTE_KIND);
+ return 0x10ffffU;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyUnicode_MAX_CHAR_VALUE(op) \
+ PyUnicode_MAX_CHAR_VALUE(_PyObject_CAST(op))
+#endif
+
+/* === Public API ========================================================= */
+
+/* --- Plain Py_UNICODE --------------------------------------------------- */
+
+/* With PEP 393, this is the recommended way to allocate a new unicode object.
+ This function will allocate the object and its buffer in a single memory
+ block. Objects created using this function are not resizable. */
+PyAPI_FUNC(PyObject*) PyUnicode_New(
+ Py_ssize_t size, /* Number of code points in the new string */
+ Py_UCS4 maxchar /* maximum code point value in the string */
+ );
+
+/* Initializes the canonical string representation from the deprecated
+ wstr/Py_UNICODE representation. This function is used to convert Unicode
+ objects which were created using the old API to the new flexible format
+ introduced with PEP 393.
+
+ Don't call this function directly, use the public PyUnicode_READY() function
+ instead. */
+PyAPI_FUNC(int) _PyUnicode_Ready(
+ PyObject *unicode /* Unicode object */
+ );
+
+/* PyUnicode_READY() does less work than _PyUnicode_Ready() in the best
+ case. If the canonical representation is not yet set, it will still call
+ _PyUnicode_Ready().
+ Returns 0 on success and -1 on errors. */
+static inline int PyUnicode_READY(PyObject *op)
+{
+ if (PyUnicode_IS_READY(op)) {
+ return 0;
+ }
+ return _PyUnicode_Ready(op);
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyUnicode_READY(op) PyUnicode_READY(_PyObject_CAST(op))
+#endif
+
+/* Get a copy of a Unicode string. */
+PyAPI_FUNC(PyObject*) _PyUnicode_Copy(
+ PyObject *unicode
+ );
+
+/* Copy character from one unicode object into another, this function performs
+ character conversion when necessary and falls back to memcpy() if possible.
+
+ Fail if to is too small (smaller than *how_many* or smaller than
+ len(from)-from_start), or if kind(from[from_start:from_start+how_many]) >
+ kind(to), or if *to* has more than 1 reference.
+
+ Return the number of written character, or return -1 and raise an exception
+ on error.
+
+ Pseudo-code:
+
+ how_many = min(how_many, len(from) - from_start)
+ to[to_start:to_start+how_many] = from[from_start:from_start+how_many]
+ return how_many
+
+ Note: The function doesn't write a terminating null character.
+ */
+PyAPI_FUNC(Py_ssize_t) PyUnicode_CopyCharacters(
+ PyObject *to,
+ Py_ssize_t to_start,
+ PyObject *from,
+ Py_ssize_t from_start,
+ Py_ssize_t how_many
+ );
+
+/* Unsafe version of PyUnicode_CopyCharacters(): don't check arguments and so
+ may crash if parameters are invalid (e.g. if the output string
+ is too short). */
+PyAPI_FUNC(void) _PyUnicode_FastCopyCharacters(
+ PyObject *to,
+ Py_ssize_t to_start,
+ PyObject *from,
+ Py_ssize_t from_start,
+ Py_ssize_t how_many
+ );
+
+/* Fill a string with a character: write fill_char into
+ unicode[start:start+length].
+
+ Fail if fill_char is bigger than the string maximum character, or if the
+ string has more than 1 reference.
+
+ Return the number of written character, or return -1 and raise an exception
+ on error. */
+PyAPI_FUNC(Py_ssize_t) PyUnicode_Fill(
+ PyObject *unicode,
+ Py_ssize_t start,
+ Py_ssize_t length,
+ Py_UCS4 fill_char
+ );
+
+/* Unsafe version of PyUnicode_Fill(): don't check arguments and so may crash
+ if parameters are invalid (e.g. if length is longer than the string). */
+PyAPI_FUNC(void) _PyUnicode_FastFill(
+ PyObject *unicode,
+ Py_ssize_t start,
+ Py_ssize_t length,
+ Py_UCS4 fill_char
+ );
+
+/* Create a new string from a buffer of Py_UCS1, Py_UCS2 or Py_UCS4 characters.
+ Scan the string to find the maximum character. */
+PyAPI_FUNC(PyObject*) PyUnicode_FromKindAndData(
+ int kind,
+ const void *buffer,
+ Py_ssize_t size);
+
+/* Create a new string from a buffer of ASCII characters.
+ WARNING: Don't check if the string contains any non-ASCII character. */
+PyAPI_FUNC(PyObject*) _PyUnicode_FromASCII(
+ const char *buffer,
+ Py_ssize_t size);
+
+/* Compute the maximum character of the substring unicode[start:end].
+ Return 127 for an empty string. */
+PyAPI_FUNC(Py_UCS4) _PyUnicode_FindMaxChar (
+ PyObject *unicode,
+ Py_ssize_t start,
+ Py_ssize_t end);
+
+/* --- Legacy deprecated API ---------------------------------------------- */
+
+/* Create a Unicode Object from the Py_UNICODE buffer u of the given
+ size.
+
+ u may be NULL which causes the contents to be undefined. It is the
+ user's responsibility to fill in the needed data afterwards. Note
+ that modifying the Unicode object contents after construction is
+ only allowed if u was set to NULL.
+
+ The buffer is copied into the new object. */
+Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_FromUnicode(
+ const Py_UNICODE *u, /* Unicode buffer */
+ Py_ssize_t size /* size of buffer */
+ );
+
+/* Return a read-only pointer to the Unicode object's internal
+ Py_UNICODE buffer.
+ If the wchar_t/Py_UNICODE representation is not yet available, this
+ function will calculate it. */
+Py_DEPRECATED(3.3) PyAPI_FUNC(Py_UNICODE *) PyUnicode_AsUnicode(
+ PyObject *unicode /* Unicode object */
+ );
+
+/* Similar to PyUnicode_AsUnicode(), but raises a ValueError if the string
+ contains null characters. */
+PyAPI_FUNC(const Py_UNICODE *) _PyUnicode_AsUnicode(
+ PyObject *unicode /* Unicode object */
+ );
+
+/* Return a read-only pointer to the Unicode object's internal
+ Py_UNICODE buffer and save the length at size.
+ If the wchar_t/Py_UNICODE representation is not yet available, this
+ function will calculate it. */
+
+Py_DEPRECATED(3.3) PyAPI_FUNC(Py_UNICODE *) PyUnicode_AsUnicodeAndSize(
+ PyObject *unicode, /* Unicode object */
+ Py_ssize_t *size /* location where to save the length */
+ );
+
+
+/* Fast access macros */
+
+Py_DEPRECATED(3.3)
+static inline Py_ssize_t PyUnicode_WSTR_LENGTH(PyObject *op)
+{
+ if (PyUnicode_IS_COMPACT_ASCII(op)) {
+ return _PyASCIIObject_CAST(op)->length;
+ }
+ else {
+ return _PyCompactUnicodeObject_CAST(op)->wstr_length;
+ }
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyUnicode_WSTR_LENGTH(op) PyUnicode_WSTR_LENGTH(_PyObject_CAST(op))
+#endif
+
+/* Returns the deprecated Py_UNICODE representation's size in code units
+ (this includes surrogate pairs as 2 units).
+ If the Py_UNICODE representation is not available, it will be computed
+ on request. Use PyUnicode_GET_LENGTH() for the length in code points. */
+
+Py_DEPRECATED(3.3)
+static inline Py_ssize_t PyUnicode_GET_SIZE(PyObject *op)
+{
+ _Py_COMP_DIAG_PUSH
+ _Py_COMP_DIAG_IGNORE_DEPR_DECLS
+ if (_PyASCIIObject_CAST(op)->wstr == _Py_NULL) {
+ (void)PyUnicode_AsUnicode(op);
+ assert(_PyASCIIObject_CAST(op)->wstr != _Py_NULL);
+ }
+ return PyUnicode_WSTR_LENGTH(op);
+ _Py_COMP_DIAG_POP
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyUnicode_GET_SIZE(op) PyUnicode_GET_SIZE(_PyObject_CAST(op))
+#endif
+
+Py_DEPRECATED(3.3)
+static inline Py_ssize_t PyUnicode_GET_DATA_SIZE(PyObject *op)
+{
+ _Py_COMP_DIAG_PUSH
+ _Py_COMP_DIAG_IGNORE_DEPR_DECLS
+ return PyUnicode_GET_SIZE(op) * Py_UNICODE_SIZE;
+ _Py_COMP_DIAG_POP
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyUnicode_GET_DATA_SIZE(op) PyUnicode_GET_DATA_SIZE(_PyObject_CAST(op))
+#endif
+
+/* Alias for PyUnicode_AsUnicode(). This will create a wchar_t/Py_UNICODE
+ representation on demand. Using this macro is very inefficient now,
+ try to port your code to use the new PyUnicode_*BYTE_DATA() macros or
+ use PyUnicode_WRITE() and PyUnicode_READ(). */
+
+Py_DEPRECATED(3.3)
+static inline Py_UNICODE* PyUnicode_AS_UNICODE(PyObject *op)
+{
+ wchar_t *wstr = _PyASCIIObject_CAST(op)->wstr;
+ if (wstr != _Py_NULL) {
+ return wstr;
+ }
+
+ _Py_COMP_DIAG_PUSH
+ _Py_COMP_DIAG_IGNORE_DEPR_DECLS
+ return PyUnicode_AsUnicode(op);
+ _Py_COMP_DIAG_POP
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyUnicode_AS_UNICODE(op) PyUnicode_AS_UNICODE(_PyObject_CAST(op))
+#endif
+
+Py_DEPRECATED(3.3)
+static inline const char* PyUnicode_AS_DATA(PyObject *op)
+{
+ _Py_COMP_DIAG_PUSH
+ _Py_COMP_DIAG_IGNORE_DEPR_DECLS
+ Py_UNICODE *data = PyUnicode_AS_UNICODE(op);
+ // In C++, casting directly PyUnicode* to const char* is not valid
+ return _Py_STATIC_CAST(const char*, _Py_STATIC_CAST(const void*, data));
+ _Py_COMP_DIAG_POP
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyUnicode_AS_DATA(op) PyUnicode_AS_DATA(_PyObject_CAST(op))
+#endif
+
+
+/* --- _PyUnicodeWriter API ----------------------------------------------- */
+
+typedef struct {
+ PyObject *buffer;
+ void *data;
+ enum PyUnicode_Kind kind;
+ Py_UCS4 maxchar;
+ Py_ssize_t size;
+ Py_ssize_t pos;
+
+ /* minimum number of allocated characters (default: 0) */
+ Py_ssize_t min_length;
+
+ /* minimum character (default: 127, ASCII) */
+ Py_UCS4 min_char;
+
+ /* If non-zero, overallocate the buffer (default: 0). */
+ unsigned char overallocate;
+
+ /* If readonly is 1, buffer is a shared string (cannot be modified)
+ and size is set to 0. */
+ unsigned char readonly;
+} _PyUnicodeWriter ;
+
+/* Initialize a Unicode writer.
+ *
+ * By default, the minimum buffer size is 0 character and overallocation is
+ * disabled. Set min_length, min_char and overallocate attributes to control
+ * the allocation of the buffer. */
+PyAPI_FUNC(void)
+_PyUnicodeWriter_Init(_PyUnicodeWriter *writer);
+
+/* Prepare the buffer to write 'length' characters
+ with the specified maximum character.
+
+ Return 0 on success, raise an exception and return -1 on error. */
+#define _PyUnicodeWriter_Prepare(WRITER, LENGTH, MAXCHAR) \
+ (((MAXCHAR) <= (WRITER)->maxchar \
+ && (LENGTH) <= (WRITER)->size - (WRITER)->pos) \
+ ? 0 \
+ : (((LENGTH) == 0) \
+ ? 0 \
+ : _PyUnicodeWriter_PrepareInternal((WRITER), (LENGTH), (MAXCHAR))))
+
+/* Don't call this function directly, use the _PyUnicodeWriter_Prepare() macro
+ instead. */
+PyAPI_FUNC(int)
+_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
+ Py_ssize_t length, Py_UCS4 maxchar);
+
+/* Prepare the buffer to have at least the kind KIND.
+ For example, kind=PyUnicode_2BYTE_KIND ensures that the writer will
+ support characters in range U+000-U+FFFF.
+
+ Return 0 on success, raise an exception and return -1 on error. */
+#define _PyUnicodeWriter_PrepareKind(WRITER, KIND) \
+ (assert((KIND) != PyUnicode_WCHAR_KIND), \
+ (KIND) <= (WRITER)->kind \
+ ? 0 \
+ : _PyUnicodeWriter_PrepareKindInternal((WRITER), (KIND)))
+
+/* Don't call this function directly, use the _PyUnicodeWriter_PrepareKind()
+ macro instead. */
+PyAPI_FUNC(int)
+_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
+ enum PyUnicode_Kind kind);
+
+/* Append a Unicode character.
+ Return 0 on success, raise an exception and return -1 on error. */
+PyAPI_FUNC(int)
+_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer,
+ Py_UCS4 ch
+ );
+
+/* Append a Unicode string.
+ Return 0 on success, raise an exception and return -1 on error. */
+PyAPI_FUNC(int)
+_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer,
+ PyObject *str /* Unicode string */
+ );
+
+/* Append a substring of a Unicode string.
+ Return 0 on success, raise an exception and return -1 on error. */
+PyAPI_FUNC(int)
+_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer,
+ PyObject *str, /* Unicode string */
+ Py_ssize_t start,
+ Py_ssize_t end
+ );
+
+/* Append an ASCII-encoded byte string.
+ Return 0 on success, raise an exception and return -1 on error. */
+PyAPI_FUNC(int)
+_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
+ const char *str, /* ASCII-encoded byte string */
+ Py_ssize_t len /* number of bytes, or -1 if unknown */
+ );
+
+/* Append a latin1-encoded byte string.
+ Return 0 on success, raise an exception and return -1 on error. */
+PyAPI_FUNC(int)
+_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
+ const char *str, /* latin1-encoded byte string */
+ Py_ssize_t len /* length in bytes */
+ );
+
+/* Get the value of the writer as a Unicode string. Clear the
+ buffer of the writer. Raise an exception and return NULL
+ on error. */
+PyAPI_FUNC(PyObject *)
+_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer);
+
+/* Deallocate memory of a writer (clear its internal buffer). */
+PyAPI_FUNC(void)
+_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer);
+
+
+/* Format the object based on the format_spec, as defined in PEP 3101
+ (Advanced String Formatting). */
+PyAPI_FUNC(int) _PyUnicode_FormatAdvancedWriter(
+ _PyUnicodeWriter *writer,
+ PyObject *obj,
+ PyObject *format_spec,
+ Py_ssize_t start,
+ Py_ssize_t end);
+
+/* --- Manage the default encoding ---------------------------------------- */
+
+/* Returns a pointer to the default encoding (UTF-8) of the
+ Unicode object unicode.
+
+ Like PyUnicode_AsUTF8AndSize(), this also caches the UTF-8 representation
+ in the unicodeobject.
+
+ _PyUnicode_AsString is a #define for PyUnicode_AsUTF8 to
+ support the previous internal function with the same behaviour.
+
+ Use of this API is DEPRECATED since no size information can be
+ extracted from the returned data.
+*/
+
+PyAPI_FUNC(const char *) PyUnicode_AsUTF8(PyObject *unicode);
+
+#define _PyUnicode_AsString PyUnicode_AsUTF8
+
+/* --- UTF-7 Codecs ------------------------------------------------------- */
+
+PyAPI_FUNC(PyObject*) _PyUnicode_EncodeUTF7(
+ PyObject *unicode, /* Unicode object */
+ int base64SetO, /* Encode RFC2152 Set O characters in base64 */
+ int base64WhiteSpace, /* Encode whitespace (sp, ht, nl, cr) in base64 */
+ const char *errors /* error handling */
+ );
+
+/* --- UTF-8 Codecs ------------------------------------------------------- */
+
+PyAPI_FUNC(PyObject*) _PyUnicode_AsUTF8String(
+ PyObject *unicode,
+ const char *errors);
+
+/* --- UTF-32 Codecs ------------------------------------------------------ */
+
+PyAPI_FUNC(PyObject*) _PyUnicode_EncodeUTF32(
+ PyObject *object, /* Unicode object */
+ const char *errors, /* error handling */
+ int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */
+ );
+
+/* --- UTF-16 Codecs ------------------------------------------------------ */
+
+/* Returns a Python string object holding the UTF-16 encoded value of
+ the Unicode data.
+
+ If byteorder is not 0, output is written according to the following
+ byte order:
+
+ byteorder == -1: little endian
+ byteorder == 0: native byte order (writes a BOM mark)
+ byteorder == 1: big endian
+
+ If byteorder is 0, the output string will always start with the
+ Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is
+ prepended.
+*/
+PyAPI_FUNC(PyObject*) _PyUnicode_EncodeUTF16(
+ PyObject* unicode, /* Unicode object */
+ const char *errors, /* error handling */
+ int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */
+ );
+
+/* --- Unicode-Escape Codecs ---------------------------------------------- */
+
+/* Variant of PyUnicode_DecodeUnicodeEscape that supports partial decoding. */
+PyAPI_FUNC(PyObject*) _PyUnicode_DecodeUnicodeEscapeStateful(
+ const char *string, /* Unicode-Escape encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors, /* error handling */
+ Py_ssize_t *consumed /* bytes consumed */
+);
+/* Helper for PyUnicode_DecodeUnicodeEscape that detects invalid escape
+ chars. */
+PyAPI_FUNC(PyObject*) _PyUnicode_DecodeUnicodeEscapeInternal(
+ const char *string, /* Unicode-Escape encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors, /* error handling */
+ Py_ssize_t *consumed, /* bytes consumed */
+ const char **first_invalid_escape /* on return, points to first
+ invalid escaped char in
+ string. */
+);
+
+/* --- Raw-Unicode-Escape Codecs ---------------------------------------------- */
+
+/* Variant of PyUnicode_DecodeRawUnicodeEscape that supports partial decoding. */
+PyAPI_FUNC(PyObject*) _PyUnicode_DecodeRawUnicodeEscapeStateful(
+ const char *string, /* Unicode-Escape encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors, /* error handling */
+ Py_ssize_t *consumed /* bytes consumed */
+);
+
+/* --- Latin-1 Codecs ----------------------------------------------------- */
+
+PyAPI_FUNC(PyObject*) _PyUnicode_AsLatin1String(
+ PyObject* unicode,
+ const char* errors);
+
+/* --- ASCII Codecs ------------------------------------------------------- */
+
+PyAPI_FUNC(PyObject*) _PyUnicode_AsASCIIString(
+ PyObject* unicode,
+ const char* errors);
+
+/* --- Character Map Codecs ----------------------------------------------- */
+
+/* Translate an Unicode object by applying a character mapping table to
+ it and return the resulting Unicode object.
+
+ The mapping table must map Unicode ordinal integers to Unicode strings,
+ Unicode ordinal integers or None (causing deletion of the character).
+
+ Mapping tables may be dictionaries or sequences. Unmapped character
+ ordinals (ones which cause a LookupError) are left untouched and
+ are copied as-is.
+*/
+PyAPI_FUNC(PyObject*) _PyUnicode_EncodeCharmap(
+ PyObject *unicode, /* Unicode object */
+ PyObject *mapping, /* encoding mapping */
+ const char *errors /* error handling */
+ );
+
+/* --- Decimal Encoder ---------------------------------------------------- */
+
+/* Coverts a Unicode object holding a decimal value to an ASCII string
+ for using in int, float and complex parsers.
+ Transforms code points that have decimal digit property to the
+ corresponding ASCII digit code points. Transforms spaces to ASCII.
+ Transforms code points starting from the first non-ASCII code point that
+ is neither a decimal digit nor a space to the end into '?'. */
+
+PyAPI_FUNC(PyObject*) _PyUnicode_TransformDecimalAndSpaceToASCII(
+ PyObject *unicode /* Unicode object */
+ );
+
+/* --- Methods & Slots ---------------------------------------------------- */
+
+PyAPI_FUNC(PyObject *) _PyUnicode_JoinArray(
+ PyObject *separator,
+ PyObject *const *items,
+ Py_ssize_t seqlen
+ );
+
+/* Test whether a unicode is equal to ASCII identifier. Return 1 if true,
+ 0 otherwise. The right argument must be ASCII identifier.
+ Any error occurs inside will be cleared before return. */
+PyAPI_FUNC(int) _PyUnicode_EqualToASCIIId(
+ PyObject *left, /* Left string */
+ _Py_Identifier *right /* Right identifier */
+ );
+
+/* Test whether a unicode is equal to ASCII string. Return 1 if true,
+ 0 otherwise. The right argument must be ASCII-encoded string.
+ Any error occurs inside will be cleared before return. */
+PyAPI_FUNC(int) _PyUnicode_EqualToASCIIString(
+ PyObject *left,
+ const char *right /* ASCII-encoded string */
+ );
+
+/* Externally visible for str.strip(unicode) */
+PyAPI_FUNC(PyObject *) _PyUnicode_XStrip(
+ PyObject *self,
+ int striptype,
+ PyObject *sepobj
+ );
+
+/* Using explicit passed-in values, insert the thousands grouping
+ into the string pointed to by buffer. For the argument descriptions,
+ see Objects/stringlib/localeutil.h */
+PyAPI_FUNC(Py_ssize_t) _PyUnicode_InsertThousandsGrouping(
+ _PyUnicodeWriter *writer,
+ Py_ssize_t n_buffer,
+ PyObject *digits,
+ Py_ssize_t d_pos,
+ Py_ssize_t n_digits,
+ Py_ssize_t min_width,
+ const char *grouping,
+ PyObject *thousands_sep,
+ Py_UCS4 *maxchar);
+
+/* === Characters Type APIs =============================================== */
+
+/* Helper array used by Py_UNICODE_ISSPACE(). */
+
+PyAPI_DATA(const unsigned char) _Py_ascii_whitespace[];
+
+/* These should not be used directly. Use the Py_UNICODE_IS* and
+ Py_UNICODE_TO* macros instead.
+
+ These APIs are implemented in Objects/unicodectype.c.
+
+*/
+
+PyAPI_FUNC(int) _PyUnicode_IsLowercase(
+ Py_UCS4 ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_IsUppercase(
+ Py_UCS4 ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_IsTitlecase(
+ Py_UCS4 ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_IsXidStart(
+ Py_UCS4 ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_IsXidContinue(
+ Py_UCS4 ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_IsWhitespace(
+ const Py_UCS4 ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_IsLinebreak(
+ const Py_UCS4 ch /* Unicode character */
+ );
+
+/* Py_DEPRECATED(3.3) */ PyAPI_FUNC(Py_UCS4) _PyUnicode_ToLowercase(
+ Py_UCS4 ch /* Unicode character */
+ );
+
+/* Py_DEPRECATED(3.3) */ PyAPI_FUNC(Py_UCS4) _PyUnicode_ToUppercase(
+ Py_UCS4 ch /* Unicode character */
+ );
+
+Py_DEPRECATED(3.3) PyAPI_FUNC(Py_UCS4) _PyUnicode_ToTitlecase(
+ Py_UCS4 ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_ToLowerFull(
+ Py_UCS4 ch, /* Unicode character */
+ Py_UCS4 *res
+ );
+
+PyAPI_FUNC(int) _PyUnicode_ToTitleFull(
+ Py_UCS4 ch, /* Unicode character */
+ Py_UCS4 *res
+ );
+
+PyAPI_FUNC(int) _PyUnicode_ToUpperFull(
+ Py_UCS4 ch, /* Unicode character */
+ Py_UCS4 *res
+ );
+
+PyAPI_FUNC(int) _PyUnicode_ToFoldedFull(
+ Py_UCS4 ch, /* Unicode character */
+ Py_UCS4 *res
+ );
+
+PyAPI_FUNC(int) _PyUnicode_IsCaseIgnorable(
+ Py_UCS4 ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_IsCased(
+ Py_UCS4 ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_ToDecimalDigit(
+ Py_UCS4 ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_ToDigit(
+ Py_UCS4 ch /* Unicode character */
+ );
+
+PyAPI_FUNC(double) _PyUnicode_ToNumeric(
+ Py_UCS4 ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_IsDecimalDigit(
+ Py_UCS4 ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_IsDigit(
+ Py_UCS4 ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_IsNumeric(
+ Py_UCS4 ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_IsPrintable(
+ Py_UCS4 ch /* Unicode character */
+ );
+
+PyAPI_FUNC(int) _PyUnicode_IsAlpha(
+ Py_UCS4 ch /* Unicode character */
+ );
+
+PyAPI_FUNC(PyObject*) _PyUnicode_FormatLong(PyObject *, int, int, int);
+
+/* Return an interned Unicode object for an Identifier; may fail if there is no memory.*/
+PyAPI_FUNC(PyObject*) _PyUnicode_FromId(_Py_Identifier*);
+
+/* Fast equality check when the inputs are known to be exact unicode types
+ and where the hash values are equal (i.e. a very probable match) */
+PyAPI_FUNC(int) _PyUnicode_EQ(PyObject *, PyObject *);
+
+/* Equality check. Returns -1 on failure. */
+PyAPI_FUNC(int) _PyUnicode_Equal(PyObject *, PyObject *);
+
+PyAPI_FUNC(int) _PyUnicode_WideCharString_Converter(PyObject *, void *);
+PyAPI_FUNC(int) _PyUnicode_WideCharString_Opt_Converter(PyObject *, void *);
+
+PyAPI_FUNC(Py_ssize_t) _PyUnicode_ScanIdentifier(PyObject *);
diff --git a/include/python3.11/cpython/warnings.h b/include/python3.11/cpython/warnings.h
new file mode 100644
index 0000000..2ef8e3c
--- /dev/null
+++ b/include/python3.11/cpython/warnings.h
@@ -0,0 +1,20 @@
+#ifndef Py_CPYTHON_WARNINGS_H
+# error "this header file must not be included directly"
+#endif
+
+PyAPI_FUNC(int) PyErr_WarnExplicitObject(
+ PyObject *category,
+ PyObject *message,
+ PyObject *filename,
+ int lineno,
+ PyObject *module,
+ PyObject *registry);
+
+PyAPI_FUNC(int) PyErr_WarnExplicitFormat(
+ PyObject *category,
+ const char *filename, int lineno,
+ const char *module, PyObject *registry,
+ const char *format, ...);
+
+// DEPRECATED: Use PyErr_WarnEx() instead.
+#define PyErr_Warn(category, msg) PyErr_WarnEx(category, msg, 1)
diff --git a/include/python3.11/cpython/weakrefobject.h b/include/python3.11/cpython/weakrefobject.h
new file mode 100644
index 0000000..26b364f
--- /dev/null
+++ b/include/python3.11/cpython/weakrefobject.h
@@ -0,0 +1,58 @@
+#ifndef Py_CPYTHON_WEAKREFOBJECT_H
+# error "this header file must not be included directly"
+#endif
+
+/* PyWeakReference is the base struct for the Python ReferenceType, ProxyType,
+ * and CallableProxyType.
+ */
+struct _PyWeakReference {
+ PyObject_HEAD
+
+ /* The object to which this is a weak reference, or Py_None if none.
+ * Note that this is a stealth reference: wr_object's refcount is
+ * not incremented to reflect this pointer.
+ */
+ PyObject *wr_object;
+
+ /* A callable to invoke when wr_object dies, or NULL if none. */
+ PyObject *wr_callback;
+
+ /* A cache for wr_object's hash code. As usual for hashes, this is -1
+ * if the hash code isn't known yet.
+ */
+ Py_hash_t hash;
+
+ /* If wr_object is weakly referenced, wr_object has a doubly-linked NULL-
+ * terminated list of weak references to it. These are the list pointers.
+ * If wr_object goes away, wr_object is set to Py_None, and these pointers
+ * have no meaning then.
+ */
+ PyWeakReference *wr_prev;
+ PyWeakReference *wr_next;
+ vectorcallfunc vectorcall;
+};
+
+PyAPI_FUNC(Py_ssize_t) _PyWeakref_GetWeakrefCount(PyWeakReference *head);
+
+PyAPI_FUNC(void) _PyWeakref_ClearRef(PyWeakReference *self);
+
+static inline PyObject* PyWeakref_GET_OBJECT(PyObject *ref_obj) {
+ PyWeakReference *ref;
+ PyObject *obj;
+ assert(PyWeakref_Check(ref_obj));
+ ref = _Py_CAST(PyWeakReference*, ref_obj);
+ obj = ref->wr_object;
+ // Explanation for the Py_REFCNT() check: when a weakref's target is part
+ // of a long chain of deallocations which triggers the trashcan mechanism,
+ // clearing the weakrefs can be delayed long after the target's refcount
+ // has dropped to zero. In the meantime, code accessing the weakref will
+ // be able to "see" the target object even though it is supposed to be
+ // unreachable. See issue gh-60806.
+ if (Py_REFCNT(obj) > 0) {
+ return obj;
+ }
+ return Py_None;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyWeakref_GET_OBJECT(ref) PyWeakref_GET_OBJECT(_PyObject_CAST(ref))
+#endif
diff --git a/include/python3.10/datetime.h b/include/python3.11/datetime.h
similarity index 100%
rename from include/python3.10/datetime.h
rename to include/python3.11/datetime.h
diff --git a/include/python3.11/descrobject.h b/include/python3.11/descrobject.h
new file mode 100644
index 0000000..77f221d
--- /dev/null
+++ b/include/python3.11/descrobject.h
@@ -0,0 +1,44 @@
+/* Descriptors */
+#ifndef Py_DESCROBJECT_H
+#define Py_DESCROBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef PyObject *(*getter)(PyObject *, void *);
+typedef int (*setter)(PyObject *, PyObject *, void *);
+
+struct PyGetSetDef {
+ const char *name;
+ getter get;
+ setter set;
+ const char *doc;
+ void *closure;
+};
+
+PyAPI_DATA(PyTypeObject) PyClassMethodDescr_Type;
+PyAPI_DATA(PyTypeObject) PyGetSetDescr_Type;
+PyAPI_DATA(PyTypeObject) PyMemberDescr_Type;
+PyAPI_DATA(PyTypeObject) PyMethodDescr_Type;
+PyAPI_DATA(PyTypeObject) PyWrapperDescr_Type;
+PyAPI_DATA(PyTypeObject) PyDictProxy_Type;
+PyAPI_DATA(PyTypeObject) PyProperty_Type;
+
+PyAPI_FUNC(PyObject *) PyDescr_NewMethod(PyTypeObject *, PyMethodDef *);
+PyAPI_FUNC(PyObject *) PyDescr_NewClassMethod(PyTypeObject *, PyMethodDef *);
+PyAPI_FUNC(PyObject *) PyDescr_NewMember(PyTypeObject *, PyMemberDef *);
+PyAPI_FUNC(PyObject *) PyDescr_NewGetSet(PyTypeObject *, PyGetSetDef *);
+
+PyAPI_FUNC(PyObject *) PyDictProxy_New(PyObject *);
+PyAPI_FUNC(PyObject *) PyWrapper_New(PyObject *, PyObject *);
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_DESCROBJECT_H
+# include "cpython/descrobject.h"
+# undef Py_CPYTHON_DESCROBJECT_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_DESCROBJECT_H */
diff --git a/include/python3.11/dictobject.h b/include/python3.11/dictobject.h
new file mode 100644
index 0000000..a6233d8
--- /dev/null
+++ b/include/python3.11/dictobject.h
@@ -0,0 +1,97 @@
+#ifndef Py_DICTOBJECT_H
+#define Py_DICTOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Dictionary object type -- mapping from hashable object to object */
+
+/* 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.
+*/
+
+PyAPI_DATA(PyTypeObject) PyDict_Type;
+
+#define PyDict_Check(op) \
+ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_DICT_SUBCLASS)
+#define PyDict_CheckExact(op) Py_IS_TYPE(op, &PyDict_Type)
+
+PyAPI_FUNC(PyObject *) PyDict_New(void);
+PyAPI_FUNC(PyObject *) PyDict_GetItem(PyObject *mp, PyObject *key);
+PyAPI_FUNC(PyObject *) PyDict_GetItemWithError(PyObject *mp, PyObject *key);
+PyAPI_FUNC(int) PyDict_SetItem(PyObject *mp, PyObject *key, PyObject *item);
+PyAPI_FUNC(int) PyDict_DelItem(PyObject *mp, PyObject *key);
+PyAPI_FUNC(void) PyDict_Clear(PyObject *mp);
+PyAPI_FUNC(int) PyDict_Next(
+ PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value);
+PyAPI_FUNC(PyObject *) PyDict_Keys(PyObject *mp);
+PyAPI_FUNC(PyObject *) PyDict_Values(PyObject *mp);
+PyAPI_FUNC(PyObject *) PyDict_Items(PyObject *mp);
+PyAPI_FUNC(Py_ssize_t) PyDict_Size(PyObject *mp);
+PyAPI_FUNC(PyObject *) PyDict_Copy(PyObject *mp);
+PyAPI_FUNC(int) PyDict_Contains(PyObject *mp, PyObject *key);
+
+/* PyDict_Update(mp, other) is equivalent to PyDict_Merge(mp, other, 1). */
+PyAPI_FUNC(int) PyDict_Update(PyObject *mp, PyObject *other);
+
+/* PyDict_Merge updates/merges from a mapping object (an object that
+ supports PyMapping_Keys() and PyObject_GetItem()). If override is true,
+ the last occurrence of a key wins, else the first. The Python
+ dict.update(other) is equivalent to PyDict_Merge(dict, other, 1).
+*/
+PyAPI_FUNC(int) PyDict_Merge(PyObject *mp,
+ PyObject *other,
+ int override);
+
+/* PyDict_MergeFromSeq2 updates/merges from an iterable object producing
+ iterable objects of length 2. If override is true, the last occurrence
+ of a key wins, else the first. The Python dict constructor dict(seq2)
+ is equivalent to dict={}; PyDict_MergeFromSeq(dict, seq2, 1).
+*/
+PyAPI_FUNC(int) PyDict_MergeFromSeq2(PyObject *d,
+ PyObject *seq2,
+ int override);
+
+PyAPI_FUNC(PyObject *) PyDict_GetItemString(PyObject *dp, const char *key);
+PyAPI_FUNC(int) PyDict_SetItemString(PyObject *dp, const char *key, PyObject *item);
+PyAPI_FUNC(int) PyDict_DelItemString(PyObject *dp, const char *key);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000
+PyAPI_FUNC(PyObject *) PyObject_GenericGetDict(PyObject *, void *);
+#endif
+
+/* Dictionary (keys, values, items) views */
+
+PyAPI_DATA(PyTypeObject) PyDictKeys_Type;
+PyAPI_DATA(PyTypeObject) PyDictValues_Type;
+PyAPI_DATA(PyTypeObject) PyDictItems_Type;
+
+#define PyDictKeys_Check(op) PyObject_TypeCheck(op, &PyDictKeys_Type)
+#define PyDictValues_Check(op) PyObject_TypeCheck(op, &PyDictValues_Type)
+#define PyDictItems_Check(op) PyObject_TypeCheck(op, &PyDictItems_Type)
+/* This excludes Values, since they are not sets. */
+# define PyDictViewSet_Check(op) \
+ (PyDictKeys_Check(op) || PyDictItems_Check(op))
+
+/* Dictionary (key, value, items) iterators */
+
+PyAPI_DATA(PyTypeObject) PyDictIterKey_Type;
+PyAPI_DATA(PyTypeObject) PyDictIterValue_Type;
+PyAPI_DATA(PyTypeObject) PyDictIterItem_Type;
+
+PyAPI_DATA(PyTypeObject) PyDictRevIterKey_Type;
+PyAPI_DATA(PyTypeObject) PyDictRevIterItem_Type;
+PyAPI_DATA(PyTypeObject) PyDictRevIterValue_Type;
+
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_DICTOBJECT_H
+# include "cpython/dictobject.h"
+# undef Py_CPYTHON_DICTOBJECT_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_DICTOBJECT_H */
diff --git a/include/python3.11/dynamic_annotations.h b/include/python3.11/dynamic_annotations.h
new file mode 100644
index 0000000..4d4def9
--- /dev/null
+++ b/include/python3.11/dynamic_annotations.h
@@ -0,0 +1,499 @@
+/* Copyright (c) 2008-2009, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * ---
+ * Author: Kostya Serebryany
+ * Copied to CPython by Jeffrey Yasskin, with all macros renamed to
+ * start with _Py_ to avoid colliding with users embedding Python, and
+ * with deprecated macros removed.
+ */
+
+/* This file defines dynamic annotations for use with dynamic analysis
+ tool such as valgrind, PIN, etc.
+
+ Dynamic annotation is a source code annotation that affects
+ the generated code (that is, the annotation is not a comment).
+ Each such annotation is attached to a particular
+ instruction and/or to a particular object (address) in the program.
+
+ The annotations that should be used by users are macros in all upper-case
+ (e.g., _Py_ANNOTATE_NEW_MEMORY).
+
+ Actual implementation of these macros may differ depending on the
+ dynamic analysis tool being used.
+
+ See https://code.google.com/p/data-race-test/ for more information.
+
+ This file supports the following dynamic analysis tools:
+ - None (DYNAMIC_ANNOTATIONS_ENABLED is not defined or zero).
+ Macros are defined empty.
+ - ThreadSanitizer, Helgrind, DRD (DYNAMIC_ANNOTATIONS_ENABLED is 1).
+ Macros are defined as calls to non-inlinable empty functions
+ that are intercepted by Valgrind. */
+
+#ifndef __DYNAMIC_ANNOTATIONS_H__
+#define __DYNAMIC_ANNOTATIONS_H__
+
+#ifndef DYNAMIC_ANNOTATIONS_ENABLED
+# define DYNAMIC_ANNOTATIONS_ENABLED 0
+#endif
+
+#if DYNAMIC_ANNOTATIONS_ENABLED != 0
+
+ /* -------------------------------------------------------------
+ Annotations useful when implementing condition variables such as CondVar,
+ using conditional critical sections (Await/LockWhen) and when constructing
+ user-defined synchronization mechanisms.
+
+ The annotations _Py_ANNOTATE_HAPPENS_BEFORE() and
+ _Py_ANNOTATE_HAPPENS_AFTER() can be used to define happens-before arcs in
+ user-defined synchronization mechanisms: the race detector will infer an
+ arc from the former to the latter when they share the same argument
+ pointer.
+
+ Example 1 (reference counting):
+
+ void Unref() {
+ _Py_ANNOTATE_HAPPENS_BEFORE(&refcount_);
+ if (AtomicDecrementByOne(&refcount_) == 0) {
+ _Py_ANNOTATE_HAPPENS_AFTER(&refcount_);
+ delete this;
+ }
+ }
+
+ Example 2 (message queue):
+
+ void MyQueue::Put(Type *e) {
+ MutexLock lock(&mu_);
+ _Py_ANNOTATE_HAPPENS_BEFORE(e);
+ PutElementIntoMyQueue(e);
+ }
+
+ Type *MyQueue::Get() {
+ MutexLock lock(&mu_);
+ Type *e = GetElementFromMyQueue();
+ _Py_ANNOTATE_HAPPENS_AFTER(e);
+ return e;
+ }
+
+ Note: when possible, please use the existing reference counting and message
+ queue implementations instead of inventing new ones. */
+
+ /* Report that wait on the condition variable at address "cv" has succeeded
+ and the lock at address "lock" is held. */
+#define _Py_ANNOTATE_CONDVAR_LOCK_WAIT(cv, lock) \
+ AnnotateCondVarWait(__FILE__, __LINE__, cv, lock)
+
+ /* Report that wait on the condition variable at "cv" has succeeded. Variant
+ w/o lock. */
+#define _Py_ANNOTATE_CONDVAR_WAIT(cv) \
+ AnnotateCondVarWait(__FILE__, __LINE__, cv, NULL)
+
+ /* Report that we are about to signal on the condition variable at address
+ "cv". */
+#define _Py_ANNOTATE_CONDVAR_SIGNAL(cv) \
+ AnnotateCondVarSignal(__FILE__, __LINE__, cv)
+
+ /* Report that we are about to signal_all on the condition variable at "cv". */
+#define _Py_ANNOTATE_CONDVAR_SIGNAL_ALL(cv) \
+ AnnotateCondVarSignalAll(__FILE__, __LINE__, cv)
+
+ /* Annotations for user-defined synchronization mechanisms. */
+#define _Py_ANNOTATE_HAPPENS_BEFORE(obj) _Py_ANNOTATE_CONDVAR_SIGNAL(obj)
+#define _Py_ANNOTATE_HAPPENS_AFTER(obj) _Py_ANNOTATE_CONDVAR_WAIT(obj)
+
+ /* Report that the bytes in the range [pointer, pointer+size) are about
+ to be published safely. The race checker will create a happens-before
+ arc from the call _Py_ANNOTATE_PUBLISH_MEMORY_RANGE(pointer, size) to
+ subsequent accesses to this memory.
+ Note: this annotation may not work properly if the race detector uses
+ sampling, i.e. does not observe all memory accesses.
+ */
+#define _Py_ANNOTATE_PUBLISH_MEMORY_RANGE(pointer, size) \
+ AnnotatePublishMemoryRange(__FILE__, __LINE__, pointer, size)
+
+ /* Instruct the tool to create a happens-before arc between mu->Unlock() and
+ mu->Lock(). This annotation may slow down the race detector and hide real
+ races. Normally it is used only when it would be difficult to annotate each
+ of the mutex's critical sections individually using the annotations above.
+ This annotation makes sense only for hybrid race detectors. For pure
+ happens-before detectors this is a no-op. For more details see
+ https://code.google.com/p/data-race-test/wiki/PureHappensBeforeVsHybrid . */
+#define _Py_ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(mu) \
+ AnnotateMutexIsUsedAsCondVar(__FILE__, __LINE__, mu)
+
+ /* -------------------------------------------------------------
+ Annotations useful when defining memory allocators, or when memory that
+ was protected in one way starts to be protected in another. */
+
+ /* Report that a new memory at "address" of size "size" has been allocated.
+ This might be used when the memory has been retrieved from a free list and
+ is about to be reused, or when the locking discipline for a variable
+ changes. */
+#define _Py_ANNOTATE_NEW_MEMORY(address, size) \
+ AnnotateNewMemory(__FILE__, __LINE__, address, size)
+
+ /* -------------------------------------------------------------
+ Annotations useful when defining FIFO queues that transfer data between
+ threads. */
+
+ /* Report that the producer-consumer queue (such as ProducerConsumerQueue) at
+ address "pcq" has been created. The _Py_ANNOTATE_PCQ_* annotations should
+ be used only for FIFO queues. For non-FIFO queues use
+ _Py_ANNOTATE_HAPPENS_BEFORE (for put) and _Py_ANNOTATE_HAPPENS_AFTER (for
+ get). */
+#define _Py_ANNOTATE_PCQ_CREATE(pcq) \
+ AnnotatePCQCreate(__FILE__, __LINE__, pcq)
+
+ /* Report that the queue at address "pcq" is about to be destroyed. */
+#define _Py_ANNOTATE_PCQ_DESTROY(pcq) \
+ AnnotatePCQDestroy(__FILE__, __LINE__, pcq)
+
+ /* Report that we are about to put an element into a FIFO queue at address
+ "pcq". */
+#define _Py_ANNOTATE_PCQ_PUT(pcq) \
+ AnnotatePCQPut(__FILE__, __LINE__, pcq)
+
+ /* Report that we've just got an element from a FIFO queue at address "pcq". */
+#define _Py_ANNOTATE_PCQ_GET(pcq) \
+ AnnotatePCQGet(__FILE__, __LINE__, pcq)
+
+ /* -------------------------------------------------------------
+ Annotations that suppress errors. It is usually better to express the
+ program's synchronization using the other annotations, but these can
+ be used when all else fails. */
+
+ /* Report that we may have a benign race at "pointer", with size
+ "sizeof(*(pointer))". "pointer" must be a non-void* pointer. Insert at the
+ point where "pointer" has been allocated, preferably close to the point
+ where the race happens. See also _Py_ANNOTATE_BENIGN_RACE_STATIC. */
+#define _Py_ANNOTATE_BENIGN_RACE(pointer, description) \
+ AnnotateBenignRaceSized(__FILE__, __LINE__, pointer, \
+ sizeof(*(pointer)), description)
+
+ /* Same as _Py_ANNOTATE_BENIGN_RACE(address, description), but applies to
+ the memory range [address, address+size). */
+#define _Py_ANNOTATE_BENIGN_RACE_SIZED(address, size, description) \
+ AnnotateBenignRaceSized(__FILE__, __LINE__, address, size, description)
+
+ /* Request the analysis tool to ignore all reads in the current thread
+ until _Py_ANNOTATE_IGNORE_READS_END is called.
+ Useful to ignore intentional racey reads, while still checking
+ other reads and all writes.
+ See also _Py_ANNOTATE_UNPROTECTED_READ. */
+#define _Py_ANNOTATE_IGNORE_READS_BEGIN() \
+ AnnotateIgnoreReadsBegin(__FILE__, __LINE__)
+
+ /* Stop ignoring reads. */
+#define _Py_ANNOTATE_IGNORE_READS_END() \
+ AnnotateIgnoreReadsEnd(__FILE__, __LINE__)
+
+ /* Similar to _Py_ANNOTATE_IGNORE_READS_BEGIN, but ignore writes. */
+#define _Py_ANNOTATE_IGNORE_WRITES_BEGIN() \
+ AnnotateIgnoreWritesBegin(__FILE__, __LINE__)
+
+ /* Stop ignoring writes. */
+#define _Py_ANNOTATE_IGNORE_WRITES_END() \
+ AnnotateIgnoreWritesEnd(__FILE__, __LINE__)
+
+ /* Start ignoring all memory accesses (reads and writes). */
+#define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() \
+ do {\
+ _Py_ANNOTATE_IGNORE_READS_BEGIN();\
+ _Py_ANNOTATE_IGNORE_WRITES_BEGIN();\
+ }while(0)\
+
+ /* Stop ignoring all memory accesses. */
+#define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_END() \
+ do {\
+ _Py_ANNOTATE_IGNORE_WRITES_END();\
+ _Py_ANNOTATE_IGNORE_READS_END();\
+ }while(0)\
+
+ /* Similar to _Py_ANNOTATE_IGNORE_READS_BEGIN, but ignore synchronization events:
+ RWLOCK* and CONDVAR*. */
+#define _Py_ANNOTATE_IGNORE_SYNC_BEGIN() \
+ AnnotateIgnoreSyncBegin(__FILE__, __LINE__)
+
+ /* Stop ignoring sync events. */
+#define _Py_ANNOTATE_IGNORE_SYNC_END() \
+ AnnotateIgnoreSyncEnd(__FILE__, __LINE__)
+
+
+ /* Enable (enable!=0) or disable (enable==0) race detection for all threads.
+ This annotation could be useful if you want to skip expensive race analysis
+ during some period of program execution, e.g. during initialization. */
+#define _Py_ANNOTATE_ENABLE_RACE_DETECTION(enable) \
+ AnnotateEnableRaceDetection(__FILE__, __LINE__, enable)
+
+ /* -------------------------------------------------------------
+ Annotations useful for debugging. */
+
+ /* Request to trace every access to "address". */
+#define _Py_ANNOTATE_TRACE_MEMORY(address) \
+ AnnotateTraceMemory(__FILE__, __LINE__, address)
+
+ /* Report the current thread name to a race detector. */
+#define _Py_ANNOTATE_THREAD_NAME(name) \
+ AnnotateThreadName(__FILE__, __LINE__, name)
+
+ /* -------------------------------------------------------------
+ Annotations useful when implementing locks. They are not
+ normally needed by modules that merely use locks.
+ The "lock" argument is a pointer to the lock object. */
+
+ /* Report that a lock has been created at address "lock". */
+#define _Py_ANNOTATE_RWLOCK_CREATE(lock) \
+ AnnotateRWLockCreate(__FILE__, __LINE__, lock)
+
+ /* Report that the lock at address "lock" is about to be destroyed. */
+#define _Py_ANNOTATE_RWLOCK_DESTROY(lock) \
+ AnnotateRWLockDestroy(__FILE__, __LINE__, lock)
+
+ /* Report that the lock at address "lock" has been acquired.
+ is_w=1 for writer lock, is_w=0 for reader lock. */
+#define _Py_ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) \
+ AnnotateRWLockAcquired(__FILE__, __LINE__, lock, is_w)
+
+ /* Report that the lock at address "lock" is about to be released. */
+#define _Py_ANNOTATE_RWLOCK_RELEASED(lock, is_w) \
+ AnnotateRWLockReleased(__FILE__, __LINE__, lock, is_w)
+
+ /* -------------------------------------------------------------
+ Annotations useful when implementing barriers. They are not
+ normally needed by modules that merely use barriers.
+ The "barrier" argument is a pointer to the barrier object. */
+
+ /* Report that the "barrier" has been initialized with initial "count".
+ If 'reinitialization_allowed' is true, initialization is allowed to happen
+ multiple times w/o calling barrier_destroy() */
+#define _Py_ANNOTATE_BARRIER_INIT(barrier, count, reinitialization_allowed) \
+ AnnotateBarrierInit(__FILE__, __LINE__, barrier, count, \
+ reinitialization_allowed)
+
+ /* Report that we are about to enter barrier_wait("barrier"). */
+#define _Py_ANNOTATE_BARRIER_WAIT_BEFORE(barrier) \
+ AnnotateBarrierWaitBefore(__FILE__, __LINE__, barrier)
+
+ /* Report that we just exited barrier_wait("barrier"). */
+#define _Py_ANNOTATE_BARRIER_WAIT_AFTER(barrier) \
+ AnnotateBarrierWaitAfter(__FILE__, __LINE__, barrier)
+
+ /* Report that the "barrier" has been destroyed. */
+#define _Py_ANNOTATE_BARRIER_DESTROY(barrier) \
+ AnnotateBarrierDestroy(__FILE__, __LINE__, barrier)
+
+ /* -------------------------------------------------------------
+ Annotations useful for testing race detectors. */
+
+ /* Report that we expect a race on the variable at "address".
+ Use only in unit tests for a race detector. */
+#define _Py_ANNOTATE_EXPECT_RACE(address, description) \
+ AnnotateExpectRace(__FILE__, __LINE__, address, description)
+
+ /* A no-op. Insert where you like to test the interceptors. */
+#define _Py_ANNOTATE_NO_OP(arg) \
+ AnnotateNoOp(__FILE__, __LINE__, arg)
+
+ /* Force the race detector to flush its state. The actual effect depends on
+ * the implementation of the detector. */
+#define _Py_ANNOTATE_FLUSH_STATE() \
+ AnnotateFlushState(__FILE__, __LINE__)
+
+
+#else /* DYNAMIC_ANNOTATIONS_ENABLED == 0 */
+
+#define _Py_ANNOTATE_RWLOCK_CREATE(lock) /* empty */
+#define _Py_ANNOTATE_RWLOCK_DESTROY(lock) /* empty */
+#define _Py_ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) /* empty */
+#define _Py_ANNOTATE_RWLOCK_RELEASED(lock, is_w) /* empty */
+#define _Py_ANNOTATE_BARRIER_INIT(barrier, count, reinitialization_allowed) /* */
+#define _Py_ANNOTATE_BARRIER_WAIT_BEFORE(barrier) /* empty */
+#define _Py_ANNOTATE_BARRIER_WAIT_AFTER(barrier) /* empty */
+#define _Py_ANNOTATE_BARRIER_DESTROY(barrier) /* empty */
+#define _Py_ANNOTATE_CONDVAR_LOCK_WAIT(cv, lock) /* empty */
+#define _Py_ANNOTATE_CONDVAR_WAIT(cv) /* empty */
+#define _Py_ANNOTATE_CONDVAR_SIGNAL(cv) /* empty */
+#define _Py_ANNOTATE_CONDVAR_SIGNAL_ALL(cv) /* empty */
+#define _Py_ANNOTATE_HAPPENS_BEFORE(obj) /* empty */
+#define _Py_ANNOTATE_HAPPENS_AFTER(obj) /* empty */
+#define _Py_ANNOTATE_PUBLISH_MEMORY_RANGE(address, size) /* empty */
+#define _Py_ANNOTATE_UNPUBLISH_MEMORY_RANGE(address, size) /* empty */
+#define _Py_ANNOTATE_SWAP_MEMORY_RANGE(address, size) /* empty */
+#define _Py_ANNOTATE_PCQ_CREATE(pcq) /* empty */
+#define _Py_ANNOTATE_PCQ_DESTROY(pcq) /* empty */
+#define _Py_ANNOTATE_PCQ_PUT(pcq) /* empty */
+#define _Py_ANNOTATE_PCQ_GET(pcq) /* empty */
+#define _Py_ANNOTATE_NEW_MEMORY(address, size) /* empty */
+#define _Py_ANNOTATE_EXPECT_RACE(address, description) /* empty */
+#define _Py_ANNOTATE_BENIGN_RACE(address, description) /* empty */
+#define _Py_ANNOTATE_BENIGN_RACE_SIZED(address, size, description) /* empty */
+#define _Py_ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(mu) /* empty */
+#define _Py_ANNOTATE_MUTEX_IS_USED_AS_CONDVAR(mu) /* empty */
+#define _Py_ANNOTATE_TRACE_MEMORY(arg) /* empty */
+#define _Py_ANNOTATE_THREAD_NAME(name) /* empty */
+#define _Py_ANNOTATE_IGNORE_READS_BEGIN() /* empty */
+#define _Py_ANNOTATE_IGNORE_READS_END() /* empty */
+#define _Py_ANNOTATE_IGNORE_WRITES_BEGIN() /* empty */
+#define _Py_ANNOTATE_IGNORE_WRITES_END() /* empty */
+#define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() /* empty */
+#define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_END() /* empty */
+#define _Py_ANNOTATE_IGNORE_SYNC_BEGIN() /* empty */
+#define _Py_ANNOTATE_IGNORE_SYNC_END() /* empty */
+#define _Py_ANNOTATE_ENABLE_RACE_DETECTION(enable) /* empty */
+#define _Py_ANNOTATE_NO_OP(arg) /* empty */
+#define _Py_ANNOTATE_FLUSH_STATE() /* empty */
+
+#endif /* DYNAMIC_ANNOTATIONS_ENABLED */
+
+/* Use the macros above rather than using these functions directly. */
+#ifdef __cplusplus
+extern "C" {
+#endif
+void AnnotateRWLockCreate(const char *file, int line,
+ const volatile void *lock);
+void AnnotateRWLockDestroy(const char *file, int line,
+ const volatile void *lock);
+void AnnotateRWLockAcquired(const char *file, int line,
+ const volatile void *lock, long is_w);
+void AnnotateRWLockReleased(const char *file, int line,
+ const volatile void *lock, long is_w);
+void AnnotateBarrierInit(const char *file, int line,
+ const volatile void *barrier, long count,
+ long reinitialization_allowed);
+void AnnotateBarrierWaitBefore(const char *file, int line,
+ const volatile void *barrier);
+void AnnotateBarrierWaitAfter(const char *file, int line,
+ const volatile void *barrier);
+void AnnotateBarrierDestroy(const char *file, int line,
+ const volatile void *barrier);
+void AnnotateCondVarWait(const char *file, int line,
+ const volatile void *cv,
+ const volatile void *lock);
+void AnnotateCondVarSignal(const char *file, int line,
+ const volatile void *cv);
+void AnnotateCondVarSignalAll(const char *file, int line,
+ const volatile void *cv);
+void AnnotatePublishMemoryRange(const char *file, int line,
+ const volatile void *address,
+ long size);
+void AnnotateUnpublishMemoryRange(const char *file, int line,
+ const volatile void *address,
+ long size);
+void AnnotatePCQCreate(const char *file, int line,
+ const volatile void *pcq);
+void AnnotatePCQDestroy(const char *file, int line,
+ const volatile void *pcq);
+void AnnotatePCQPut(const char *file, int line,
+ const volatile void *pcq);
+void AnnotatePCQGet(const char *file, int line,
+ const volatile void *pcq);
+void AnnotateNewMemory(const char *file, int line,
+ const volatile void *address,
+ long size);
+void AnnotateExpectRace(const char *file, int line,
+ const volatile void *address,
+ const char *description);
+void AnnotateBenignRace(const char *file, int line,
+ const volatile void *address,
+ const char *description);
+void AnnotateBenignRaceSized(const char *file, int line,
+ const volatile void *address,
+ long size,
+ const char *description);
+void AnnotateMutexIsUsedAsCondVar(const char *file, int line,
+ const volatile void *mu);
+void AnnotateTraceMemory(const char *file, int line,
+ const volatile void *arg);
+void AnnotateThreadName(const char *file, int line,
+ const char *name);
+void AnnotateIgnoreReadsBegin(const char *file, int line);
+void AnnotateIgnoreReadsEnd(const char *file, int line);
+void AnnotateIgnoreWritesBegin(const char *file, int line);
+void AnnotateIgnoreWritesEnd(const char *file, int line);
+void AnnotateEnableRaceDetection(const char *file, int line, int enable);
+void AnnotateNoOp(const char *file, int line,
+ const volatile void *arg);
+void AnnotateFlushState(const char *file, int line);
+
+/* Return non-zero value if running under valgrind.
+
+ If "valgrind.h" is included into dynamic_annotations.c,
+ the regular valgrind mechanism will be used.
+ See http://valgrind.org/docs/manual/manual-core-adv.html about
+ RUNNING_ON_VALGRIND and other valgrind "client requests".
+ The file "valgrind.h" may be obtained by doing
+ svn co svn://svn.valgrind.org/valgrind/trunk/include
+
+ If for some reason you can't use "valgrind.h" or want to fake valgrind,
+ there are two ways to make this function return non-zero:
+ - Use environment variable: export RUNNING_ON_VALGRIND=1
+ - Make your tool intercept the function RunningOnValgrind() and
+ change its return value.
+ */
+int RunningOnValgrind(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#if DYNAMIC_ANNOTATIONS_ENABLED != 0 && defined(__cplusplus)
+
+ /* _Py_ANNOTATE_UNPROTECTED_READ is the preferred way to annotate racey reads.
+
+ Instead of doing
+ _Py_ANNOTATE_IGNORE_READS_BEGIN();
+ ... = x;
+ _Py_ANNOTATE_IGNORE_READS_END();
+ one can use
+ ... = _Py_ANNOTATE_UNPROTECTED_READ(x); */
+ template <class T>
+ inline T _Py_ANNOTATE_UNPROTECTED_READ(const volatile T &x) {
+ _Py_ANNOTATE_IGNORE_READS_BEGIN();
+ T res = x;
+ _Py_ANNOTATE_IGNORE_READS_END();
+ return res;
+ }
+ /* Apply _Py_ANNOTATE_BENIGN_RACE_SIZED to a static variable. */
+#define _Py_ANNOTATE_BENIGN_RACE_STATIC(static_var, description) \
+ namespace { \
+ class static_var ## _annotator { \
+ public: \
+ static_var ## _annotator() { \
+ _Py_ANNOTATE_BENIGN_RACE_SIZED(&static_var, \
+ sizeof(static_var), \
+ # static_var ": " description); \
+ } \
+ }; \
+ static static_var ## _annotator the ## static_var ## _annotator;\
+ }
+#else /* DYNAMIC_ANNOTATIONS_ENABLED == 0 */
+
+#define _Py_ANNOTATE_UNPROTECTED_READ(x) (x)
+#define _Py_ANNOTATE_BENIGN_RACE_STATIC(static_var, description) /* empty */
+
+#endif /* DYNAMIC_ANNOTATIONS_ENABLED */
+
+#endif /* __DYNAMIC_ANNOTATIONS_H__ */
diff --git a/include/python3.10/enumobject.h b/include/python3.11/enumobject.h
similarity index 100%
rename from include/python3.10/enumobject.h
rename to include/python3.11/enumobject.h
diff --git a/include/python3.10/errcode.h b/include/python3.11/errcode.h
similarity index 100%
rename from include/python3.10/errcode.h
rename to include/python3.11/errcode.h
diff --git a/include/python3.10/exports.h b/include/python3.11/exports.h
similarity index 100%
rename from include/python3.10/exports.h
rename to include/python3.11/exports.h
diff --git a/include/python3.11/fileobject.h b/include/python3.11/fileobject.h
new file mode 100644
index 0000000..4c983e7
--- /dev/null
+++ b/include/python3.11/fileobject.h
@@ -0,0 +1,49 @@
+/* File object interface (what's left of it -- see io.py) */
+
+#ifndef Py_FILEOBJECT_H
+#define Py_FILEOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define PY_STDIOTEXTMODE "b"
+
+PyAPI_FUNC(PyObject *) PyFile_FromFd(int, const char *, const char *, int,
+ const char *, const char *,
+ const char *, int);
+PyAPI_FUNC(PyObject *) PyFile_GetLine(PyObject *, int);
+PyAPI_FUNC(int) PyFile_WriteObject(PyObject *, PyObject *, int);
+PyAPI_FUNC(int) PyFile_WriteString(const char *, PyObject *);
+PyAPI_FUNC(int) PyObject_AsFileDescriptor(PyObject *);
+
+/* The default encoding used by the platform file system APIs
+ If non-NULL, this is different than the default encoding for strings
+*/
+PyAPI_DATA(const char *) Py_FileSystemDefaultEncoding;
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000
+PyAPI_DATA(const char *) Py_FileSystemDefaultEncodeErrors;
+#endif
+PyAPI_DATA(int) Py_HasFileSystemDefaultEncoding;
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03070000
+PyAPI_DATA(int) Py_UTF8Mode;
+#endif
+
+/* A routine to check if a file descriptor can be select()-ed. */
+#ifdef _MSC_VER
+ /* On Windows, any socket fd can be select()-ed, no matter how high */
+ #define _PyIsSelectable_fd(FD) (1)
+#else
+ #define _PyIsSelectable_fd(FD) ((unsigned int)(FD) < (unsigned int)FD_SETSIZE)
+#endif
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_FILEOBJECT_H
+# include "cpython/fileobject.h"
+# undef Py_CPYTHON_FILEOBJECT_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_FILEOBJECT_H */
diff --git a/include/python3.11/fileutils.h b/include/python3.11/fileutils.h
new file mode 100644
index 0000000..ba5acc8
--- /dev/null
+++ b/include/python3.11/fileutils.h
@@ -0,0 +1,26 @@
+#ifndef Py_FILEUTILS_H
+#define Py_FILEUTILS_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
+PyAPI_FUNC(wchar_t *) Py_DecodeLocale(
+ const char *arg,
+ size_t *size);
+
+PyAPI_FUNC(char*) Py_EncodeLocale(
+ const wchar_t *text,
+ size_t *error_pos);
+#endif
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_FILEUTILS_H
+# include "cpython/fileutils.h"
+# undef Py_CPYTHON_FILEUTILS_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_FILEUTILS_H */
diff --git a/include/python3.11/floatobject.h b/include/python3.11/floatobject.h
new file mode 100644
index 0000000..9d2fff3
--- /dev/null
+++ b/include/python3.11/floatobject.h
@@ -0,0 +1,54 @@
+
+/* Float object interface */
+
+/*
+PyFloatObject represents a (double precision) floating point number.
+*/
+
+#ifndef Py_FLOATOBJECT_H
+#define Py_FLOATOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_DATA(PyTypeObject) PyFloat_Type;
+
+#define PyFloat_Check(op) PyObject_TypeCheck(op, &PyFloat_Type)
+#define PyFloat_CheckExact(op) Py_IS_TYPE(op, &PyFloat_Type)
+
+#define Py_RETURN_NAN return PyFloat_FromDouble(Py_NAN)
+
+#define Py_RETURN_INF(sign) \
+ do { \
+ if (copysign(1., sign) == 1.) { \
+ return PyFloat_FromDouble(Py_HUGE_VAL); \
+ } \
+ else { \
+ return PyFloat_FromDouble(-Py_HUGE_VAL); \
+ } \
+ } while(0)
+
+PyAPI_FUNC(double) PyFloat_GetMax(void);
+PyAPI_FUNC(double) PyFloat_GetMin(void);
+PyAPI_FUNC(PyObject*) PyFloat_GetInfo(void);
+
+/* Return Python float from string PyObject. */
+PyAPI_FUNC(PyObject*) PyFloat_FromString(PyObject*);
+
+/* Return Python float from C double. */
+PyAPI_FUNC(PyObject*) PyFloat_FromDouble(double);
+
+/* Extract C double from Python float. The macro version trades safety for
+ speed. */
+PyAPI_FUNC(double) PyFloat_AsDouble(PyObject*);
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_FLOATOBJECT_H
+# include "cpython/floatobject.h"
+# undef Py_CPYTHON_FLOATOBJECT_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_FLOATOBJECT_H */
diff --git a/include/python3.11/frameobject.h b/include/python3.11/frameobject.h
new file mode 100644
index 0000000..adb628f
--- /dev/null
+++ b/include/python3.11/frameobject.h
@@ -0,0 +1,20 @@
+/* Frame object interface */
+
+#ifndef Py_FRAMEOBJECT_H
+#define Py_FRAMEOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "pyframe.h"
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_FRAMEOBJECT_H
+# include "cpython/frameobject.h"
+# undef Py_CPYTHON_FRAMEOBJECT_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_FRAMEOBJECT_H */
diff --git a/include/python3.10/genericaliasobject.h b/include/python3.11/genericaliasobject.h
similarity index 100%
rename from include/python3.10/genericaliasobject.h
rename to include/python3.11/genericaliasobject.h
diff --git a/include/python3.11/import.h b/include/python3.11/import.h
new file mode 100644
index 0000000..a87677b
--- /dev/null
+++ b/include/python3.11/import.h
@@ -0,0 +1,98 @@
+/* Module definition and import interface */
+
+#ifndef Py_IMPORT_H
+#define Py_IMPORT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_FUNC(long) PyImport_GetMagicNumber(void);
+PyAPI_FUNC(const char *) PyImport_GetMagicTag(void);
+PyAPI_FUNC(PyObject *) PyImport_ExecCodeModule(
+ const char *name, /* UTF-8 encoded string */
+ PyObject *co
+ );
+PyAPI_FUNC(PyObject *) PyImport_ExecCodeModuleEx(
+ const char *name, /* UTF-8 encoded string */
+ PyObject *co,
+ const char *pathname /* decoded from the filesystem encoding */
+ );
+PyAPI_FUNC(PyObject *) PyImport_ExecCodeModuleWithPathnames(
+ const char *name, /* UTF-8 encoded string */
+ PyObject *co,
+ const char *pathname, /* decoded from the filesystem encoding */
+ const char *cpathname /* decoded from the filesystem encoding */
+ );
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+PyAPI_FUNC(PyObject *) PyImport_ExecCodeModuleObject(
+ PyObject *name,
+ PyObject *co,
+ PyObject *pathname,
+ PyObject *cpathname
+ );
+#endif
+PyAPI_FUNC(PyObject *) PyImport_GetModuleDict(void);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03070000
+PyAPI_FUNC(PyObject *) PyImport_GetModule(PyObject *name);
+#endif
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+PyAPI_FUNC(PyObject *) PyImport_AddModuleObject(
+ PyObject *name
+ );
+#endif
+PyAPI_FUNC(PyObject *) PyImport_AddModule(
+ const char *name /* UTF-8 encoded string */
+ );
+PyAPI_FUNC(PyObject *) PyImport_ImportModule(
+ const char *name /* UTF-8 encoded string */
+ );
+PyAPI_FUNC(PyObject *) PyImport_ImportModuleNoBlock(
+ const char *name /* UTF-8 encoded string */
+ );
+PyAPI_FUNC(PyObject *) PyImport_ImportModuleLevel(
+ const char *name, /* UTF-8 encoded string */
+ PyObject *globals,
+ PyObject *locals,
+ PyObject *fromlist,
+ int level
+ );
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
+PyAPI_FUNC(PyObject *) PyImport_ImportModuleLevelObject(
+ PyObject *name,
+ PyObject *globals,
+ PyObject *locals,
+ PyObject *fromlist,
+ int level
+ );
+#endif
+
+#define PyImport_ImportModuleEx(n, g, l, f) \
+ PyImport_ImportModuleLevel(n, g, l, f, 0)
+
+PyAPI_FUNC(PyObject *) PyImport_GetImporter(PyObject *path);
+PyAPI_FUNC(PyObject *) PyImport_Import(PyObject *name);
+PyAPI_FUNC(PyObject *) PyImport_ReloadModule(PyObject *m);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+PyAPI_FUNC(int) PyImport_ImportFrozenModuleObject(
+ PyObject *name
+ );
+#endif
+PyAPI_FUNC(int) PyImport_ImportFrozenModule(
+ const char *name /* UTF-8 encoded string */
+ );
+
+PyAPI_FUNC(int) PyImport_AppendInittab(
+ const char *name, /* ASCII encoded string */
+ PyObject* (*initfunc)(void)
+ );
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_IMPORT_H
+# include "cpython/import.h"
+# undef Py_CPYTHON_IMPORT_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_IMPORT_H */
diff --git a/include/python3.11/internal/pycore_abstract.h b/include/python3.11/internal/pycore_abstract.h
new file mode 100644
index 0000000..b1afb2d
--- /dev/null
+++ b/include/python3.11/internal/pycore_abstract.h
@@ -0,0 +1,25 @@
+#ifndef Py_INTERNAL_ABSTRACT_H
+#define Py_INTERNAL_ABSTRACT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+// Fast inlined version of PyIndex_Check()
+static inline int
+_PyIndex_Check(PyObject *obj)
+{
+ PyNumberMethods *tp_as_number = Py_TYPE(obj)->tp_as_number;
+ return (tp_as_number != NULL && tp_as_number->nb_index != NULL);
+}
+
+PyObject *_PyNumber_PowerNoMod(PyObject *lhs, PyObject *rhs);
+PyObject *_PyNumber_InPlacePowerNoMod(PyObject *lhs, PyObject *rhs);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_ABSTRACT_H */
diff --git a/include/python3.10/internal/pycore_accu.h b/include/python3.11/internal/pycore_accu.h
similarity index 100%
rename from include/python3.10/internal/pycore_accu.h
rename to include/python3.11/internal/pycore_accu.h
diff --git a/include/python3.11/internal/pycore_asdl.h b/include/python3.11/internal/pycore_asdl.h
new file mode 100644
index 0000000..5b01c7a
--- /dev/null
+++ b/include/python3.11/internal/pycore_asdl.h
@@ -0,0 +1,112 @@
+#ifndef Py_INTERNAL_ASDL_H
+#define Py_INTERNAL_ASDL_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#include "pycore_pyarena.h" // _PyArena_Malloc()
+
+typedef PyObject * identifier;
+typedef PyObject * string;
+typedef PyObject * object;
+typedef PyObject * constant;
+
+/* It would be nice if the code generated by asdl_c.py was completely
+ independent of Python, but it is a goal the requires too much work
+ at this stage. So, for example, I'll represent identifiers as
+ interned Python strings.
+*/
+
+#define _ASDL_SEQ_HEAD \
+ Py_ssize_t size; \
+ void **elements;
+
+typedef struct {
+ _ASDL_SEQ_HEAD
+} asdl_seq;
+
+typedef struct {
+ _ASDL_SEQ_HEAD
+ void *typed_elements[1];
+} asdl_generic_seq;
+
+typedef struct {
+ _ASDL_SEQ_HEAD
+ PyObject *typed_elements[1];
+} asdl_identifier_seq;
+
+typedef struct {
+ _ASDL_SEQ_HEAD
+ int typed_elements[1];
+} asdl_int_seq;
+
+asdl_generic_seq *_Py_asdl_generic_seq_new(Py_ssize_t size, PyArena *arena);
+asdl_identifier_seq *_Py_asdl_identifier_seq_new(Py_ssize_t size, PyArena *arena);
+asdl_int_seq *_Py_asdl_int_seq_new(Py_ssize_t size, PyArena *arena);
+
+
+#define GENERATE_ASDL_SEQ_CONSTRUCTOR(NAME, TYPE) \
+asdl_ ## NAME ## _seq *_Py_asdl_ ## NAME ## _seq_new(Py_ssize_t size, PyArena *arena) \
+{ \
+ asdl_ ## NAME ## _seq *seq = NULL; \
+ size_t n; \
+ /* check size is sane */ \
+ if (size < 0 || \
+ (size && (((size_t)size - 1) > (SIZE_MAX / sizeof(void *))))) { \
+ PyErr_NoMemory(); \
+ return NULL; \
+ } \
+ n = (size ? (sizeof(TYPE *) * (size - 1)) : 0); \
+ /* check if size can be added safely */ \
+ if (n > SIZE_MAX - sizeof(asdl_ ## NAME ## _seq)) { \
+ PyErr_NoMemory(); \
+ return NULL; \
+ } \
+ n += sizeof(asdl_ ## NAME ## _seq); \
+ seq = (asdl_ ## NAME ## _seq *)_PyArena_Malloc(arena, n); \
+ if (!seq) { \
+ PyErr_NoMemory(); \
+ return NULL; \
+ } \
+ memset(seq, 0, n); \
+ seq->size = size; \
+ seq->elements = (void**)seq->typed_elements; \
+ return seq; \
+}
+
+#define asdl_seq_GET_UNTYPED(S, I) _Py_RVALUE((S)->elements[(I)])
+#define asdl_seq_GET(S, I) _Py_RVALUE((S)->typed_elements[(I)])
+#define asdl_seq_LEN(S) _Py_RVALUE(((S) == NULL ? 0 : (S)->size))
+
+#ifdef Py_DEBUG
+# define asdl_seq_SET(S, I, V) \
+ do { \
+ Py_ssize_t _asdl_i = (I); \
+ assert((S) != NULL); \
+ assert(0 <= _asdl_i && _asdl_i < (S)->size); \
+ (S)->typed_elements[_asdl_i] = (V); \
+ } while (0)
+#else
+# define asdl_seq_SET(S, I, V) _Py_RVALUE((S)->typed_elements[I] = (V))
+#endif
+
+#ifdef Py_DEBUG
+# define asdl_seq_SET_UNTYPED(S, I, V) \
+ do { \
+ Py_ssize_t _asdl_i = (I); \
+ assert((S) != NULL); \
+ assert(0 <= _asdl_i && _asdl_i < (S)->size); \
+ (S)->elements[_asdl_i] = (V); \
+ } while (0)
+#else
+# define asdl_seq_SET_UNTYPED(S, I, V) _Py_RVALUE((S)->elements[I] = (V))
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_ASDL_H */
diff --git a/include/python3.11/internal/pycore_ast.h b/include/python3.11/internal/pycore_ast.h
new file mode 100644
index 0000000..36277ef
--- /dev/null
+++ b/include/python3.11/internal/pycore_ast.h
@@ -0,0 +1,866 @@
+// File automatically generated by Parser/asdl_c.py.
+
+#ifndef Py_INTERNAL_AST_H
+#define Py_INTERNAL_AST_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#include "pycore_asdl.h"
+
+typedef struct _mod *mod_ty;
+
+typedef struct _stmt *stmt_ty;
+
+typedef struct _expr *expr_ty;
+
+typedef enum _expr_context { Load=1, Store=2, Del=3 } expr_context_ty;
+
+typedef enum _boolop { And=1, Or=2 } boolop_ty;
+
+typedef enum _operator { Add=1, Sub=2, Mult=3, MatMult=4, Div=5, Mod=6, Pow=7,
+ LShift=8, RShift=9, BitOr=10, BitXor=11, BitAnd=12,
+ FloorDiv=13 } operator_ty;
+
+typedef enum _unaryop { Invert=1, Not=2, UAdd=3, USub=4 } unaryop_ty;
+
+typedef enum _cmpop { Eq=1, NotEq=2, Lt=3, LtE=4, Gt=5, GtE=6, Is=7, IsNot=8,
+ In=9, NotIn=10 } cmpop_ty;
+
+typedef struct _comprehension *comprehension_ty;
+
+typedef struct _excepthandler *excepthandler_ty;
+
+typedef struct _arguments *arguments_ty;
+
+typedef struct _arg *arg_ty;
+
+typedef struct _keyword *keyword_ty;
+
+typedef struct _alias *alias_ty;
+
+typedef struct _withitem *withitem_ty;
+
+typedef struct _match_case *match_case_ty;
+
+typedef struct _pattern *pattern_ty;
+
+typedef struct _type_ignore *type_ignore_ty;
+
+
+typedef struct {
+ _ASDL_SEQ_HEAD
+ mod_ty typed_elements[1];
+} asdl_mod_seq;
+
+asdl_mod_seq *_Py_asdl_mod_seq_new(Py_ssize_t size, PyArena *arena);
+
+typedef struct {
+ _ASDL_SEQ_HEAD
+ stmt_ty typed_elements[1];
+} asdl_stmt_seq;
+
+asdl_stmt_seq *_Py_asdl_stmt_seq_new(Py_ssize_t size, PyArena *arena);
+
+typedef struct {
+ _ASDL_SEQ_HEAD
+ expr_ty typed_elements[1];
+} asdl_expr_seq;
+
+asdl_expr_seq *_Py_asdl_expr_seq_new(Py_ssize_t size, PyArena *arena);
+
+typedef struct {
+ _ASDL_SEQ_HEAD
+ comprehension_ty typed_elements[1];
+} asdl_comprehension_seq;
+
+asdl_comprehension_seq *_Py_asdl_comprehension_seq_new(Py_ssize_t size, PyArena
+ *arena);
+
+typedef struct {
+ _ASDL_SEQ_HEAD
+ excepthandler_ty typed_elements[1];
+} asdl_excepthandler_seq;
+
+asdl_excepthandler_seq *_Py_asdl_excepthandler_seq_new(Py_ssize_t size, PyArena
+ *arena);
+
+typedef struct {
+ _ASDL_SEQ_HEAD
+ arguments_ty typed_elements[1];
+} asdl_arguments_seq;
+
+asdl_arguments_seq *_Py_asdl_arguments_seq_new(Py_ssize_t size, PyArena *arena);
+
+typedef struct {
+ _ASDL_SEQ_HEAD
+ arg_ty typed_elements[1];
+} asdl_arg_seq;
+
+asdl_arg_seq *_Py_asdl_arg_seq_new(Py_ssize_t size, PyArena *arena);
+
+typedef struct {
+ _ASDL_SEQ_HEAD
+ keyword_ty typed_elements[1];
+} asdl_keyword_seq;
+
+asdl_keyword_seq *_Py_asdl_keyword_seq_new(Py_ssize_t size, PyArena *arena);
+
+typedef struct {
+ _ASDL_SEQ_HEAD
+ alias_ty typed_elements[1];
+} asdl_alias_seq;
+
+asdl_alias_seq *_Py_asdl_alias_seq_new(Py_ssize_t size, PyArena *arena);
+
+typedef struct {
+ _ASDL_SEQ_HEAD
+ withitem_ty typed_elements[1];
+} asdl_withitem_seq;
+
+asdl_withitem_seq *_Py_asdl_withitem_seq_new(Py_ssize_t size, PyArena *arena);
+
+typedef struct {
+ _ASDL_SEQ_HEAD
+ match_case_ty typed_elements[1];
+} asdl_match_case_seq;
+
+asdl_match_case_seq *_Py_asdl_match_case_seq_new(Py_ssize_t size, PyArena
+ *arena);
+
+typedef struct {
+ _ASDL_SEQ_HEAD
+ pattern_ty typed_elements[1];
+} asdl_pattern_seq;
+
+asdl_pattern_seq *_Py_asdl_pattern_seq_new(Py_ssize_t size, PyArena *arena);
+
+typedef struct {
+ _ASDL_SEQ_HEAD
+ type_ignore_ty typed_elements[1];
+} asdl_type_ignore_seq;
+
+asdl_type_ignore_seq *_Py_asdl_type_ignore_seq_new(Py_ssize_t size, PyArena
+ *arena);
+
+
+enum _mod_kind {Module_kind=1, Interactive_kind=2, Expression_kind=3,
+ FunctionType_kind=4};
+struct _mod {
+ enum _mod_kind kind;
+ union {
+ struct {
+ asdl_stmt_seq *body;
+ asdl_type_ignore_seq *type_ignores;
+ } Module;
+
+ struct {
+ asdl_stmt_seq *body;
+ } Interactive;
+
+ struct {
+ expr_ty body;
+ } Expression;
+
+ struct {
+ asdl_expr_seq *argtypes;
+ expr_ty returns;
+ } FunctionType;
+
+ } v;
+};
+
+enum _stmt_kind {FunctionDef_kind=1, AsyncFunctionDef_kind=2, ClassDef_kind=3,
+ Return_kind=4, Delete_kind=5, Assign_kind=6,
+ AugAssign_kind=7, AnnAssign_kind=8, For_kind=9,
+ AsyncFor_kind=10, While_kind=11, If_kind=12, With_kind=13,
+ AsyncWith_kind=14, Match_kind=15, Raise_kind=16, Try_kind=17,
+ TryStar_kind=18, Assert_kind=19, Import_kind=20,
+ ImportFrom_kind=21, Global_kind=22, Nonlocal_kind=23,
+ Expr_kind=24, Pass_kind=25, Break_kind=26, Continue_kind=27};
+struct _stmt {
+ enum _stmt_kind kind;
+ union {
+ struct {
+ identifier name;
+ arguments_ty args;
+ asdl_stmt_seq *body;
+ asdl_expr_seq *decorator_list;
+ expr_ty returns;
+ string type_comment;
+ } FunctionDef;
+
+ struct {
+ identifier name;
+ arguments_ty args;
+ asdl_stmt_seq *body;
+ asdl_expr_seq *decorator_list;
+ expr_ty returns;
+ string type_comment;
+ } AsyncFunctionDef;
+
+ struct {
+ identifier name;
+ asdl_expr_seq *bases;
+ asdl_keyword_seq *keywords;
+ asdl_stmt_seq *body;
+ asdl_expr_seq *decorator_list;
+ } ClassDef;
+
+ struct {
+ expr_ty value;
+ } Return;
+
+ struct {
+ asdl_expr_seq *targets;
+ } Delete;
+
+ struct {
+ asdl_expr_seq *targets;
+ expr_ty value;
+ string type_comment;
+ } Assign;
+
+ struct {
+ expr_ty target;
+ operator_ty op;
+ expr_ty value;
+ } AugAssign;
+
+ struct {
+ expr_ty target;
+ expr_ty annotation;
+ expr_ty value;
+ int simple;
+ } AnnAssign;
+
+ struct {
+ expr_ty target;
+ expr_ty iter;
+ asdl_stmt_seq *body;
+ asdl_stmt_seq *orelse;
+ string type_comment;
+ } For;
+
+ struct {
+ expr_ty target;
+ expr_ty iter;
+ asdl_stmt_seq *body;
+ asdl_stmt_seq *orelse;
+ string type_comment;
+ } AsyncFor;
+
+ struct {
+ expr_ty test;
+ asdl_stmt_seq *body;
+ asdl_stmt_seq *orelse;
+ } While;
+
+ struct {
+ expr_ty test;
+ asdl_stmt_seq *body;
+ asdl_stmt_seq *orelse;
+ } If;
+
+ struct {
+ asdl_withitem_seq *items;
+ asdl_stmt_seq *body;
+ string type_comment;
+ } With;
+
+ struct {
+ asdl_withitem_seq *items;
+ asdl_stmt_seq *body;
+ string type_comment;
+ } AsyncWith;
+
+ struct {
+ expr_ty subject;
+ asdl_match_case_seq *cases;
+ } Match;
+
+ struct {
+ expr_ty exc;
+ expr_ty cause;
+ } Raise;
+
+ struct {
+ asdl_stmt_seq *body;
+ asdl_excepthandler_seq *handlers;
+ asdl_stmt_seq *orelse;
+ asdl_stmt_seq *finalbody;
+ } Try;
+
+ struct {
+ asdl_stmt_seq *body;
+ asdl_excepthandler_seq *handlers;
+ asdl_stmt_seq *orelse;
+ asdl_stmt_seq *finalbody;
+ } TryStar;
+
+ struct {
+ expr_ty test;
+ expr_ty msg;
+ } Assert;
+
+ struct {
+ asdl_alias_seq *names;
+ } Import;
+
+ struct {
+ identifier module;
+ asdl_alias_seq *names;
+ int level;
+ } ImportFrom;
+
+ struct {
+ asdl_identifier_seq *names;
+ } Global;
+
+ struct {
+ asdl_identifier_seq *names;
+ } Nonlocal;
+
+ struct {
+ expr_ty value;
+ } Expr;
+
+ } v;
+ int lineno;
+ int col_offset;
+ int end_lineno;
+ int end_col_offset;
+};
+
+enum _expr_kind {BoolOp_kind=1, NamedExpr_kind=2, BinOp_kind=3, UnaryOp_kind=4,
+ Lambda_kind=5, IfExp_kind=6, Dict_kind=7, Set_kind=8,
+ ListComp_kind=9, SetComp_kind=10, DictComp_kind=11,
+ GeneratorExp_kind=12, Await_kind=13, Yield_kind=14,
+ YieldFrom_kind=15, Compare_kind=16, Call_kind=17,
+ FormattedValue_kind=18, JoinedStr_kind=19, Constant_kind=20,
+ Attribute_kind=21, Subscript_kind=22, Starred_kind=23,
+ Name_kind=24, List_kind=25, Tuple_kind=26, Slice_kind=27};
+struct _expr {
+ enum _expr_kind kind;
+ union {
+ struct {
+ boolop_ty op;
+ asdl_expr_seq *values;
+ } BoolOp;
+
+ struct {
+ expr_ty target;
+ expr_ty value;
+ } NamedExpr;
+
+ struct {
+ expr_ty left;
+ operator_ty op;
+ expr_ty right;
+ } BinOp;
+
+ struct {
+ unaryop_ty op;
+ expr_ty operand;
+ } UnaryOp;
+
+ struct {
+ arguments_ty args;
+ expr_ty body;
+ } Lambda;
+
+ struct {
+ expr_ty test;
+ expr_ty body;
+ expr_ty orelse;
+ } IfExp;
+
+ struct {
+ asdl_expr_seq *keys;
+ asdl_expr_seq *values;
+ } Dict;
+
+ struct {
+ asdl_expr_seq *elts;
+ } Set;
+
+ struct {
+ expr_ty elt;
+ asdl_comprehension_seq *generators;
+ } ListComp;
+
+ struct {
+ expr_ty elt;
+ asdl_comprehension_seq *generators;
+ } SetComp;
+
+ struct {
+ expr_ty key;
+ expr_ty value;
+ asdl_comprehension_seq *generators;
+ } DictComp;
+
+ struct {
+ expr_ty elt;
+ asdl_comprehension_seq *generators;
+ } GeneratorExp;
+
+ struct {
+ expr_ty value;
+ } Await;
+
+ struct {
+ expr_ty value;
+ } Yield;
+
+ struct {
+ expr_ty value;
+ } YieldFrom;
+
+ struct {
+ expr_ty left;
+ asdl_int_seq *ops;
+ asdl_expr_seq *comparators;
+ } Compare;
+
+ struct {
+ expr_ty func;
+ asdl_expr_seq *args;
+ asdl_keyword_seq *keywords;
+ } Call;
+
+ struct {
+ expr_ty value;
+ int conversion;
+ expr_ty format_spec;
+ } FormattedValue;
+
+ struct {
+ asdl_expr_seq *values;
+ } JoinedStr;
+
+ struct {
+ constant value;
+ string kind;
+ } Constant;
+
+ struct {
+ expr_ty value;
+ identifier attr;
+ expr_context_ty ctx;
+ } Attribute;
+
+ struct {
+ expr_ty value;
+ expr_ty slice;
+ expr_context_ty ctx;
+ } Subscript;
+
+ struct {
+ expr_ty value;
+ expr_context_ty ctx;
+ } Starred;
+
+ struct {
+ identifier id;
+ expr_context_ty ctx;
+ } Name;
+
+ struct {
+ asdl_expr_seq *elts;
+ expr_context_ty ctx;
+ } List;
+
+ struct {
+ asdl_expr_seq *elts;
+ expr_context_ty ctx;
+ } Tuple;
+
+ struct {
+ expr_ty lower;
+ expr_ty upper;
+ expr_ty step;
+ } Slice;
+
+ } v;
+ int lineno;
+ int col_offset;
+ int end_lineno;
+ int end_col_offset;
+};
+
+struct _comprehension {
+ expr_ty target;
+ expr_ty iter;
+ asdl_expr_seq *ifs;
+ int is_async;
+};
+
+enum _excepthandler_kind {ExceptHandler_kind=1};
+struct _excepthandler {
+ enum _excepthandler_kind kind;
+ union {
+ struct {
+ expr_ty type;
+ identifier name;
+ asdl_stmt_seq *body;
+ } ExceptHandler;
+
+ } v;
+ int lineno;
+ int col_offset;
+ int end_lineno;
+ int end_col_offset;
+};
+
+struct _arguments {
+ asdl_arg_seq *posonlyargs;
+ asdl_arg_seq *args;
+ arg_ty vararg;
+ asdl_arg_seq *kwonlyargs;
+ asdl_expr_seq *kw_defaults;
+ arg_ty kwarg;
+ asdl_expr_seq *defaults;
+};
+
+struct _arg {
+ identifier arg;
+ expr_ty annotation;
+ string type_comment;
+ int lineno;
+ int col_offset;
+ int end_lineno;
+ int end_col_offset;
+};
+
+struct _keyword {
+ identifier arg;
+ expr_ty value;
+ int lineno;
+ int col_offset;
+ int end_lineno;
+ int end_col_offset;
+};
+
+struct _alias {
+ identifier name;
+ identifier asname;
+ int lineno;
+ int col_offset;
+ int end_lineno;
+ int end_col_offset;
+};
+
+struct _withitem {
+ expr_ty context_expr;
+ expr_ty optional_vars;
+};
+
+struct _match_case {
+ pattern_ty pattern;
+ expr_ty guard;
+ asdl_stmt_seq *body;
+};
+
+enum _pattern_kind {MatchValue_kind=1, MatchSingleton_kind=2,
+ MatchSequence_kind=3, MatchMapping_kind=4,
+ MatchClass_kind=5, MatchStar_kind=6, MatchAs_kind=7,
+ MatchOr_kind=8};
+struct _pattern {
+ enum _pattern_kind kind;
+ union {
+ struct {
+ expr_ty value;
+ } MatchValue;
+
+ struct {
+ constant value;
+ } MatchSingleton;
+
+ struct {
+ asdl_pattern_seq *patterns;
+ } MatchSequence;
+
+ struct {
+ asdl_expr_seq *keys;
+ asdl_pattern_seq *patterns;
+ identifier rest;
+ } MatchMapping;
+
+ struct {
+ expr_ty cls;
+ asdl_pattern_seq *patterns;
+ asdl_identifier_seq *kwd_attrs;
+ asdl_pattern_seq *kwd_patterns;
+ } MatchClass;
+
+ struct {
+ identifier name;
+ } MatchStar;
+
+ struct {
+ pattern_ty pattern;
+ identifier name;
+ } MatchAs;
+
+ struct {
+ asdl_pattern_seq *patterns;
+ } MatchOr;
+
+ } v;
+ int lineno;
+ int col_offset;
+ int end_lineno;
+ int end_col_offset;
+};
+
+enum _type_ignore_kind {TypeIgnore_kind=1};
+struct _type_ignore {
+ enum _type_ignore_kind kind;
+ union {
+ struct {
+ int lineno;
+ string tag;
+ } TypeIgnore;
+
+ } v;
+};
+
+
+// Note: these macros affect function definitions, not only call sites.
+mod_ty _PyAST_Module(asdl_stmt_seq * body, asdl_type_ignore_seq * type_ignores,
+ PyArena *arena);
+mod_ty _PyAST_Interactive(asdl_stmt_seq * body, PyArena *arena);
+mod_ty _PyAST_Expression(expr_ty body, PyArena *arena);
+mod_ty _PyAST_FunctionType(asdl_expr_seq * argtypes, expr_ty returns, PyArena
+ *arena);
+stmt_ty _PyAST_FunctionDef(identifier name, arguments_ty args, asdl_stmt_seq *
+ body, asdl_expr_seq * decorator_list, expr_ty
+ returns, string type_comment, int lineno, int
+ col_offset, int end_lineno, int end_col_offset,
+ PyArena *arena);
+stmt_ty _PyAST_AsyncFunctionDef(identifier name, arguments_ty args,
+ asdl_stmt_seq * body, asdl_expr_seq *
+ decorator_list, expr_ty returns, string
+ type_comment, int lineno, int col_offset, int
+ end_lineno, int end_col_offset, PyArena *arena);
+stmt_ty _PyAST_ClassDef(identifier name, asdl_expr_seq * bases,
+ asdl_keyword_seq * keywords, asdl_stmt_seq * body,
+ asdl_expr_seq * decorator_list, int lineno, int
+ col_offset, int end_lineno, int end_col_offset, PyArena
+ *arena);
+stmt_ty _PyAST_Return(expr_ty value, int lineno, int col_offset, int
+ end_lineno, int end_col_offset, PyArena *arena);
+stmt_ty _PyAST_Delete(asdl_expr_seq * targets, int lineno, int col_offset, int
+ end_lineno, int end_col_offset, PyArena *arena);
+stmt_ty _PyAST_Assign(asdl_expr_seq * targets, expr_ty value, string
+ type_comment, int lineno, int col_offset, int end_lineno,
+ int end_col_offset, PyArena *arena);
+stmt_ty _PyAST_AugAssign(expr_ty target, operator_ty op, expr_ty value, int
+ lineno, int col_offset, int end_lineno, int
+ end_col_offset, PyArena *arena);
+stmt_ty _PyAST_AnnAssign(expr_ty target, expr_ty annotation, expr_ty value, int
+ simple, int lineno, int col_offset, int end_lineno,
+ int end_col_offset, PyArena *arena);
+stmt_ty _PyAST_For(expr_ty target, expr_ty iter, asdl_stmt_seq * body,
+ asdl_stmt_seq * orelse, string type_comment, int lineno, int
+ col_offset, int end_lineno, int end_col_offset, PyArena
+ *arena);
+stmt_ty _PyAST_AsyncFor(expr_ty target, expr_ty iter, asdl_stmt_seq * body,
+ asdl_stmt_seq * orelse, string type_comment, int
+ lineno, int col_offset, int end_lineno, int
+ end_col_offset, PyArena *arena);
+stmt_ty _PyAST_While(expr_ty test, asdl_stmt_seq * body, asdl_stmt_seq *
+ orelse, int lineno, int col_offset, int end_lineno, int
+ end_col_offset, PyArena *arena);
+stmt_ty _PyAST_If(expr_ty test, asdl_stmt_seq * body, asdl_stmt_seq * orelse,
+ int lineno, int col_offset, int end_lineno, int
+ end_col_offset, PyArena *arena);
+stmt_ty _PyAST_With(asdl_withitem_seq * items, asdl_stmt_seq * body, string
+ type_comment, int lineno, int col_offset, int end_lineno,
+ int end_col_offset, PyArena *arena);
+stmt_ty _PyAST_AsyncWith(asdl_withitem_seq * items, asdl_stmt_seq * body,
+ string type_comment, int lineno, int col_offset, int
+ end_lineno, int end_col_offset, PyArena *arena);
+stmt_ty _PyAST_Match(expr_ty subject, asdl_match_case_seq * cases, int lineno,
+ int col_offset, int end_lineno, int end_col_offset,
+ PyArena *arena);
+stmt_ty _PyAST_Raise(expr_ty exc, expr_ty cause, int lineno, int col_offset,
+ int end_lineno, int end_col_offset, PyArena *arena);
+stmt_ty _PyAST_Try(asdl_stmt_seq * body, asdl_excepthandler_seq * handlers,
+ asdl_stmt_seq * orelse, asdl_stmt_seq * finalbody, int
+ lineno, int col_offset, int end_lineno, int end_col_offset,
+ PyArena *arena);
+stmt_ty _PyAST_TryStar(asdl_stmt_seq * body, asdl_excepthandler_seq * handlers,
+ asdl_stmt_seq * orelse, asdl_stmt_seq * finalbody, int
+ lineno, int col_offset, int end_lineno, int
+ end_col_offset, PyArena *arena);
+stmt_ty _PyAST_Assert(expr_ty test, expr_ty msg, int lineno, int col_offset,
+ int end_lineno, int end_col_offset, PyArena *arena);
+stmt_ty _PyAST_Import(asdl_alias_seq * names, int lineno, int col_offset, int
+ end_lineno, int end_col_offset, PyArena *arena);
+stmt_ty _PyAST_ImportFrom(identifier module, asdl_alias_seq * names, int level,
+ int lineno, int col_offset, int end_lineno, int
+ end_col_offset, PyArena *arena);
+stmt_ty _PyAST_Global(asdl_identifier_seq * names, int lineno, int col_offset,
+ int end_lineno, int end_col_offset, PyArena *arena);
+stmt_ty _PyAST_Nonlocal(asdl_identifier_seq * names, int lineno, int
+ col_offset, int end_lineno, int end_col_offset, PyArena
+ *arena);
+stmt_ty _PyAST_Expr(expr_ty value, int lineno, int col_offset, int end_lineno,
+ int end_col_offset, PyArena *arena);
+stmt_ty _PyAST_Pass(int lineno, int col_offset, int end_lineno, int
+ end_col_offset, PyArena *arena);
+stmt_ty _PyAST_Break(int lineno, int col_offset, int end_lineno, int
+ end_col_offset, PyArena *arena);
+stmt_ty _PyAST_Continue(int lineno, int col_offset, int end_lineno, int
+ end_col_offset, PyArena *arena);
+expr_ty _PyAST_BoolOp(boolop_ty op, asdl_expr_seq * values, int lineno, int
+ col_offset, int end_lineno, int end_col_offset, PyArena
+ *arena);
+expr_ty _PyAST_NamedExpr(expr_ty target, expr_ty value, int lineno, int
+ col_offset, int end_lineno, int end_col_offset,
+ PyArena *arena);
+expr_ty _PyAST_BinOp(expr_ty left, operator_ty op, expr_ty right, int lineno,
+ int col_offset, int end_lineno, int end_col_offset,
+ PyArena *arena);
+expr_ty _PyAST_UnaryOp(unaryop_ty op, expr_ty operand, int lineno, int
+ col_offset, int end_lineno, int end_col_offset, PyArena
+ *arena);
+expr_ty _PyAST_Lambda(arguments_ty args, expr_ty body, int lineno, int
+ col_offset, int end_lineno, int end_col_offset, PyArena
+ *arena);
+expr_ty _PyAST_IfExp(expr_ty test, expr_ty body, expr_ty orelse, int lineno,
+ int col_offset, int end_lineno, int end_col_offset,
+ PyArena *arena);
+expr_ty _PyAST_Dict(asdl_expr_seq * keys, asdl_expr_seq * values, int lineno,
+ int col_offset, int end_lineno, int end_col_offset, PyArena
+ *arena);
+expr_ty _PyAST_Set(asdl_expr_seq * elts, int lineno, int col_offset, int
+ end_lineno, int end_col_offset, PyArena *arena);
+expr_ty _PyAST_ListComp(expr_ty elt, asdl_comprehension_seq * generators, int
+ lineno, int col_offset, int end_lineno, int
+ end_col_offset, PyArena *arena);
+expr_ty _PyAST_SetComp(expr_ty elt, asdl_comprehension_seq * generators, int
+ lineno, int col_offset, int end_lineno, int
+ end_col_offset, PyArena *arena);
+expr_ty _PyAST_DictComp(expr_ty key, expr_ty value, asdl_comprehension_seq *
+ generators, int lineno, int col_offset, int end_lineno,
+ int end_col_offset, PyArena *arena);
+expr_ty _PyAST_GeneratorExp(expr_ty elt, asdl_comprehension_seq * generators,
+ int lineno, int col_offset, int end_lineno, int
+ end_col_offset, PyArena *arena);
+expr_ty _PyAST_Await(expr_ty value, int lineno, int col_offset, int end_lineno,
+ int end_col_offset, PyArena *arena);
+expr_ty _PyAST_Yield(expr_ty value, int lineno, int col_offset, int end_lineno,
+ int end_col_offset, PyArena *arena);
+expr_ty _PyAST_YieldFrom(expr_ty value, int lineno, int col_offset, int
+ end_lineno, int end_col_offset, PyArena *arena);
+expr_ty _PyAST_Compare(expr_ty left, asdl_int_seq * ops, asdl_expr_seq *
+ comparators, int lineno, int col_offset, int end_lineno,
+ int end_col_offset, PyArena *arena);
+expr_ty _PyAST_Call(expr_ty func, asdl_expr_seq * args, asdl_keyword_seq *
+ keywords, int lineno, int col_offset, int end_lineno, int
+ end_col_offset, PyArena *arena);
+expr_ty _PyAST_FormattedValue(expr_ty value, int conversion, expr_ty
+ format_spec, int lineno, int col_offset, int
+ end_lineno, int end_col_offset, PyArena *arena);
+expr_ty _PyAST_JoinedStr(asdl_expr_seq * values, int lineno, int col_offset,
+ int end_lineno, int end_col_offset, PyArena *arena);
+expr_ty _PyAST_Constant(constant value, string kind, int lineno, int
+ col_offset, int end_lineno, int end_col_offset, PyArena
+ *arena);
+expr_ty _PyAST_Attribute(expr_ty value, identifier attr, expr_context_ty ctx,
+ int lineno, int col_offset, int end_lineno, int
+ end_col_offset, PyArena *arena);
+expr_ty _PyAST_Subscript(expr_ty value, expr_ty slice, expr_context_ty ctx, int
+ lineno, int col_offset, int end_lineno, int
+ end_col_offset, PyArena *arena);
+expr_ty _PyAST_Starred(expr_ty value, expr_context_ty ctx, int lineno, int
+ col_offset, int end_lineno, int end_col_offset, PyArena
+ *arena);
+expr_ty _PyAST_Name(identifier id, expr_context_ty ctx, int lineno, int
+ col_offset, int end_lineno, int end_col_offset, PyArena
+ *arena);
+expr_ty _PyAST_List(asdl_expr_seq * elts, expr_context_ty ctx, int lineno, int
+ col_offset, int end_lineno, int end_col_offset, PyArena
+ *arena);
+expr_ty _PyAST_Tuple(asdl_expr_seq * elts, expr_context_ty ctx, int lineno, int
+ col_offset, int end_lineno, int end_col_offset, PyArena
+ *arena);
+expr_ty _PyAST_Slice(expr_ty lower, expr_ty upper, expr_ty step, int lineno,
+ int col_offset, int end_lineno, int end_col_offset,
+ PyArena *arena);
+comprehension_ty _PyAST_comprehension(expr_ty target, expr_ty iter,
+ asdl_expr_seq * ifs, int is_async,
+ PyArena *arena);
+excepthandler_ty _PyAST_ExceptHandler(expr_ty type, identifier name,
+ asdl_stmt_seq * body, int lineno, int
+ col_offset, int end_lineno, int
+ end_col_offset, PyArena *arena);
+arguments_ty _PyAST_arguments(asdl_arg_seq * posonlyargs, asdl_arg_seq * args,
+ arg_ty vararg, asdl_arg_seq * kwonlyargs,
+ asdl_expr_seq * kw_defaults, arg_ty kwarg,
+ asdl_expr_seq * defaults, PyArena *arena);
+arg_ty _PyAST_arg(identifier arg, expr_ty annotation, string type_comment, int
+ lineno, int col_offset, int end_lineno, int end_col_offset,
+ PyArena *arena);
+keyword_ty _PyAST_keyword(identifier arg, expr_ty value, int lineno, int
+ col_offset, int end_lineno, int end_col_offset,
+ PyArena *arena);
+alias_ty _PyAST_alias(identifier name, identifier asname, int lineno, int
+ col_offset, int end_lineno, int end_col_offset, PyArena
+ *arena);
+withitem_ty _PyAST_withitem(expr_ty context_expr, expr_ty optional_vars,
+ PyArena *arena);
+match_case_ty _PyAST_match_case(pattern_ty pattern, expr_ty guard,
+ asdl_stmt_seq * body, PyArena *arena);
+pattern_ty _PyAST_MatchValue(expr_ty value, int lineno, int col_offset, int
+ end_lineno, int end_col_offset, PyArena *arena);
+pattern_ty _PyAST_MatchSingleton(constant value, int lineno, int col_offset,
+ int end_lineno, int end_col_offset, PyArena
+ *arena);
+pattern_ty _PyAST_MatchSequence(asdl_pattern_seq * patterns, int lineno, int
+ col_offset, int end_lineno, int end_col_offset,
+ PyArena *arena);
+pattern_ty _PyAST_MatchMapping(asdl_expr_seq * keys, asdl_pattern_seq *
+ patterns, identifier rest, int lineno, int
+ col_offset, int end_lineno, int end_col_offset,
+ PyArena *arena);
+pattern_ty _PyAST_MatchClass(expr_ty cls, asdl_pattern_seq * patterns,
+ asdl_identifier_seq * kwd_attrs, asdl_pattern_seq
+ * kwd_patterns, int lineno, int col_offset, int
+ end_lineno, int end_col_offset, PyArena *arena);
+pattern_ty _PyAST_MatchStar(identifier name, int lineno, int col_offset, int
+ end_lineno, int end_col_offset, PyArena *arena);
+pattern_ty _PyAST_MatchAs(pattern_ty pattern, identifier name, int lineno, int
+ col_offset, int end_lineno, int end_col_offset,
+ PyArena *arena);
+pattern_ty _PyAST_MatchOr(asdl_pattern_seq * patterns, int lineno, int
+ col_offset, int end_lineno, int end_col_offset,
+ PyArena *arena);
+type_ignore_ty _PyAST_TypeIgnore(int lineno, string tag, PyArena *arena);
+
+
+PyObject* PyAST_mod2obj(mod_ty t);
+mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode);
+int PyAST_Check(PyObject* obj);
+
+extern int _PyAST_Validate(mod_ty);
+
+/* _PyAST_ExprAsUnicode is defined in ast_unparse.c */
+extern PyObject* _PyAST_ExprAsUnicode(expr_ty);
+
+/* Return the borrowed reference to the first literal string in the
+ sequence of statements or NULL if it doesn't start from a literal string.
+ Doesn't set exception. */
+extern PyObject* _PyAST_GetDocString(asdl_stmt_seq *);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_AST_H */
diff --git a/include/python3.11/internal/pycore_ast_state.h b/include/python3.11/internal/pycore_ast_state.h
new file mode 100644
index 0000000..f15b490
--- /dev/null
+++ b/include/python3.11/internal/pycore_ast_state.h
@@ -0,0 +1,258 @@
+// File automatically generated by Parser/asdl_c.py.
+
+#ifndef Py_INTERNAL_AST_STATE_H
+#define Py_INTERNAL_AST_STATE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+struct ast_state {
+ int initialized;
+ int recursion_depth;
+ int recursion_limit;
+ PyObject *AST_type;
+ PyObject *Add_singleton;
+ PyObject *Add_type;
+ PyObject *And_singleton;
+ PyObject *And_type;
+ PyObject *AnnAssign_type;
+ PyObject *Assert_type;
+ PyObject *Assign_type;
+ PyObject *AsyncFor_type;
+ PyObject *AsyncFunctionDef_type;
+ PyObject *AsyncWith_type;
+ PyObject *Attribute_type;
+ PyObject *AugAssign_type;
+ PyObject *Await_type;
+ PyObject *BinOp_type;
+ PyObject *BitAnd_singleton;
+ PyObject *BitAnd_type;
+ PyObject *BitOr_singleton;
+ PyObject *BitOr_type;
+ PyObject *BitXor_singleton;
+ PyObject *BitXor_type;
+ PyObject *BoolOp_type;
+ PyObject *Break_type;
+ PyObject *Call_type;
+ PyObject *ClassDef_type;
+ PyObject *Compare_type;
+ PyObject *Constant_type;
+ PyObject *Continue_type;
+ PyObject *Del_singleton;
+ PyObject *Del_type;
+ PyObject *Delete_type;
+ PyObject *DictComp_type;
+ PyObject *Dict_type;
+ PyObject *Div_singleton;
+ PyObject *Div_type;
+ PyObject *Eq_singleton;
+ PyObject *Eq_type;
+ PyObject *ExceptHandler_type;
+ PyObject *Expr_type;
+ PyObject *Expression_type;
+ PyObject *FloorDiv_singleton;
+ PyObject *FloorDiv_type;
+ PyObject *For_type;
+ PyObject *FormattedValue_type;
+ PyObject *FunctionDef_type;
+ PyObject *FunctionType_type;
+ PyObject *GeneratorExp_type;
+ PyObject *Global_type;
+ PyObject *GtE_singleton;
+ PyObject *GtE_type;
+ PyObject *Gt_singleton;
+ PyObject *Gt_type;
+ PyObject *IfExp_type;
+ PyObject *If_type;
+ PyObject *ImportFrom_type;
+ PyObject *Import_type;
+ PyObject *In_singleton;
+ PyObject *In_type;
+ PyObject *Interactive_type;
+ PyObject *Invert_singleton;
+ PyObject *Invert_type;
+ PyObject *IsNot_singleton;
+ PyObject *IsNot_type;
+ PyObject *Is_singleton;
+ PyObject *Is_type;
+ PyObject *JoinedStr_type;
+ PyObject *LShift_singleton;
+ PyObject *LShift_type;
+ PyObject *Lambda_type;
+ PyObject *ListComp_type;
+ PyObject *List_type;
+ PyObject *Load_singleton;
+ PyObject *Load_type;
+ PyObject *LtE_singleton;
+ PyObject *LtE_type;
+ PyObject *Lt_singleton;
+ PyObject *Lt_type;
+ PyObject *MatMult_singleton;
+ PyObject *MatMult_type;
+ PyObject *MatchAs_type;
+ PyObject *MatchClass_type;
+ PyObject *MatchMapping_type;
+ PyObject *MatchOr_type;
+ PyObject *MatchSequence_type;
+ PyObject *MatchSingleton_type;
+ PyObject *MatchStar_type;
+ PyObject *MatchValue_type;
+ PyObject *Match_type;
+ PyObject *Mod_singleton;
+ PyObject *Mod_type;
+ PyObject *Module_type;
+ PyObject *Mult_singleton;
+ PyObject *Mult_type;
+ PyObject *Name_type;
+ PyObject *NamedExpr_type;
+ PyObject *Nonlocal_type;
+ PyObject *NotEq_singleton;
+ PyObject *NotEq_type;
+ PyObject *NotIn_singleton;
+ PyObject *NotIn_type;
+ PyObject *Not_singleton;
+ PyObject *Not_type;
+ PyObject *Or_singleton;
+ PyObject *Or_type;
+ PyObject *Pass_type;
+ PyObject *Pow_singleton;
+ PyObject *Pow_type;
+ PyObject *RShift_singleton;
+ PyObject *RShift_type;
+ PyObject *Raise_type;
+ PyObject *Return_type;
+ PyObject *SetComp_type;
+ PyObject *Set_type;
+ PyObject *Slice_type;
+ PyObject *Starred_type;
+ PyObject *Store_singleton;
+ PyObject *Store_type;
+ PyObject *Sub_singleton;
+ PyObject *Sub_type;
+ PyObject *Subscript_type;
+ PyObject *TryStar_type;
+ PyObject *Try_type;
+ PyObject *Tuple_type;
+ PyObject *TypeIgnore_type;
+ PyObject *UAdd_singleton;
+ PyObject *UAdd_type;
+ PyObject *USub_singleton;
+ PyObject *USub_type;
+ PyObject *UnaryOp_type;
+ PyObject *While_type;
+ PyObject *With_type;
+ PyObject *YieldFrom_type;
+ PyObject *Yield_type;
+ PyObject *__dict__;
+ PyObject *__doc__;
+ PyObject *__match_args__;
+ PyObject *__module__;
+ PyObject *_attributes;
+ PyObject *_fields;
+ PyObject *alias_type;
+ PyObject *annotation;
+ PyObject *arg;
+ PyObject *arg_type;
+ PyObject *args;
+ PyObject *argtypes;
+ PyObject *arguments_type;
+ PyObject *asname;
+ PyObject *ast;
+ PyObject *attr;
+ PyObject *bases;
+ PyObject *body;
+ PyObject *boolop_type;
+ PyObject *cases;
+ PyObject *cause;
+ PyObject *cls;
+ PyObject *cmpop_type;
+ PyObject *col_offset;
+ PyObject *comparators;
+ PyObject *comprehension_type;
+ PyObject *context_expr;
+ PyObject *conversion;
+ PyObject *ctx;
+ PyObject *decorator_list;
+ PyObject *defaults;
+ PyObject *elt;
+ PyObject *elts;
+ PyObject *end_col_offset;
+ PyObject *end_lineno;
+ PyObject *exc;
+ PyObject *excepthandler_type;
+ PyObject *expr_context_type;
+ PyObject *expr_type;
+ PyObject *finalbody;
+ PyObject *format_spec;
+ PyObject *func;
+ PyObject *generators;
+ PyObject *guard;
+ PyObject *handlers;
+ PyObject *id;
+ PyObject *ifs;
+ PyObject *is_async;
+ PyObject *items;
+ PyObject *iter;
+ PyObject *key;
+ PyObject *keys;
+ PyObject *keyword_type;
+ PyObject *keywords;
+ PyObject *kind;
+ PyObject *kw_defaults;
+ PyObject *kwarg;
+ PyObject *kwd_attrs;
+ PyObject *kwd_patterns;
+ PyObject *kwonlyargs;
+ PyObject *left;
+ PyObject *level;
+ PyObject *lineno;
+ PyObject *lower;
+ PyObject *match_case_type;
+ PyObject *mod_type;
+ PyObject *module;
+ PyObject *msg;
+ PyObject *name;
+ PyObject *names;
+ PyObject *op;
+ PyObject *operand;
+ PyObject *operator_type;
+ PyObject *ops;
+ PyObject *optional_vars;
+ PyObject *orelse;
+ PyObject *pattern;
+ PyObject *pattern_type;
+ PyObject *patterns;
+ PyObject *posonlyargs;
+ PyObject *rest;
+ PyObject *returns;
+ PyObject *right;
+ PyObject *simple;
+ PyObject *slice;
+ PyObject *step;
+ PyObject *stmt_type;
+ PyObject *subject;
+ PyObject *tag;
+ PyObject *target;
+ PyObject *targets;
+ PyObject *test;
+ PyObject *type;
+ PyObject *type_comment;
+ PyObject *type_ignore_type;
+ PyObject *type_ignores;
+ PyObject *unaryop_type;
+ PyObject *upper;
+ PyObject *value;
+ PyObject *values;
+ PyObject *vararg;
+ PyObject *withitem_type;
+};
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_AST_STATE_H */
+
diff --git a/include/python3.11/internal/pycore_atomic.h b/include/python3.11/internal/pycore_atomic.h
new file mode 100644
index 0000000..425d69f
--- /dev/null
+++ b/include/python3.11/internal/pycore_atomic.h
@@ -0,0 +1,557 @@
+#ifndef Py_ATOMIC_H
+#define Py_ATOMIC_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#include "dynamic_annotations.h" /* _Py_ANNOTATE_MEMORY_ORDER */
+#include "pyconfig.h"
+
+#ifdef HAVE_STD_ATOMIC
+# include <stdatomic.h>
+#endif
+
+
+#if defined(_MSC_VER)
+#include <intrin.h>
+#if defined(_M_IX86) || defined(_M_X64)
+# include <immintrin.h>
+#endif
+#endif
+
+/* This is modeled after the atomics interface from C1x, according to
+ * the draft at
+ * http://www.open-std.org/JTC1/SC22/wg14/www/docs/n1425.pdf.
+ * Operations and types are named the same except with a _Py_ prefix
+ * and have the same semantics.
+ *
+ * Beware, the implementations here are deep magic.
+ */
+
+#if defined(HAVE_STD_ATOMIC)
+
+typedef enum _Py_memory_order {
+ _Py_memory_order_relaxed = memory_order_relaxed,
+ _Py_memory_order_acquire = memory_order_acquire,
+ _Py_memory_order_release = memory_order_release,
+ _Py_memory_order_acq_rel = memory_order_acq_rel,
+ _Py_memory_order_seq_cst = memory_order_seq_cst
+} _Py_memory_order;
+
+typedef struct _Py_atomic_address {
+ atomic_uintptr_t _value;
+} _Py_atomic_address;
+
+typedef struct _Py_atomic_int {
+ atomic_int _value;
+} _Py_atomic_int;
+
+#define _Py_atomic_signal_fence(/*memory_order*/ ORDER) \
+ atomic_signal_fence(ORDER)
+
+#define _Py_atomic_thread_fence(/*memory_order*/ ORDER) \
+ atomic_thread_fence(ORDER)
+
+#define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \
+ atomic_store_explicit(&((ATOMIC_VAL)->_value), NEW_VAL, ORDER)
+
+#define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \
+ atomic_load_explicit(&((ATOMIC_VAL)->_value), ORDER)
+
+// Use builtin atomic operations in GCC >= 4.7 and clang
+#elif defined(HAVE_BUILTIN_ATOMIC)
+
+typedef enum _Py_memory_order {
+ _Py_memory_order_relaxed = __ATOMIC_RELAXED,
+ _Py_memory_order_acquire = __ATOMIC_ACQUIRE,
+ _Py_memory_order_release = __ATOMIC_RELEASE,
+ _Py_memory_order_acq_rel = __ATOMIC_ACQ_REL,
+ _Py_memory_order_seq_cst = __ATOMIC_SEQ_CST
+} _Py_memory_order;
+
+typedef struct _Py_atomic_address {
+ uintptr_t _value;
+} _Py_atomic_address;
+
+typedef struct _Py_atomic_int {
+ int _value;
+} _Py_atomic_int;
+
+#define _Py_atomic_signal_fence(/*memory_order*/ ORDER) \
+ __atomic_signal_fence(ORDER)
+
+#define _Py_atomic_thread_fence(/*memory_order*/ ORDER) \
+ __atomic_thread_fence(ORDER)
+
+#define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \
+ (assert((ORDER) == __ATOMIC_RELAXED \
+ || (ORDER) == __ATOMIC_SEQ_CST \
+ || (ORDER) == __ATOMIC_RELEASE), \
+ __atomic_store_n(&((ATOMIC_VAL)->_value), NEW_VAL, ORDER))
+
+#define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \
+ (assert((ORDER) == __ATOMIC_RELAXED \
+ || (ORDER) == __ATOMIC_SEQ_CST \
+ || (ORDER) == __ATOMIC_ACQUIRE \
+ || (ORDER) == __ATOMIC_CONSUME), \
+ __atomic_load_n(&((ATOMIC_VAL)->_value), ORDER))
+
+/* Only support GCC (for expression statements) and x86 (for simple
+ * atomic semantics) and MSVC x86/x64/ARM */
+#elif defined(__GNUC__) && (defined(__i386__) || defined(__amd64))
+typedef enum _Py_memory_order {
+ _Py_memory_order_relaxed,
+ _Py_memory_order_acquire,
+ _Py_memory_order_release,
+ _Py_memory_order_acq_rel,
+ _Py_memory_order_seq_cst
+} _Py_memory_order;
+
+typedef struct _Py_atomic_address {
+ uintptr_t _value;
+} _Py_atomic_address;
+
+typedef struct _Py_atomic_int {
+ int _value;
+} _Py_atomic_int;
+
+
+static __inline__ void
+_Py_atomic_signal_fence(_Py_memory_order order)
+{
+ if (order != _Py_memory_order_relaxed)
+ __asm__ volatile("":::"memory");
+}
+
+static __inline__ void
+_Py_atomic_thread_fence(_Py_memory_order order)
+{
+ if (order != _Py_memory_order_relaxed)
+ __asm__ volatile("mfence":::"memory");
+}
+
+/* Tell the race checker about this operation's effects. */
+static __inline__ void
+_Py_ANNOTATE_MEMORY_ORDER(const volatile void *address, _Py_memory_order order)
+{
+ (void)address; /* shut up -Wunused-parameter */
+ switch(order) {
+ case _Py_memory_order_release:
+ case _Py_memory_order_acq_rel:
+ case _Py_memory_order_seq_cst:
+ _Py_ANNOTATE_HAPPENS_BEFORE(address);
+ break;
+ case _Py_memory_order_relaxed:
+ case _Py_memory_order_acquire:
+ break;
+ }
+ switch(order) {
+ case _Py_memory_order_acquire:
+ case _Py_memory_order_acq_rel:
+ case _Py_memory_order_seq_cst:
+ _Py_ANNOTATE_HAPPENS_AFTER(address);
+ break;
+ case _Py_memory_order_relaxed:
+ case _Py_memory_order_release:
+ break;
+ }
+}
+
+#define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \
+ __extension__ ({ \
+ __typeof__(ATOMIC_VAL) atomic_val = ATOMIC_VAL; \
+ __typeof__(atomic_val->_value) new_val = NEW_VAL;\
+ volatile __typeof__(new_val) *volatile_data = &atomic_val->_value; \
+ _Py_memory_order order = ORDER; \
+ _Py_ANNOTATE_MEMORY_ORDER(atomic_val, order); \
+ \
+ /* Perform the operation. */ \
+ _Py_ANNOTATE_IGNORE_WRITES_BEGIN(); \
+ switch(order) { \
+ case _Py_memory_order_release: \
+ _Py_atomic_signal_fence(_Py_memory_order_release); \
+ /* fallthrough */ \
+ case _Py_memory_order_relaxed: \
+ *volatile_data = new_val; \
+ break; \
+ \
+ case _Py_memory_order_acquire: \
+ case _Py_memory_order_acq_rel: \
+ case _Py_memory_order_seq_cst: \
+ __asm__ volatile("xchg %0, %1" \
+ : "+r"(new_val) \
+ : "m"(atomic_val->_value) \
+ : "memory"); \
+ break; \
+ } \
+ _Py_ANNOTATE_IGNORE_WRITES_END(); \
+ })
+
+#define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \
+ __extension__ ({ \
+ __typeof__(ATOMIC_VAL) atomic_val = ATOMIC_VAL; \
+ __typeof__(atomic_val->_value) result; \
+ volatile __typeof__(result) *volatile_data = &atomic_val->_value; \
+ _Py_memory_order order = ORDER; \
+ _Py_ANNOTATE_MEMORY_ORDER(atomic_val, order); \
+ \
+ /* Perform the operation. */ \
+ _Py_ANNOTATE_IGNORE_READS_BEGIN(); \
+ switch(order) { \
+ case _Py_memory_order_release: \
+ case _Py_memory_order_acq_rel: \
+ case _Py_memory_order_seq_cst: \
+ /* Loads on x86 are not releases by default, so need a */ \
+ /* thread fence. */ \
+ _Py_atomic_thread_fence(_Py_memory_order_release); \
+ break; \
+ default: \
+ /* No fence */ \
+ break; \
+ } \
+ result = *volatile_data; \
+ switch(order) { \
+ case _Py_memory_order_acquire: \
+ case _Py_memory_order_acq_rel: \
+ case _Py_memory_order_seq_cst: \
+ /* Loads on x86 are automatically acquire operations so */ \
+ /* can get by with just a compiler fence. */ \
+ _Py_atomic_signal_fence(_Py_memory_order_acquire); \
+ break; \
+ default: \
+ /* No fence */ \
+ break; \
+ } \
+ _Py_ANNOTATE_IGNORE_READS_END(); \
+ result; \
+ })
+
+#elif defined(_MSC_VER)
+/* _Interlocked* functions provide a full memory barrier and are therefore
+ enough for acq_rel and seq_cst. If the HLE variants aren't available
+ in hardware they will fall back to a full memory barrier as well.
+
+ This might affect performance but likely only in some very specific and
+ hard to measure scenario.
+*/
+#if defined(_M_IX86) || defined(_M_X64)
+typedef enum _Py_memory_order {
+ _Py_memory_order_relaxed,
+ _Py_memory_order_acquire,
+ _Py_memory_order_release,
+ _Py_memory_order_acq_rel,
+ _Py_memory_order_seq_cst
+} _Py_memory_order;
+
+typedef struct _Py_atomic_address {
+ volatile uintptr_t _value;
+} _Py_atomic_address;
+
+typedef struct _Py_atomic_int {
+ volatile int _value;
+} _Py_atomic_int;
+
+
+#if defined(_M_X64)
+#define _Py_atomic_store_64bit(ATOMIC_VAL, NEW_VAL, ORDER) \
+ switch (ORDER) { \
+ case _Py_memory_order_acquire: \
+ _InterlockedExchange64_HLEAcquire((__int64 volatile*)&((ATOMIC_VAL)->_value), (__int64)(NEW_VAL)); \
+ break; \
+ case _Py_memory_order_release: \
+ _InterlockedExchange64_HLERelease((__int64 volatile*)&((ATOMIC_VAL)->_value), (__int64)(NEW_VAL)); \
+ break; \
+ default: \
+ _InterlockedExchange64((__int64 volatile*)&((ATOMIC_VAL)->_value), (__int64)(NEW_VAL)); \
+ break; \
+ }
+#else
+#define _Py_atomic_store_64bit(ATOMIC_VAL, NEW_VAL, ORDER) ((void)0);
+#endif
+
+#define _Py_atomic_store_32bit(ATOMIC_VAL, NEW_VAL, ORDER) \
+ switch (ORDER) { \
+ case _Py_memory_order_acquire: \
+ _InterlockedExchange_HLEAcquire((volatile long*)&((ATOMIC_VAL)->_value), (int)(NEW_VAL)); \
+ break; \
+ case _Py_memory_order_release: \
+ _InterlockedExchange_HLERelease((volatile long*)&((ATOMIC_VAL)->_value), (int)(NEW_VAL)); \
+ break; \
+ default: \
+ _InterlockedExchange((volatile long*)&((ATOMIC_VAL)->_value), (int)(NEW_VAL)); \
+ break; \
+ }
+
+#if defined(_M_X64)
+/* This has to be an intptr_t for now.
+ gil_created() uses -1 as a sentinel value, if this returns
+ a uintptr_t it will do an unsigned compare and crash
+*/
+inline intptr_t _Py_atomic_load_64bit_impl(volatile uintptr_t* value, int order) {
+ __int64 old;
+ switch (order) {
+ case _Py_memory_order_acquire:
+ {
+ do {
+ old = *value;
+ } while(_InterlockedCompareExchange64_HLEAcquire((volatile __int64*)value, old, old) != old);
+ break;
+ }
+ case _Py_memory_order_release:
+ {
+ do {
+ old = *value;
+ } while(_InterlockedCompareExchange64_HLERelease((volatile __int64*)value, old, old) != old);
+ break;
+ }
+ case _Py_memory_order_relaxed:
+ old = *value;
+ break;
+ default:
+ {
+ do {
+ old = *value;
+ } while(_InterlockedCompareExchange64((volatile __int64*)value, old, old) != old);
+ break;
+ }
+ }
+ return old;
+}
+
+#define _Py_atomic_load_64bit(ATOMIC_VAL, ORDER) \
+ _Py_atomic_load_64bit_impl((volatile uintptr_t*)&((ATOMIC_VAL)->_value), (ORDER))
+
+#else
+#define _Py_atomic_load_64bit(ATOMIC_VAL, ORDER) ((ATOMIC_VAL)->_value)
+#endif
+
+inline int _Py_atomic_load_32bit_impl(volatile int* value, int order) {
+ long old;
+ switch (order) {
+ case _Py_memory_order_acquire:
+ {
+ do {
+ old = *value;
+ } while(_InterlockedCompareExchange_HLEAcquire((volatile long*)value, old, old) != old);
+ break;
+ }
+ case _Py_memory_order_release:
+ {
+ do {
+ old = *value;
+ } while(_InterlockedCompareExchange_HLERelease((volatile long*)value, old, old) != old);
+ break;
+ }
+ case _Py_memory_order_relaxed:
+ old = *value;
+ break;
+ default:
+ {
+ do {
+ old = *value;
+ } while(_InterlockedCompareExchange((volatile long*)value, old, old) != old);
+ break;
+ }
+ }
+ return old;
+}
+
+#define _Py_atomic_load_32bit(ATOMIC_VAL, ORDER) \
+ _Py_atomic_load_32bit_impl((volatile int*)&((ATOMIC_VAL)->_value), (ORDER))
+
+#define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \
+ if (sizeof((ATOMIC_VAL)->_value) == 8) { \
+ _Py_atomic_store_64bit((ATOMIC_VAL), NEW_VAL, ORDER) } else { \
+ _Py_atomic_store_32bit((ATOMIC_VAL), NEW_VAL, ORDER) }
+
+#define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \
+ ( \
+ sizeof((ATOMIC_VAL)->_value) == 8 ? \
+ _Py_atomic_load_64bit((ATOMIC_VAL), ORDER) : \
+ _Py_atomic_load_32bit((ATOMIC_VAL), ORDER) \
+ )
+#elif defined(_M_ARM) || defined(_M_ARM64)
+typedef enum _Py_memory_order {
+ _Py_memory_order_relaxed,
+ _Py_memory_order_acquire,
+ _Py_memory_order_release,
+ _Py_memory_order_acq_rel,
+ _Py_memory_order_seq_cst
+} _Py_memory_order;
+
+typedef struct _Py_atomic_address {
+ volatile uintptr_t _value;
+} _Py_atomic_address;
+
+typedef struct _Py_atomic_int {
+ volatile int _value;
+} _Py_atomic_int;
+
+
+#if defined(_M_ARM64)
+#define _Py_atomic_store_64bit(ATOMIC_VAL, NEW_VAL, ORDER) \
+ switch (ORDER) { \
+ case _Py_memory_order_acquire: \
+ _InterlockedExchange64_acq((__int64 volatile*)&((ATOMIC_VAL)->_value), (__int64)NEW_VAL); \
+ break; \
+ case _Py_memory_order_release: \
+ _InterlockedExchange64_rel((__int64 volatile*)&((ATOMIC_VAL)->_value), (__int64)NEW_VAL); \
+ break; \
+ default: \
+ _InterlockedExchange64((__int64 volatile*)&((ATOMIC_VAL)->_value), (__int64)NEW_VAL); \
+ break; \
+ }
+#else
+#define _Py_atomic_store_64bit(ATOMIC_VAL, NEW_VAL, ORDER) ((void)0);
+#endif
+
+#define _Py_atomic_store_32bit(ATOMIC_VAL, NEW_VAL, ORDER) \
+ switch (ORDER) { \
+ case _Py_memory_order_acquire: \
+ _InterlockedExchange_acq((volatile long*)&((ATOMIC_VAL)->_value), (int)NEW_VAL); \
+ break; \
+ case _Py_memory_order_release: \
+ _InterlockedExchange_rel((volatile long*)&((ATOMIC_VAL)->_value), (int)NEW_VAL); \
+ break; \
+ default: \
+ _InterlockedExchange((volatile long*)&((ATOMIC_VAL)->_value), (int)NEW_VAL); \
+ break; \
+ }
+
+#if defined(_M_ARM64)
+/* This has to be an intptr_t for now.
+ gil_created() uses -1 as a sentinel value, if this returns
+ a uintptr_t it will do an unsigned compare and crash
+*/
+inline intptr_t _Py_atomic_load_64bit_impl(volatile uintptr_t* value, int order) {
+ uintptr_t old;
+ switch (order) {
+ case _Py_memory_order_acquire:
+ {
+ do {
+ old = *value;
+ } while(_InterlockedCompareExchange64_acq(value, old, old) != old);
+ break;
+ }
+ case _Py_memory_order_release:
+ {
+ do {
+ old = *value;
+ } while(_InterlockedCompareExchange64_rel(value, old, old) != old);
+ break;
+ }
+ case _Py_memory_order_relaxed:
+ old = *value;
+ break;
+ default:
+ {
+ do {
+ old = *value;
+ } while(_InterlockedCompareExchange64(value, old, old) != old);
+ break;
+ }
+ }
+ return old;
+}
+
+#define _Py_atomic_load_64bit(ATOMIC_VAL, ORDER) \
+ _Py_atomic_load_64bit_impl((volatile uintptr_t*)&((ATOMIC_VAL)->_value), (ORDER))
+
+#else
+#define _Py_atomic_load_64bit(ATOMIC_VAL, ORDER) ((ATOMIC_VAL)->_value)
+#endif
+
+inline int _Py_atomic_load_32bit_impl(volatile int* value, int order) {
+ int old;
+ switch (order) {
+ case _Py_memory_order_acquire:
+ {
+ do {
+ old = *value;
+ } while(_InterlockedCompareExchange_acq(value, old, old) != old);
+ break;
+ }
+ case _Py_memory_order_release:
+ {
+ do {
+ old = *value;
+ } while(_InterlockedCompareExchange_rel(value, old, old) != old);
+ break;
+ }
+ case _Py_memory_order_relaxed:
+ old = *value;
+ break;
+ default:
+ {
+ do {
+ old = *value;
+ } while(_InterlockedCompareExchange(value, old, old) != old);
+ break;
+ }
+ }
+ return old;
+}
+
+#define _Py_atomic_load_32bit(ATOMIC_VAL, ORDER) \
+ _Py_atomic_load_32bit_impl((volatile int*)&((ATOMIC_VAL)->_value), (ORDER))
+
+#define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \
+ if (sizeof((ATOMIC_VAL)->_value) == 8) { \
+ _Py_atomic_store_64bit((ATOMIC_VAL), (NEW_VAL), (ORDER)) } else { \
+ _Py_atomic_store_32bit((ATOMIC_VAL), (NEW_VAL), (ORDER)) }
+
+#define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \
+ ( \
+ sizeof((ATOMIC_VAL)->_value) == 8 ? \
+ _Py_atomic_load_64bit((ATOMIC_VAL), (ORDER)) : \
+ _Py_atomic_load_32bit((ATOMIC_VAL), (ORDER)) \
+ )
+#endif
+#else /* !gcc x86 !_msc_ver */
+typedef enum _Py_memory_order {
+ _Py_memory_order_relaxed,
+ _Py_memory_order_acquire,
+ _Py_memory_order_release,
+ _Py_memory_order_acq_rel,
+ _Py_memory_order_seq_cst
+} _Py_memory_order;
+
+typedef struct _Py_atomic_address {
+ uintptr_t _value;
+} _Py_atomic_address;
+
+typedef struct _Py_atomic_int {
+ int _value;
+} _Py_atomic_int;
+/* Fall back to other compilers and processors by assuming that simple
+ volatile accesses are atomic. This is false, so people should port
+ this. */
+#define _Py_atomic_signal_fence(/*memory_order*/ ORDER) ((void)0)
+#define _Py_atomic_thread_fence(/*memory_order*/ ORDER) ((void)0)
+#define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \
+ ((ATOMIC_VAL)->_value = NEW_VAL)
+#define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \
+ ((ATOMIC_VAL)->_value)
+#endif
+
+/* Standardized shortcuts. */
+#define _Py_atomic_store(ATOMIC_VAL, NEW_VAL) \
+ _Py_atomic_store_explicit((ATOMIC_VAL), (NEW_VAL), _Py_memory_order_seq_cst)
+#define _Py_atomic_load(ATOMIC_VAL) \
+ _Py_atomic_load_explicit((ATOMIC_VAL), _Py_memory_order_seq_cst)
+
+/* Python-local extensions */
+
+#define _Py_atomic_store_relaxed(ATOMIC_VAL, NEW_VAL) \
+ _Py_atomic_store_explicit((ATOMIC_VAL), (NEW_VAL), _Py_memory_order_relaxed)
+#define _Py_atomic_load_relaxed(ATOMIC_VAL) \
+ _Py_atomic_load_explicit((ATOMIC_VAL), _Py_memory_order_relaxed)
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* Py_ATOMIC_H */
diff --git a/include/python3.10/internal/pycore_atomic_funcs.h b/include/python3.11/internal/pycore_atomic_funcs.h
similarity index 100%
rename from include/python3.10/internal/pycore_atomic_funcs.h
rename to include/python3.11/internal/pycore_atomic_funcs.h
diff --git a/include/python3.11/internal/pycore_bitutils.h b/include/python3.11/internal/pycore_bitutils.h
new file mode 100644
index 0000000..e6bf61e
--- /dev/null
+++ b/include/python3.11/internal/pycore_bitutils.h
@@ -0,0 +1,186 @@
+/* Bit and bytes utilities.
+
+ Bytes swap functions, reverse order of bytes:
+
+ - _Py_bswap16(uint16_t)
+ - _Py_bswap32(uint32_t)
+ - _Py_bswap64(uint64_t)
+*/
+
+#ifndef Py_INTERNAL_BITUTILS_H
+#define Py_INTERNAL_BITUTILS_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#if defined(__GNUC__) \
+ && ((__GNUC__ >= 5) || (__GNUC__ == 4) && (__GNUC_MINOR__ >= 8))
+ /* __builtin_bswap16() is available since GCC 4.8,
+ __builtin_bswap32() is available since GCC 4.3,
+ __builtin_bswap64() is available since GCC 4.3. */
+# define _PY_HAVE_BUILTIN_BSWAP
+#endif
+
+#ifdef _MSC_VER
+ /* Get _byteswap_ushort(), _byteswap_ulong(), _byteswap_uint64() */
+# include <intrin.h>
+#endif
+
+static inline uint16_t
+_Py_bswap16(uint16_t word)
+{
+#if defined(_PY_HAVE_BUILTIN_BSWAP) || _Py__has_builtin(__builtin_bswap16)
+ return __builtin_bswap16(word);
+#elif defined(_MSC_VER)
+ Py_BUILD_ASSERT(sizeof(word) == sizeof(unsigned short));
+ return _byteswap_ushort(word);
+#else
+ // Portable implementation which doesn't rely on circular bit shift
+ return ( ((word & UINT16_C(0x00FF)) << 8)
+ | ((word & UINT16_C(0xFF00)) >> 8));
+#endif
+}
+
+static inline uint32_t
+_Py_bswap32(uint32_t word)
+{
+#if defined(_PY_HAVE_BUILTIN_BSWAP) || _Py__has_builtin(__builtin_bswap32)
+ return __builtin_bswap32(word);
+#elif defined(_MSC_VER)
+ Py_BUILD_ASSERT(sizeof(word) == sizeof(unsigned long));
+ return _byteswap_ulong(word);
+#else
+ // Portable implementation which doesn't rely on circular bit shift
+ return ( ((word & UINT32_C(0x000000FF)) << 24)
+ | ((word & UINT32_C(0x0000FF00)) << 8)
+ | ((word & UINT32_C(0x00FF0000)) >> 8)
+ | ((word & UINT32_C(0xFF000000)) >> 24));
+#endif
+}
+
+static inline uint64_t
+_Py_bswap64(uint64_t word)
+{
+#if defined(_PY_HAVE_BUILTIN_BSWAP) || _Py__has_builtin(__builtin_bswap64)
+ return __builtin_bswap64(word);
+#elif defined(_MSC_VER)
+ return _byteswap_uint64(word);
+#else
+ // Portable implementation which doesn't rely on circular bit shift
+ return ( ((word & UINT64_C(0x00000000000000FF)) << 56)
+ | ((word & UINT64_C(0x000000000000FF00)) << 40)
+ | ((word & UINT64_C(0x0000000000FF0000)) << 24)
+ | ((word & UINT64_C(0x00000000FF000000)) << 8)
+ | ((word & UINT64_C(0x000000FF00000000)) >> 8)
+ | ((word & UINT64_C(0x0000FF0000000000)) >> 24)
+ | ((word & UINT64_C(0x00FF000000000000)) >> 40)
+ | ((word & UINT64_C(0xFF00000000000000)) >> 56));
+#endif
+}
+
+
+// Population count: count the number of 1's in 'x'
+// (number of bits set to 1), also known as the hamming weight.
+//
+// Implementation note. CPUID is not used, to test if x86 POPCNT instruction
+// can be used, to keep the implementation simple. For example, Visual Studio
+// __popcnt() is not used this reason. The clang and GCC builtin function can
+// use the x86 POPCNT instruction if the target architecture has SSE4a or
+// newer.
+static inline int
+_Py_popcount32(uint32_t x)
+{
+#if (defined(__clang__) || defined(__GNUC__))
+
+#if SIZEOF_INT >= 4
+ Py_BUILD_ASSERT(sizeof(x) <= sizeof(unsigned int));
+ return __builtin_popcount(x);
+#else
+ // The C standard guarantees that unsigned long will always be big enough
+ // to hold a uint32_t value without losing information.
+ Py_BUILD_ASSERT(sizeof(x) <= sizeof(unsigned long));
+ return __builtin_popcountl(x);
+#endif
+
+#else
+ // 32-bit SWAR (SIMD Within A Register) popcount
+
+ // Binary: 0 1 0 1 ...
+ const uint32_t M1 = 0x55555555;
+ // Binary: 00 11 00 11. ..
+ const uint32_t M2 = 0x33333333;
+ // Binary: 0000 1111 0000 1111 ...
+ const uint32_t M4 = 0x0F0F0F0F;
+
+ // Put count of each 2 bits into those 2 bits
+ x = x - ((x >> 1) & M1);
+ // Put count of each 4 bits into those 4 bits
+ x = (x & M2) + ((x >> 2) & M2);
+ // Put count of each 8 bits into those 8 bits
+ x = (x + (x >> 4)) & M4;
+ // Sum of the 4 byte counts.
+ // Take care when considering changes to the next line. Portability and
+ // correctness are delicate here, thanks to C's "integer promotions" (C99
+ // §6.3.1.1p2). On machines where the `int` type has width greater than 32
+ // bits, `x` will be promoted to an `int`, and following C's "usual
+ // arithmetic conversions" (C99 §6.3.1.8), the multiplication will be
+ // performed as a multiplication of two `unsigned int` operands. In this
+ // case it's critical that we cast back to `uint32_t` in order to keep only
+ // the least significant 32 bits. On machines where the `int` type has
+ // width no greater than 32, the multiplication is of two 32-bit unsigned
+ // integer types, and the (uint32_t) cast is a no-op. In both cases, we
+ // avoid the risk of undefined behaviour due to overflow of a
+ // multiplication of signed integer types.
+ return (uint32_t)(x * 0x01010101U) >> 24;
+#endif
+}
+
+
+// Return the index of the most significant 1 bit in 'x'. This is the smallest
+// integer k such that x < 2**k. Equivalent to floor(log2(x)) + 1 for x != 0.
+static inline int
+_Py_bit_length(unsigned long x)
+{
+#if (defined(__clang__) || defined(__GNUC__))
+ if (x != 0) {
+ // __builtin_clzl() is available since GCC 3.4.
+ // Undefined behavior for x == 0.
+ return (int)sizeof(unsigned long) * 8 - __builtin_clzl(x);
+ }
+ else {
+ return 0;
+ }
+#elif defined(_MSC_VER)
+ // _BitScanReverse() is documented to search 32 bits.
+ Py_BUILD_ASSERT(sizeof(unsigned long) <= 4);
+ unsigned long msb;
+ if (_BitScanReverse(&msb, x)) {
+ return (int)msb + 1;
+ }
+ else {
+ return 0;
+ }
+#else
+ const int BIT_LENGTH_TABLE[32] = {
+ 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
+ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
+ };
+ int msb = 0;
+ while (x >= 32) {
+ msb += 6;
+ x >>= 6;
+ }
+ msb += BIT_LENGTH_TABLE[x];
+ return msb;
+#endif
+}
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_BITUTILS_H */
diff --git a/include/python3.10/internal/pycore_blocks_output_buffer.h b/include/python3.11/internal/pycore_blocks_output_buffer.h
similarity index 100%
rename from include/python3.10/internal/pycore_blocks_output_buffer.h
rename to include/python3.11/internal/pycore_blocks_output_buffer.h
diff --git a/include/python3.10/internal/pycore_bytes_methods.h b/include/python3.11/internal/pycore_bytes_methods.h
similarity index 100%
rename from include/python3.10/internal/pycore_bytes_methods.h
rename to include/python3.11/internal/pycore_bytes_methods.h
diff --git a/include/python3.11/internal/pycore_bytesobject.h b/include/python3.11/internal/pycore_bytesobject.h
new file mode 100644
index 0000000..9173a4f
--- /dev/null
+++ b/include/python3.11/internal/pycore_bytesobject.h
@@ -0,0 +1,52 @@
+#ifndef Py_INTERNAL_BYTESOBJECT_H
+#define Py_INTERNAL_BYTESOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+
+/* runtime lifecycle */
+
+extern PyStatus _PyBytes_InitTypes(PyInterpreterState *);
+
+
+/* Substring Search.
+
+ Returns the index of the first occurrence of
+ a substring ("needle") in a larger text ("haystack").
+ If the needle is not found, return -1.
+ If the needle is found, add offset to the index.
+*/
+
+PyAPI_FUNC(Py_ssize_t)
+_PyBytes_Find(const char *haystack, Py_ssize_t len_haystack,
+ const char *needle, Py_ssize_t len_needle,
+ Py_ssize_t offset);
+
+/* Same as above, but search right-to-left */
+PyAPI_FUNC(Py_ssize_t)
+_PyBytes_ReverseFind(const char *haystack, Py_ssize_t len_haystack,
+ const char *needle, Py_ssize_t len_needle,
+ Py_ssize_t offset);
+
+
+/** Helper function to implement the repeat and inplace repeat methods on a buffer
+ *
+ * len_dest is assumed to be an integer multiple of len_src.
+ * If src equals dest, then assume the operation is inplace.
+ *
+ * This method repeately doubles the number of bytes copied to reduce
+ * the number of invocations of memcpy.
+ */
+PyAPI_FUNC(void)
+_PyBytes_Repeat(char* dest, Py_ssize_t len_dest,
+ const char* src, Py_ssize_t len_src);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_BYTESOBJECT_H */
diff --git a/include/python3.11/internal/pycore_call.h b/include/python3.11/internal/pycore_call.h
new file mode 100644
index 0000000..3ccacfa
--- /dev/null
+++ b/include/python3.11/internal/pycore_call.h
@@ -0,0 +1,121 @@
+#ifndef Py_INTERNAL_CALL_H
+#define Py_INTERNAL_CALL_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#include "pycore_pystate.h" // _PyThreadState_GET()
+
+PyAPI_FUNC(PyObject *) _PyObject_Call_Prepend(
+ PyThreadState *tstate,
+ PyObject *callable,
+ PyObject *obj,
+ PyObject *args,
+ PyObject *kwargs);
+
+PyAPI_FUNC(PyObject *) _PyObject_FastCallDictTstate(
+ PyThreadState *tstate,
+ PyObject *callable,
+ PyObject *const *args,
+ size_t nargsf,
+ PyObject *kwargs);
+
+PyAPI_FUNC(PyObject *) _PyObject_Call(
+ PyThreadState *tstate,
+ PyObject *callable,
+ PyObject *args,
+ PyObject *kwargs);
+
+extern PyObject * _PyObject_CallMethodFormat(
+ PyThreadState *tstate, PyObject *callable, const char *format, ...);
+
+
+// Static inline variant of public PyVectorcall_Function().
+static inline vectorcallfunc
+_PyVectorcall_FunctionInline(PyObject *callable)
+{
+ assert(callable != NULL);
+
+ PyTypeObject *tp = Py_TYPE(callable);
+ if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_VECTORCALL)) {
+ return NULL;
+ }
+ assert(PyCallable_Check(callable));
+
+ Py_ssize_t offset = tp->tp_vectorcall_offset;
+ assert(offset > 0);
+
+ vectorcallfunc ptr;
+ memcpy(&ptr, (char *) callable + offset, sizeof(ptr));
+ return ptr;
+}
+
+
+/* Call the callable object 'callable' with the "vectorcall" calling
+ convention.
+
+ args is a C array for positional arguments.
+
+ nargsf is the number of positional arguments plus optionally the flag
+ PY_VECTORCALL_ARGUMENTS_OFFSET which means that the caller is allowed to
+ modify args[-1].
+
+ kwnames is a tuple of keyword names. The values of the keyword arguments
+ are stored in "args" after the positional arguments (note that the number
+ of keyword arguments does not change nargsf). kwnames can also be NULL if
+ there are no keyword arguments.
+
+ keywords must only contain strings and all keys must be unique.
+
+ Return the result on success. Raise an exception and return NULL on
+ error. */
+static inline PyObject *
+_PyObject_VectorcallTstate(PyThreadState *tstate, PyObject *callable,
+ PyObject *const *args, size_t nargsf,
+ PyObject *kwnames)
+{
+ vectorcallfunc func;
+ PyObject *res;
+
+ assert(kwnames == NULL || PyTuple_Check(kwnames));
+ assert(args != NULL || PyVectorcall_NARGS(nargsf) == 0);
+
+ func = _PyVectorcall_FunctionInline(callable);
+ if (func == NULL) {
+ Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
+ return _PyObject_MakeTpCall(tstate, callable, args, nargs, kwnames);
+ }
+ res = func(callable, args, nargsf, kwnames);
+ return _Py_CheckFunctionResult(tstate, callable, res, NULL);
+}
+
+
+static inline PyObject *
+_PyObject_CallNoArgsTstate(PyThreadState *tstate, PyObject *func) {
+ return _PyObject_VectorcallTstate(tstate, func, NULL, 0, NULL);
+}
+
+
+// Private static inline function variant of public PyObject_CallNoArgs()
+static inline PyObject *
+_PyObject_CallNoArgs(PyObject *func) {
+ PyThreadState *tstate = _PyThreadState_GET();
+ return _PyObject_VectorcallTstate(tstate, func, NULL, 0, NULL);
+}
+
+
+static inline PyObject *
+_PyObject_FastCallTstate(PyThreadState *tstate, PyObject *func, PyObject *const *args, Py_ssize_t nargs)
+{
+ return _PyObject_VectorcallTstate(tstate, func, args, (size_t)nargs, NULL);
+}
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_CALL_H */
diff --git a/include/python3.11/internal/pycore_ceval.h b/include/python3.11/internal/pycore_ceval.h
new file mode 100644
index 0000000..8d18d20
--- /dev/null
+++ b/include/python3.11/internal/pycore_ceval.h
@@ -0,0 +1,138 @@
+#ifndef Py_INTERNAL_CEVAL_H
+#define Py_INTERNAL_CEVAL_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+/* Forward declarations */
+struct pyruntimestate;
+struct _ceval_runtime_state;
+
+/* WASI has limited call stack. Python's recursion limit depends on code
+ layout, optimization, and WASI runtime. Wasmtime can handle about 700-750
+ recursions, sometimes less. 600 is a more conservative limit. */
+#ifndef Py_DEFAULT_RECURSION_LIMIT
+# ifdef __wasi__
+# define Py_DEFAULT_RECURSION_LIMIT 600
+# else
+# define Py_DEFAULT_RECURSION_LIMIT 1000
+# endif
+#endif
+
+#include "pycore_interp.h" // PyInterpreterState.eval_frame
+#include "pycore_pystate.h" // _PyThreadState_GET()
+
+
+extern void _Py_FinishPendingCalls(PyThreadState *tstate);
+extern void _PyEval_InitRuntimeState(struct _ceval_runtime_state *);
+extern void _PyEval_InitState(struct _ceval_state *, PyThread_type_lock);
+extern void _PyEval_FiniState(struct _ceval_state *ceval);
+PyAPI_FUNC(void) _PyEval_SignalReceived(PyInterpreterState *interp);
+PyAPI_FUNC(int) _PyEval_AddPendingCall(
+ PyInterpreterState *interp,
+ int (*func)(void *),
+ void *arg);
+PyAPI_FUNC(void) _PyEval_SignalAsyncExc(PyInterpreterState *interp);
+#ifdef HAVE_FORK
+extern PyStatus _PyEval_ReInitThreads(PyThreadState *tstate);
+#endif
+
+// Used by sys.call_tracing()
+extern PyObject* _PyEval_CallTracing(PyObject *func, PyObject *args);
+
+// Used by sys.get_asyncgen_hooks()
+extern PyObject* _PyEval_GetAsyncGenFirstiter(void);
+extern PyObject* _PyEval_GetAsyncGenFinalizer(void);
+
+// Used by sys.set_asyncgen_hooks()
+extern int _PyEval_SetAsyncGenFirstiter(PyObject *);
+extern int _PyEval_SetAsyncGenFinalizer(PyObject *);
+
+// Used by sys.get_coroutine_origin_tracking_depth()
+// and sys.set_coroutine_origin_tracking_depth()
+extern int _PyEval_GetCoroutineOriginTrackingDepth(void);
+extern int _PyEval_SetCoroutineOriginTrackingDepth(int depth);
+
+extern void _PyEval_Fini(void);
+
+
+extern PyObject* _PyEval_GetBuiltins(PyThreadState *tstate);
+extern PyObject* _PyEval_BuiltinsFromGlobals(
+ PyThreadState *tstate,
+ PyObject *globals);
+
+
+static inline PyObject*
+_PyEval_EvalFrame(PyThreadState *tstate, struct _PyInterpreterFrame *frame, int throwflag)
+{
+ if (tstate->interp->eval_frame == NULL) {
+ return _PyEval_EvalFrameDefault(tstate, frame, throwflag);
+ }
+ return tstate->interp->eval_frame(tstate, frame, throwflag);
+}
+
+extern PyObject*
+_PyEval_Vector(PyThreadState *tstate,
+ PyFunctionObject *func, PyObject *locals,
+ PyObject* const* args, size_t argcount,
+ PyObject *kwnames);
+
+extern int _PyEval_ThreadsInitialized(struct pyruntimestate *runtime);
+extern PyStatus _PyEval_InitGIL(PyThreadState *tstate);
+extern void _PyEval_FiniGIL(PyInterpreterState *interp);
+
+extern void _PyEval_ReleaseLock(PyThreadState *tstate);
+
+extern void _PyEval_DeactivateOpCache(void);
+
+
+/* --- _Py_EnterRecursiveCall() ----------------------------------------- */
+
+#ifdef USE_STACKCHECK
+/* With USE_STACKCHECK macro defined, trigger stack checks in
+ _Py_CheckRecursiveCall() on every 64th call to _Py_EnterRecursiveCall. */
+static inline int _Py_MakeRecCheck(PyThreadState *tstate) {
+ return (tstate->recursion_remaining-- <= 0
+ || (tstate->recursion_remaining & 63) == 0);
+}
+#else
+static inline int _Py_MakeRecCheck(PyThreadState *tstate) {
+ return tstate->recursion_remaining-- <= 0;
+}
+#endif
+
+PyAPI_FUNC(int) _Py_CheckRecursiveCall(
+ PyThreadState *tstate,
+ const char *where);
+
+static inline int _Py_EnterRecursiveCallTstate(PyThreadState *tstate,
+ const char *where) {
+ return (_Py_MakeRecCheck(tstate) && _Py_CheckRecursiveCall(tstate, where));
+}
+
+static inline int _Py_EnterRecursiveCall(const char *where) {
+ PyThreadState *tstate = _PyThreadState_GET();
+ return _Py_EnterRecursiveCallTstate(tstate, where);
+}
+
+static inline void _Py_LeaveRecursiveCallTstate(PyThreadState *tstate) {
+ tstate->recursion_remaining++;
+}
+
+static inline void _Py_LeaveRecursiveCall(void) {
+ PyThreadState *tstate = _PyThreadState_GET();
+ _Py_LeaveRecursiveCallTstate(tstate);
+}
+
+extern struct _PyInterpreterFrame* _PyEval_GetFrame(void);
+
+extern PyObject* _Py_MakeCoro(PyFunctionObject *func);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_CEVAL_H */
diff --git a/include/python3.11/internal/pycore_code.h b/include/python3.11/internal/pycore_code.h
new file mode 100644
index 0000000..3a24a65
--- /dev/null
+++ b/include/python3.11/internal/pycore_code.h
@@ -0,0 +1,564 @@
+#ifndef Py_INTERNAL_CODE_H
+#define Py_INTERNAL_CODE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* PEP 659
+ * Specialization and quickening structs and helper functions
+ */
+
+
+// Inline caches. If you change the number of cache entries for an instruction,
+// you must *also* update the number of cache entries in Lib/opcode.py and bump
+// the magic number in Lib/importlib/_bootstrap_external.py!
+
+#define CACHE_ENTRIES(cache) (sizeof(cache)/sizeof(_Py_CODEUNIT))
+
+typedef struct {
+ _Py_CODEUNIT counter;
+ _Py_CODEUNIT index;
+ _Py_CODEUNIT module_keys_version[2];
+ _Py_CODEUNIT builtin_keys_version;
+} _PyLoadGlobalCache;
+
+#define INLINE_CACHE_ENTRIES_LOAD_GLOBAL CACHE_ENTRIES(_PyLoadGlobalCache)
+
+typedef struct {
+ _Py_CODEUNIT counter;
+} _PyBinaryOpCache;
+
+#define INLINE_CACHE_ENTRIES_BINARY_OP CACHE_ENTRIES(_PyBinaryOpCache)
+
+typedef struct {
+ _Py_CODEUNIT counter;
+} _PyUnpackSequenceCache;
+
+#define INLINE_CACHE_ENTRIES_UNPACK_SEQUENCE \
+ CACHE_ENTRIES(_PyUnpackSequenceCache)
+
+typedef struct {
+ _Py_CODEUNIT counter;
+ _Py_CODEUNIT mask;
+} _PyCompareOpCache;
+
+#define INLINE_CACHE_ENTRIES_COMPARE_OP CACHE_ENTRIES(_PyCompareOpCache)
+
+typedef struct {
+ _Py_CODEUNIT counter;
+ _Py_CODEUNIT type_version[2];
+ _Py_CODEUNIT func_version;
+} _PyBinarySubscrCache;
+
+#define INLINE_CACHE_ENTRIES_BINARY_SUBSCR CACHE_ENTRIES(_PyBinarySubscrCache)
+
+typedef struct {
+ _Py_CODEUNIT counter;
+ _Py_CODEUNIT version[2];
+ _Py_CODEUNIT index;
+} _PyAttrCache;
+
+#define INLINE_CACHE_ENTRIES_LOAD_ATTR CACHE_ENTRIES(_PyAttrCache)
+
+#define INLINE_CACHE_ENTRIES_STORE_ATTR CACHE_ENTRIES(_PyAttrCache)
+
+typedef struct {
+ _Py_CODEUNIT counter;
+ _Py_CODEUNIT type_version[2];
+ _Py_CODEUNIT dict_offset;
+ _Py_CODEUNIT keys_version[2];
+ _Py_CODEUNIT descr[4];
+} _PyLoadMethodCache;
+
+#define INLINE_CACHE_ENTRIES_LOAD_METHOD CACHE_ENTRIES(_PyLoadMethodCache)
+
+typedef struct {
+ _Py_CODEUNIT counter;
+ _Py_CODEUNIT func_version[2];
+ _Py_CODEUNIT min_args;
+} _PyCallCache;
+
+#define INLINE_CACHE_ENTRIES_CALL CACHE_ENTRIES(_PyCallCache)
+
+typedef struct {
+ _Py_CODEUNIT counter;
+} _PyPrecallCache;
+
+#define INLINE_CACHE_ENTRIES_PRECALL CACHE_ENTRIES(_PyPrecallCache)
+
+typedef struct {
+ _Py_CODEUNIT counter;
+} _PyStoreSubscrCache;
+
+#define INLINE_CACHE_ENTRIES_STORE_SUBSCR CACHE_ENTRIES(_PyStoreSubscrCache)
+
+#define QUICKENING_WARMUP_DELAY 8
+
+/* We want to compare to zero for efficiency, so we offset values accordingly */
+#define QUICKENING_INITIAL_WARMUP_VALUE (-QUICKENING_WARMUP_DELAY)
+
+void _PyCode_Quicken(PyCodeObject *code);
+
+static inline void
+_PyCode_Warmup(PyCodeObject *code)
+{
+ if (code->co_warmup != 0) {
+ code->co_warmup++;
+ if (code->co_warmup == 0) {
+ _PyCode_Quicken(code);
+ }
+ }
+}
+
+extern uint8_t _PyOpcode_Adaptive[256];
+
+extern Py_ssize_t _Py_QuickenedCount;
+
+// Borrowed references to common callables:
+struct callable_cache {
+ PyObject *isinstance;
+ PyObject *len;
+ PyObject *list_append;
+};
+
+/* "Locals plus" for a code object is the set of locals + cell vars +
+ * free vars. This relates to variable names as well as offsets into
+ * the "fast locals" storage array of execution frames. The compiler
+ * builds the list of names, their offsets, and the corresponding
+ * kind of local.
+ *
+ * Those kinds represent the source of the initial value and the
+ * variable's scope (as related to closures). A "local" is an
+ * argument or other variable defined in the current scope. A "free"
+ * variable is one that is defined in an outer scope and comes from
+ * the function's closure. A "cell" variable is a local that escapes
+ * into an inner function as part of a closure, and thus must be
+ * wrapped in a cell. Any "local" can also be a "cell", but the
+ * "free" kind is mutually exclusive with both.
+ */
+
+// Note that these all fit within a byte, as do combinations.
+// Later, we will use the smaller numbers to differentiate the different
+// kinds of locals (e.g. pos-only arg, varkwargs, local-only).
+#define CO_FAST_LOCAL 0x20
+#define CO_FAST_CELL 0x40
+#define CO_FAST_FREE 0x80
+
+typedef unsigned char _PyLocals_Kind;
+
+static inline _PyLocals_Kind
+_PyLocals_GetKind(PyObject *kinds, int i)
+{
+ assert(PyBytes_Check(kinds));
+ assert(0 <= i && i < PyBytes_GET_SIZE(kinds));
+ char *ptr = PyBytes_AS_STRING(kinds);
+ return (_PyLocals_Kind)(ptr[i]);
+}
+
+static inline void
+_PyLocals_SetKind(PyObject *kinds, int i, _PyLocals_Kind kind)
+{
+ assert(PyBytes_Check(kinds));
+ assert(0 <= i && i < PyBytes_GET_SIZE(kinds));
+ char *ptr = PyBytes_AS_STRING(kinds);
+ ptr[i] = (char) kind;
+}
+
+
+struct _PyCodeConstructor {
+ /* metadata */
+ PyObject *filename;
+ PyObject *name;
+ PyObject *qualname;
+ int flags;
+
+ /* the code */
+ PyObject *code;
+ int firstlineno;
+ PyObject *linetable;
+
+ /* used by the code */
+ PyObject *consts;
+ PyObject *names;
+
+ /* mapping frame offsets to information */
+ PyObject *localsplusnames; // Tuple of strings
+ PyObject *localspluskinds; // Bytes object, one byte per variable
+
+ /* args (within varnames) */
+ int argcount;
+ int posonlyargcount;
+ // XXX Replace argcount with posorkwargcount (argcount - posonlyargcount).
+ int kwonlyargcount;
+
+ /* needed to create the frame */
+ int stacksize;
+
+ /* used by the eval loop */
+ PyObject *exceptiontable;
+};
+
+// Using an "arguments struct" like this is helpful for maintainability
+// in a case such as this with many parameters. It does bear a risk:
+// if the struct changes and callers are not updated properly then the
+// compiler will not catch problems (like a missing argument). This can
+// cause hard-to-debug problems. The risk is mitigated by the use of
+// check_code() in codeobject.c. However, we may decide to switch
+// back to a regular function signature. Regardless, this approach
+// wouldn't be appropriate if this weren't a strictly internal API.
+// (See the comments in https://github.com/python/cpython/pull/26258.)
+PyAPI_FUNC(int) _PyCode_Validate(struct _PyCodeConstructor *);
+PyAPI_FUNC(PyCodeObject *) _PyCode_New(struct _PyCodeConstructor *);
+
+
+/* Private API */
+
+/* Getters for internal PyCodeObject data. */
+extern PyObject* _PyCode_GetVarnames(PyCodeObject *);
+extern PyObject* _PyCode_GetCellvars(PyCodeObject *);
+extern PyObject* _PyCode_GetFreevars(PyCodeObject *);
+extern PyObject* _PyCode_GetCode(PyCodeObject *);
+
+/** API for initializing the line number tables. */
+extern int _PyCode_InitAddressRange(PyCodeObject* co, PyCodeAddressRange *bounds);
+
+/** Out of process API for initializing the location table. */
+extern void _PyLineTable_InitAddressRange(
+ const char *linetable,
+ Py_ssize_t length,
+ int firstlineno,
+ PyCodeAddressRange *range);
+
+/** API for traversing the line number table. */
+extern int _PyLineTable_NextAddressRange(PyCodeAddressRange *range);
+extern int _PyLineTable_PreviousAddressRange(PyCodeAddressRange *range);
+
+/* Specialization functions */
+
+extern int _Py_Specialize_LoadAttr(PyObject *owner, _Py_CODEUNIT *instr,
+ PyObject *name);
+extern int _Py_Specialize_StoreAttr(PyObject *owner, _Py_CODEUNIT *instr,
+ PyObject *name);
+extern int _Py_Specialize_LoadGlobal(PyObject *globals, PyObject *builtins, _Py_CODEUNIT *instr, PyObject *name);
+extern int _Py_Specialize_LoadMethod(PyObject *owner, _Py_CODEUNIT *instr,
+ PyObject *name);
+extern int _Py_Specialize_BinarySubscr(PyObject *sub, PyObject *container, _Py_CODEUNIT *instr);
+extern int _Py_Specialize_StoreSubscr(PyObject *container, PyObject *sub, _Py_CODEUNIT *instr);
+extern int _Py_Specialize_Call(PyObject *callable, _Py_CODEUNIT *instr,
+ int nargs, PyObject *kwnames);
+extern int _Py_Specialize_Precall(PyObject *callable, _Py_CODEUNIT *instr,
+ int nargs, PyObject *kwnames, int oparg);
+extern void _Py_Specialize_BinaryOp(PyObject *lhs, PyObject *rhs, _Py_CODEUNIT *instr,
+ int oparg, PyObject **locals);
+extern void _Py_Specialize_CompareOp(PyObject *lhs, PyObject *rhs,
+ _Py_CODEUNIT *instr, int oparg);
+extern void _Py_Specialize_UnpackSequence(PyObject *seq, _Py_CODEUNIT *instr,
+ int oparg);
+
+/* Deallocator function for static codeobjects used in deepfreeze.py */
+extern void _PyStaticCode_Dealloc(PyCodeObject *co);
+/* Function to intern strings of codeobjects */
+extern int _PyStaticCode_InternStrings(PyCodeObject *co);
+
+#ifdef Py_STATS
+
+#define SPECIALIZATION_FAILURE_KINDS 30
+
+typedef struct _specialization_stats {
+ uint64_t success;
+ uint64_t failure;
+ uint64_t hit;
+ uint64_t deferred;
+ uint64_t miss;
+ uint64_t deopt;
+ uint64_t failure_kinds[SPECIALIZATION_FAILURE_KINDS];
+} SpecializationStats;
+
+typedef struct _opcode_stats {
+ SpecializationStats specialization;
+ uint64_t execution_count;
+ uint64_t pair_count[256];
+} OpcodeStats;
+
+typedef struct _call_stats {
+ uint64_t inlined_py_calls;
+ uint64_t pyeval_calls;
+ uint64_t frames_pushed;
+ uint64_t frame_objects_created;
+} CallStats;
+
+typedef struct _object_stats {
+ uint64_t allocations;
+ uint64_t allocations512;
+ uint64_t allocations4k;
+ uint64_t allocations_big;
+ uint64_t frees;
+ uint64_t to_freelist;
+ uint64_t from_freelist;
+ uint64_t new_values;
+ uint64_t dict_materialized_on_request;
+ uint64_t dict_materialized_new_key;
+ uint64_t dict_materialized_too_big;
+ uint64_t dict_materialized_str_subclass;
+} ObjectStats;
+
+typedef struct _stats {
+ OpcodeStats opcode_stats[256];
+ CallStats call_stats;
+ ObjectStats object_stats;
+} PyStats;
+
+extern PyStats _py_stats;
+
+#define STAT_INC(opname, name) _py_stats.opcode_stats[opname].specialization.name++
+#define STAT_DEC(opname, name) _py_stats.opcode_stats[opname].specialization.name--
+#define OPCODE_EXE_INC(opname) _py_stats.opcode_stats[opname].execution_count++
+#define CALL_STAT_INC(name) _py_stats.call_stats.name++
+#define OBJECT_STAT_INC(name) _py_stats.object_stats.name++
+#define OBJECT_STAT_INC_COND(name, cond) \
+ do { if (cond) _py_stats.object_stats.name++; } while (0)
+
+extern void _Py_PrintSpecializationStats(int to_file);
+
+// Used by the _opcode extension which is built as a shared library
+PyAPI_FUNC(PyObject*) _Py_GetSpecializationStats(void);
+
+#else
+#define STAT_INC(opname, name) ((void)0)
+#define STAT_DEC(opname, name) ((void)0)
+#define OPCODE_EXE_INC(opname) ((void)0)
+#define CALL_STAT_INC(name) ((void)0)
+#define OBJECT_STAT_INC(name) ((void)0)
+#define OBJECT_STAT_INC_COND(name, cond) ((void)0)
+#endif // !Py_STATS
+
+// Cache values are only valid in memory, so use native endianness.
+#ifdef WORDS_BIGENDIAN
+
+static inline void
+write_u32(uint16_t *p, uint32_t val)
+{
+ p[0] = (uint16_t)(val >> 16);
+ p[1] = (uint16_t)(val >> 0);
+}
+
+static inline void
+write_u64(uint16_t *p, uint64_t val)
+{
+ p[0] = (uint16_t)(val >> 48);
+ p[1] = (uint16_t)(val >> 32);
+ p[2] = (uint16_t)(val >> 16);
+ p[3] = (uint16_t)(val >> 0);
+}
+
+static inline uint32_t
+read_u32(uint16_t *p)
+{
+ uint32_t val = 0;
+ val |= (uint32_t)p[0] << 16;
+ val |= (uint32_t)p[1] << 0;
+ return val;
+}
+
+static inline uint64_t
+read_u64(uint16_t *p)
+{
+ uint64_t val = 0;
+ val |= (uint64_t)p[0] << 48;
+ val |= (uint64_t)p[1] << 32;
+ val |= (uint64_t)p[2] << 16;
+ val |= (uint64_t)p[3] << 0;
+ return val;
+}
+
+#else
+
+static inline void
+write_u32(uint16_t *p, uint32_t val)
+{
+ p[0] = (uint16_t)(val >> 0);
+ p[1] = (uint16_t)(val >> 16);
+}
+
+static inline void
+write_u64(uint16_t *p, uint64_t val)
+{
+ p[0] = (uint16_t)(val >> 0);
+ p[1] = (uint16_t)(val >> 16);
+ p[2] = (uint16_t)(val >> 32);
+ p[3] = (uint16_t)(val >> 48);
+}
+
+static inline uint32_t
+read_u32(uint16_t *p)
+{
+ uint32_t val = 0;
+ val |= (uint32_t)p[0] << 0;
+ val |= (uint32_t)p[1] << 16;
+ return val;
+}
+
+static inline uint64_t
+read_u64(uint16_t *p)
+{
+ uint64_t val = 0;
+ val |= (uint64_t)p[0] << 0;
+ val |= (uint64_t)p[1] << 16;
+ val |= (uint64_t)p[2] << 32;
+ val |= (uint64_t)p[3] << 48;
+ return val;
+}
+
+#endif
+
+static inline void
+write_obj(uint16_t *p, PyObject *obj)
+{
+ uintptr_t val = (uintptr_t)obj;
+#if SIZEOF_VOID_P == 8
+ write_u64(p, val);
+#elif SIZEOF_VOID_P == 4
+ write_u32(p, val);
+#else
+ #error "SIZEOF_VOID_P must be 4 or 8"
+#endif
+}
+
+static inline PyObject *
+read_obj(uint16_t *p)
+{
+ uintptr_t val;
+#if SIZEOF_VOID_P == 8
+ val = read_u64(p);
+#elif SIZEOF_VOID_P == 4
+ val = read_u32(p);
+#else
+ #error "SIZEOF_VOID_P must be 4 or 8"
+#endif
+ return (PyObject *)val;
+}
+
+/* See Objects/exception_handling_notes.txt for details.
+ */
+static inline unsigned char *
+parse_varint(unsigned char *p, int *result) {
+ int val = p[0] & 63;
+ while (p[0] & 64) {
+ p++;
+ val = (val << 6) | (p[0] & 63);
+ }
+ *result = val;
+ return p+1;
+}
+
+static inline int
+write_varint(uint8_t *ptr, unsigned int val)
+{
+ int written = 1;
+ while (val >= 64) {
+ *ptr++ = 64 | (val & 63);
+ val >>= 6;
+ written++;
+ }
+ *ptr = val;
+ return written;
+}
+
+static inline int
+write_signed_varint(uint8_t *ptr, int val)
+{
+ if (val < 0) {
+ val = ((-val)<<1) | 1;
+ }
+ else {
+ val = val << 1;
+ }
+ return write_varint(ptr, val);
+}
+
+static inline int
+write_location_entry_start(uint8_t *ptr, int code, int length)
+{
+ assert((code & 15) == code);
+ *ptr = 128 | (code << 3) | (length - 1);
+ return 1;
+}
+
+
+/** Counters
+ * The first 16-bit value in each inline cache is a counter.
+ * When counting misses, the counter is treated as a simple unsigned value.
+ *
+ * When counting executions until the next specialization attempt,
+ * exponential backoff is used to reduce the number of specialization failures.
+ * The high 12 bits store the counter, the low 4 bits store the backoff exponent.
+ * On a specialization failure, the backoff exponent is incremented and the
+ * counter set to (2**backoff - 1).
+ * Backoff == 6 -> starting counter == 63, backoff == 10 -> starting counter == 1023.
+ */
+
+/* With a 16-bit counter, we have 12 bits for the counter value, and 4 bits for the backoff */
+#define ADAPTIVE_BACKOFF_BITS 4
+/* The initial counter value is 31 == 2**ADAPTIVE_BACKOFF_START - 1 */
+#define ADAPTIVE_BACKOFF_START 5
+
+#define MAX_BACKOFF_VALUE (16 - ADAPTIVE_BACKOFF_BITS)
+
+
+static inline uint16_t
+adaptive_counter_bits(int value, int backoff) {
+ return (value << ADAPTIVE_BACKOFF_BITS) |
+ (backoff & ((1<<ADAPTIVE_BACKOFF_BITS)-1));
+}
+
+static inline uint16_t
+adaptive_counter_start(void) {
+ unsigned int value = (1 << ADAPTIVE_BACKOFF_START) - 1;
+ return adaptive_counter_bits(value, ADAPTIVE_BACKOFF_START);
+}
+
+static inline uint16_t
+adaptive_counter_backoff(uint16_t counter) {
+ unsigned int backoff = counter & ((1<<ADAPTIVE_BACKOFF_BITS)-1);
+ backoff++;
+ if (backoff > MAX_BACKOFF_VALUE) {
+ backoff = MAX_BACKOFF_VALUE;
+ }
+ unsigned int value = (1 << backoff) - 1;
+ return adaptive_counter_bits(value, backoff);
+}
+
+
+/* Line array cache for tracing */
+
+extern int _PyCode_CreateLineArray(PyCodeObject *co);
+
+static inline int
+_PyCode_InitLineArray(PyCodeObject *co)
+{
+ if (co->_co_linearray) {
+ return 0;
+ }
+ return _PyCode_CreateLineArray(co);
+}
+
+static inline int
+_PyCode_LineNumberFromArray(PyCodeObject *co, int index)
+{
+ assert(co->_co_linearray != NULL);
+ assert(index >= 0);
+ assert(index < Py_SIZE(co));
+ if (co->_co_linearray_entry_size == 2) {
+ return ((int16_t *)co->_co_linearray)[index];
+ }
+ else {
+ assert(co->_co_linearray_entry_size == 4);
+ return ((int32_t *)co->_co_linearray)[index];
+ }
+}
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_CODE_H */
diff --git a/include/python3.10/internal/pycore_compile.h b/include/python3.11/internal/pycore_compile.h
similarity index 100%
rename from include/python3.10/internal/pycore_compile.h
rename to include/python3.11/internal/pycore_compile.h
diff --git a/include/python3.11/internal/pycore_condvar.h b/include/python3.11/internal/pycore_condvar.h
new file mode 100644
index 0000000..981c962
--- /dev/null
+++ b/include/python3.11/internal/pycore_condvar.h
@@ -0,0 +1,97 @@
+#ifndef Py_INTERNAL_CONDVAR_H
+#define Py_INTERNAL_CONDVAR_H
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#ifndef _POSIX_THREADS
+/* This means pthreads are not implemented in libc headers, hence the macro
+ not present in unistd.h. But they still can be implemented as an external
+ library (e.g. gnu pth in pthread emulation) */
+# ifdef HAVE_PTHREAD_H
+# include <pthread.h> /* _POSIX_THREADS */
+# endif
+#endif
+
+#ifdef _POSIX_THREADS
+/*
+ * POSIX support
+ */
+#define Py_HAVE_CONDVAR
+
+#ifdef HAVE_PTHREAD_H
+# include <pthread.h>
+#endif
+
+#define PyMUTEX_T pthread_mutex_t
+#define PyCOND_T pthread_cond_t
+
+#elif defined(NT_THREADS)
+/*
+ * Windows (XP, 2003 server and later, as well as (hopefully) CE) support
+ *
+ * Emulated condition variables ones that work with XP and later, plus
+ * example native support on VISTA and onwards.
+ */
+#define Py_HAVE_CONDVAR
+
+/* include windows if it hasn't been done before */
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+
+/* options */
+/* non-emulated condition variables are provided for those that want
+ * to target Windows Vista. Modify this macro to enable them.
+ */
+#ifndef _PY_EMULATED_WIN_CV
+#define _PY_EMULATED_WIN_CV 1 /* use emulated condition variables */
+#endif
+
+/* fall back to emulation if not targeting Vista */
+#if !defined NTDDI_VISTA || NTDDI_VERSION < NTDDI_VISTA
+#undef _PY_EMULATED_WIN_CV
+#define _PY_EMULATED_WIN_CV 1
+#endif
+
+#if _PY_EMULATED_WIN_CV
+
+typedef CRITICAL_SECTION PyMUTEX_T;
+
+/* The ConditionVariable object. From XP onwards it is easily emulated
+ with a Semaphore.
+ Semaphores are available on Windows XP (2003 server) and later.
+ We use a Semaphore rather than an auto-reset event, because although
+ an auto-reset event might appear to solve the lost-wakeup bug (race
+ condition between releasing the outer lock and waiting) because it
+ maintains state even though a wait hasn't happened, there is still
+ a lost wakeup problem if more than one thread are interrupted in the
+ critical place. A semaphore solves that, because its state is
+ counted, not Boolean.
+ Because it is ok to signal a condition variable with no one
+ waiting, we need to keep track of the number of
+ waiting threads. Otherwise, the semaphore's state could rise
+ without bound. This also helps reduce the number of "spurious wakeups"
+ that would otherwise happen.
+ */
+
+typedef struct _PyCOND_T
+{
+ HANDLE sem;
+ int waiting; /* to allow PyCOND_SIGNAL to be a no-op */
+} PyCOND_T;
+
+#else /* !_PY_EMULATED_WIN_CV */
+
+/* Use native Win7 primitives if build target is Win7 or higher */
+
+/* SRWLOCK is faster and better than CriticalSection */
+typedef SRWLOCK PyMUTEX_T;
+
+typedef CONDITION_VARIABLE PyCOND_T;
+
+#endif /* _PY_EMULATED_WIN_CV */
+
+#endif /* _POSIX_THREADS, NT_THREADS */
+
+#endif /* Py_INTERNAL_CONDVAR_H */
diff --git a/include/python3.11/internal/pycore_context.h b/include/python3.11/internal/pycore_context.h
new file mode 100644
index 0000000..1bf4e8f
--- /dev/null
+++ b/include/python3.11/internal/pycore_context.h
@@ -0,0 +1,67 @@
+#ifndef Py_INTERNAL_CONTEXT_H
+#define Py_INTERNAL_CONTEXT_H
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#include "pycore_hamt.h" /* PyHamtObject */
+
+
+extern PyTypeObject _PyContextTokenMissing_Type;
+
+/* runtime lifecycle */
+
+PyStatus _PyContext_Init(PyInterpreterState *);
+void _PyContext_Fini(PyInterpreterState *);
+
+
+/* other API */
+
+#ifndef WITH_FREELISTS
+// without freelists
+# define PyContext_MAXFREELIST 0
+#endif
+
+#ifndef PyContext_MAXFREELIST
+# define PyContext_MAXFREELIST 255
+#endif
+
+struct _Py_context_state {
+#if PyContext_MAXFREELIST > 0
+ // List of free PyContext objects
+ PyContext *freelist;
+ int numfree;
+#endif
+};
+
+struct _pycontextobject {
+ PyObject_HEAD
+ PyContext *ctx_prev;
+ PyHamtObject *ctx_vars;
+ PyObject *ctx_weakreflist;
+ int ctx_entered;
+};
+
+
+struct _pycontextvarobject {
+ PyObject_HEAD
+ PyObject *var_name;
+ PyObject *var_default;
+ PyObject *var_cached;
+ uint64_t var_cached_tsid;
+ uint64_t var_cached_tsver;
+ Py_hash_t var_hash;
+};
+
+
+struct _pycontexttokenobject {
+ PyObject_HEAD
+ PyContext *tok_ctx;
+ PyContextVar *tok_var;
+ PyObject *tok_oldval;
+ int tok_used;
+};
+
+
+#endif /* !Py_INTERNAL_CONTEXT_H */
diff --git a/include/python3.11/internal/pycore_dict.h b/include/python3.11/internal/pycore_dict.h
new file mode 100644
index 0000000..dc308fe
--- /dev/null
+++ b/include/python3.11/internal/pycore_dict.h
@@ -0,0 +1,178 @@
+
+#ifndef Py_INTERNAL_DICT_H
+#define Py_INTERNAL_DICT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+
+/* runtime lifecycle */
+
+extern void _PyDict_Fini(PyInterpreterState *interp);
+
+
+/* other API */
+
+#ifndef WITH_FREELISTS
+// without freelists
+# define PyDict_MAXFREELIST 0
+#endif
+
+#ifndef PyDict_MAXFREELIST
+# define PyDict_MAXFREELIST 80
+#endif
+
+struct _Py_dict_state {
+#if PyDict_MAXFREELIST > 0
+ /* Dictionary reuse scheme to save calls to malloc and free */
+ PyDictObject *free_list[PyDict_MAXFREELIST];
+ int numfree;
+ PyDictKeysObject *keys_free_list[PyDict_MAXFREELIST];
+ int keys_numfree;
+#endif
+};
+
+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 struct {
+ PyObject *me_key; /* The key must be Unicode and have hash. */
+ PyObject *me_value; /* This field is only meaningful for combined tables */
+} PyDictUnicodeEntry;
+
+extern PyDictKeysObject *_PyDict_NewKeysForClass(void);
+extern PyObject *_PyDict_FromKeys(PyObject *, PyObject *, PyObject *);
+
+/* Gets a version number unique to the current state of the keys of dict, if possible.
+ * Returns the version number, or zero if it was not possible to get a version number. */
+extern uint32_t _PyDictKeys_GetVersionForCurrentState(PyDictKeysObject *dictkeys);
+
+extern Py_ssize_t _PyDict_KeysSize(PyDictKeysObject *keys);
+
+/* _Py_dict_lookup() returns index of entry which can be used like DK_ENTRIES(dk)[index].
+ * -1 when no entry found, -3 when compare raises error.
+ */
+extern Py_ssize_t _Py_dict_lookup(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject **value_addr);
+
+extern Py_ssize_t _PyDict_GetItemHint(PyDictObject *, PyObject *, Py_ssize_t, PyObject **);
+extern Py_ssize_t _PyDictKeys_StringLookup(PyDictKeysObject* dictkeys, PyObject *key);
+extern PyObject *_PyDict_LoadGlobal(PyDictObject *, PyDictObject *, PyObject *);
+
+/* Consumes references to key and value */
+extern int _PyDict_SetItem_Take2(PyDictObject *op, PyObject *key, PyObject *value);
+extern int _PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr, PyObject *name, PyObject *value);
+
+extern PyObject *_PyDict_Pop_KnownHash(PyObject *, PyObject *, Py_hash_t, PyObject *);
+
+#define DKIX_EMPTY (-1)
+#define DKIX_DUMMY (-2) /* Used internally */
+#define DKIX_ERROR (-3)
+#define DKIX_KEY_CHANGED (-4) /* Used internally */
+
+typedef enum {
+ DICT_KEYS_GENERAL = 0,
+ DICT_KEYS_UNICODE = 1,
+ DICT_KEYS_SPLIT = 2
+} DictKeysKind;
+
+/* See dictobject.c for actual layout of DictKeysObject */
+struct _dictkeysobject {
+ Py_ssize_t dk_refcnt;
+
+ /* Size of the hash table (dk_indices). It must be a power of 2. */
+ uint8_t dk_log2_size;
+
+ /* Size of the hash table (dk_indices) by bytes. */
+ uint8_t dk_log2_index_bytes;
+
+ /* Kind of keys */
+ uint8_t dk_kind;
+
+ /* Version number -- Reset to 0 by any modification to keys */
+ uint32_t dk_version;
+
+ /* Number of usable entries in dk_entries. */
+ Py_ssize_t dk_usable;
+
+ /* Number of used entries in dk_entries. */
+ Py_ssize_t dk_nentries;
+
+ /* Actual hash table of dk_size entries. It holds indices in dk_entries,
+ or DKIX_EMPTY(-1) or DKIX_DUMMY(-2).
+
+ Indices must be: 0 <= indice < USABLE_FRACTION(dk_size).
+
+ The size in bytes of an indice depends on dk_size:
+
+ - 1 byte if dk_size <= 0xff (char*)
+ - 2 bytes if dk_size <= 0xffff (int16_t*)
+ - 4 bytes if dk_size <= 0xffffffff (int32_t*)
+ - 8 bytes otherwise (int64_t*)
+
+ Dynamically sized, SIZEOF_VOID_P is minimum. */
+ char dk_indices[]; /* char is required to avoid strict aliasing. */
+
+ /* "PyDictKeyEntry or PyDictUnicodeEntry dk_entries[USABLE_FRACTION(DK_SIZE(dk))];" array follows:
+ see the DK_ENTRIES() macro */
+};
+
+/* This must be no more than 250, for the prefix size to fit in one byte. */
+#define SHARED_KEYS_MAX_SIZE 30
+#define NEXT_LOG2_SHARED_KEYS_MAX_SIZE 6
+
+/* Layout of dict values:
+ *
+ * The PyObject *values are preceded by an array of bytes holding
+ * the insertion order and size.
+ * [-1] = prefix size. [-2] = used size. size[-2-n...] = insertion order.
+ */
+struct _dictvalues {
+ PyObject *values[1];
+};
+
+#define DK_LOG_SIZE(dk) ((dk)->dk_log2_size)
+#if SIZEOF_VOID_P > 4
+#define DK_SIZE(dk) (((int64_t)1)<<DK_LOG_SIZE(dk))
+#else
+#define DK_SIZE(dk) (1<<DK_LOG_SIZE(dk))
+#endif
+#define DK_ENTRIES(dk) \
+ (assert(dk->dk_kind == DICT_KEYS_GENERAL), (PyDictKeyEntry*)(&((int8_t*)((dk)->dk_indices))[(size_t)1 << (dk)->dk_log2_index_bytes]))
+#define DK_UNICODE_ENTRIES(dk) \
+ (assert(dk->dk_kind != DICT_KEYS_GENERAL), (PyDictUnicodeEntry*)(&((int8_t*)((dk)->dk_indices))[(size_t)1 << (dk)->dk_log2_index_bytes]))
+#define DK_IS_UNICODE(dk) ((dk)->dk_kind != DICT_KEYS_GENERAL)
+
+extern uint64_t _pydict_global_version;
+
+#define DICT_NEXT_VERSION() (++_pydict_global_version)
+
+extern PyObject *_PyObject_MakeDictFromInstanceAttributes(PyObject *obj, PyDictValues *values);
+extern PyObject *_PyDict_FromItems(
+ PyObject *const *keys, Py_ssize_t keys_offset,
+ PyObject *const *values, Py_ssize_t values_offset,
+ Py_ssize_t length);
+
+static inline void
+_PyDictValues_AddToInsertionOrder(PyDictValues *values, Py_ssize_t ix)
+{
+ assert(ix < SHARED_KEYS_MAX_SIZE);
+ uint8_t *size_ptr = ((uint8_t *)values)-2;
+ int size = *size_ptr;
+ assert(size+2 < ((uint8_t *)values)[-1]);
+ size++;
+ size_ptr[-size] = (uint8_t)ix;
+ *size_ptr = size;
+}
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_DICT_H */
diff --git a/include/python3.11/internal/pycore_dtoa.h b/include/python3.11/internal/pycore_dtoa.h
new file mode 100644
index 0000000..c77cf6e
--- /dev/null
+++ b/include/python3.11/internal/pycore_dtoa.h
@@ -0,0 +1,28 @@
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#include "pycore_pymath.h" // _PY_SHORT_FLOAT_REPR
+
+
+#if _PY_SHORT_FLOAT_REPR == 1
+
+/* These functions are used by modules compiled as C extension like math:
+ they must be exported. */
+
+PyAPI_FUNC(double) _Py_dg_strtod(const char *str, char **ptr);
+PyAPI_FUNC(char *) _Py_dg_dtoa(double d, int mode, int ndigits,
+ int *decpt, int *sign, char **rve);
+PyAPI_FUNC(void) _Py_dg_freedtoa(char *s);
+PyAPI_FUNC(double) _Py_dg_stdnan(int sign);
+PyAPI_FUNC(double) _Py_dg_infinity(int sign);
+
+#endif // _PY_SHORT_FLOAT_REPR == 1
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/include/python3.11/internal/pycore_emscripten_signal.h b/include/python3.11/internal/pycore_emscripten_signal.h
new file mode 100644
index 0000000..8b3287d
--- /dev/null
+++ b/include/python3.11/internal/pycore_emscripten_signal.h
@@ -0,0 +1,25 @@
+#ifndef Py_EMSCRIPTEN_SIGNAL_H
+#define Py_EMSCRIPTEN_SIGNAL_H
+
+#if defined(__EMSCRIPTEN__)
+
+void
+_Py_CheckEmscriptenSignals(void);
+
+void
+_Py_CheckEmscriptenSignalsPeriodically(void);
+
+#define _Py_CHECK_EMSCRIPTEN_SIGNALS() _Py_CheckEmscriptenSignals()
+
+#define _Py_CHECK_EMSCRIPTEN_SIGNALS_PERIODICALLY() _Py_CheckEmscriptenSignalsPeriodically()
+
+extern int Py_EMSCRIPTEN_SIGNAL_HANDLING;
+
+#else
+
+#define _Py_CHECK_EMSCRIPTEN_SIGNALS()
+#define _Py_CHECK_EMSCRIPTEN_SIGNALS_PERIODICALLY()
+
+#endif // defined(__EMSCRIPTEN__)
+
+#endif // ndef Py_EMSCRIPTEN_SIGNAL_H
diff --git a/include/python3.11/internal/pycore_exceptions.h b/include/python3.11/internal/pycore_exceptions.h
new file mode 100644
index 0000000..4a9df70
--- /dev/null
+++ b/include/python3.11/internal/pycore_exceptions.h
@@ -0,0 +1,37 @@
+#ifndef Py_INTERNAL_EXCEPTIONS_H
+#define Py_INTERNAL_EXCEPTIONS_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+
+/* runtime lifecycle */
+
+extern PyStatus _PyExc_InitState(PyInterpreterState *);
+extern PyStatus _PyExc_InitGlobalObjects(PyInterpreterState *);
+extern int _PyExc_InitTypes(PyInterpreterState *);
+extern void _PyExc_Fini(PyInterpreterState *);
+
+
+/* other API */
+
+struct _Py_exc_state {
+ // The dict mapping from errno codes to OSError subclasses
+ PyObject *errnomap;
+ PyBaseExceptionObject *memerrors_freelist;
+ int memerrors_numfree;
+ // The ExceptionGroup type
+ PyObject *PyExc_ExceptionGroup;
+};
+
+extern void _PyExc_ClearExceptionGroupType(PyInterpreterState *);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_EXCEPTIONS_H */
diff --git a/include/python3.11/internal/pycore_fileutils.h b/include/python3.11/internal/pycore_fileutils.h
new file mode 100644
index 0000000..3ce8108
--- /dev/null
+++ b/include/python3.11/internal/pycore_fileutils.h
@@ -0,0 +1,275 @@
+#ifndef Py_INTERNAL_FILEUTILS_H
+#define Py_INTERNAL_FILEUTILS_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "Py_BUILD_CORE must be defined to include this header"
+#endif
+
+#include <locale.h> /* struct lconv */
+
+typedef enum {
+ _Py_ERROR_UNKNOWN=0,
+ _Py_ERROR_STRICT,
+ _Py_ERROR_SURROGATEESCAPE,
+ _Py_ERROR_REPLACE,
+ _Py_ERROR_IGNORE,
+ _Py_ERROR_BACKSLASHREPLACE,
+ _Py_ERROR_SURROGATEPASS,
+ _Py_ERROR_XMLCHARREFREPLACE,
+ _Py_ERROR_OTHER
+} _Py_error_handler;
+
+PyAPI_FUNC(_Py_error_handler) _Py_GetErrorHandler(const char *errors);
+
+PyAPI_FUNC(int) _Py_DecodeLocaleEx(
+ const char *arg,
+ wchar_t **wstr,
+ size_t *wlen,
+ const char **reason,
+ int current_locale,
+ _Py_error_handler errors);
+
+PyAPI_FUNC(int) _Py_EncodeLocaleEx(
+ const wchar_t *text,
+ char **str,
+ size_t *error_pos,
+ const char **reason,
+ int current_locale,
+ _Py_error_handler errors);
+
+PyAPI_FUNC(char*) _Py_EncodeLocaleRaw(
+ const wchar_t *text,
+ size_t *error_pos);
+
+PyAPI_FUNC(PyObject *) _Py_device_encoding(int);
+
+#if defined(MS_WINDOWS) || defined(__APPLE__)
+ /* On Windows, the count parameter of read() is an int (bpo-9015, bpo-9611).
+ On macOS 10.13, read() and write() with more than INT_MAX bytes
+ fail with EINVAL (bpo-24658). */
+# define _PY_READ_MAX INT_MAX
+# define _PY_WRITE_MAX INT_MAX
+#else
+ /* write() should truncate the input to PY_SSIZE_T_MAX bytes,
+ but it's safer to do it ourself to have a portable behaviour */
+# define _PY_READ_MAX PY_SSIZE_T_MAX
+# define _PY_WRITE_MAX PY_SSIZE_T_MAX
+#endif
+
+#ifdef MS_WINDOWS
+struct _Py_stat_struct {
+ unsigned long st_dev;
+ uint64_t st_ino;
+ unsigned short st_mode;
+ int st_nlink;
+ int st_uid;
+ int st_gid;
+ unsigned long st_rdev;
+ __int64 st_size;
+ time_t st_atime;
+ int st_atime_nsec;
+ time_t st_mtime;
+ int st_mtime_nsec;
+ time_t st_ctime;
+ int st_ctime_nsec;
+ unsigned long st_file_attributes;
+ unsigned long st_reparse_tag;
+};
+#else
+# define _Py_stat_struct stat
+#endif
+
+PyAPI_FUNC(int) _Py_fstat(
+ int fd,
+ struct _Py_stat_struct *status);
+
+PyAPI_FUNC(int) _Py_fstat_noraise(
+ int fd,
+ struct _Py_stat_struct *status);
+
+PyAPI_FUNC(int) _Py_stat(
+ PyObject *path,
+ struct stat *status);
+
+PyAPI_FUNC(int) _Py_open(
+ const char *pathname,
+ int flags);
+
+PyAPI_FUNC(int) _Py_open_noraise(
+ const char *pathname,
+ int flags);
+
+PyAPI_FUNC(FILE *) _Py_wfopen(
+ const wchar_t *path,
+ const wchar_t *mode);
+
+PyAPI_FUNC(Py_ssize_t) _Py_read(
+ int fd,
+ void *buf,
+ size_t count);
+
+PyAPI_FUNC(Py_ssize_t) _Py_write(
+ int fd,
+ const void *buf,
+ size_t count);
+
+PyAPI_FUNC(Py_ssize_t) _Py_write_noraise(
+ int fd,
+ const void *buf,
+ size_t count);
+
+#ifdef HAVE_READLINK
+PyAPI_FUNC(int) _Py_wreadlink(
+ const wchar_t *path,
+ wchar_t *buf,
+ /* Number of characters of 'buf' buffer
+ including the trailing NUL character */
+ size_t buflen);
+#endif
+
+#ifdef HAVE_REALPATH
+PyAPI_FUNC(wchar_t*) _Py_wrealpath(
+ const wchar_t *path,
+ wchar_t *resolved_path,
+ /* Number of characters of 'resolved_path' buffer
+ including the trailing NUL character */
+ size_t resolved_path_len);
+#endif
+
+PyAPI_FUNC(wchar_t*) _Py_wgetcwd(
+ wchar_t *buf,
+ /* Number of characters of 'buf' buffer
+ including the trailing NUL character */
+ size_t buflen);
+
+PyAPI_FUNC(int) _Py_get_inheritable(int fd);
+
+PyAPI_FUNC(int) _Py_set_inheritable(int fd, int inheritable,
+ int *atomic_flag_works);
+
+PyAPI_FUNC(int) _Py_set_inheritable_async_safe(int fd, int inheritable,
+ int *atomic_flag_works);
+
+PyAPI_FUNC(int) _Py_dup(int fd);
+
+#ifndef MS_WINDOWS
+PyAPI_FUNC(int) _Py_get_blocking(int fd);
+
+PyAPI_FUNC(int) _Py_set_blocking(int fd, int blocking);
+#else /* MS_WINDOWS */
+PyAPI_FUNC(void*) _Py_get_osfhandle_noraise(int fd);
+
+PyAPI_FUNC(void*) _Py_get_osfhandle(int fd);
+
+PyAPI_FUNC(int) _Py_open_osfhandle_noraise(void *handle, int flags);
+
+PyAPI_FUNC(int) _Py_open_osfhandle(void *handle, int flags);
+#endif /* MS_WINDOWS */
+
+// This is used after getting NULL back from Py_DecodeLocale().
+#define DECODE_LOCALE_ERR(NAME, LEN) \
+ ((LEN) == (size_t)-2) \
+ ? _PyStatus_ERR("cannot decode " NAME) \
+ : _PyStatus_NO_MEMORY()
+
+PyAPI_DATA(int) _Py_HasFileSystemDefaultEncodeErrors;
+
+PyAPI_FUNC(int) _Py_DecodeUTF8Ex(
+ const char *arg,
+ Py_ssize_t arglen,
+ wchar_t **wstr,
+ size_t *wlen,
+ const char **reason,
+ _Py_error_handler errors);
+
+PyAPI_FUNC(int) _Py_EncodeUTF8Ex(
+ const wchar_t *text,
+ char **str,
+ size_t *error_pos,
+ const char **reason,
+ int raw_malloc,
+ _Py_error_handler errors);
+
+PyAPI_FUNC(wchar_t*) _Py_DecodeUTF8_surrogateescape(
+ const char *arg,
+ Py_ssize_t arglen,
+ size_t *wlen);
+
+extern int
+_Py_wstat(const wchar_t *, struct stat *);
+
+PyAPI_FUNC(int) _Py_GetForceASCII(void);
+
+/* Reset "force ASCII" mode (if it was initialized).
+
+ This function should be called when Python changes the LC_CTYPE locale,
+ so the "force ASCII" mode can be detected again on the new locale
+ encoding. */
+PyAPI_FUNC(void) _Py_ResetForceASCII(void);
+
+
+PyAPI_FUNC(int) _Py_GetLocaleconvNumeric(
+ struct lconv *lc,
+ PyObject **decimal_point,
+ PyObject **thousands_sep);
+
+PyAPI_FUNC(void) _Py_closerange(int first, int last);
+
+PyAPI_FUNC(wchar_t*) _Py_GetLocaleEncoding(void);
+PyAPI_FUNC(PyObject*) _Py_GetLocaleEncodingObject(void);
+
+#ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
+extern int _Py_LocaleUsesNonUnicodeWchar(void);
+
+extern wchar_t* _Py_DecodeNonUnicodeWchar(
+ const wchar_t* native,
+ Py_ssize_t size);
+
+extern int _Py_EncodeNonUnicodeWchar_InPlace(
+ wchar_t* unicode,
+ Py_ssize_t size);
+#endif
+
+extern int _Py_isabs(const wchar_t *path);
+extern int _Py_abspath(const wchar_t *path, wchar_t **abspath_p);
+#ifdef MS_WINDOWS
+extern int _PyOS_getfullpathname(const wchar_t *path, wchar_t **abspath_p);
+#endif
+extern wchar_t * _Py_join_relfile(const wchar_t *dirname,
+ const wchar_t *relfile);
+extern int _Py_add_relfile(wchar_t *dirname,
+ const wchar_t *relfile,
+ size_t bufsize);
+extern size_t _Py_find_basename(const wchar_t *filename);
+PyAPI_FUNC(wchar_t *) _Py_normpath(wchar_t *path, Py_ssize_t size);
+
+
+// Macros to protect CRT calls against instant termination when passed an
+// invalid parameter (bpo-23524). IPH stands for Invalid Parameter Handler.
+// Usage:
+//
+// _Py_BEGIN_SUPPRESS_IPH
+// ...
+// _Py_END_SUPPRESS_IPH
+#if defined _MSC_VER && _MSC_VER >= 1900
+
+# include <stdlib.h> // _set_thread_local_invalid_parameter_handler()
+
+ extern _invalid_parameter_handler _Py_silent_invalid_parameter_handler;
+# define _Py_BEGIN_SUPPRESS_IPH \
+ { _invalid_parameter_handler _Py_old_handler = \
+ _set_thread_local_invalid_parameter_handler(_Py_silent_invalid_parameter_handler);
+# define _Py_END_SUPPRESS_IPH \
+ _set_thread_local_invalid_parameter_handler(_Py_old_handler); }
+#else
+# define _Py_BEGIN_SUPPRESS_IPH
+# define _Py_END_SUPPRESS_IPH
+#endif /* _MSC_VER >= 1900 */
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_FILEUTILS_H */
diff --git a/include/python3.11/internal/pycore_floatobject.h b/include/python3.11/internal/pycore_floatobject.h
new file mode 100644
index 0000000..8a65554
--- /dev/null
+++ b/include/python3.11/internal/pycore_floatobject.h
@@ -0,0 +1,59 @@
+#ifndef Py_INTERNAL_FLOATOBJECT_H
+#define Py_INTERNAL_FLOATOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+
+/* runtime lifecycle */
+
+extern void _PyFloat_InitState(PyInterpreterState *);
+extern PyStatus _PyFloat_InitTypes(PyInterpreterState *);
+extern void _PyFloat_Fini(PyInterpreterState *);
+extern void _PyFloat_FiniType(PyInterpreterState *);
+
+
+/* other API */
+
+#ifndef WITH_FREELISTS
+// without freelists
+# define PyFloat_MAXFREELIST 0
+#endif
+
+#ifndef PyFloat_MAXFREELIST
+# define PyFloat_MAXFREELIST 100
+#endif
+
+struct _Py_float_state {
+#if PyFloat_MAXFREELIST > 0
+ /* Special free list
+ free_list is a singly-linked list of available PyFloatObjects,
+ linked via abuse of their ob_type members. */
+ int numfree;
+ PyFloatObject *free_list;
+#endif
+};
+
+void _PyFloat_ExactDealloc(PyObject *op);
+
+
+PyAPI_FUNC(void) _PyFloat_DebugMallocStats(FILE* out);
+
+
+/* Format the object based on the format_spec, as defined in PEP 3101
+ (Advanced String Formatting). */
+PyAPI_FUNC(int) _PyFloat_FormatAdvancedWriter(
+ _PyUnicodeWriter *writer,
+ PyObject *obj,
+ PyObject *format_spec,
+ Py_ssize_t start,
+ Py_ssize_t end);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_FLOATOBJECT_H */
diff --git a/include/python3.10/internal/pycore_format.h b/include/python3.11/internal/pycore_format.h
similarity index 100%
rename from include/python3.10/internal/pycore_format.h
rename to include/python3.11/internal/pycore_format.h
diff --git a/include/python3.11/internal/pycore_frame.h b/include/python3.11/internal/pycore_frame.h
new file mode 100644
index 0000000..4866ea2
--- /dev/null
+++ b/include/python3.11/internal/pycore_frame.h
@@ -0,0 +1,240 @@
+#ifndef Py_INTERNAL_FRAME_H
+#define Py_INTERNAL_FRAME_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdbool.h>
+#include <stddef.h>
+
+/* See Objects/frame_layout.md for an explanation of the frame stack
+ * including explanation of the PyFrameObject and _PyInterpreterFrame
+ * structs. */
+
+
+struct _frame {
+ PyObject_HEAD
+ PyFrameObject *f_back; /* previous frame, or NULL */
+ struct _PyInterpreterFrame *f_frame; /* points to the frame data */
+ PyObject *f_trace; /* Trace function */
+ int f_lineno; /* Current line number. Only valid if non-zero */
+ char f_trace_lines; /* Emit per-line trace events? */
+ char f_trace_opcodes; /* Emit per-opcode trace events? */
+ char f_fast_as_locals; /* Have the fast locals of this frame been converted to a dict? */
+ /* The frame data, if this frame object owns the frame */
+ PyObject *_f_frame_data[1];
+};
+
+extern PyFrameObject* _PyFrame_New_NoTrack(PyCodeObject *code);
+
+
+/* other API */
+
+typedef enum _framestate {
+ FRAME_CREATED = -2,
+ FRAME_SUSPENDED = -1,
+ FRAME_EXECUTING = 0,
+ FRAME_COMPLETED = 1,
+ FRAME_CLEARED = 4
+} PyFrameState;
+
+enum _frameowner {
+ FRAME_OWNED_BY_THREAD = 0,
+ FRAME_OWNED_BY_GENERATOR = 1,
+ FRAME_OWNED_BY_FRAME_OBJECT = 2
+};
+
+typedef struct _PyInterpreterFrame {
+ /* "Specials" section */
+ PyFunctionObject *f_func; /* Strong reference */
+ PyObject *f_globals; /* Borrowed reference */
+ PyObject *f_builtins; /* Borrowed reference */
+ PyObject *f_locals; /* Strong reference, may be NULL */
+ PyCodeObject *f_code; /* Strong reference */
+ PyFrameObject *frame_obj; /* Strong reference, may be NULL */
+ /* Linkage section */
+ struct _PyInterpreterFrame *previous;
+ // NOTE: This is not necessarily the last instruction started in the given
+ // frame. Rather, it is the code unit *prior to* the *next* instruction. For
+ // example, it may be an inline CACHE entry, an instruction we just jumped
+ // over, or (in the case of a newly-created frame) a totally invalid value:
+ _Py_CODEUNIT *prev_instr;
+ int stacktop; /* Offset of TOS from localsplus */
+ bool is_entry; // Whether this is the "root" frame for the current _PyCFrame.
+ char owner;
+ /* Locals and stack */
+ PyObject *localsplus[1];
+} _PyInterpreterFrame;
+
+#define _PyInterpreterFrame_LASTI(IF) \
+ ((int)((IF)->prev_instr - _PyCode_CODE((IF)->f_code)))
+
+static inline PyObject **_PyFrame_Stackbase(_PyInterpreterFrame *f) {
+ return f->localsplus + f->f_code->co_nlocalsplus;
+}
+
+static inline PyObject *_PyFrame_StackPeek(_PyInterpreterFrame *f) {
+ assert(f->stacktop > f->f_code->co_nlocalsplus);
+ assert(f->localsplus[f->stacktop-1] != NULL);
+ return f->localsplus[f->stacktop-1];
+}
+
+static inline PyObject *_PyFrame_StackPop(_PyInterpreterFrame *f) {
+ assert(f->stacktop > f->f_code->co_nlocalsplus);
+ f->stacktop--;
+ return f->localsplus[f->stacktop];
+}
+
+static inline void _PyFrame_StackPush(_PyInterpreterFrame *f, PyObject *value) {
+ f->localsplus[f->stacktop] = value;
+ f->stacktop++;
+}
+
+#define FRAME_SPECIALS_SIZE ((sizeof(_PyInterpreterFrame)-1)/sizeof(PyObject *))
+
+void _PyFrame_Copy(_PyInterpreterFrame *src, _PyInterpreterFrame *dest);
+
+/* Consumes reference to func and locals.
+ Does not initialize frame->previous, which happens
+ when frame is linked into the frame stack.
+ */
+static inline void
+_PyFrame_InitializeSpecials(
+ _PyInterpreterFrame *frame, PyFunctionObject *func,
+ PyObject *locals, int nlocalsplus)
+{
+ frame->f_func = func;
+ frame->f_code = (PyCodeObject *)Py_NewRef(func->func_code);
+ frame->f_builtins = func->func_builtins;
+ frame->f_globals = func->func_globals;
+ frame->f_locals = Py_XNewRef(locals);
+ frame->stacktop = nlocalsplus;
+ frame->frame_obj = NULL;
+ frame->prev_instr = _PyCode_CODE(frame->f_code) - 1;
+ frame->is_entry = false;
+ frame->owner = FRAME_OWNED_BY_THREAD;
+}
+
+/* Gets the pointer to the locals array
+ * that precedes this frame.
+ */
+static inline PyObject**
+_PyFrame_GetLocalsArray(_PyInterpreterFrame *frame)
+{
+ return frame->localsplus;
+}
+
+static inline PyObject**
+_PyFrame_GetStackPointer(_PyInterpreterFrame *frame)
+{
+ return frame->localsplus+frame->stacktop;
+}
+
+static inline void
+_PyFrame_SetStackPointer(_PyInterpreterFrame *frame, PyObject **stack_pointer)
+{
+ frame->stacktop = (int)(stack_pointer - frame->localsplus);
+}
+
+/* Determine whether a frame is incomplete.
+ * A frame is incomplete if it is part way through
+ * creating cell objects or a generator or coroutine.
+ *
+ * Frames on the frame stack are incomplete until the
+ * first RESUME instruction.
+ * Frames owned by a generator are always complete.
+ */
+static inline bool
+_PyFrame_IsIncomplete(_PyInterpreterFrame *frame)
+{
+ return frame->owner != FRAME_OWNED_BY_GENERATOR &&
+ frame->prev_instr < _PyCode_CODE(frame->f_code) + frame->f_code->_co_firsttraceable;
+}
+
+/* For use by _PyFrame_GetFrameObject
+ Do not call directly. */
+PyFrameObject *
+_PyFrame_MakeAndSetFrameObject(_PyInterpreterFrame *frame);
+
+/* Gets the PyFrameObject for this frame, lazily
+ * creating it if necessary.
+ * Returns a borrowed referennce */
+static inline PyFrameObject *
+_PyFrame_GetFrameObject(_PyInterpreterFrame *frame)
+{
+
+ assert(!_PyFrame_IsIncomplete(frame));
+ PyFrameObject *res = frame->frame_obj;
+ if (res != NULL) {
+ return res;
+ }
+ return _PyFrame_MakeAndSetFrameObject(frame);
+}
+
+/* Clears all references in the frame.
+ * If take is non-zero, then the _PyInterpreterFrame frame
+ * may be transferred to the frame object it references
+ * instead of being cleared. Either way
+ * the caller no longer owns the references
+ * in the frame.
+ * take should be set to 1 for heap allocated
+ * frames like the ones in generators and coroutines.
+ */
+void
+_PyFrame_Clear(_PyInterpreterFrame * frame);
+
+int
+_PyFrame_Traverse(_PyInterpreterFrame *frame, visitproc visit, void *arg);
+
+int
+_PyFrame_FastToLocalsWithError(_PyInterpreterFrame *frame);
+
+void
+_PyFrame_LocalsToFast(_PyInterpreterFrame *frame, int clear);
+
+extern _PyInterpreterFrame *
+_PyThreadState_BumpFramePointerSlow(PyThreadState *tstate, size_t size);
+
+static inline bool
+_PyThreadState_HasStackSpace(PyThreadState *tstate, size_t size)
+{
+ assert(
+ (tstate->datastack_top == NULL && tstate->datastack_limit == NULL)
+ ||
+ (tstate->datastack_top != NULL && tstate->datastack_limit != NULL)
+ );
+ return tstate->datastack_top != NULL &&
+ size < (size_t)(tstate->datastack_limit - tstate->datastack_top);
+}
+
+static inline _PyInterpreterFrame *
+_PyThreadState_BumpFramePointer(PyThreadState *tstate, size_t size)
+{
+ if (_PyThreadState_HasStackSpace(tstate, size)) {
+ _PyInterpreterFrame *res = (_PyInterpreterFrame *)tstate->datastack_top;
+ tstate->datastack_top += size;
+ return res;
+ }
+ return _PyThreadState_BumpFramePointerSlow(tstate, size);
+}
+
+void _PyThreadState_PopFrame(PyThreadState *tstate, _PyInterpreterFrame *frame);
+
+/* Consume reference to func */
+_PyInterpreterFrame *
+_PyFrame_Push(PyThreadState *tstate, PyFunctionObject *func);
+
+int _PyInterpreterFrame_GetLine(_PyInterpreterFrame *frame);
+
+static inline
+PyGenObject *_PyFrame_GetGenerator(_PyInterpreterFrame *frame)
+{
+ assert(frame->owner == FRAME_OWNED_BY_GENERATOR);
+ size_t offset_in_gen = offsetof(PyGenObject, gi_iframe);
+ return (PyGenObject *)(((char *)frame) - offset_in_gen);
+}
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_FRAME_H */
diff --git a/include/python3.11/internal/pycore_function.h b/include/python3.11/internal/pycore_function.h
new file mode 100644
index 0000000..1c87aa3
--- /dev/null
+++ b/include/python3.11/internal/pycore_function.h
@@ -0,0 +1,18 @@
+#ifndef Py_INTERNAL_FUNCTION_H
+#define Py_INTERNAL_FUNCTION_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+extern PyFunctionObject* _PyFunction_FromConstructor(PyFrameConstructor *constr);
+
+extern uint32_t _PyFunction_GetVersionForCurrentState(PyFunctionObject *func);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_FUNCTION_H */
diff --git a/include/python3.11/internal/pycore_gc.h b/include/python3.11/internal/pycore_gc.h
new file mode 100644
index 0000000..16c1893
--- /dev/null
+++ b/include/python3.11/internal/pycore_gc.h
@@ -0,0 +1,183 @@
+#ifndef Py_INTERNAL_GC_H
+#define Py_INTERNAL_GC_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+/* GC information is stored BEFORE the object structure. */
+typedef struct {
+ // Pointer to next object in the list.
+ // 0 means the object is not tracked
+ uintptr_t _gc_next;
+
+ // Pointer to previous object in the list.
+ // Lowest two bits are used for flags documented later.
+ uintptr_t _gc_prev;
+} PyGC_Head;
+
+#define _Py_AS_GC(o) ((PyGC_Head *)(o)-1)
+#define _PyGC_Head_UNUSED PyGC_Head
+
+/* True if the object is currently tracked by the GC. */
+#define _PyObject_GC_IS_TRACKED(o) (_Py_AS_GC(o)->_gc_next != 0)
+
+/* True if the object may be tracked by the GC in the future, or already is.
+ This can be useful to implement some optimizations. */
+#define _PyObject_GC_MAY_BE_TRACKED(obj) \
+ (PyObject_IS_GC(obj) && \
+ (!PyTuple_CheckExact(obj) || _PyObject_GC_IS_TRACKED(obj)))
+
+
+/* Bit flags for _gc_prev */
+/* Bit 0 is set when tp_finalize is called */
+#define _PyGC_PREV_MASK_FINALIZED (1)
+/* Bit 1 is set when the object is in generation which is GCed currently. */
+#define _PyGC_PREV_MASK_COLLECTING (2)
+/* The (N-2) most significant bits contain the real address. */
+#define _PyGC_PREV_SHIFT (2)
+#define _PyGC_PREV_MASK (((uintptr_t) -1) << _PyGC_PREV_SHIFT)
+
+// Lowest bit of _gc_next is used for flags only in GC.
+// But it is always 0 for normal code.
+#define _PyGCHead_NEXT(g) ((PyGC_Head*)(g)->_gc_next)
+#define _PyGCHead_SET_NEXT(g, p) _Py_RVALUE((g)->_gc_next = (uintptr_t)(p))
+
+// Lowest two bits of _gc_prev is used for _PyGC_PREV_MASK_* flags.
+#define _PyGCHead_PREV(g) ((PyGC_Head*)((g)->_gc_prev & _PyGC_PREV_MASK))
+#define _PyGCHead_SET_PREV(g, p) do { \
+ assert(((uintptr_t)p & ~_PyGC_PREV_MASK) == 0); \
+ (g)->_gc_prev = ((g)->_gc_prev & ~_PyGC_PREV_MASK) \
+ | ((uintptr_t)(p)); \
+ } while (0)
+
+#define _PyGCHead_FINALIZED(g) \
+ (((g)->_gc_prev & _PyGC_PREV_MASK_FINALIZED) != 0)
+#define _PyGCHead_SET_FINALIZED(g) \
+ _Py_RVALUE((g)->_gc_prev |= _PyGC_PREV_MASK_FINALIZED)
+
+#define _PyGC_FINALIZED(o) \
+ _PyGCHead_FINALIZED(_Py_AS_GC(o))
+#define _PyGC_SET_FINALIZED(o) \
+ _PyGCHead_SET_FINALIZED(_Py_AS_GC(o))
+
+
+/* GC runtime state */
+
+/* If we change this, we need to change the default value in the
+ signature of gc.collect. */
+#define NUM_GENERATIONS 3
+/*
+ NOTE: about untracking of mutable objects.
+
+ Certain types of container cannot participate in a reference cycle, and
+ so do not need to be tracked by the garbage collector. Untracking these
+ objects reduces the cost of garbage collections. However, determining
+ which objects may be untracked is not free, and the costs must be
+ weighed against the benefits for garbage collection.
+
+ There are two possible strategies for when to untrack a container:
+
+ i) When the container is created.
+ ii) When the container is examined by the garbage collector.
+
+ Tuples containing only immutable objects (integers, strings etc, and
+ recursively, tuples of immutable objects) do not need to be tracked.
+ The interpreter creates a large number of tuples, many of which will
+ not survive until garbage collection. It is therefore not worthwhile
+ to untrack eligible tuples at creation time.
+
+ Instead, all tuples except the empty tuple are tracked when created.
+ During garbage collection it is determined whether any surviving tuples
+ can be untracked. A tuple can be untracked if all of its contents are
+ already not tracked. Tuples are examined for untracking in all garbage
+ collection cycles. It may take more than one cycle to untrack a tuple.
+
+ Dictionaries containing only immutable objects also do not need to be
+ tracked. Dictionaries are untracked when created. If a tracked item is
+ inserted into a dictionary (either as a key or value), the dictionary
+ becomes tracked. During a full garbage collection (all generations),
+ the collector will untrack any dictionaries whose contents are not
+ tracked.
+
+ The module provides the python function is_tracked(obj), which returns
+ the CURRENT tracking status of the object. Subsequent garbage
+ collections may change the tracking status of the object.
+
+ Untracking of certain containers was introduced in issue #4688, and
+ the algorithm was refined in response to issue #14775.
+*/
+
+struct gc_generation {
+ PyGC_Head head;
+ int threshold; /* collection threshold */
+ int count; /* count of allocations or collections of younger
+ generations */
+};
+
+/* Running stats per generation */
+struct gc_generation_stats {
+ /* total number of collections */
+ Py_ssize_t collections;
+ /* total number of collected objects */
+ Py_ssize_t collected;
+ /* total number of uncollectable objects (put into gc.garbage) */
+ Py_ssize_t uncollectable;
+};
+
+struct _gc_runtime_state {
+ /* List of objects that still need to be cleaned up, singly linked
+ * via their gc headers' gc_prev pointers. */
+ PyObject *trash_delete_later;
+ /* Current call-stack depth of tp_dealloc calls. */
+ int trash_delete_nesting;
+
+ /* Is automatic collection enabled? */
+ int enabled;
+ int debug;
+ /* linked lists of container objects */
+ struct gc_generation generations[NUM_GENERATIONS];
+ PyGC_Head *generation0;
+ /* a permanent generation which won't be collected */
+ struct gc_generation permanent_generation;
+ struct gc_generation_stats generation_stats[NUM_GENERATIONS];
+ /* true if we are currently running the collector */
+ int collecting;
+ /* list of uncollectable objects */
+ PyObject *garbage;
+ /* a list of callbacks to be invoked when collection is performed */
+ PyObject *callbacks;
+ /* This is the number of objects that survived the last full
+ collection. It approximates the number of long lived objects
+ tracked by the GC.
+
+ (by "full collection", we mean a collection of the oldest
+ generation). */
+ Py_ssize_t long_lived_total;
+ /* This is the number of objects that survived all "non-full"
+ collections, and are awaiting to undergo a full collection for
+ the first time. */
+ Py_ssize_t long_lived_pending;
+};
+
+
+extern void _PyGC_InitState(struct _gc_runtime_state *);
+
+extern Py_ssize_t _PyGC_CollectNoFail(PyThreadState *tstate);
+
+
+// Functions to clear types free lists
+extern void _PyTuple_ClearFreeList(PyInterpreterState *interp);
+extern void _PyFloat_ClearFreeList(PyInterpreterState *interp);
+extern void _PyList_ClearFreeList(PyInterpreterState *interp);
+extern void _PyDict_ClearFreeList(PyInterpreterState *interp);
+extern void _PyAsyncGen_ClearFreeLists(PyInterpreterState *interp);
+extern void _PyContext_ClearFreeList(PyInterpreterState *interp);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_GC_H */
diff --git a/include/python3.11/internal/pycore_genobject.h b/include/python3.11/internal/pycore_genobject.h
new file mode 100644
index 0000000..42db0d8
--- /dev/null
+++ b/include/python3.11/internal/pycore_genobject.h
@@ -0,0 +1,49 @@
+#ifndef Py_INTERNAL_GENOBJECT_H
+#define Py_INTERNAL_GENOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+extern PyObject *_PyGen_yf(PyGenObject *);
+extern PyObject *_PyCoro_GetAwaitableIter(PyObject *o);
+extern PyObject *_PyAsyncGenValueWrapperNew(PyObject *);
+
+/* runtime lifecycle */
+
+extern void _PyAsyncGen_Fini(PyInterpreterState *);
+
+
+/* other API */
+
+#ifndef WITH_FREELISTS
+// without freelists
+# define _PyAsyncGen_MAXFREELIST 0
+#endif
+
+#ifndef _PyAsyncGen_MAXFREELIST
+# define _PyAsyncGen_MAXFREELIST 80
+#endif
+
+struct _Py_async_gen_state {
+#if _PyAsyncGen_MAXFREELIST > 0
+ /* Freelists boost performance 6-10%; they also reduce memory
+ fragmentation, as _PyAsyncGenWrappedValue and PyAsyncGenASend
+ are short-living objects that are instantiated for every
+ __anext__() call. */
+ struct _PyAsyncGenWrappedValue* value_freelist[_PyAsyncGen_MAXFREELIST];
+ int value_numfree;
+
+ struct PyAsyncGenASend* asend_freelist[_PyAsyncGen_MAXFREELIST];
+ int asend_numfree;
+#endif
+};
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_GENOBJECT_H */
diff --git a/include/python3.10/internal/pycore_getopt.h b/include/python3.11/internal/pycore_getopt.h
similarity index 100%
rename from include/python3.10/internal/pycore_getopt.h
rename to include/python3.11/internal/pycore_getopt.h
diff --git a/include/python3.10/internal/pycore_gil.h b/include/python3.11/internal/pycore_gil.h
similarity index 100%
rename from include/python3.10/internal/pycore_gil.h
rename to include/python3.11/internal/pycore_gil.h
diff --git a/include/python3.11/internal/pycore_global_objects.h b/include/python3.11/internal/pycore_global_objects.h
new file mode 100644
index 0000000..98673d4
--- /dev/null
+++ b/include/python3.11/internal/pycore_global_objects.h
@@ -0,0 +1,54 @@
+#ifndef Py_INTERNAL_GLOBAL_OBJECTS_H
+#define Py_INTERNAL_GLOBAL_OBJECTS_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#include "pycore_gc.h" // PyGC_Head
+#include "pycore_global_strings.h" // struct _Py_global_strings
+
+
+// These would be in pycore_long.h if it weren't for an include cycle.
+#define _PY_NSMALLPOSINTS 257
+#define _PY_NSMALLNEGINTS 5
+
+
+// Only immutable objects should be considered runtime-global.
+// All others must be per-interpreter.
+
+#define _Py_GLOBAL_OBJECT(NAME) \
+ _PyRuntime.global_objects.NAME
+#define _Py_SINGLETON(NAME) \
+ _Py_GLOBAL_OBJECT(singletons.NAME)
+
+struct _Py_global_objects {
+ struct {
+ /* Small integers are preallocated in this array so that they
+ * can be shared.
+ * The integers that are preallocated are those in the range
+ * -_PY_NSMALLNEGINTS (inclusive) to _PY_NSMALLPOSINTS (exclusive).
+ */
+ PyLongObject small_ints[_PY_NSMALLNEGINTS + _PY_NSMALLPOSINTS];
+
+ PyBytesObject bytes_empty;
+ struct {
+ PyBytesObject ob;
+ char eos;
+ } bytes_characters[256];
+
+ struct _Py_global_strings strings;
+
+ _PyGC_Head_UNUSED _tuple_empty_gc_not_used;
+ PyTupleObject tuple_empty;
+ } singletons;
+};
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_GLOBAL_OBJECTS_H */
diff --git a/include/python3.11/internal/pycore_global_strings.h b/include/python3.11/internal/pycore_global_strings.h
new file mode 100644
index 0000000..ca97062
--- /dev/null
+++ b/include/python3.11/internal/pycore_global_strings.h
@@ -0,0 +1,395 @@
+#ifndef Py_INTERNAL_GLOBAL_STRINGS_H
+#define Py_INTERNAL_GLOBAL_STRINGS_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+// The data structure & init here are inspired by Tools/scripts/deepfreeze.py.
+
+// All field names generated by ASCII_STR() have a common prefix,
+// to help avoid collisions with keywords, etc.
+
+#define STRUCT_FOR_ASCII_STR(LITERAL) \
+ struct { \
+ PyASCIIObject _ascii; \
+ uint8_t _data[sizeof(LITERAL)]; \
+ }
+#define STRUCT_FOR_STR(NAME, LITERAL) \
+ STRUCT_FOR_ASCII_STR(LITERAL) _ ## NAME;
+#define STRUCT_FOR_ID(NAME) \
+ STRUCT_FOR_ASCII_STR(#NAME) _ ## NAME;
+
+// XXX Order by frequency of use?
+
+/* The following is auto-generated by Tools/scripts/generate_global_objects.py. */
+struct _Py_global_strings {
+ struct {
+ STRUCT_FOR_STR(anon_dictcomp, "<dictcomp>")
+ STRUCT_FOR_STR(anon_genexpr, "<genexpr>")
+ STRUCT_FOR_STR(anon_lambda, "<lambda>")
+ STRUCT_FOR_STR(anon_listcomp, "<listcomp>")
+ STRUCT_FOR_STR(anon_module, "<module>")
+ STRUCT_FOR_STR(anon_setcomp, "<setcomp>")
+ STRUCT_FOR_STR(anon_string, "<string>")
+ STRUCT_FOR_STR(anon_unknown, "<unknown>")
+ STRUCT_FOR_STR(close_br, "}")
+ STRUCT_FOR_STR(comma_sep, ", ")
+ STRUCT_FOR_STR(dbl_close_br, "}}")
+ STRUCT_FOR_STR(dbl_open_br, "{{")
+ STRUCT_FOR_STR(dbl_percent, "%%")
+ STRUCT_FOR_STR(dot, ".")
+ STRUCT_FOR_STR(dot_locals, ".<locals>")
+ STRUCT_FOR_STR(empty, "")
+ STRUCT_FOR_STR(list_err, "list index out of range")
+ STRUCT_FOR_STR(newline, "\n")
+ STRUCT_FOR_STR(open_br, "{")
+ STRUCT_FOR_STR(percent, "%")
+ STRUCT_FOR_STR(utf_8, "utf-8")
+ } literals;
+
+ struct {
+ STRUCT_FOR_ID(False)
+ STRUCT_FOR_ID(Py_Repr)
+ STRUCT_FOR_ID(TextIOWrapper)
+ STRUCT_FOR_ID(True)
+ STRUCT_FOR_ID(WarningMessage)
+ STRUCT_FOR_ID(_)
+ STRUCT_FOR_ID(__IOBase_closed)
+ STRUCT_FOR_ID(__abc_tpflags__)
+ STRUCT_FOR_ID(__abs__)
+ STRUCT_FOR_ID(__abstractmethods__)
+ STRUCT_FOR_ID(__add__)
+ STRUCT_FOR_ID(__aenter__)
+ STRUCT_FOR_ID(__aexit__)
+ STRUCT_FOR_ID(__aiter__)
+ STRUCT_FOR_ID(__all__)
+ STRUCT_FOR_ID(__and__)
+ STRUCT_FOR_ID(__anext__)
+ STRUCT_FOR_ID(__annotations__)
+ STRUCT_FOR_ID(__args__)
+ STRUCT_FOR_ID(__await__)
+ STRUCT_FOR_ID(__bases__)
+ STRUCT_FOR_ID(__bool__)
+ STRUCT_FOR_ID(__build_class__)
+ STRUCT_FOR_ID(__builtins__)
+ STRUCT_FOR_ID(__bytes__)
+ STRUCT_FOR_ID(__call__)
+ STRUCT_FOR_ID(__cantrace__)
+ STRUCT_FOR_ID(__class__)
+ STRUCT_FOR_ID(__class_getitem__)
+ STRUCT_FOR_ID(__classcell__)
+ STRUCT_FOR_ID(__complex__)
+ STRUCT_FOR_ID(__contains__)
+ STRUCT_FOR_ID(__copy__)
+ STRUCT_FOR_ID(__del__)
+ STRUCT_FOR_ID(__delattr__)
+ STRUCT_FOR_ID(__delete__)
+ STRUCT_FOR_ID(__delitem__)
+ STRUCT_FOR_ID(__dict__)
+ STRUCT_FOR_ID(__dir__)
+ STRUCT_FOR_ID(__divmod__)
+ STRUCT_FOR_ID(__doc__)
+ STRUCT_FOR_ID(__enter__)
+ STRUCT_FOR_ID(__eq__)
+ STRUCT_FOR_ID(__exit__)
+ STRUCT_FOR_ID(__file__)
+ STRUCT_FOR_ID(__float__)
+ STRUCT_FOR_ID(__floordiv__)
+ STRUCT_FOR_ID(__format__)
+ STRUCT_FOR_ID(__fspath__)
+ STRUCT_FOR_ID(__ge__)
+ STRUCT_FOR_ID(__get__)
+ STRUCT_FOR_ID(__getattr__)
+ STRUCT_FOR_ID(__getattribute__)
+ STRUCT_FOR_ID(__getinitargs__)
+ STRUCT_FOR_ID(__getitem__)
+ STRUCT_FOR_ID(__getnewargs__)
+ STRUCT_FOR_ID(__getnewargs_ex__)
+ STRUCT_FOR_ID(__getstate__)
+ STRUCT_FOR_ID(__gt__)
+ STRUCT_FOR_ID(__hash__)
+ STRUCT_FOR_ID(__iadd__)
+ STRUCT_FOR_ID(__iand__)
+ STRUCT_FOR_ID(__ifloordiv__)
+ STRUCT_FOR_ID(__ilshift__)
+ STRUCT_FOR_ID(__imatmul__)
+ STRUCT_FOR_ID(__imod__)
+ STRUCT_FOR_ID(__import__)
+ STRUCT_FOR_ID(__imul__)
+ STRUCT_FOR_ID(__index__)
+ STRUCT_FOR_ID(__init__)
+ STRUCT_FOR_ID(__init_subclass__)
+ STRUCT_FOR_ID(__instancecheck__)
+ STRUCT_FOR_ID(__int__)
+ STRUCT_FOR_ID(__invert__)
+ STRUCT_FOR_ID(__ior__)
+ STRUCT_FOR_ID(__ipow__)
+ STRUCT_FOR_ID(__irshift__)
+ STRUCT_FOR_ID(__isabstractmethod__)
+ STRUCT_FOR_ID(__isub__)
+ STRUCT_FOR_ID(__iter__)
+ STRUCT_FOR_ID(__itruediv__)
+ STRUCT_FOR_ID(__ixor__)
+ STRUCT_FOR_ID(__le__)
+ STRUCT_FOR_ID(__len__)
+ STRUCT_FOR_ID(__length_hint__)
+ STRUCT_FOR_ID(__lltrace__)
+ STRUCT_FOR_ID(__loader__)
+ STRUCT_FOR_ID(__lshift__)
+ STRUCT_FOR_ID(__lt__)
+ STRUCT_FOR_ID(__main__)
+ STRUCT_FOR_ID(__matmul__)
+ STRUCT_FOR_ID(__missing__)
+ STRUCT_FOR_ID(__mod__)
+ STRUCT_FOR_ID(__module__)
+ STRUCT_FOR_ID(__mro_entries__)
+ STRUCT_FOR_ID(__mul__)
+ STRUCT_FOR_ID(__name__)
+ STRUCT_FOR_ID(__ne__)
+ STRUCT_FOR_ID(__neg__)
+ STRUCT_FOR_ID(__new__)
+ STRUCT_FOR_ID(__newobj__)
+ STRUCT_FOR_ID(__newobj_ex__)
+ STRUCT_FOR_ID(__next__)
+ STRUCT_FOR_ID(__notes__)
+ STRUCT_FOR_ID(__or__)
+ STRUCT_FOR_ID(__orig_class__)
+ STRUCT_FOR_ID(__origin__)
+ STRUCT_FOR_ID(__package__)
+ STRUCT_FOR_ID(__parameters__)
+ STRUCT_FOR_ID(__path__)
+ STRUCT_FOR_ID(__pos__)
+ STRUCT_FOR_ID(__pow__)
+ STRUCT_FOR_ID(__prepare__)
+ STRUCT_FOR_ID(__qualname__)
+ STRUCT_FOR_ID(__radd__)
+ STRUCT_FOR_ID(__rand__)
+ STRUCT_FOR_ID(__rdivmod__)
+ STRUCT_FOR_ID(__reduce__)
+ STRUCT_FOR_ID(__reduce_ex__)
+ STRUCT_FOR_ID(__repr__)
+ STRUCT_FOR_ID(__reversed__)
+ STRUCT_FOR_ID(__rfloordiv__)
+ STRUCT_FOR_ID(__rlshift__)
+ STRUCT_FOR_ID(__rmatmul__)
+ STRUCT_FOR_ID(__rmod__)
+ STRUCT_FOR_ID(__rmul__)
+ STRUCT_FOR_ID(__ror__)
+ STRUCT_FOR_ID(__round__)
+ STRUCT_FOR_ID(__rpow__)
+ STRUCT_FOR_ID(__rrshift__)
+ STRUCT_FOR_ID(__rshift__)
+ STRUCT_FOR_ID(__rsub__)
+ STRUCT_FOR_ID(__rtruediv__)
+ STRUCT_FOR_ID(__rxor__)
+ STRUCT_FOR_ID(__set__)
+ STRUCT_FOR_ID(__set_name__)
+ STRUCT_FOR_ID(__setattr__)
+ STRUCT_FOR_ID(__setitem__)
+ STRUCT_FOR_ID(__setstate__)
+ STRUCT_FOR_ID(__sizeof__)
+ STRUCT_FOR_ID(__slotnames__)
+ STRUCT_FOR_ID(__slots__)
+ STRUCT_FOR_ID(__spec__)
+ STRUCT_FOR_ID(__str__)
+ STRUCT_FOR_ID(__sub__)
+ STRUCT_FOR_ID(__subclasscheck__)
+ STRUCT_FOR_ID(__subclasshook__)
+ STRUCT_FOR_ID(__truediv__)
+ STRUCT_FOR_ID(__trunc__)
+ STRUCT_FOR_ID(__typing_is_unpacked_typevartuple__)
+ STRUCT_FOR_ID(__typing_prepare_subst__)
+ STRUCT_FOR_ID(__typing_subst__)
+ STRUCT_FOR_ID(__typing_unpacked_tuple_args__)
+ STRUCT_FOR_ID(__warningregistry__)
+ STRUCT_FOR_ID(__weakref__)
+ STRUCT_FOR_ID(__xor__)
+ STRUCT_FOR_ID(_abc_impl)
+ STRUCT_FOR_ID(_annotation)
+ STRUCT_FOR_ID(_blksize)
+ STRUCT_FOR_ID(_bootstrap)
+ STRUCT_FOR_ID(_dealloc_warn)
+ STRUCT_FOR_ID(_finalizing)
+ STRUCT_FOR_ID(_find_and_load)
+ STRUCT_FOR_ID(_fix_up_module)
+ STRUCT_FOR_ID(_get_sourcefile)
+ STRUCT_FOR_ID(_handle_fromlist)
+ STRUCT_FOR_ID(_initializing)
+ STRUCT_FOR_ID(_is_text_encoding)
+ STRUCT_FOR_ID(_lock_unlock_module)
+ STRUCT_FOR_ID(_showwarnmsg)
+ STRUCT_FOR_ID(_shutdown)
+ STRUCT_FOR_ID(_slotnames)
+ STRUCT_FOR_ID(_strptime_time)
+ STRUCT_FOR_ID(_uninitialized_submodules)
+ STRUCT_FOR_ID(_warn_unawaited_coroutine)
+ STRUCT_FOR_ID(_xoptions)
+ STRUCT_FOR_ID(add)
+ STRUCT_FOR_ID(append)
+ STRUCT_FOR_ID(big)
+ STRUCT_FOR_ID(buffer)
+ STRUCT_FOR_ID(builtins)
+ STRUCT_FOR_ID(c_call)
+ STRUCT_FOR_ID(c_exception)
+ STRUCT_FOR_ID(c_return)
+ STRUCT_FOR_ID(call)
+ STRUCT_FOR_ID(clear)
+ STRUCT_FOR_ID(close)
+ STRUCT_FOR_ID(closed)
+ STRUCT_FOR_ID(code)
+ STRUCT_FOR_ID(copy)
+ STRUCT_FOR_ID(copyreg)
+ STRUCT_FOR_ID(decode)
+ STRUCT_FOR_ID(default)
+ STRUCT_FOR_ID(defaultaction)
+ STRUCT_FOR_ID(dictcomp)
+ STRUCT_FOR_ID(difference_update)
+ STRUCT_FOR_ID(dispatch_table)
+ STRUCT_FOR_ID(displayhook)
+ STRUCT_FOR_ID(enable)
+ STRUCT_FOR_ID(encode)
+ STRUCT_FOR_ID(encoding)
+ STRUCT_FOR_ID(end_lineno)
+ STRUCT_FOR_ID(end_offset)
+ STRUCT_FOR_ID(errors)
+ STRUCT_FOR_ID(excepthook)
+ STRUCT_FOR_ID(exception)
+ STRUCT_FOR_ID(extend)
+ STRUCT_FOR_ID(filename)
+ STRUCT_FOR_ID(fileno)
+ STRUCT_FOR_ID(fillvalue)
+ STRUCT_FOR_ID(filters)
+ STRUCT_FOR_ID(find_class)
+ STRUCT_FOR_ID(flush)
+ STRUCT_FOR_ID(genexpr)
+ STRUCT_FOR_ID(get)
+ STRUCT_FOR_ID(get_source)
+ STRUCT_FOR_ID(getattr)
+ STRUCT_FOR_ID(getstate)
+ STRUCT_FOR_ID(ignore)
+ STRUCT_FOR_ID(importlib)
+ STRUCT_FOR_ID(inf)
+ STRUCT_FOR_ID(intersection)
+ STRUCT_FOR_ID(isatty)
+ STRUCT_FOR_ID(isinstance)
+ STRUCT_FOR_ID(items)
+ STRUCT_FOR_ID(iter)
+ STRUCT_FOR_ID(join)
+ STRUCT_FOR_ID(keys)
+ STRUCT_FOR_ID(lambda)
+ STRUCT_FOR_ID(last_traceback)
+ STRUCT_FOR_ID(last_type)
+ STRUCT_FOR_ID(last_value)
+ STRUCT_FOR_ID(latin1)
+ STRUCT_FOR_ID(len)
+ STRUCT_FOR_ID(line)
+ STRUCT_FOR_ID(lineno)
+ STRUCT_FOR_ID(listcomp)
+ STRUCT_FOR_ID(little)
+ STRUCT_FOR_ID(locale)
+ STRUCT_FOR_ID(match)
+ STRUCT_FOR_ID(metaclass)
+ STRUCT_FOR_ID(mode)
+ STRUCT_FOR_ID(modules)
+ STRUCT_FOR_ID(mro)
+ STRUCT_FOR_ID(msg)
+ STRUCT_FOR_ID(n_fields)
+ STRUCT_FOR_ID(n_sequence_fields)
+ STRUCT_FOR_ID(n_unnamed_fields)
+ STRUCT_FOR_ID(name)
+ STRUCT_FOR_ID(newlines)
+ STRUCT_FOR_ID(next)
+ STRUCT_FOR_ID(obj)
+ STRUCT_FOR_ID(offset)
+ STRUCT_FOR_ID(onceregistry)
+ STRUCT_FOR_ID(opcode)
+ STRUCT_FOR_ID(open)
+ STRUCT_FOR_ID(parent)
+ STRUCT_FOR_ID(partial)
+ STRUCT_FOR_ID(path)
+ STRUCT_FOR_ID(peek)
+ STRUCT_FOR_ID(persistent_id)
+ STRUCT_FOR_ID(persistent_load)
+ STRUCT_FOR_ID(print_file_and_line)
+ STRUCT_FOR_ID(ps1)
+ STRUCT_FOR_ID(ps2)
+ STRUCT_FOR_ID(raw)
+ STRUCT_FOR_ID(read)
+ STRUCT_FOR_ID(read1)
+ STRUCT_FOR_ID(readable)
+ STRUCT_FOR_ID(readall)
+ STRUCT_FOR_ID(readinto)
+ STRUCT_FOR_ID(readinto1)
+ STRUCT_FOR_ID(readline)
+ STRUCT_FOR_ID(reducer_override)
+ STRUCT_FOR_ID(reload)
+ STRUCT_FOR_ID(replace)
+ STRUCT_FOR_ID(reset)
+ STRUCT_FOR_ID(return)
+ STRUCT_FOR_ID(reversed)
+ STRUCT_FOR_ID(seek)
+ STRUCT_FOR_ID(seekable)
+ STRUCT_FOR_ID(send)
+ STRUCT_FOR_ID(setcomp)
+ STRUCT_FOR_ID(setstate)
+ STRUCT_FOR_ID(sort)
+ STRUCT_FOR_ID(stderr)
+ STRUCT_FOR_ID(stdin)
+ STRUCT_FOR_ID(stdout)
+ STRUCT_FOR_ID(strict)
+ STRUCT_FOR_ID(symmetric_difference_update)
+ STRUCT_FOR_ID(tell)
+ STRUCT_FOR_ID(text)
+ STRUCT_FOR_ID(threading)
+ STRUCT_FOR_ID(throw)
+ STRUCT_FOR_ID(top)
+ STRUCT_FOR_ID(truncate)
+ STRUCT_FOR_ID(unraisablehook)
+ STRUCT_FOR_ID(values)
+ STRUCT_FOR_ID(version)
+ STRUCT_FOR_ID(warnings)
+ STRUCT_FOR_ID(warnoptions)
+ STRUCT_FOR_ID(writable)
+ STRUCT_FOR_ID(write)
+ STRUCT_FOR_ID(zipimporter)
+ } identifiers;
+ struct {
+ PyASCIIObject _ascii;
+ uint8_t _data[2];
+ } ascii[128];
+ struct {
+ PyCompactUnicodeObject _latin1;
+ uint8_t _data[2];
+ } latin1[128];
+};
+/* End auto-generated code */
+
+#undef ID
+#undef STR
+
+
+#define _Py_ID(NAME) \
+ (_Py_SINGLETON(strings.identifiers._ ## NAME._ascii.ob_base))
+#define _Py_STR(NAME) \
+ (_Py_SINGLETON(strings.literals._ ## NAME._ascii.ob_base))
+
+/* _Py_DECLARE_STR() should precede all uses of _Py_STR() in a function.
+
+ This is true even if the same string has already been declared
+ elsewhere, even in the same file. Mismatched duplicates are detected
+ by Tools/scripts/generate-global-objects.py.
+
+ Pairing _Py_DECLARE_STR() with every use of _Py_STR() makes sure the
+ string keeps working even if the declaration is removed somewhere
+ else. It also makes it clear what the actual string is at every
+ place it is being used. */
+#define _Py_DECLARE_STR(name, str)
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_GLOBAL_STRINGS_H */
diff --git a/include/python3.11/internal/pycore_hamt.h b/include/python3.11/internal/pycore_hamt.h
new file mode 100644
index 0000000..4d64288
--- /dev/null
+++ b/include/python3.11/internal/pycore_hamt.h
@@ -0,0 +1,131 @@
+#ifndef Py_INTERNAL_HAMT_H
+#define Py_INTERNAL_HAMT_H
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+
+/*
+HAMT tree is shaped by hashes of keys. Every group of 5 bits of a hash denotes
+the exact position of the key in one level of the tree. Since we're using
+32 bit hashes, we can have at most 7 such levels. Although if there are
+two distinct keys with equal hashes, they will have to occupy the same
+cell in the 7th level of the tree -- so we'd put them in a "collision" node.
+Which brings the total possible tree depth to 8. Read more about the actual
+layout of the HAMT tree in `hamt.c`.
+
+This constant is used to define a datastucture for storing iteration state.
+*/
+#define _Py_HAMT_MAX_TREE_DEPTH 8
+
+
+extern PyTypeObject _PyHamt_Type;
+extern PyTypeObject _PyHamt_ArrayNode_Type;
+extern PyTypeObject _PyHamt_BitmapNode_Type;
+extern PyTypeObject _PyHamt_CollisionNode_Type;
+extern PyTypeObject _PyHamtKeys_Type;
+extern PyTypeObject _PyHamtValues_Type;
+extern PyTypeObject _PyHamtItems_Type;
+
+/* runtime lifecycle */
+
+void _PyHamt_Fini(PyInterpreterState *);
+
+
+/* other API */
+
+#define PyHamt_Check(o) Py_IS_TYPE(o, &_PyHamt_Type)
+
+
+/* Abstract tree node. */
+typedef struct {
+ PyObject_HEAD
+} PyHamtNode;
+
+
+/* An HAMT immutable mapping collection. */
+typedef struct {
+ PyObject_HEAD
+ PyHamtNode *h_root;
+ PyObject *h_weakreflist;
+ Py_ssize_t h_count;
+} PyHamtObject;
+
+
+/* A struct to hold the state of depth-first traverse of the tree.
+
+ HAMT is an immutable collection. Iterators will hold a strong reference
+ to it, and every node in the HAMT has strong references to its children.
+
+ So for iterators, we can implement zero allocations and zero reference
+ inc/dec depth-first iteration.
+
+ - i_nodes: an array of seven pointers to tree nodes
+ - i_level: the current node in i_nodes
+ - i_pos: an array of positions within nodes in i_nodes.
+*/
+typedef struct {
+ PyHamtNode *i_nodes[_Py_HAMT_MAX_TREE_DEPTH];
+ Py_ssize_t i_pos[_Py_HAMT_MAX_TREE_DEPTH];
+ int8_t i_level;
+} PyHamtIteratorState;
+
+
+/* Base iterator object.
+
+ Contains the iteration state, a pointer to the HAMT tree,
+ and a pointer to the 'yield function'. The latter is a simple
+ function that returns a key/value tuple for the 'Items' iterator,
+ just a key for the 'Keys' iterator, and a value for the 'Values'
+ iterator.
+*/
+typedef struct {
+ PyObject_HEAD
+ PyHamtObject *hi_obj;
+ PyHamtIteratorState hi_iter;
+ binaryfunc hi_yield;
+} PyHamtIterator;
+
+
+/* Create a new HAMT immutable mapping. */
+PyHamtObject * _PyHamt_New(void);
+
+/* Return a new collection based on "o", but with an additional
+ key/val pair. */
+PyHamtObject * _PyHamt_Assoc(PyHamtObject *o, PyObject *key, PyObject *val);
+
+/* Return a new collection based on "o", but without "key". */
+PyHamtObject * _PyHamt_Without(PyHamtObject *o, PyObject *key);
+
+/* Find "key" in the "o" collection.
+
+ Return:
+ - -1: An error occurred.
+ - 0: "key" wasn't found in "o".
+ - 1: "key" is in "o"; "*val" is set to its value (a borrowed ref).
+*/
+int _PyHamt_Find(PyHamtObject *o, PyObject *key, PyObject **val);
+
+/* Check if "v" is equal to "w".
+
+ Return:
+ - 0: v != w
+ - 1: v == w
+ - -1: An error occurred.
+*/
+int _PyHamt_Eq(PyHamtObject *v, PyHamtObject *w);
+
+/* Return the size of "o"; equivalent of "len(o)". */
+Py_ssize_t _PyHamt_Len(PyHamtObject *o);
+
+/* Return a Keys iterator over "o". */
+PyObject * _PyHamt_NewIterKeys(PyHamtObject *o);
+
+/* Return a Values iterator over "o". */
+PyObject * _PyHamt_NewIterValues(PyHamtObject *o);
+
+/* Return a Items iterator over "o". */
+PyObject * _PyHamt_NewIterItems(PyHamtObject *o);
+
+#endif /* !Py_INTERNAL_HAMT_H */
diff --git a/include/python3.10/internal/pycore_hashtable.h b/include/python3.11/internal/pycore_hashtable.h
similarity index 100%
rename from include/python3.10/internal/pycore_hashtable.h
rename to include/python3.11/internal/pycore_hashtable.h
diff --git a/include/python3.11/internal/pycore_import.h b/include/python3.11/internal/pycore_import.h
new file mode 100644
index 0000000..aee1f66
--- /dev/null
+++ b/include/python3.11/internal/pycore_import.h
@@ -0,0 +1,27 @@
+#ifndef Py_LIMITED_API
+#ifndef Py_INTERNAL_IMPORT_H
+#define Py_INTERNAL_IMPORT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef HAVE_FORK
+extern PyStatus _PyImport_ReInitLock(void);
+#endif
+extern PyObject* _PyImport_BootstrapImp(PyThreadState *tstate);
+
+struct _module_alias {
+ const char *name; /* ASCII encoded string */
+ const char *orig; /* ASCII encoded string */
+};
+
+PyAPI_DATA(const struct _frozen *) _PyImport_FrozenBootstrap;
+PyAPI_DATA(const struct _frozen *) _PyImport_FrozenStdlib;
+PyAPI_DATA(const struct _frozen *) _PyImport_FrozenTest;
+extern const struct _module_alias * _PyImport_FrozenAliases;
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_IMPORT_H */
+#endif /* !Py_LIMITED_API */
diff --git a/include/python3.11/internal/pycore_initconfig.h b/include/python3.11/internal/pycore_initconfig.h
new file mode 100644
index 0000000..d765600
--- /dev/null
+++ b/include/python3.11/internal/pycore_initconfig.h
@@ -0,0 +1,183 @@
+#ifndef Py_INTERNAL_CORECONFIG_H
+#define Py_INTERNAL_CORECONFIG_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+/* Forward declaration */
+struct pyruntimestate;
+
+/* --- PyStatus ----------------------------------------------- */
+
+/* Almost all errors causing Python initialization to fail */
+#ifdef _MSC_VER
+ /* Visual Studio 2015 doesn't implement C99 __func__ in C */
+# define _PyStatus_GET_FUNC() __FUNCTION__
+#else
+# define _PyStatus_GET_FUNC() __func__
+#endif
+
+#define _PyStatus_OK() \
+ (PyStatus){._type = _PyStatus_TYPE_OK,}
+ /* other fields are set to 0 */
+#define _PyStatus_ERR(ERR_MSG) \
+ (PyStatus){ \
+ ._type = _PyStatus_TYPE_ERROR, \
+ .func = _PyStatus_GET_FUNC(), \
+ .err_msg = (ERR_MSG)}
+ /* other fields are set to 0 */
+#define _PyStatus_NO_MEMORY() _PyStatus_ERR("memory allocation failed")
+#define _PyStatus_EXIT(EXITCODE) \
+ (PyStatus){ \
+ ._type = _PyStatus_TYPE_EXIT, \
+ .exitcode = (EXITCODE)}
+#define _PyStatus_IS_ERROR(err) \
+ (err._type == _PyStatus_TYPE_ERROR)
+#define _PyStatus_IS_EXIT(err) \
+ (err._type == _PyStatus_TYPE_EXIT)
+#define _PyStatus_EXCEPTION(err) \
+ (err._type != _PyStatus_TYPE_OK)
+#define _PyStatus_UPDATE_FUNC(err) \
+ do { err.func = _PyStatus_GET_FUNC(); } while (0)
+
+PyObject* _PyErr_SetFromPyStatus(PyStatus status);
+
+/* --- PyWideStringList ------------------------------------------------ */
+
+#define _PyWideStringList_INIT (PyWideStringList){.length = 0, .items = NULL}
+
+#ifndef NDEBUG
+PyAPI_FUNC(int) _PyWideStringList_CheckConsistency(const PyWideStringList *list);
+#endif
+PyAPI_FUNC(void) _PyWideStringList_Clear(PyWideStringList *list);
+PyAPI_FUNC(int) _PyWideStringList_Copy(PyWideStringList *list,
+ const PyWideStringList *list2);
+PyAPI_FUNC(PyStatus) _PyWideStringList_Extend(PyWideStringList *list,
+ const PyWideStringList *list2);
+PyAPI_FUNC(PyObject*) _PyWideStringList_AsList(const PyWideStringList *list);
+
+
+/* --- _PyArgv ---------------------------------------------------- */
+
+typedef struct _PyArgv {
+ Py_ssize_t argc;
+ int use_bytes_argv;
+ char * const *bytes_argv;
+ wchar_t * const *wchar_argv;
+} _PyArgv;
+
+PyAPI_FUNC(PyStatus) _PyArgv_AsWstrList(const _PyArgv *args,
+ PyWideStringList *list);
+
+
+/* --- Helper functions ------------------------------------------- */
+
+PyAPI_FUNC(int) _Py_str_to_int(
+ const char *str,
+ int *result);
+PyAPI_FUNC(const wchar_t*) _Py_get_xoption(
+ const PyWideStringList *xoptions,
+ const wchar_t *name);
+PyAPI_FUNC(const char*) _Py_GetEnv(
+ int use_environment,
+ const char *name);
+PyAPI_FUNC(void) _Py_get_env_flag(
+ int use_environment,
+ int *flag,
+ const char *name);
+
+/* Py_GetArgcArgv() helper */
+PyAPI_FUNC(void) _Py_ClearArgcArgv(void);
+
+
+/* --- _PyPreCmdline ------------------------------------------------- */
+
+typedef struct {
+ PyWideStringList argv;
+ PyWideStringList xoptions; /* "-X value" option */
+ int isolated; /* -I option */
+ int use_environment; /* -E option */
+ int dev_mode; /* -X dev and PYTHONDEVMODE */
+ int warn_default_encoding; /* -X warn_default_encoding and PYTHONWARNDEFAULTENCODING */
+} _PyPreCmdline;
+
+#define _PyPreCmdline_INIT \
+ (_PyPreCmdline){ \
+ .use_environment = -1, \
+ .isolated = -1, \
+ .dev_mode = -1}
+/* Note: _PyPreCmdline_INIT sets other fields to 0/NULL */
+
+extern void _PyPreCmdline_Clear(_PyPreCmdline *cmdline);
+extern PyStatus _PyPreCmdline_SetArgv(_PyPreCmdline *cmdline,
+ const _PyArgv *args);
+extern PyStatus _PyPreCmdline_SetConfig(
+ const _PyPreCmdline *cmdline,
+ PyConfig *config);
+extern PyStatus _PyPreCmdline_Read(_PyPreCmdline *cmdline,
+ const PyPreConfig *preconfig);
+
+
+/* --- PyPreConfig ----------------------------------------------- */
+
+PyAPI_FUNC(void) _PyPreConfig_InitCompatConfig(PyPreConfig *preconfig);
+extern void _PyPreConfig_InitFromConfig(
+ PyPreConfig *preconfig,
+ const PyConfig *config);
+extern PyStatus _PyPreConfig_InitFromPreConfig(
+ PyPreConfig *preconfig,
+ const PyPreConfig *config2);
+extern PyObject* _PyPreConfig_AsDict(const PyPreConfig *preconfig);
+extern void _PyPreConfig_GetConfig(PyPreConfig *preconfig,
+ const PyConfig *config);
+extern PyStatus _PyPreConfig_Read(PyPreConfig *preconfig,
+ const _PyArgv *args);
+extern PyStatus _PyPreConfig_Write(const PyPreConfig *preconfig);
+
+
+/* --- PyConfig ---------------------------------------------- */
+
+typedef enum {
+ /* Py_Initialize() API: backward compatibility with Python 3.6 and 3.7 */
+ _PyConfig_INIT_COMPAT = 1,
+ _PyConfig_INIT_PYTHON = 2,
+ _PyConfig_INIT_ISOLATED = 3
+} _PyConfigInitEnum;
+
+PyAPI_FUNC(void) _PyConfig_InitCompatConfig(PyConfig *config);
+extern PyStatus _PyConfig_Copy(
+ PyConfig *config,
+ const PyConfig *config2);
+extern PyStatus _PyConfig_InitPathConfig(
+ PyConfig *config,
+ int compute_path_config);
+extern PyStatus _PyConfig_InitImportConfig(PyConfig *config);
+extern PyStatus _PyConfig_Read(PyConfig *config, int compute_path_config);
+extern PyStatus _PyConfig_Write(const PyConfig *config,
+ struct pyruntimestate *runtime);
+extern PyStatus _PyConfig_SetPyArgv(
+ PyConfig *config,
+ const _PyArgv *args);
+
+PyAPI_FUNC(PyObject*) _PyConfig_AsDict(const PyConfig *config);
+PyAPI_FUNC(int) _PyConfig_FromDict(PyConfig *config, PyObject *dict);
+
+extern void _Py_DumpPathConfig(PyThreadState *tstate);
+
+PyAPI_FUNC(PyObject*) _Py_Get_Getpath_CodeObject(void);
+
+extern int _Py_global_config_int_max_str_digits;
+
+
+/* --- Function used for testing ---------------------------------- */
+
+PyAPI_FUNC(PyObject*) _Py_GetConfigsAsDict(void);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_CORECONFIG_H */
diff --git a/include/python3.11/internal/pycore_interp.h b/include/python3.11/internal/pycore_interp.h
new file mode 100644
index 0000000..02d25d6
--- /dev/null
+++ b/include/python3.11/internal/pycore_interp.h
@@ -0,0 +1,227 @@
+#ifndef Py_INTERNAL_INTERP_H
+#define Py_INTERNAL_INTERP_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#include <stdbool.h>
+
+#include "pycore_atomic.h" // _Py_atomic_address
+#include "pycore_ast_state.h" // struct ast_state
+#include "pycore_code.h" // struct callable_cache
+#include "pycore_context.h" // struct _Py_context_state
+#include "pycore_dict.h" // struct _Py_dict_state
+#include "pycore_exceptions.h" // struct _Py_exc_state
+#include "pycore_floatobject.h" // struct _Py_float_state
+#include "pycore_genobject.h" // struct _Py_async_gen_state
+#include "pycore_gil.h" // struct _gil_runtime_state
+#include "pycore_gc.h" // struct _gc_runtime_state
+#include "pycore_list.h" // struct _Py_list_state
+#include "pycore_tuple.h" // struct _Py_tuple_state
+#include "pycore_typeobject.h" // struct type_cache
+#include "pycore_unicodeobject.h" // struct _Py_unicode_state
+#include "pycore_warnings.h" // struct _warnings_runtime_state
+
+struct _pending_calls {
+ PyThread_type_lock lock;
+ /* Request for running pending calls. */
+ _Py_atomic_int calls_to_do;
+ /* Request for looking at the `async_exc` field of the current
+ thread state.
+ Guarded by the GIL. */
+ int async_exc;
+#define NPENDINGCALLS 32
+ struct {
+ int (*func)(void *);
+ void *arg;
+ } calls[NPENDINGCALLS];
+ int first;
+ int last;
+};
+
+struct _ceval_state {
+ int recursion_limit;
+ /* This single variable consolidates all requests to break out of
+ the fast path in the eval loop. */
+ _Py_atomic_int eval_breaker;
+ /* Request for dropping the GIL */
+ _Py_atomic_int gil_drop_request;
+ struct _pending_calls pending;
+};
+
+
+// atexit state
+typedef struct {
+ PyObject *func;
+ PyObject *args;
+ PyObject *kwargs;
+} atexit_callback;
+
+struct atexit_state {
+ atexit_callback **callbacks;
+ int ncallbacks;
+ int callback_len;
+};
+
+
+/* interpreter state */
+
+/* PyInterpreterState holds the global state for one of the runtime's
+ interpreters. Typically the initial (main) interpreter is the only one.
+
+ The PyInterpreterState typedef is in Include/pystate.h.
+ */
+struct _is {
+
+ PyInterpreterState *next;
+
+ struct pythreads {
+ uint64_t next_unique_id;
+ /* The linked list of threads, newest first. */
+ PyThreadState *head;
+ /* Used in Modules/_threadmodule.c. */
+ long count;
+ /* Support for runtime thread stack size tuning.
+ A value of 0 means using the platform's default stack size
+ or the size specified by the THREAD_STACK_SIZE macro. */
+ /* Used in Python/thread.c. */
+ size_t stacksize;
+ } threads;
+
+ /* Reference to the _PyRuntime global variable. This field exists
+ to not have to pass runtime in addition to tstate to a function.
+ Get runtime from tstate: tstate->interp->runtime. */
+ struct pyruntimestate *runtime;
+
+ int64_t id;
+ int64_t id_refcount;
+ int requires_idref;
+ PyThread_type_lock id_mutex;
+
+ /* Has been initialized to a safe state.
+
+ In order to be effective, this must be set to 0 during or right
+ after allocation. */
+ int _initialized;
+ int finalizing;
+
+ /* Was this interpreter statically allocated? */
+ bool _static;
+
+ struct _ceval_state ceval;
+ struct _gc_runtime_state gc;
+
+ // sys.modules dictionary
+ PyObject *modules;
+ PyObject *modules_by_index;
+ // Dictionary of the sys module
+ PyObject *sysdict;
+ // Dictionary of the builtins module
+ PyObject *builtins;
+ // importlib module
+ PyObject *importlib;
+ // override for config->use_frozen_modules (for tests)
+ // (-1: "off", 1: "on", 0: no override)
+ int override_frozen_modules;
+
+ PyObject *codec_search_path;
+ PyObject *codec_search_cache;
+ PyObject *codec_error_registry;
+ int codecs_initialized;
+
+ PyConfig config;
+#ifdef HAVE_DLOPEN
+ int dlopenflags;
+#endif
+
+ PyObject *dict; /* Stores per-interpreter state */
+
+ PyObject *builtins_copy;
+ PyObject *import_func;
+ // Initialized to _PyEval_EvalFrameDefault().
+ _PyFrameEvalFunction eval_frame;
+
+ Py_ssize_t co_extra_user_count;
+ freefunc co_extra_freefuncs[MAX_CO_EXTRA_USERS];
+
+#ifdef HAVE_FORK
+ PyObject *before_forkers;
+ PyObject *after_forkers_parent;
+ PyObject *after_forkers_child;
+#endif
+
+ struct _warnings_runtime_state warnings;
+ struct atexit_state atexit;
+
+ PyObject *audit_hooks;
+
+ struct _Py_unicode_state unicode;
+ struct _Py_float_state float_state;
+ /* Using a cache is very effective since typically only a single slice is
+ created and then deleted again. */
+ PySliceObject *slice_cache;
+
+ struct _Py_tuple_state tuple;
+ struct _Py_list_state list;
+ struct _Py_dict_state dict_state;
+ struct _Py_async_gen_state async_gen;
+ struct _Py_context_state context;
+ struct _Py_exc_state exc_state;
+
+ struct ast_state ast;
+ struct type_cache type_cache;
+ struct callable_cache callable_cache;
+
+ int int_max_str_digits;
+
+ /* The following fields are here to avoid allocation during init.
+ The data is exposed through PyInterpreterState pointer fields.
+ These fields should not be accessed directly outside of init.
+
+ All other PyInterpreterState pointer fields are populated when
+ needed and default to NULL.
+
+ For now there are some exceptions to that rule, which require
+ allocation during init. These will be addressed on a case-by-case
+ basis. Also see _PyRuntimeState regarding the various mutex fields.
+ */
+
+ /* the initial PyInterpreterState.threads.head */
+ PyThreadState _initial_thread;
+};
+
+
+/* other API */
+
+extern void _PyInterpreterState_ClearModules(PyInterpreterState *interp);
+extern void _PyInterpreterState_Clear(PyThreadState *tstate);
+
+
+/* cross-interpreter data registry */
+
+/* For now we use a global registry of shareable classes. An
+ alternative would be to add a tp_* slot for a class's
+ crossinterpdatafunc. It would be simpler and more efficient. */
+
+struct _xidregitem;
+
+struct _xidregitem {
+ PyTypeObject *cls;
+ crossinterpdatafunc getdata;
+ struct _xidregitem *next;
+};
+
+PyAPI_FUNC(PyInterpreterState*) _PyInterpreterState_LookUpID(int64_t);
+
+PyAPI_FUNC(int) _PyInterpreterState_IDInitref(PyInterpreterState *);
+PyAPI_FUNC(int) _PyInterpreterState_IDIncref(PyInterpreterState *);
+PyAPI_FUNC(void) _PyInterpreterState_IDDecref(PyInterpreterState *);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_INTERP_H */
diff --git a/include/python3.11/internal/pycore_interpreteridobject.h b/include/python3.11/internal/pycore_interpreteridobject.h
new file mode 100644
index 0000000..804831e
--- /dev/null
+++ b/include/python3.11/internal/pycore_interpreteridobject.h
@@ -0,0 +1,22 @@
+/* Interpreter ID Object */
+
+#ifndef Py_INTERNAL_INTERPRETERIDOBJECT_H
+#define Py_INTERNAL_INTERPRETERIDOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+PyAPI_DATA(PyTypeObject) _PyInterpreterID_Type;
+
+PyAPI_FUNC(PyObject *) _PyInterpreterID_New(int64_t);
+PyAPI_FUNC(PyObject *) _PyInterpreterState_GetIDObject(PyInterpreterState *);
+PyAPI_FUNC(PyInterpreterState *) _PyInterpreterID_LookUp(PyObject *);
+
+#ifdef __cplusplus
+}
+#endif
+#endif // !Py_INTERNAL_INTERPRETERIDOBJECT_H
diff --git a/include/python3.11/internal/pycore_list.h b/include/python3.11/internal/pycore_list.h
new file mode 100644
index 0000000..860dce1
--- /dev/null
+++ b/include/python3.11/internal/pycore_list.h
@@ -0,0 +1,62 @@
+#ifndef Py_INTERNAL_LIST_H
+#define Py_INTERNAL_LIST_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#include "listobject.h" // _PyList_CAST()
+
+
+/* runtime lifecycle */
+
+extern void _PyList_Fini(PyInterpreterState *);
+
+
+/* other API */
+
+#ifndef WITH_FREELISTS
+// without freelists
+# define PyList_MAXFREELIST 0
+#endif
+
+/* Empty list reuse scheme to save calls to malloc and free */
+#ifndef PyList_MAXFREELIST
+# define PyList_MAXFREELIST 80
+#endif
+
+struct _Py_list_state {
+#if PyList_MAXFREELIST > 0
+ PyListObject *free_list[PyList_MAXFREELIST];
+ int numfree;
+#endif
+};
+
+#define _PyList_ITEMS(op) (_PyList_CAST(op)->ob_item)
+
+extern int
+_PyList_AppendTakeRefListResize(PyListObject *self, PyObject *newitem);
+
+static inline int
+_PyList_AppendTakeRef(PyListObject *self, PyObject *newitem)
+{
+ assert(self != NULL && newitem != NULL);
+ assert(PyList_Check(self));
+ Py_ssize_t len = PyList_GET_SIZE(self);
+ Py_ssize_t allocated = self->allocated;
+ assert((size_t)len + 1 < PY_SSIZE_T_MAX);
+ if (allocated > len) {
+ PyList_SET_ITEM(self, len, newitem);
+ Py_SET_SIZE(self, len + 1);
+ return 0;
+ }
+ return _PyList_AppendTakeRefListResize(self, newitem);
+}
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_LIST_H */
diff --git a/include/python3.11/internal/pycore_long.h b/include/python3.11/internal/pycore_long.h
new file mode 100644
index 0000000..0f466eb
--- /dev/null
+++ b/include/python3.11/internal/pycore_long.h
@@ -0,0 +1,114 @@
+#ifndef Py_INTERNAL_LONG_H
+#define Py_INTERNAL_LONG_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#include "pycore_global_objects.h" // _PY_NSMALLNEGINTS
+#include "pycore_runtime.h" // _PyRuntime
+
+/*
+ * Default int base conversion size limitation: Denial of Service prevention.
+ *
+ * Chosen such that this isn't wildly slow on modern hardware and so that
+ * everyone's existing deployed numpy test suite passes before
+ * https://github.com/numpy/numpy/issues/22098 is widely available.
+ *
+ * $ python -m timeit -s 's = "1"*4300' 'int(s)'
+ * 2000 loops, best of 5: 125 usec per loop
+ * $ python -m timeit -s 's = "1"*4300; v = int(s)' 'str(v)'
+ * 1000 loops, best of 5: 311 usec per loop
+ * (zen2 cloud VM)
+ *
+ * 4300 decimal digits fits a ~14284 bit number.
+ */
+#define _PY_LONG_DEFAULT_MAX_STR_DIGITS 4300
+/*
+ * Threshold for max digits check. For performance reasons int() and
+ * int.__str__() don't checks values that are smaller than this
+ * threshold. Acts as a guaranteed minimum size limit for bignums that
+ * applications can expect from CPython.
+ *
+ * % python -m timeit -s 's = "1"*640; v = int(s)' 'str(int(s))'
+ * 20000 loops, best of 5: 12 usec per loop
+ *
+ * "640 digits should be enough for anyone." - gps
+ * fits a ~2126 bit decimal number.
+ */
+#define _PY_LONG_MAX_STR_DIGITS_THRESHOLD 640
+
+#if ((_PY_LONG_DEFAULT_MAX_STR_DIGITS != 0) && \
+ (_PY_LONG_DEFAULT_MAX_STR_DIGITS < _PY_LONG_MAX_STR_DIGITS_THRESHOLD))
+# error "_PY_LONG_DEFAULT_MAX_STR_DIGITS smaller than threshold."
+#endif
+
+
+/* runtime lifecycle */
+
+extern PyStatus _PyLong_InitTypes(PyInterpreterState *);
+extern void _PyLong_FiniTypes(PyInterpreterState *interp);
+
+
+/* other API */
+
+#define _PyLong_SMALL_INTS _Py_SINGLETON(small_ints)
+
+// _PyLong_GetZero() and _PyLong_GetOne() must always be available
+// _PyLong_FromUnsignedChar must always be available
+#if _PY_NSMALLPOSINTS < 257
+# error "_PY_NSMALLPOSINTS must be greater than or equal to 257"
+#endif
+
+// Return a borrowed reference to the zero singleton.
+// The function cannot return NULL.
+static inline PyObject* _PyLong_GetZero(void)
+{ return (PyObject *)&_PyLong_SMALL_INTS[_PY_NSMALLNEGINTS]; }
+
+// Return a borrowed reference to the one singleton.
+// The function cannot return NULL.
+static inline PyObject* _PyLong_GetOne(void)
+{ return (PyObject *)&_PyLong_SMALL_INTS[_PY_NSMALLNEGINTS+1]; }
+
+static inline PyObject* _PyLong_FromUnsignedChar(unsigned char i)
+{
+ return Py_NewRef((PyObject *)&_PyLong_SMALL_INTS[_PY_NSMALLNEGINTS+i]);
+}
+
+PyObject *_PyLong_Add(PyLongObject *left, PyLongObject *right);
+PyObject *_PyLong_Multiply(PyLongObject *left, PyLongObject *right);
+PyObject *_PyLong_Subtract(PyLongObject *left, PyLongObject *right);
+
+/* Used by Python/mystrtoul.c, _PyBytes_FromHex(),
+ _PyBytes_DecodeEscape(), etc. */
+PyAPI_DATA(unsigned char) _PyLong_DigitValue[256];
+
+/* Format the object based on the format_spec, as defined in PEP 3101
+ (Advanced String Formatting). */
+PyAPI_FUNC(int) _PyLong_FormatAdvancedWriter(
+ _PyUnicodeWriter *writer,
+ PyObject *obj,
+ PyObject *format_spec,
+ Py_ssize_t start,
+ Py_ssize_t end);
+
+PyAPI_FUNC(int) _PyLong_FormatWriter(
+ _PyUnicodeWriter *writer,
+ PyObject *obj,
+ int base,
+ int alternate);
+
+PyAPI_FUNC(char*) _PyLong_FormatBytesWriter(
+ _PyBytesWriter *writer,
+ char *str,
+ PyObject *obj,
+ int base,
+ int alternate);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_LONG_H */
diff --git a/include/python3.11/internal/pycore_moduleobject.h b/include/python3.11/internal/pycore_moduleobject.h
new file mode 100644
index 0000000..76361b8
--- /dev/null
+++ b/include/python3.11/internal/pycore_moduleobject.h
@@ -0,0 +1,42 @@
+#ifndef Py_INTERNAL_MODULEOBJECT_H
+#define Py_INTERNAL_MODULEOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+typedef struct {
+ PyObject_HEAD
+ PyObject *md_dict;
+ PyModuleDef *md_def;
+ void *md_state;
+ PyObject *md_weaklist;
+ // for logging purposes after md_dict is cleared
+ PyObject *md_name;
+} PyModuleObject;
+
+static inline PyModuleDef* _PyModule_GetDef(PyObject *mod) {
+ assert(PyModule_Check(mod));
+ return ((PyModuleObject *)mod)->md_def;
+}
+
+static inline void* _PyModule_GetState(PyObject* mod) {
+ assert(PyModule_Check(mod));
+ return ((PyModuleObject *)mod)->md_state;
+}
+
+static inline PyObject* _PyModule_GetDict(PyObject *mod) {
+ assert(PyModule_Check(mod));
+ PyObject *dict = ((PyModuleObject *)mod) -> md_dict;
+ // _PyModule_GetDict(mod) must not be used after calling module_clear(mod)
+ assert(dict != NULL);
+ return dict;
+}
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_MODULEOBJECT_H */
diff --git a/include/python3.11/internal/pycore_namespace.h b/include/python3.11/internal/pycore_namespace.h
new file mode 100644
index 0000000..cb76f04
--- /dev/null
+++ b/include/python3.11/internal/pycore_namespace.h
@@ -0,0 +1,20 @@
+// Simple namespace object interface
+
+#ifndef Py_INTERNAL_NAMESPACE_H
+#define Py_INTERNAL_NAMESPACE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+PyAPI_DATA(PyTypeObject) _PyNamespace_Type;
+
+PyAPI_FUNC(PyObject *) _PyNamespace_New(PyObject *kwds);
+
+#ifdef __cplusplus
+}
+#endif
+#endif // !Py_INTERNAL_NAMESPACE_H
diff --git a/include/python3.11/internal/pycore_object.h b/include/python3.11/internal/pycore_object.h
new file mode 100644
index 0000000..f022f82
--- /dev/null
+++ b/include/python3.11/internal/pycore_object.h
@@ -0,0 +1,310 @@
+#ifndef Py_INTERNAL_OBJECT_H
+#define Py_INTERNAL_OBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#include <stdbool.h>
+#include "pycore_gc.h" // _PyObject_GC_IS_TRACKED()
+#include "pycore_interp.h" // PyInterpreterState.gc
+#include "pycore_pystate.h" // _PyInterpreterState_GET()
+#include "pycore_runtime.h" // _PyRuntime
+
+#define _PyObject_IMMORTAL_INIT(type) \
+ { \
+ .ob_refcnt = 999999999, \
+ .ob_type = type, \
+ }
+#define _PyVarObject_IMMORTAL_INIT(type, size) \
+ { \
+ .ob_base = _PyObject_IMMORTAL_INIT(type), \
+ .ob_size = size, \
+ }
+
+PyAPI_FUNC(void) _Py_NO_RETURN _Py_FatalRefcountErrorFunc(
+ const char *func,
+ const char *message);
+
+#define _Py_FatalRefcountError(message) _Py_FatalRefcountErrorFunc(__func__, message)
+
+static inline void
+_Py_DECREF_SPECIALIZED(PyObject *op, const destructor destruct)
+{
+#ifdef Py_REF_DEBUG
+ _Py_RefTotal--;
+#endif
+ if (--op->ob_refcnt != 0) {
+ assert(op->ob_refcnt > 0);
+ }
+ else {
+#ifdef Py_TRACE_REFS
+ _Py_ForgetReference(op);
+#endif
+ destruct(op);
+ }
+}
+
+static inline void
+_Py_DECREF_NO_DEALLOC(PyObject *op)
+{
+#ifdef Py_REF_DEBUG
+ _Py_RefTotal--;
+#endif
+ op->ob_refcnt--;
+#ifdef Py_DEBUG
+ if (op->ob_refcnt <= 0) {
+ _Py_FatalRefcountError("Expected a positive remaining refcount");
+ }
+#endif
+}
+
+PyAPI_FUNC(int) _PyType_CheckConsistency(PyTypeObject *type);
+PyAPI_FUNC(int) _PyDict_CheckConsistency(PyObject *mp, int check_content);
+
+/* Update the Python traceback of an object. This function must be called
+ when a memory block is reused from a free list.
+
+ Internal function called by _Py_NewReference(). */
+extern int _PyTraceMalloc_NewReference(PyObject *op);
+
+// Fast inlined version of PyType_HasFeature()
+static inline int
+_PyType_HasFeature(PyTypeObject *type, unsigned long feature) {
+ return ((type->tp_flags & feature) != 0);
+}
+
+extern void _PyType_InitCache(PyInterpreterState *interp);
+
+
+/* Inline functions trading binary compatibility for speed:
+ _PyObject_Init() is the fast version of PyObject_Init(), and
+ _PyObject_InitVar() is the fast version of PyObject_InitVar().
+
+ These inline functions must not be called with op=NULL. */
+static inline void
+_PyObject_Init(PyObject *op, PyTypeObject *typeobj)
+{
+ assert(op != NULL);
+ Py_SET_TYPE(op, typeobj);
+ if (_PyType_HasFeature(typeobj, Py_TPFLAGS_HEAPTYPE)) {
+ Py_INCREF(typeobj);
+ }
+ _Py_NewReference(op);
+}
+
+static inline void
+_PyObject_InitVar(PyVarObject *op, PyTypeObject *typeobj, Py_ssize_t size)
+{
+ assert(op != NULL);
+ Py_SET_SIZE(op, size);
+ _PyObject_Init((PyObject *)op, typeobj);
+}
+
+
+/* Tell the GC to track this object.
+ *
+ * The object must not be tracked by the GC.
+ *
+ * NB: While the object is tracked by the collector, it must be safe to call the
+ * ob_traverse method.
+ *
+ * Internal note: interp->gc.generation0->_gc_prev doesn't have any bit flags
+ * because it's not object header. So we don't use _PyGCHead_PREV() and
+ * _PyGCHead_SET_PREV() for it to avoid unnecessary bitwise operations.
+ *
+ * See also the public PyObject_GC_Track() function.
+ */
+static inline void _PyObject_GC_TRACK(
+// The preprocessor removes _PyObject_ASSERT_FROM() calls if NDEBUG is defined
+#ifndef NDEBUG
+ const char *filename, int lineno,
+#endif
+ PyObject *op)
+{
+ _PyObject_ASSERT_FROM(op, !_PyObject_GC_IS_TRACKED(op),
+ "object already tracked by the garbage collector",
+ filename, lineno, __func__);
+
+ PyGC_Head *gc = _Py_AS_GC(op);
+ _PyObject_ASSERT_FROM(op,
+ (gc->_gc_prev & _PyGC_PREV_MASK_COLLECTING) == 0,
+ "object is in generation which is garbage collected",
+ filename, lineno, __func__);
+
+ PyInterpreterState *interp = _PyInterpreterState_GET();
+ PyGC_Head *generation0 = interp->gc.generation0;
+ PyGC_Head *last = (PyGC_Head*)(generation0->_gc_prev);
+ _PyGCHead_SET_NEXT(last, gc);
+ _PyGCHead_SET_PREV(gc, last);
+ _PyGCHead_SET_NEXT(gc, generation0);
+ generation0->_gc_prev = (uintptr_t)gc;
+}
+
+/* Tell the GC to stop tracking this object.
+ *
+ * Internal note: This may be called while GC. So _PyGC_PREV_MASK_COLLECTING
+ * must be cleared. But _PyGC_PREV_MASK_FINALIZED bit is kept.
+ *
+ * The object must be tracked by the GC.
+ *
+ * See also the public PyObject_GC_UnTrack() which accept an object which is
+ * not tracked.
+ */
+static inline void _PyObject_GC_UNTRACK(
+// The preprocessor removes _PyObject_ASSERT_FROM() calls if NDEBUG is defined
+#ifndef NDEBUG
+ const char *filename, int lineno,
+#endif
+ PyObject *op)
+{
+ _PyObject_ASSERT_FROM(op, _PyObject_GC_IS_TRACKED(op),
+ "object not tracked by the garbage collector",
+ filename, lineno, __func__);
+
+ PyGC_Head *gc = _Py_AS_GC(op);
+ PyGC_Head *prev = _PyGCHead_PREV(gc);
+ PyGC_Head *next = _PyGCHead_NEXT(gc);
+ _PyGCHead_SET_NEXT(prev, next);
+ _PyGCHead_SET_PREV(next, prev);
+ gc->_gc_next = 0;
+ gc->_gc_prev &= _PyGC_PREV_MASK_FINALIZED;
+}
+
+// Macros to accept any type for the parameter, and to automatically pass
+// the filename and the filename (if NDEBUG is not defined) where the macro
+// is called.
+#ifdef NDEBUG
+# define _PyObject_GC_TRACK(op) \
+ _PyObject_GC_TRACK(_PyObject_CAST(op))
+# define _PyObject_GC_UNTRACK(op) \
+ _PyObject_GC_UNTRACK(_PyObject_CAST(op))
+#else
+# define _PyObject_GC_TRACK(op) \
+ _PyObject_GC_TRACK(__FILE__, __LINE__, _PyObject_CAST(op))
+# define _PyObject_GC_UNTRACK(op) \
+ _PyObject_GC_UNTRACK(__FILE__, __LINE__, _PyObject_CAST(op))
+#endif
+
+#ifdef Py_REF_DEBUG
+extern void _PyDebug_PrintTotalRefs(void);
+#endif
+
+#ifdef Py_TRACE_REFS
+extern void _Py_AddToAllObjects(PyObject *op, int force);
+extern void _Py_PrintReferences(FILE *);
+extern void _Py_PrintReferenceAddresses(FILE *);
+#endif
+
+static inline PyObject **
+_PyObject_GET_WEAKREFS_LISTPTR(PyObject *op)
+{
+ Py_ssize_t offset = Py_TYPE(op)->tp_weaklistoffset;
+ return (PyObject **)((char *)op + offset);
+}
+
+// Fast inlined version of PyObject_IS_GC()
+static inline int
+_PyObject_IS_GC(PyObject *obj)
+{
+ return (PyType_IS_GC(Py_TYPE(obj))
+ && (Py_TYPE(obj)->tp_is_gc == NULL
+ || Py_TYPE(obj)->tp_is_gc(obj)));
+}
+
+// Fast inlined version of PyType_IS_GC()
+#define _PyType_IS_GC(t) _PyType_HasFeature((t), Py_TPFLAGS_HAVE_GC)
+
+static inline size_t
+_PyType_PreHeaderSize(PyTypeObject *tp)
+{
+ return _PyType_IS_GC(tp) * sizeof(PyGC_Head) +
+ _PyType_HasFeature(tp, Py_TPFLAGS_MANAGED_DICT) * 2 * sizeof(PyObject *);
+}
+
+void _PyObject_GC_Link(PyObject *op);
+
+// Usage: assert(_Py_CheckSlotResult(obj, "__getitem__", result != NULL));
+extern int _Py_CheckSlotResult(
+ PyObject *obj,
+ const char *slot_name,
+ int success);
+
+// PyType_Ready() must be called if _PyType_IsReady() is false.
+// See also the Py_TPFLAGS_READY flag.
+#define _PyType_IsReady(type) ((type)->tp_dict != NULL)
+
+// Test if a type supports weak references
+static inline int _PyType_SUPPORTS_WEAKREFS(PyTypeObject *type) {
+ return (type->tp_weaklistoffset > 0);
+}
+
+extern PyObject* _PyType_AllocNoTrack(PyTypeObject *type, Py_ssize_t nitems);
+
+extern int _PyObject_InitializeDict(PyObject *obj);
+extern int _PyObject_StoreInstanceAttribute(PyObject *obj, PyDictValues *values,
+ PyObject *name, PyObject *value);
+PyObject * _PyObject_GetInstanceAttribute(PyObject *obj, PyDictValues *values,
+ PyObject *name);
+
+static inline PyDictValues **_PyObject_ValuesPointer(PyObject *obj)
+{
+ assert(Py_TYPE(obj)->tp_flags & Py_TPFLAGS_MANAGED_DICT);
+ return ((PyDictValues **)obj)-4;
+}
+
+static inline PyObject **_PyObject_ManagedDictPointer(PyObject *obj)
+{
+ assert(Py_TYPE(obj)->tp_flags & Py_TPFLAGS_MANAGED_DICT);
+ return ((PyObject **)obj)-3;
+}
+
+#define MANAGED_DICT_OFFSET (((int)sizeof(PyObject *))*-3)
+
+extern PyObject ** _PyObject_DictPointer(PyObject *);
+extern int _PyObject_VisitInstanceAttributes(PyObject *self, visitproc visit, void *arg);
+extern void _PyObject_ClearInstanceAttributes(PyObject *self);
+extern void _PyObject_FreeInstanceAttributes(PyObject *self);
+extern int _PyObject_IsInstanceDictEmpty(PyObject *);
+extern PyObject* _PyType_GetSubclasses(PyTypeObject *);
+
+// Access macro to the members which are floating "behind" the object
+#define _PyHeapType_GET_MEMBERS(etype) \
+ ((PyMemberDef *)(((char *)etype) + Py_TYPE(etype)->tp_basicsize))
+
+PyAPI_FUNC(PyObject *) _PyObject_LookupSpecial(PyObject *, PyObject *);
+
+/* C function call trampolines to mitigate bad function pointer casts.
+ *
+ * Typical native ABIs ignore additional arguments or fill in missing
+ * values with 0/NULL in function pointer cast. Compilers do not show
+ * warnings when a function pointer is explicitly casted to an
+ * incompatible type.
+ *
+ * Bad fpcasts are an issue in WebAssembly. WASM's indirect_call has strict
+ * function signature checks. Argument count, types, and return type must
+ * match.
+ *
+ * Third party code unintentionally rely on problematic fpcasts. The call
+ * trampoline mitigates common occurences of bad fpcasts on Emscripten.
+ */
+#if defined(__EMSCRIPTEN__) && defined(PY_CALL_TRAMPOLINE)
+#define _PyCFunction_TrampolineCall(meth, self, args) \
+ _PyCFunctionWithKeywords_TrampolineCall( \
+ (*(PyCFunctionWithKeywords)(void(*)(void))meth), self, args, NULL)
+extern PyObject* _PyCFunctionWithKeywords_TrampolineCall(
+ PyCFunctionWithKeywords meth, PyObject *, PyObject *, PyObject *);
+#else
+#define _PyCFunction_TrampolineCall(meth, self, args) \
+ (meth)((self), (args))
+#define _PyCFunctionWithKeywords_TrampolineCall(meth, self, args, kw) \
+ (meth)((self), (args), (kw))
+#endif // __EMSCRIPTEN__ && PY_CALL_TRAMPOLINE
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_OBJECT_H */
diff --git a/include/python3.11/internal/pycore_opcode.h b/include/python3.11/internal/pycore_opcode.h
new file mode 100644
index 0000000..eadcba1
--- /dev/null
+++ b/include/python3.11/internal/pycore_opcode.h
@@ -0,0 +1,581 @@
+// Auto-generated by Tools/scripts/generate_opcode_h.py from Lib/opcode.py
+
+#ifndef Py_INTERNAL_OPCODE_H
+#define Py_INTERNAL_OPCODE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#include "opcode.h"
+
+extern const uint8_t _PyOpcode_Caches[256];
+
+extern const uint8_t _PyOpcode_Deopt[256];
+
+#ifdef NEED_OPCODE_TABLES
+static const uint32_t _PyOpcode_RelativeJump[8] = {
+ 0U,
+ 0U,
+ 536870912U,
+ 135118848U,
+ 4163U,
+ 122880U,
+ 0U,
+ 0U,
+};
+static const uint32_t _PyOpcode_Jump[8] = {
+ 0U,
+ 0U,
+ 536870912U,
+ 135118848U,
+ 4163U,
+ 122880U,
+ 0U,
+ 0U,
+};
+
+const uint8_t _PyOpcode_Caches[256] = {
+ [BINARY_SUBSCR] = 4,
+ [STORE_SUBSCR] = 1,
+ [UNPACK_SEQUENCE] = 1,
+ [STORE_ATTR] = 4,
+ [LOAD_ATTR] = 4,
+ [COMPARE_OP] = 2,
+ [LOAD_GLOBAL] = 5,
+ [BINARY_OP] = 1,
+ [LOAD_METHOD] = 10,
+ [PRECALL] = 1,
+ [CALL] = 4,
+};
+
+const uint8_t _PyOpcode_Deopt[256] = {
+ [ASYNC_GEN_WRAP] = ASYNC_GEN_WRAP,
+ [BEFORE_ASYNC_WITH] = BEFORE_ASYNC_WITH,
+ [BEFORE_WITH] = BEFORE_WITH,
+ [BINARY_OP] = BINARY_OP,
+ [BINARY_OP_ADAPTIVE] = BINARY_OP,
+ [BINARY_OP_ADD_FLOAT] = BINARY_OP,
+ [BINARY_OP_ADD_INT] = BINARY_OP,
+ [BINARY_OP_ADD_UNICODE] = BINARY_OP,
+ [BINARY_OP_INPLACE_ADD_UNICODE] = BINARY_OP,
+ [BINARY_OP_MULTIPLY_FLOAT] = BINARY_OP,
+ [BINARY_OP_MULTIPLY_INT] = BINARY_OP,
+ [BINARY_OP_SUBTRACT_FLOAT] = BINARY_OP,
+ [BINARY_OP_SUBTRACT_INT] = BINARY_OP,
+ [BINARY_SUBSCR] = BINARY_SUBSCR,
+ [BINARY_SUBSCR_ADAPTIVE] = BINARY_SUBSCR,
+ [BINARY_SUBSCR_DICT] = BINARY_SUBSCR,
+ [BINARY_SUBSCR_GETITEM] = BINARY_SUBSCR,
+ [BINARY_SUBSCR_LIST_INT] = BINARY_SUBSCR,
+ [BINARY_SUBSCR_TUPLE_INT] = BINARY_SUBSCR,
+ [BUILD_CONST_KEY_MAP] = BUILD_CONST_KEY_MAP,
+ [BUILD_LIST] = BUILD_LIST,
+ [BUILD_MAP] = BUILD_MAP,
+ [BUILD_SET] = BUILD_SET,
+ [BUILD_SLICE] = BUILD_SLICE,
+ [BUILD_STRING] = BUILD_STRING,
+ [BUILD_TUPLE] = BUILD_TUPLE,
+ [CACHE] = CACHE,
+ [CALL] = CALL,
+ [CALL_ADAPTIVE] = CALL,
+ [CALL_FUNCTION_EX] = CALL_FUNCTION_EX,
+ [CALL_PY_EXACT_ARGS] = CALL,
+ [CALL_PY_WITH_DEFAULTS] = CALL,
+ [CHECK_EG_MATCH] = CHECK_EG_MATCH,
+ [CHECK_EXC_MATCH] = CHECK_EXC_MATCH,
+ [COMPARE_OP] = COMPARE_OP,
+ [COMPARE_OP_ADAPTIVE] = COMPARE_OP,
+ [COMPARE_OP_FLOAT_JUMP] = COMPARE_OP,
+ [COMPARE_OP_INT_JUMP] = COMPARE_OP,
+ [COMPARE_OP_STR_JUMP] = COMPARE_OP,
+ [CONTAINS_OP] = CONTAINS_OP,
+ [COPY] = COPY,
+ [COPY_FREE_VARS] = COPY_FREE_VARS,
+ [DELETE_ATTR] = DELETE_ATTR,
+ [DELETE_DEREF] = DELETE_DEREF,
+ [DELETE_FAST] = DELETE_FAST,
+ [DELETE_GLOBAL] = DELETE_GLOBAL,
+ [DELETE_NAME] = DELETE_NAME,
+ [DELETE_SUBSCR] = DELETE_SUBSCR,
+ [DICT_MERGE] = DICT_MERGE,
+ [DICT_UPDATE] = DICT_UPDATE,
+ [END_ASYNC_FOR] = END_ASYNC_FOR,
+ [EXTENDED_ARG] = EXTENDED_ARG,
+ [EXTENDED_ARG_QUICK] = EXTENDED_ARG,
+ [FORMAT_VALUE] = FORMAT_VALUE,
+ [FOR_ITER] = FOR_ITER,
+ [GET_AITER] = GET_AITER,
+ [GET_ANEXT] = GET_ANEXT,
+ [GET_AWAITABLE] = GET_AWAITABLE,
+ [GET_ITER] = GET_ITER,
+ [GET_LEN] = GET_LEN,
+ [GET_YIELD_FROM_ITER] = GET_YIELD_FROM_ITER,
+ [IMPORT_FROM] = IMPORT_FROM,
+ [IMPORT_NAME] = IMPORT_NAME,
+ [IMPORT_STAR] = IMPORT_STAR,
+ [IS_OP] = IS_OP,
+ [JUMP_BACKWARD] = JUMP_BACKWARD,
+ [JUMP_BACKWARD_NO_INTERRUPT] = JUMP_BACKWARD_NO_INTERRUPT,
+ [JUMP_BACKWARD_QUICK] = JUMP_BACKWARD,
+ [JUMP_FORWARD] = JUMP_FORWARD,
+ [JUMP_IF_FALSE_OR_POP] = JUMP_IF_FALSE_OR_POP,
+ [JUMP_IF_TRUE_OR_POP] = JUMP_IF_TRUE_OR_POP,
+ [KW_NAMES] = KW_NAMES,
+ [LIST_APPEND] = LIST_APPEND,
+ [LIST_EXTEND] = LIST_EXTEND,
+ [LIST_TO_TUPLE] = LIST_TO_TUPLE,
+ [LOAD_ASSERTION_ERROR] = LOAD_ASSERTION_ERROR,
+ [LOAD_ATTR] = LOAD_ATTR,
+ [LOAD_ATTR_ADAPTIVE] = LOAD_ATTR,
+ [LOAD_ATTR_INSTANCE_VALUE] = LOAD_ATTR,
+ [LOAD_ATTR_MODULE] = LOAD_ATTR,
+ [LOAD_ATTR_SLOT] = LOAD_ATTR,
+ [LOAD_ATTR_WITH_HINT] = LOAD_ATTR,
+ [LOAD_BUILD_CLASS] = LOAD_BUILD_CLASS,
+ [LOAD_CLASSDEREF] = LOAD_CLASSDEREF,
+ [LOAD_CLOSURE] = LOAD_CLOSURE,
+ [LOAD_CONST] = LOAD_CONST,
+ [LOAD_CONST__LOAD_FAST] = LOAD_CONST,
+ [LOAD_DEREF] = LOAD_DEREF,
+ [LOAD_FAST] = LOAD_FAST,
+ [LOAD_FAST__LOAD_CONST] = LOAD_FAST,
+ [LOAD_FAST__LOAD_FAST] = LOAD_FAST,
+ [LOAD_GLOBAL] = LOAD_GLOBAL,
+ [LOAD_GLOBAL_ADAPTIVE] = LOAD_GLOBAL,
+ [LOAD_GLOBAL_BUILTIN] = LOAD_GLOBAL,
+ [LOAD_GLOBAL_MODULE] = LOAD_GLOBAL,
+ [LOAD_METHOD] = LOAD_METHOD,
+ [LOAD_METHOD_ADAPTIVE] = LOAD_METHOD,
+ [LOAD_METHOD_CLASS] = LOAD_METHOD,
+ [LOAD_METHOD_MODULE] = LOAD_METHOD,
+ [LOAD_METHOD_NO_DICT] = LOAD_METHOD,
+ [LOAD_METHOD_WITH_DICT] = LOAD_METHOD,
+ [LOAD_METHOD_WITH_VALUES] = LOAD_METHOD,
+ [LOAD_NAME] = LOAD_NAME,
+ [MAKE_CELL] = MAKE_CELL,
+ [MAKE_FUNCTION] = MAKE_FUNCTION,
+ [MAP_ADD] = MAP_ADD,
+ [MATCH_CLASS] = MATCH_CLASS,
+ [MATCH_KEYS] = MATCH_KEYS,
+ [MATCH_MAPPING] = MATCH_MAPPING,
+ [MATCH_SEQUENCE] = MATCH_SEQUENCE,
+ [NOP] = NOP,
+ [POP_EXCEPT] = POP_EXCEPT,
+ [POP_JUMP_BACKWARD_IF_FALSE] = POP_JUMP_BACKWARD_IF_FALSE,
+ [POP_JUMP_BACKWARD_IF_NONE] = POP_JUMP_BACKWARD_IF_NONE,
+ [POP_JUMP_BACKWARD_IF_NOT_NONE] = POP_JUMP_BACKWARD_IF_NOT_NONE,
+ [POP_JUMP_BACKWARD_IF_TRUE] = POP_JUMP_BACKWARD_IF_TRUE,
+ [POP_JUMP_FORWARD_IF_FALSE] = POP_JUMP_FORWARD_IF_FALSE,
+ [POP_JUMP_FORWARD_IF_NONE] = POP_JUMP_FORWARD_IF_NONE,
+ [POP_JUMP_FORWARD_IF_NOT_NONE] = POP_JUMP_FORWARD_IF_NOT_NONE,
+ [POP_JUMP_FORWARD_IF_TRUE] = POP_JUMP_FORWARD_IF_TRUE,
+ [POP_TOP] = POP_TOP,
+ [PRECALL] = PRECALL,
+ [PRECALL_ADAPTIVE] = PRECALL,
+ [PRECALL_BOUND_METHOD] = PRECALL,
+ [PRECALL_BUILTIN_CLASS] = PRECALL,
+ [PRECALL_BUILTIN_FAST_WITH_KEYWORDS] = PRECALL,
+ [PRECALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS] = PRECALL,
+ [PRECALL_NO_KW_BUILTIN_FAST] = PRECALL,
+ [PRECALL_NO_KW_BUILTIN_O] = PRECALL,
+ [PRECALL_NO_KW_ISINSTANCE] = PRECALL,
+ [PRECALL_NO_KW_LEN] = PRECALL,
+ [PRECALL_NO_KW_LIST_APPEND] = PRECALL,
+ [PRECALL_NO_KW_METHOD_DESCRIPTOR_FAST] = PRECALL,
+ [PRECALL_NO_KW_METHOD_DESCRIPTOR_NOARGS] = PRECALL,
+ [PRECALL_NO_KW_METHOD_DESCRIPTOR_O] = PRECALL,
+ [PRECALL_NO_KW_STR_1] = PRECALL,
+ [PRECALL_NO_KW_TUPLE_1] = PRECALL,
+ [PRECALL_NO_KW_TYPE_1] = PRECALL,
+ [PRECALL_PYFUNC] = PRECALL,
+ [PREP_RERAISE_STAR] = PREP_RERAISE_STAR,
+ [PRINT_EXPR] = PRINT_EXPR,
+ [PUSH_EXC_INFO] = PUSH_EXC_INFO,
+ [PUSH_NULL] = PUSH_NULL,
+ [RAISE_VARARGS] = RAISE_VARARGS,
+ [RERAISE] = RERAISE,
+ [RESUME] = RESUME,
+ [RESUME_QUICK] = RESUME,
+ [RETURN_GENERATOR] = RETURN_GENERATOR,
+ [RETURN_VALUE] = RETURN_VALUE,
+ [SEND] = SEND,
+ [SETUP_ANNOTATIONS] = SETUP_ANNOTATIONS,
+ [SET_ADD] = SET_ADD,
+ [SET_UPDATE] = SET_UPDATE,
+ [STORE_ATTR] = STORE_ATTR,
+ [STORE_ATTR_ADAPTIVE] = STORE_ATTR,
+ [STORE_ATTR_INSTANCE_VALUE] = STORE_ATTR,
+ [STORE_ATTR_SLOT] = STORE_ATTR,
+ [STORE_ATTR_WITH_HINT] = STORE_ATTR,
+ [STORE_DEREF] = STORE_DEREF,
+ [STORE_FAST] = STORE_FAST,
+ [STORE_FAST__LOAD_FAST] = STORE_FAST,
+ [STORE_FAST__STORE_FAST] = STORE_FAST,
+ [STORE_GLOBAL] = STORE_GLOBAL,
+ [STORE_NAME] = STORE_NAME,
+ [STORE_SUBSCR] = STORE_SUBSCR,
+ [STORE_SUBSCR_ADAPTIVE] = STORE_SUBSCR,
+ [STORE_SUBSCR_DICT] = STORE_SUBSCR,
+ [STORE_SUBSCR_LIST_INT] = STORE_SUBSCR,
+ [SWAP] = SWAP,
+ [UNARY_INVERT] = UNARY_INVERT,
+ [UNARY_NEGATIVE] = UNARY_NEGATIVE,
+ [UNARY_NOT] = UNARY_NOT,
+ [UNARY_POSITIVE] = UNARY_POSITIVE,
+ [UNPACK_EX] = UNPACK_EX,
+ [UNPACK_SEQUENCE] = UNPACK_SEQUENCE,
+ [UNPACK_SEQUENCE_ADAPTIVE] = UNPACK_SEQUENCE,
+ [UNPACK_SEQUENCE_LIST] = UNPACK_SEQUENCE,
+ [UNPACK_SEQUENCE_TUPLE] = UNPACK_SEQUENCE,
+ [UNPACK_SEQUENCE_TWO_TUPLE] = UNPACK_SEQUENCE,
+ [WITH_EXCEPT_START] = WITH_EXCEPT_START,
+ [YIELD_VALUE] = YIELD_VALUE,
+};
+#endif // NEED_OPCODE_TABLES
+
+#ifdef Py_DEBUG
+static const char *const _PyOpcode_OpName[256] = {
+ [CACHE] = "CACHE",
+ [POP_TOP] = "POP_TOP",
+ [PUSH_NULL] = "PUSH_NULL",
+ [BINARY_OP_ADAPTIVE] = "BINARY_OP_ADAPTIVE",
+ [BINARY_OP_ADD_FLOAT] = "BINARY_OP_ADD_FLOAT",
+ [BINARY_OP_ADD_INT] = "BINARY_OP_ADD_INT",
+ [BINARY_OP_ADD_UNICODE] = "BINARY_OP_ADD_UNICODE",
+ [BINARY_OP_INPLACE_ADD_UNICODE] = "BINARY_OP_INPLACE_ADD_UNICODE",
+ [BINARY_OP_MULTIPLY_FLOAT] = "BINARY_OP_MULTIPLY_FLOAT",
+ [NOP] = "NOP",
+ [UNARY_POSITIVE] = "UNARY_POSITIVE",
+ [UNARY_NEGATIVE] = "UNARY_NEGATIVE",
+ [UNARY_NOT] = "UNARY_NOT",
+ [BINARY_OP_MULTIPLY_INT] = "BINARY_OP_MULTIPLY_INT",
+ [BINARY_OP_SUBTRACT_FLOAT] = "BINARY_OP_SUBTRACT_FLOAT",
+ [UNARY_INVERT] = "UNARY_INVERT",
+ [BINARY_OP_SUBTRACT_INT] = "BINARY_OP_SUBTRACT_INT",
+ [BINARY_SUBSCR_ADAPTIVE] = "BINARY_SUBSCR_ADAPTIVE",
+ [BINARY_SUBSCR_DICT] = "BINARY_SUBSCR_DICT",
+ [BINARY_SUBSCR_GETITEM] = "BINARY_SUBSCR_GETITEM",
+ [BINARY_SUBSCR_LIST_INT] = "BINARY_SUBSCR_LIST_INT",
+ [BINARY_SUBSCR_TUPLE_INT] = "BINARY_SUBSCR_TUPLE_INT",
+ [CALL_ADAPTIVE] = "CALL_ADAPTIVE",
+ [CALL_PY_EXACT_ARGS] = "CALL_PY_EXACT_ARGS",
+ [CALL_PY_WITH_DEFAULTS] = "CALL_PY_WITH_DEFAULTS",
+ [BINARY_SUBSCR] = "BINARY_SUBSCR",
+ [COMPARE_OP_ADAPTIVE] = "COMPARE_OP_ADAPTIVE",
+ [COMPARE_OP_FLOAT_JUMP] = "COMPARE_OP_FLOAT_JUMP",
+ [COMPARE_OP_INT_JUMP] = "COMPARE_OP_INT_JUMP",
+ [COMPARE_OP_STR_JUMP] = "COMPARE_OP_STR_JUMP",
+ [GET_LEN] = "GET_LEN",
+ [MATCH_MAPPING] = "MATCH_MAPPING",
+ [MATCH_SEQUENCE] = "MATCH_SEQUENCE",
+ [MATCH_KEYS] = "MATCH_KEYS",
+ [EXTENDED_ARG_QUICK] = "EXTENDED_ARG_QUICK",
+ [PUSH_EXC_INFO] = "PUSH_EXC_INFO",
+ [CHECK_EXC_MATCH] = "CHECK_EXC_MATCH",
+ [CHECK_EG_MATCH] = "CHECK_EG_MATCH",
+ [JUMP_BACKWARD_QUICK] = "JUMP_BACKWARD_QUICK",
+ [LOAD_ATTR_ADAPTIVE] = "LOAD_ATTR_ADAPTIVE",
+ [LOAD_ATTR_INSTANCE_VALUE] = "LOAD_ATTR_INSTANCE_VALUE",
+ [LOAD_ATTR_MODULE] = "LOAD_ATTR_MODULE",
+ [LOAD_ATTR_SLOT] = "LOAD_ATTR_SLOT",
+ [LOAD_ATTR_WITH_HINT] = "LOAD_ATTR_WITH_HINT",
+ [LOAD_CONST__LOAD_FAST] = "LOAD_CONST__LOAD_FAST",
+ [LOAD_FAST__LOAD_CONST] = "LOAD_FAST__LOAD_CONST",
+ [LOAD_FAST__LOAD_FAST] = "LOAD_FAST__LOAD_FAST",
+ [LOAD_GLOBAL_ADAPTIVE] = "LOAD_GLOBAL_ADAPTIVE",
+ [LOAD_GLOBAL_BUILTIN] = "LOAD_GLOBAL_BUILTIN",
+ [WITH_EXCEPT_START] = "WITH_EXCEPT_START",
+ [GET_AITER] = "GET_AITER",
+ [GET_ANEXT] = "GET_ANEXT",
+ [BEFORE_ASYNC_WITH] = "BEFORE_ASYNC_WITH",
+ [BEFORE_WITH] = "BEFORE_WITH",
+ [END_ASYNC_FOR] = "END_ASYNC_FOR",
+ [LOAD_GLOBAL_MODULE] = "LOAD_GLOBAL_MODULE",
+ [LOAD_METHOD_ADAPTIVE] = "LOAD_METHOD_ADAPTIVE",
+ [LOAD_METHOD_CLASS] = "LOAD_METHOD_CLASS",
+ [LOAD_METHOD_MODULE] = "LOAD_METHOD_MODULE",
+ [LOAD_METHOD_NO_DICT] = "LOAD_METHOD_NO_DICT",
+ [STORE_SUBSCR] = "STORE_SUBSCR",
+ [DELETE_SUBSCR] = "DELETE_SUBSCR",
+ [LOAD_METHOD_WITH_DICT] = "LOAD_METHOD_WITH_DICT",
+ [LOAD_METHOD_WITH_VALUES] = "LOAD_METHOD_WITH_VALUES",
+ [PRECALL_ADAPTIVE] = "PRECALL_ADAPTIVE",
+ [PRECALL_BOUND_METHOD] = "PRECALL_BOUND_METHOD",
+ [PRECALL_BUILTIN_CLASS] = "PRECALL_BUILTIN_CLASS",
+ [PRECALL_BUILTIN_FAST_WITH_KEYWORDS] = "PRECALL_BUILTIN_FAST_WITH_KEYWORDS",
+ [GET_ITER] = "GET_ITER",
+ [GET_YIELD_FROM_ITER] = "GET_YIELD_FROM_ITER",
+ [PRINT_EXPR] = "PRINT_EXPR",
+ [LOAD_BUILD_CLASS] = "LOAD_BUILD_CLASS",
+ [PRECALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS] = "PRECALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS",
+ [PRECALL_NO_KW_BUILTIN_FAST] = "PRECALL_NO_KW_BUILTIN_FAST",
+ [LOAD_ASSERTION_ERROR] = "LOAD_ASSERTION_ERROR",
+ [RETURN_GENERATOR] = "RETURN_GENERATOR",
+ [PRECALL_NO_KW_BUILTIN_O] = "PRECALL_NO_KW_BUILTIN_O",
+ [PRECALL_NO_KW_ISINSTANCE] = "PRECALL_NO_KW_ISINSTANCE",
+ [PRECALL_NO_KW_LEN] = "PRECALL_NO_KW_LEN",
+ [PRECALL_NO_KW_LIST_APPEND] = "PRECALL_NO_KW_LIST_APPEND",
+ [PRECALL_NO_KW_METHOD_DESCRIPTOR_FAST] = "PRECALL_NO_KW_METHOD_DESCRIPTOR_FAST",
+ [PRECALL_NO_KW_METHOD_DESCRIPTOR_NOARGS] = "PRECALL_NO_KW_METHOD_DESCRIPTOR_NOARGS",
+ [LIST_TO_TUPLE] = "LIST_TO_TUPLE",
+ [RETURN_VALUE] = "RETURN_VALUE",
+ [IMPORT_STAR] = "IMPORT_STAR",
+ [SETUP_ANNOTATIONS] = "SETUP_ANNOTATIONS",
+ [YIELD_VALUE] = "YIELD_VALUE",
+ [ASYNC_GEN_WRAP] = "ASYNC_GEN_WRAP",
+ [PREP_RERAISE_STAR] = "PREP_RERAISE_STAR",
+ [POP_EXCEPT] = "POP_EXCEPT",
+ [STORE_NAME] = "STORE_NAME",
+ [DELETE_NAME] = "DELETE_NAME",
+ [UNPACK_SEQUENCE] = "UNPACK_SEQUENCE",
+ [FOR_ITER] = "FOR_ITER",
+ [UNPACK_EX] = "UNPACK_EX",
+ [STORE_ATTR] = "STORE_ATTR",
+ [DELETE_ATTR] = "DELETE_ATTR",
+ [STORE_GLOBAL] = "STORE_GLOBAL",
+ [DELETE_GLOBAL] = "DELETE_GLOBAL",
+ [SWAP] = "SWAP",
+ [LOAD_CONST] = "LOAD_CONST",
+ [LOAD_NAME] = "LOAD_NAME",
+ [BUILD_TUPLE] = "BUILD_TUPLE",
+ [BUILD_LIST] = "BUILD_LIST",
+ [BUILD_SET] = "BUILD_SET",
+ [BUILD_MAP] = "BUILD_MAP",
+ [LOAD_ATTR] = "LOAD_ATTR",
+ [COMPARE_OP] = "COMPARE_OP",
+ [IMPORT_NAME] = "IMPORT_NAME",
+ [IMPORT_FROM] = "IMPORT_FROM",
+ [JUMP_FORWARD] = "JUMP_FORWARD",
+ [JUMP_IF_FALSE_OR_POP] = "JUMP_IF_FALSE_OR_POP",
+ [JUMP_IF_TRUE_OR_POP] = "JUMP_IF_TRUE_OR_POP",
+ [PRECALL_NO_KW_METHOD_DESCRIPTOR_O] = "PRECALL_NO_KW_METHOD_DESCRIPTOR_O",
+ [POP_JUMP_FORWARD_IF_FALSE] = "POP_JUMP_FORWARD_IF_FALSE",
+ [POP_JUMP_FORWARD_IF_TRUE] = "POP_JUMP_FORWARD_IF_TRUE",
+ [LOAD_GLOBAL] = "LOAD_GLOBAL",
+ [IS_OP] = "IS_OP",
+ [CONTAINS_OP] = "CONTAINS_OP",
+ [RERAISE] = "RERAISE",
+ [COPY] = "COPY",
+ [PRECALL_NO_KW_STR_1] = "PRECALL_NO_KW_STR_1",
+ [BINARY_OP] = "BINARY_OP",
+ [SEND] = "SEND",
+ [LOAD_FAST] = "LOAD_FAST",
+ [STORE_FAST] = "STORE_FAST",
+ [DELETE_FAST] = "DELETE_FAST",
+ [PRECALL_NO_KW_TUPLE_1] = "PRECALL_NO_KW_TUPLE_1",
+ [POP_JUMP_FORWARD_IF_NOT_NONE] = "POP_JUMP_FORWARD_IF_NOT_NONE",
+ [POP_JUMP_FORWARD_IF_NONE] = "POP_JUMP_FORWARD_IF_NONE",
+ [RAISE_VARARGS] = "RAISE_VARARGS",
+ [GET_AWAITABLE] = "GET_AWAITABLE",
+ [MAKE_FUNCTION] = "MAKE_FUNCTION",
+ [BUILD_SLICE] = "BUILD_SLICE",
+ [JUMP_BACKWARD_NO_INTERRUPT] = "JUMP_BACKWARD_NO_INTERRUPT",
+ [MAKE_CELL] = "MAKE_CELL",
+ [LOAD_CLOSURE] = "LOAD_CLOSURE",
+ [LOAD_DEREF] = "LOAD_DEREF",
+ [STORE_DEREF] = "STORE_DEREF",
+ [DELETE_DEREF] = "DELETE_DEREF",
+ [JUMP_BACKWARD] = "JUMP_BACKWARD",
+ [PRECALL_NO_KW_TYPE_1] = "PRECALL_NO_KW_TYPE_1",
+ [CALL_FUNCTION_EX] = "CALL_FUNCTION_EX",
+ [PRECALL_PYFUNC] = "PRECALL_PYFUNC",
+ [EXTENDED_ARG] = "EXTENDED_ARG",
+ [LIST_APPEND] = "LIST_APPEND",
+ [SET_ADD] = "SET_ADD",
+ [MAP_ADD] = "MAP_ADD",
+ [LOAD_CLASSDEREF] = "LOAD_CLASSDEREF",
+ [COPY_FREE_VARS] = "COPY_FREE_VARS",
+ [RESUME_QUICK] = "RESUME_QUICK",
+ [RESUME] = "RESUME",
+ [MATCH_CLASS] = "MATCH_CLASS",
+ [STORE_ATTR_ADAPTIVE] = "STORE_ATTR_ADAPTIVE",
+ [STORE_ATTR_INSTANCE_VALUE] = "STORE_ATTR_INSTANCE_VALUE",
+ [FORMAT_VALUE] = "FORMAT_VALUE",
+ [BUILD_CONST_KEY_MAP] = "BUILD_CONST_KEY_MAP",
+ [BUILD_STRING] = "BUILD_STRING",
+ [STORE_ATTR_SLOT] = "STORE_ATTR_SLOT",
+ [STORE_ATTR_WITH_HINT] = "STORE_ATTR_WITH_HINT",
+ [LOAD_METHOD] = "LOAD_METHOD",
+ [STORE_FAST__LOAD_FAST] = "STORE_FAST__LOAD_FAST",
+ [LIST_EXTEND] = "LIST_EXTEND",
+ [SET_UPDATE] = "SET_UPDATE",
+ [DICT_MERGE] = "DICT_MERGE",
+ [DICT_UPDATE] = "DICT_UPDATE",
+ [PRECALL] = "PRECALL",
+ [STORE_FAST__STORE_FAST] = "STORE_FAST__STORE_FAST",
+ [STORE_SUBSCR_ADAPTIVE] = "STORE_SUBSCR_ADAPTIVE",
+ [STORE_SUBSCR_DICT] = "STORE_SUBSCR_DICT",
+ [STORE_SUBSCR_LIST_INT] = "STORE_SUBSCR_LIST_INT",
+ [CALL] = "CALL",
+ [KW_NAMES] = "KW_NAMES",
+ [POP_JUMP_BACKWARD_IF_NOT_NONE] = "POP_JUMP_BACKWARD_IF_NOT_NONE",
+ [POP_JUMP_BACKWARD_IF_NONE] = "POP_JUMP_BACKWARD_IF_NONE",
+ [POP_JUMP_BACKWARD_IF_FALSE] = "POP_JUMP_BACKWARD_IF_FALSE",
+ [POP_JUMP_BACKWARD_IF_TRUE] = "POP_JUMP_BACKWARD_IF_TRUE",
+ [UNPACK_SEQUENCE_ADAPTIVE] = "UNPACK_SEQUENCE_ADAPTIVE",
+ [UNPACK_SEQUENCE_LIST] = "UNPACK_SEQUENCE_LIST",
+ [UNPACK_SEQUENCE_TUPLE] = "UNPACK_SEQUENCE_TUPLE",
+ [UNPACK_SEQUENCE_TWO_TUPLE] = "UNPACK_SEQUENCE_TWO_TUPLE",
+ [181] = "<181>",
+ [182] = "<182>",
+ [183] = "<183>",
+ [184] = "<184>",
+ [185] = "<185>",
+ [186] = "<186>",
+ [187] = "<187>",
+ [188] = "<188>",
+ [189] = "<189>",
+ [190] = "<190>",
+ [191] = "<191>",
+ [192] = "<192>",
+ [193] = "<193>",
+ [194] = "<194>",
+ [195] = "<195>",
+ [196] = "<196>",
+ [197] = "<197>",
+ [198] = "<198>",
+ [199] = "<199>",
+ [200] = "<200>",
+ [201] = "<201>",
+ [202] = "<202>",
+ [203] = "<203>",
+ [204] = "<204>",
+ [205] = "<205>",
+ [206] = "<206>",
+ [207] = "<207>",
+ [208] = "<208>",
+ [209] = "<209>",
+ [210] = "<210>",
+ [211] = "<211>",
+ [212] = "<212>",
+ [213] = "<213>",
+ [214] = "<214>",
+ [215] = "<215>",
+ [216] = "<216>",
+ [217] = "<217>",
+ [218] = "<218>",
+ [219] = "<219>",
+ [220] = "<220>",
+ [221] = "<221>",
+ [222] = "<222>",
+ [223] = "<223>",
+ [224] = "<224>",
+ [225] = "<225>",
+ [226] = "<226>",
+ [227] = "<227>",
+ [228] = "<228>",
+ [229] = "<229>",
+ [230] = "<230>",
+ [231] = "<231>",
+ [232] = "<232>",
+ [233] = "<233>",
+ [234] = "<234>",
+ [235] = "<235>",
+ [236] = "<236>",
+ [237] = "<237>",
+ [238] = "<238>",
+ [239] = "<239>",
+ [240] = "<240>",
+ [241] = "<241>",
+ [242] = "<242>",
+ [243] = "<243>",
+ [244] = "<244>",
+ [245] = "<245>",
+ [246] = "<246>",
+ [247] = "<247>",
+ [248] = "<248>",
+ [249] = "<249>",
+ [250] = "<250>",
+ [251] = "<251>",
+ [252] = "<252>",
+ [253] = "<253>",
+ [254] = "<254>",
+ [DO_TRACING] = "DO_TRACING",
+};
+#endif
+
+#define EXTRA_CASES \
+ case 181: \
+ case 182: \
+ case 183: \
+ case 184: \
+ case 185: \
+ case 186: \
+ case 187: \
+ case 188: \
+ case 189: \
+ case 190: \
+ case 191: \
+ case 192: \
+ case 193: \
+ case 194: \
+ case 195: \
+ case 196: \
+ case 197: \
+ case 198: \
+ case 199: \
+ case 200: \
+ case 201: \
+ case 202: \
+ case 203: \
+ case 204: \
+ case 205: \
+ case 206: \
+ case 207: \
+ case 208: \
+ case 209: \
+ case 210: \
+ case 211: \
+ case 212: \
+ case 213: \
+ case 214: \
+ case 215: \
+ case 216: \
+ case 217: \
+ case 218: \
+ case 219: \
+ case 220: \
+ case 221: \
+ case 222: \
+ case 223: \
+ case 224: \
+ case 225: \
+ case 226: \
+ case 227: \
+ case 228: \
+ case 229: \
+ case 230: \
+ case 231: \
+ case 232: \
+ case 233: \
+ case 234: \
+ case 235: \
+ case 236: \
+ case 237: \
+ case 238: \
+ case 239: \
+ case 240: \
+ case 241: \
+ case 242: \
+ case 243: \
+ case 244: \
+ case 245: \
+ case 246: \
+ case 247: \
+ case 248: \
+ case 249: \
+ case 250: \
+ case 251: \
+ case 252: \
+ case 253: \
+ case 254: \
+ ;
+
+#ifdef __cplusplus
+}
+#endif
+#endif // !Py_INTERNAL_OPCODE_H
diff --git a/include/python3.10/internal/pycore_parser.h b/include/python3.11/internal/pycore_parser.h
similarity index 100%
rename from include/python3.10/internal/pycore_parser.h
rename to include/python3.11/internal/pycore_parser.h
diff --git a/include/python3.11/internal/pycore_pathconfig.h b/include/python3.11/internal/pycore_pathconfig.h
new file mode 100644
index 0000000..b8deaa0
--- /dev/null
+++ b/include/python3.11/internal/pycore_pathconfig.h
@@ -0,0 +1,24 @@
+#ifndef Py_INTERNAL_PATHCONFIG_H
+#define Py_INTERNAL_PATHCONFIG_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+PyAPI_FUNC(void) _PyPathConfig_ClearGlobal(void);
+extern PyStatus _PyPathConfig_ReadGlobal(PyConfig *config);
+extern PyStatus _PyPathConfig_UpdateGlobal(const PyConfig *config);
+extern const wchar_t * _PyPathConfig_GetGlobalModuleSearchPath(void);
+
+extern int _PyPathConfig_ComputeSysPath0(
+ const PyWideStringList *argv,
+ PyObject **path0);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_PATHCONFIG_H */
diff --git a/include/python3.10/internal/pycore_pyarena.h b/include/python3.11/internal/pycore_pyarena.h
similarity index 100%
rename from include/python3.10/internal/pycore_pyarena.h
rename to include/python3.11/internal/pycore_pyarena.h
diff --git a/include/python3.11/internal/pycore_pyerrors.h b/include/python3.11/internal/pycore_pyerrors.h
new file mode 100644
index 0000000..66f3794
--- /dev/null
+++ b/include/python3.11/internal/pycore_pyerrors.h
@@ -0,0 +1,106 @@
+#ifndef Py_INTERNAL_PYERRORS_H
+#define Py_INTERNAL_PYERRORS_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+
+/* runtime lifecycle */
+
+extern PyStatus _PyErr_InitTypes(PyInterpreterState *);
+extern void _PyErr_FiniTypes(PyInterpreterState *);
+
+
+/* other API */
+
+static inline PyObject* _PyErr_Occurred(PyThreadState *tstate)
+{
+ assert(tstate != NULL);
+ return tstate->curexc_type;
+}
+
+static inline void _PyErr_ClearExcState(_PyErr_StackItem *exc_state)
+{
+ Py_CLEAR(exc_state->exc_value);
+}
+
+PyAPI_FUNC(PyObject*) _PyErr_StackItemToExcInfoTuple(
+ _PyErr_StackItem *err_info);
+
+PyAPI_FUNC(void) _PyErr_Fetch(
+ PyThreadState *tstate,
+ PyObject **type,
+ PyObject **value,
+ PyObject **traceback);
+
+PyAPI_FUNC(int) _PyErr_ExceptionMatches(
+ PyThreadState *tstate,
+ PyObject *exc);
+
+PyAPI_FUNC(void) _PyErr_Restore(
+ PyThreadState *tstate,
+ PyObject *type,
+ PyObject *value,
+ PyObject *traceback);
+
+PyAPI_FUNC(void) _PyErr_SetObject(
+ PyThreadState *tstate,
+ PyObject *type,
+ PyObject *value);
+
+PyAPI_FUNC(void) _PyErr_ChainStackItem(
+ _PyErr_StackItem *exc_info);
+
+PyAPI_FUNC(void) _PyErr_Clear(PyThreadState *tstate);
+
+PyAPI_FUNC(void) _PyErr_SetNone(PyThreadState *tstate, PyObject *exception);
+
+PyAPI_FUNC(PyObject *) _PyErr_NoMemory(PyThreadState *tstate);
+
+PyAPI_FUNC(void) _PyErr_SetString(
+ PyThreadState *tstate,
+ PyObject *exception,
+ const char *string);
+
+PyAPI_FUNC(PyObject *) _PyErr_Format(
+ PyThreadState *tstate,
+ PyObject *exception,
+ const char *format,
+ ...);
+
+PyAPI_FUNC(void) _PyErr_NormalizeException(
+ PyThreadState *tstate,
+ PyObject **exc,
+ PyObject **val,
+ PyObject **tb);
+
+PyAPI_FUNC(PyObject *) _PyErr_FormatFromCauseTstate(
+ PyThreadState *tstate,
+ PyObject *exception,
+ const char *format,
+ ...);
+
+PyAPI_FUNC(PyObject *) _PyExc_CreateExceptionGroup(
+ const char *msg,
+ PyObject *excs);
+
+PyAPI_FUNC(PyObject *) _PyExc_PrepReraiseStar(
+ PyObject *orig,
+ PyObject *excs);
+
+PyAPI_FUNC(int) _PyErr_CheckSignalsTstate(PyThreadState *tstate);
+
+PyAPI_FUNC(void) _Py_DumpExtensionModules(int fd, PyInterpreterState *interp);
+
+extern PyObject* _Py_Offer_Suggestions(PyObject* exception);
+PyAPI_FUNC(Py_ssize_t) _Py_UTF8_Edit_Cost(PyObject *str_a, PyObject *str_b,
+ Py_ssize_t max_cost);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_PYERRORS_H */
diff --git a/include/python3.10/internal/pycore_pyhash.h b/include/python3.11/internal/pycore_pyhash.h
similarity index 100%
rename from include/python3.10/internal/pycore_pyhash.h
rename to include/python3.11/internal/pycore_pyhash.h
diff --git a/include/python3.11/internal/pycore_pylifecycle.h b/include/python3.11/internal/pycore_pylifecycle.h
new file mode 100644
index 0000000..b4718b8
--- /dev/null
+++ b/include/python3.11/internal/pycore_pylifecycle.h
@@ -0,0 +1,103 @@
+#ifndef Py_INTERNAL_LIFECYCLE_H
+#define Py_INTERNAL_LIFECYCLE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#include "pycore_runtime.h" // _PyRuntimeState
+
+/* Forward declarations */
+struct _PyArgv;
+struct pyruntimestate;
+
+/* True if the main interpreter thread exited due to an unhandled
+ * KeyboardInterrupt exception, suggesting the user pressed ^C. */
+PyAPI_DATA(int) _Py_UnhandledKeyboardInterrupt;
+
+extern int _Py_SetFileSystemEncoding(
+ const char *encoding,
+ const char *errors);
+extern void _Py_ClearFileSystemEncoding(void);
+extern PyStatus _PyUnicode_InitEncodings(PyThreadState *tstate);
+#ifdef MS_WINDOWS
+extern int _PyUnicode_EnableLegacyWindowsFSEncoding(void);
+#endif
+
+PyAPI_FUNC(void) _Py_ClearStandardStreamEncoding(void);
+
+PyAPI_FUNC(int) _Py_IsLocaleCoercionTarget(const char *ctype_loc);
+
+/* Various one-time initializers */
+
+extern PyStatus _PyFaulthandler_Init(int enable);
+extern int _PyTraceMalloc_Init(int enable);
+extern PyObject * _PyBuiltin_Init(PyInterpreterState *interp);
+extern PyStatus _PySys_Create(
+ PyThreadState *tstate,
+ PyObject **sysmod_p);
+extern PyStatus _PySys_ReadPreinitWarnOptions(PyWideStringList *options);
+extern PyStatus _PySys_ReadPreinitXOptions(PyConfig *config);
+extern int _PySys_UpdateConfig(PyThreadState *tstate);
+extern void _PySys_Fini(PyInterpreterState *interp);
+extern int _PyBuiltins_AddExceptions(PyObject * bltinmod);
+extern PyStatus _Py_HashRandomization_Init(const PyConfig *);
+
+extern PyStatus _PyImportZip_Init(PyThreadState *tstate);
+extern PyStatus _PyGC_Init(PyInterpreterState *interp);
+extern PyStatus _PyAtExit_Init(PyInterpreterState *interp);
+extern int _Py_Deepfreeze_Init(void);
+
+/* Various internal finalizers */
+
+extern int _PySignal_Init(int install_signal_handlers);
+extern void _PySignal_Fini(void);
+
+extern void _PyImport_Fini(void);
+extern void _PyImport_Fini2(void);
+extern void _PyGC_Fini(PyInterpreterState *interp);
+extern void _Py_HashRandomization_Fini(void);
+extern void _PyFaulthandler_Fini(void);
+extern void _PyHash_Fini(void);
+extern void _PyTraceMalloc_Fini(void);
+extern void _PyWarnings_Fini(PyInterpreterState *interp);
+extern void _PyAST_Fini(PyInterpreterState *interp);
+extern void _PyAtExit_Fini(PyInterpreterState *interp);
+extern void _PyThread_FiniType(PyInterpreterState *interp);
+extern void _Py_Deepfreeze_Fini(void);
+extern void _PyArg_Fini(void);
+
+extern PyStatus _PyGILState_Init(_PyRuntimeState *runtime);
+extern PyStatus _PyGILState_SetTstate(PyThreadState *tstate);
+extern void _PyGILState_Fini(PyInterpreterState *interp);
+
+PyAPI_FUNC(void) _PyGC_DumpShutdownStats(PyInterpreterState *interp);
+
+PyAPI_FUNC(PyStatus) _Py_PreInitializeFromPyArgv(
+ const PyPreConfig *src_config,
+ const struct _PyArgv *args);
+PyAPI_FUNC(PyStatus) _Py_PreInitializeFromConfig(
+ const PyConfig *config,
+ const struct _PyArgv *args);
+
+PyAPI_FUNC(wchar_t *) _Py_GetStdlibDir(void);
+
+PyAPI_FUNC(int) _Py_HandleSystemExit(int *exitcode_p);
+
+PyAPI_FUNC(PyObject*) _PyErr_WriteUnraisableDefaultHook(PyObject *unraisable);
+
+PyAPI_FUNC(void) _PyErr_Print(PyThreadState *tstate);
+PyAPI_FUNC(void) _PyErr_Display(PyObject *file, PyObject *exception,
+ PyObject *value, PyObject *tb);
+
+PyAPI_FUNC(void) _PyThreadState_DeleteCurrent(PyThreadState *tstate);
+
+extern void _PyAtExit_Call(PyInterpreterState *interp);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_LIFECYCLE_H */
diff --git a/include/python3.11/internal/pycore_pymath.h b/include/python3.11/internal/pycore_pymath.h
new file mode 100644
index 0000000..5c6aee2
--- /dev/null
+++ b/include/python3.11/internal/pycore_pymath.h
@@ -0,0 +1,224 @@
+#ifndef Py_INTERNAL_PYMATH_H
+#define Py_INTERNAL_PYMATH_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+
+/* _Py_ADJUST_ERANGE1(x)
+ * _Py_ADJUST_ERANGE2(x, y)
+ * Set errno to 0 before calling a libm function, and invoke one of these
+ * macros after, passing the function result(s) (_Py_ADJUST_ERANGE2 is useful
+ * for functions returning complex results). This makes two kinds of
+ * adjustments to errno: (A) If it looks like the platform libm set
+ * errno=ERANGE due to underflow, clear errno. (B) If it looks like the
+ * platform libm overflowed but didn't set errno, force errno to ERANGE. In
+ * effect, we're trying to force a useful implementation of C89 errno
+ * behavior.
+ * Caution:
+ * This isn't reliable. C99 no longer requires libm to set errno under
+ * any exceptional condition, but does require +- HUGE_VAL return
+ * values on overflow. A 754 box *probably* maps HUGE_VAL to a
+ * double infinity, and we're cool if that's so, unless the input
+ * was an infinity and an infinity is the expected result. A C89
+ * system sets errno to ERANGE, so we check for that too. We're
+ * out of luck if a C99 754 box doesn't map HUGE_VAL to +Inf, or
+ * if the returned result is a NaN, or if a C89 box returns HUGE_VAL
+ * in non-overflow cases.
+ */
+static inline void _Py_ADJUST_ERANGE1(double x)
+{
+ if (errno == 0) {
+ if (x == Py_HUGE_VAL || x == -Py_HUGE_VAL) {
+ errno = ERANGE;
+ }
+ }
+ else if (errno == ERANGE && x == 0.0) {
+ errno = 0;
+ }
+}
+
+static inline void _Py_ADJUST_ERANGE2(double x, double y)
+{
+ if (x == Py_HUGE_VAL || x == -Py_HUGE_VAL ||
+ y == Py_HUGE_VAL || y == -Py_HUGE_VAL)
+ {
+ if (errno == 0) {
+ errno = ERANGE;
+ }
+ }
+ else if (errno == ERANGE) {
+ errno = 0;
+ }
+}
+
+// Return whether integral type *type* is signed or not.
+#define _Py_IntegralTypeSigned(type) \
+ ((type)(-1) < 0)
+
+// Return the maximum value of integral type *type*.
+#define _Py_IntegralTypeMax(type) \
+ ((_Py_IntegralTypeSigned(type)) ? (((((type)1 << (sizeof(type)*CHAR_BIT - 2)) - 1) << 1) + 1) : ~(type)0)
+
+// Return the minimum value of integral type *type*.
+#define _Py_IntegralTypeMin(type) \
+ ((_Py_IntegralTypeSigned(type)) ? -_Py_IntegralTypeMax(type) - 1 : 0)
+
+// Check whether *v* is in the range of integral type *type*. This is most
+// useful if *v* is floating-point, since demoting a floating-point *v* to an
+// integral type that cannot represent *v*'s integral part is undefined
+// behavior.
+#define _Py_InIntegralTypeRange(type, v) \
+ (_Py_IntegralTypeMin(type) <= v && v <= _Py_IntegralTypeMax(type))
+
+
+//--- HAVE_PY_SET_53BIT_PRECISION macro ------------------------------------
+//
+// The functions _Py_dg_strtod() and _Py_dg_dtoa() in Python/dtoa.c (which are
+// required to support the short float repr introduced in Python 3.1) require
+// that the floating-point unit that's being used for arithmetic operations on
+// C doubles is set to use 53-bit precision. It also requires that the FPU
+// rounding mode is round-half-to-even, but that's less often an issue.
+//
+// If your FPU isn't already set to 53-bit precision/round-half-to-even, and
+// you want to make use of _Py_dg_strtod() and _Py_dg_dtoa(), then you should:
+//
+// #define HAVE_PY_SET_53BIT_PRECISION 1
+//
+// and also give appropriate definitions for the following three macros:
+//
+// * _Py_SET_53BIT_PRECISION_HEADER: any variable declarations needed to
+// use the two macros below.
+// * _Py_SET_53BIT_PRECISION_START: store original FPU settings, and
+// set FPU to 53-bit precision/round-half-to-even
+// * _Py_SET_53BIT_PRECISION_END: restore original FPU settings
+//
+// The macros are designed to be used within a single C function: see
+// Python/pystrtod.c for an example of their use.
+
+
+// Get and set x87 control word for gcc/x86
+#ifdef HAVE_GCC_ASM_FOR_X87
+#define HAVE_PY_SET_53BIT_PRECISION 1
+
+// Functions defined in Python/pymath.c
+extern unsigned short _Py_get_387controlword(void);
+extern void _Py_set_387controlword(unsigned short);
+
+#define _Py_SET_53BIT_PRECISION_HEADER \
+ unsigned short old_387controlword, new_387controlword
+#define _Py_SET_53BIT_PRECISION_START \
+ do { \
+ old_387controlword = _Py_get_387controlword(); \
+ new_387controlword = (old_387controlword & ~0x0f00) | 0x0200; \
+ if (new_387controlword != old_387controlword) { \
+ _Py_set_387controlword(new_387controlword); \
+ } \
+ } while (0)
+#define _Py_SET_53BIT_PRECISION_END \
+ do { \
+ if (new_387controlword != old_387controlword) { \
+ _Py_set_387controlword(old_387controlword); \
+ } \
+ } while (0)
+#endif
+
+// Get and set x87 control word for VisualStudio/x86.
+// x87 is not supported in 64-bit or ARM.
+#if defined(_MSC_VER) && !defined(_WIN64) && !defined(_M_ARM)
+#define HAVE_PY_SET_53BIT_PRECISION 1
+
+#include <float.h> // __control87_2()
+
+#define _Py_SET_53BIT_PRECISION_HEADER \
+ unsigned int old_387controlword, new_387controlword, out_387controlword
+ // We use the __control87_2 function to set only the x87 control word.
+ // The SSE control word is unaffected.
+#define _Py_SET_53BIT_PRECISION_START \
+ do { \
+ __control87_2(0, 0, &old_387controlword, NULL); \
+ new_387controlword = \
+ (old_387controlword & ~(_MCW_PC | _MCW_RC)) | (_PC_53 | _RC_NEAR); \
+ if (new_387controlword != old_387controlword) { \
+ __control87_2(new_387controlword, _MCW_PC | _MCW_RC, \
+ &out_387controlword, NULL); \
+ } \
+ } while (0)
+#define _Py_SET_53BIT_PRECISION_END \
+ do { \
+ if (new_387controlword != old_387controlword) { \
+ __control87_2(old_387controlword, _MCW_PC | _MCW_RC, \
+ &out_387controlword, NULL); \
+ } \
+ } while (0)
+#endif
+
+
+// MC68881
+#ifdef HAVE_GCC_ASM_FOR_MC68881
+#define HAVE_PY_SET_53BIT_PRECISION 1
+#define _Py_SET_53BIT_PRECISION_HEADER \
+ unsigned int old_fpcr, new_fpcr
+#define _Py_SET_53BIT_PRECISION_START \
+ do { \
+ __asm__ ("fmove.l %%fpcr,%0" : "=g" (old_fpcr)); \
+ /* Set double precision / round to nearest. */ \
+ new_fpcr = (old_fpcr & ~0xf0) | 0x80; \
+ if (new_fpcr != old_fpcr) { \
+ __asm__ volatile ("fmove.l %0,%%fpcr" : : "g" (new_fpcr));\
+ } \
+ } while (0)
+#define _Py_SET_53BIT_PRECISION_END \
+ do { \
+ if (new_fpcr != old_fpcr) { \
+ __asm__ volatile ("fmove.l %0,%%fpcr" : : "g" (old_fpcr)); \
+ } \
+ } while (0)
+#endif
+
+// Default definitions are empty
+#ifndef _Py_SET_53BIT_PRECISION_HEADER
+# define _Py_SET_53BIT_PRECISION_HEADER
+# define _Py_SET_53BIT_PRECISION_START
+# define _Py_SET_53BIT_PRECISION_END
+#endif
+
+
+//--- _PY_SHORT_FLOAT_REPR macro -------------------------------------------
+
+// If we can't guarantee 53-bit precision, don't use the code
+// in Python/dtoa.c, but fall back to standard code. This
+// means that repr of a float will be long (17 significant digits).
+//
+// Realistically, there are two things that could go wrong:
+//
+// (1) doubles aren't IEEE 754 doubles, or
+// (2) we're on x86 with the rounding precision set to 64-bits
+// (extended precision), and we don't know how to change
+// the rounding precision.
+#if !defined(DOUBLE_IS_LITTLE_ENDIAN_IEEE754) && \
+ !defined(DOUBLE_IS_BIG_ENDIAN_IEEE754) && \
+ !defined(DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754)
+# define _PY_SHORT_FLOAT_REPR 0
+#endif
+
+// Double rounding is symptomatic of use of extended precision on x86.
+// If we're seeing double rounding, and we don't have any mechanism available
+// for changing the FPU rounding precision, then don't use Python/dtoa.c.
+#if defined(X87_DOUBLE_ROUNDING) && !defined(HAVE_PY_SET_53BIT_PRECISION)
+# define _PY_SHORT_FLOAT_REPR 0
+#endif
+
+#ifndef _PY_SHORT_FLOAT_REPR
+# define _PY_SHORT_FLOAT_REPR 1
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_PYMATH_H */
diff --git a/include/python3.11/internal/pycore_pymem.h b/include/python3.11/internal/pycore_pymem.h
new file mode 100644
index 0000000..b9eea9d
--- /dev/null
+++ b/include/python3.11/internal/pycore_pymem.h
@@ -0,0 +1,114 @@
+#ifndef Py_INTERNAL_PYMEM_H
+#define Py_INTERNAL_PYMEM_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#include "pymem.h" // PyMemAllocatorName
+
+
+/* Set the memory allocator of the specified domain to the default.
+ Save the old allocator into *old_alloc if it's non-NULL.
+ Return on success, or return -1 if the domain is unknown. */
+PyAPI_FUNC(int) _PyMem_SetDefaultAllocator(
+ PyMemAllocatorDomain domain,
+ PyMemAllocatorEx *old_alloc);
+
+/* Special bytes broadcast into debug memory blocks at appropriate times.
+ Strings of these are unlikely to be valid addresses, floats, ints or
+ 7-bit ASCII.
+
+ - PYMEM_CLEANBYTE: clean (newly allocated) memory
+ - PYMEM_DEADBYTE dead (newly freed) memory
+ - PYMEM_FORBIDDENBYTE: untouchable bytes at each end of a block
+
+ Byte patterns 0xCB, 0xDB and 0xFB have been replaced with 0xCD, 0xDD and
+ 0xFD to use the same values than Windows CRT debug malloc() and free().
+ If modified, _PyMem_IsPtrFreed() should be updated as well. */
+#define PYMEM_CLEANBYTE 0xCD
+#define PYMEM_DEADBYTE 0xDD
+#define PYMEM_FORBIDDENBYTE 0xFD
+
+/* Heuristic checking if a pointer value is newly allocated
+ (uninitialized), newly freed or NULL (is equal to zero).
+
+ The pointer is not dereferenced, only the pointer value is checked.
+
+ The heuristic relies on the debug hooks on Python memory allocators which
+ fills newly allocated memory with CLEANBYTE (0xCD) and newly freed memory
+ with DEADBYTE (0xDD). Detect also "untouchable bytes" marked
+ with FORBIDDENBYTE (0xFD). */
+static inline int _PyMem_IsPtrFreed(const void *ptr)
+{
+ uintptr_t value = (uintptr_t)ptr;
+#if SIZEOF_VOID_P == 8
+ return (value == 0
+ || value == (uintptr_t)0xCDCDCDCDCDCDCDCD
+ || value == (uintptr_t)0xDDDDDDDDDDDDDDDD
+ || value == (uintptr_t)0xFDFDFDFDFDFDFDFD);
+#elif SIZEOF_VOID_P == 4
+ return (value == 0
+ || value == (uintptr_t)0xCDCDCDCD
+ || value == (uintptr_t)0xDDDDDDDD
+ || value == (uintptr_t)0xFDFDFDFD);
+#else
+# error "unknown pointer size"
+#endif
+}
+
+PyAPI_FUNC(int) _PyMem_GetAllocatorName(
+ const char *name,
+ PyMemAllocatorName *allocator);
+
+/* Configure the Python memory allocators.
+ Pass PYMEM_ALLOCATOR_DEFAULT to use default allocators.
+ PYMEM_ALLOCATOR_NOT_SET does nothing. */
+PyAPI_FUNC(int) _PyMem_SetupAllocators(PyMemAllocatorName allocator);
+
+struct _PyTraceMalloc_Config {
+ /* Module initialized?
+ Variable protected by the GIL */
+ enum {
+ TRACEMALLOC_NOT_INITIALIZED,
+ TRACEMALLOC_INITIALIZED,
+ TRACEMALLOC_FINALIZED
+ } initialized;
+
+ /* Is tracemalloc tracing memory allocations?
+ Variable protected by the GIL */
+ int tracing;
+
+ /* limit of the number of frames in a traceback, 1 by default.
+ Variable protected by the GIL. */
+ int max_nframe;
+};
+
+#define _PyTraceMalloc_Config_INIT \
+ {.initialized = TRACEMALLOC_NOT_INITIALIZED, \
+ .tracing = 0, \
+ .max_nframe = 1}
+
+PyAPI_DATA(struct _PyTraceMalloc_Config) _Py_tracemalloc_config;
+
+/* Allocate memory directly from the O/S virtual memory system,
+ * where supported. Otherwise fallback on malloc */
+void *_PyObject_VirtualAlloc(size_t size);
+void _PyObject_VirtualFree(void *, size_t size);
+
+/* This function returns the number of allocated memory blocks, regardless of size */
+PyAPI_FUNC(Py_ssize_t) _Py_GetAllocatedBlocks(void);
+
+/* Macros */
+#ifdef WITH_PYMALLOC
+// Export the symbol for the 3rd party guppy3 project
+PyAPI_FUNC(int) _PyObject_DebugMallocStats(FILE *out);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif // !Py_INTERNAL_PYMEM_H
diff --git a/include/python3.11/internal/pycore_pystate.h b/include/python3.11/internal/pycore_pystate.h
new file mode 100644
index 0000000..cb8f115
--- /dev/null
+++ b/include/python3.11/internal/pycore_pystate.h
@@ -0,0 +1,167 @@
+#ifndef Py_INTERNAL_PYSTATE_H
+#define Py_INTERNAL_PYSTATE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#include "pycore_runtime.h" /* PyRuntimeState */
+
+
+/* Check if the current thread is the main thread.
+ Use _Py_IsMainInterpreter() to check if it's the main interpreter. */
+static inline int
+_Py_IsMainThread(void)
+{
+ unsigned long thread = PyThread_get_thread_ident();
+ return (thread == _PyRuntime.main_thread);
+}
+
+
+static inline PyInterpreterState *
+_PyInterpreterState_Main(void)
+{
+ return _PyRuntime.interpreters.main;
+}
+
+static inline int
+_Py_IsMainInterpreter(PyInterpreterState *interp)
+{
+ return (interp == _PyInterpreterState_Main());
+}
+
+
+static inline const PyConfig *
+_Py_GetMainConfig(void)
+{
+ PyInterpreterState *interp = _PyInterpreterState_Main();
+ if (interp == NULL) {
+ return NULL;
+ }
+ return _PyInterpreterState_GetConfig(interp);
+}
+
+
+/* Only handle signals on the main thread of the main interpreter. */
+static inline int
+_Py_ThreadCanHandleSignals(PyInterpreterState *interp)
+{
+ return (_Py_IsMainThread() && _Py_IsMainInterpreter(interp));
+}
+
+
+/* Only execute pending calls on the main thread. */
+static inline int
+_Py_ThreadCanHandlePendingCalls(void)
+{
+ return _Py_IsMainThread();
+}
+
+
+/* Variable and macro for in-line access to current thread
+ and interpreter state */
+
+static inline PyThreadState*
+_PyRuntimeState_GetThreadState(_PyRuntimeState *runtime)
+{
+ return (PyThreadState*)_Py_atomic_load_relaxed(&runtime->gilstate.tstate_current);
+}
+
+/* Get the current Python thread state.
+
+ Efficient macro reading directly the 'gilstate.tstate_current' atomic
+ variable. The macro is unsafe: it does not check for error and it can
+ return NULL.
+
+ The caller must hold the GIL.
+
+ See also PyThreadState_Get() and _PyThreadState_UncheckedGet(). */
+static inline PyThreadState*
+_PyThreadState_GET(void)
+{
+ return _PyRuntimeState_GetThreadState(&_PyRuntime);
+}
+
+PyAPI_FUNC(void) _Py_NO_RETURN _Py_FatalError_TstateNULL(const char *func);
+
+static inline void
+_Py_EnsureFuncTstateNotNULL(const char *func, PyThreadState *tstate)
+{
+ if (tstate == NULL) {
+ _Py_FatalError_TstateNULL(func);
+ }
+}
+
+// Call Py_FatalError() if tstate is NULL
+#define _Py_EnsureTstateNotNULL(tstate) \
+ _Py_EnsureFuncTstateNotNULL(__func__, tstate)
+
+
+/* Get the current interpreter state.
+
+ The macro is unsafe: it does not check for error and it can return NULL.
+
+ The caller must hold the GIL.
+
+ See also _PyInterpreterState_Get()
+ and _PyGILState_GetInterpreterStateUnsafe(). */
+static inline PyInterpreterState* _PyInterpreterState_GET(void) {
+ PyThreadState *tstate = _PyThreadState_GET();
+#ifdef Py_DEBUG
+ _Py_EnsureTstateNotNULL(tstate);
+#endif
+ return tstate->interp;
+}
+
+
+// PyThreadState functions
+
+PyAPI_FUNC(void) _PyThreadState_SetCurrent(PyThreadState *tstate);
+// We keep this around exclusively for stable ABI compatibility.
+PyAPI_FUNC(void) _PyThreadState_Init(
+ PyThreadState *tstate);
+PyAPI_FUNC(void) _PyThreadState_DeleteExcept(
+ _PyRuntimeState *runtime,
+ PyThreadState *tstate);
+
+
+static inline void
+_PyThreadState_UpdateTracingState(PyThreadState *tstate)
+{
+ bool use_tracing =
+ (tstate->tracing == 0) &&
+ (tstate->c_tracefunc != NULL || tstate->c_profilefunc != NULL);
+ tstate->cframe->use_tracing = (use_tracing ? 255 : 0);
+}
+
+
+/* Other */
+
+PyAPI_FUNC(PyThreadState *) _PyThreadState_Swap(
+ struct _gilstate_runtime_state *gilstate,
+ PyThreadState *newts);
+
+PyAPI_FUNC(PyStatus) _PyInterpreterState_Enable(_PyRuntimeState *runtime);
+
+#ifdef HAVE_FORK
+extern PyStatus _PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime);
+extern PyStatus _PyGILState_Reinit(_PyRuntimeState *runtime);
+extern void _PySignal_AfterFork(void);
+#endif
+
+
+PyAPI_FUNC(int) _PyState_AddModule(
+ PyThreadState *tstate,
+ PyObject* module,
+ PyModuleDef* def);
+
+
+PyAPI_FUNC(int) _PyOS_InterruptOccurred(PyThreadState *tstate);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_PYSTATE_H */
diff --git a/include/python3.11/internal/pycore_runtime.h b/include/python3.11/internal/pycore_runtime.h
new file mode 100644
index 0000000..ae63ae7
--- /dev/null
+++ b/include/python3.11/internal/pycore_runtime.h
@@ -0,0 +1,181 @@
+#ifndef Py_INTERNAL_RUNTIME_H
+#define Py_INTERNAL_RUNTIME_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#include "pycore_atomic.h" /* _Py_atomic_address */
+#include "pycore_gil.h" // struct _gil_runtime_state
+#include "pycore_global_objects.h" // struct _Py_global_objects
+#include "pycore_interp.h" // PyInterpreterState
+#include "pycore_unicodeobject.h" // struct _Py_unicode_runtime_ids
+
+
+/* ceval state */
+
+struct _ceval_runtime_state {
+ /* Request for checking signals. It is shared by all interpreters (see
+ bpo-40513). Any thread of any interpreter can receive a signal, but only
+ the main thread of the main interpreter can handle signals: see
+ _Py_ThreadCanHandleSignals(). */
+ _Py_atomic_int signals_pending;
+ struct _gil_runtime_state gil;
+};
+
+/* GIL state */
+
+struct _gilstate_runtime_state {
+ /* bpo-26558: Flag to disable PyGILState_Check().
+ If set to non-zero, PyGILState_Check() always return 1. */
+ int check_enabled;
+ /* Assuming the current thread holds the GIL, this is the
+ PyThreadState for the current thread. */
+ _Py_atomic_address tstate_current;
+ /* The single PyInterpreterState used by this process'
+ GILState implementation
+ */
+ /* TODO: Given interp_main, it may be possible to kill this ref */
+ PyInterpreterState *autoInterpreterState;
+ Py_tss_t autoTSSkey;
+};
+
+/* Runtime audit hook state */
+
+typedef struct _Py_AuditHookEntry {
+ struct _Py_AuditHookEntry *next;
+ Py_AuditHookFunction hookCFunction;
+ void *userData;
+} _Py_AuditHookEntry;
+
+/* Full Python runtime state */
+
+/* _PyRuntimeState holds the global state for the CPython runtime.
+ That data is exposed in the internal API as a static variable (_PyRuntime).
+ */
+typedef struct pyruntimestate {
+ /* Has been initialized to a safe state.
+
+ In order to be effective, this must be set to 0 during or right
+ after allocation. */
+ int _initialized;
+
+ /* Is running Py_PreInitialize()? */
+ int preinitializing;
+
+ /* Is Python preinitialized? Set to 1 by Py_PreInitialize() */
+ int preinitialized;
+
+ /* Is Python core initialized? Set to 1 by _Py_InitializeCore() */
+ int core_initialized;
+
+ /* Is Python fully initialized? Set to 1 by Py_Initialize() */
+ int initialized;
+
+ /* Set by Py_FinalizeEx(). Only reset to NULL if Py_Initialize()
+ is called again.
+
+ Use _PyRuntimeState_GetFinalizing() and _PyRuntimeState_SetFinalizing()
+ to access it, don't access it directly. */
+ _Py_atomic_address _finalizing;
+
+ struct pyinterpreters {
+ PyThread_type_lock mutex;
+ /* The linked list of interpreters, newest first. */
+ PyInterpreterState *head;
+ /* The runtime's initial interpreter, which has a special role
+ in the operation of the runtime. It is also often the only
+ interpreter. */
+ PyInterpreterState *main;
+ /* _next_interp_id is an auto-numbered sequence of small
+ integers. It gets initialized in _PyInterpreterState_Init(),
+ which is called in Py_Initialize(), and used in
+ PyInterpreterState_New(). A negative interpreter ID
+ indicates an error occurred. The main interpreter will
+ always have an ID of 0. Overflow results in a RuntimeError.
+ If that becomes a problem later then we can adjust, e.g. by
+ using a Python int. */
+ int64_t next_id;
+ } interpreters;
+ // XXX Remove this field once we have a tp_* slot.
+ struct _xidregistry {
+ PyThread_type_lock mutex;
+ struct _xidregitem *head;
+ } xidregistry;
+
+ unsigned long main_thread;
+
+#define NEXITFUNCS 32
+ void (*exitfuncs[NEXITFUNCS])(void);
+ int nexitfuncs;
+
+ struct _ceval_runtime_state ceval;
+ struct _gilstate_runtime_state gilstate;
+
+ PyPreConfig preconfig;
+
+ // Audit values must be preserved when Py_Initialize()/Py_Finalize()
+ // is called multiple times.
+ Py_OpenCodeHookFunction open_code_hook;
+ void *open_code_userdata;
+ _Py_AuditHookEntry *audit_hook_head;
+
+ struct _Py_unicode_runtime_ids unicode_ids;
+
+ /* All the objects that are shared by the runtime's interpreters. */
+ struct _Py_global_objects global_objects;
+
+ /* The following fields are here to avoid allocation during init.
+ The data is exposed through _PyRuntimeState pointer fields.
+ These fields should not be accessed directly outside of init.
+
+ All other _PyRuntimeState pointer fields are populated when
+ needed and default to NULL.
+
+ For now there are some exceptions to that rule, which require
+ allocation during init. These will be addressed on a case-by-case
+ basis. Most notably, we don't pre-allocated the several mutex
+ (PyThread_type_lock) fields, because on Windows we only ever get
+ a pointer type.
+ */
+
+ /* PyInterpreterState.interpreters.main */
+ PyInterpreterState _main_interpreter;
+} _PyRuntimeState;
+
+
+/* other API */
+
+PyAPI_DATA(_PyRuntimeState) _PyRuntime;
+
+PyAPI_FUNC(PyStatus) _PyRuntimeState_Init(_PyRuntimeState *runtime);
+PyAPI_FUNC(void) _PyRuntimeState_Fini(_PyRuntimeState *runtime);
+
+#ifdef HAVE_FORK
+extern PyStatus _PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime);
+#endif
+
+/* Initialize _PyRuntimeState.
+ Return NULL on success, or return an error message on failure. */
+PyAPI_FUNC(PyStatus) _PyRuntime_Initialize(void);
+
+PyAPI_FUNC(void) _PyRuntime_Finalize(void);
+
+
+static inline PyThreadState*
+_PyRuntimeState_GetFinalizing(_PyRuntimeState *runtime) {
+ return (PyThreadState*)_Py_atomic_load_relaxed(&runtime->_finalizing);
+}
+
+static inline void
+_PyRuntimeState_SetFinalizing(_PyRuntimeState *runtime, PyThreadState *tstate) {
+ _Py_atomic_store_relaxed(&runtime->_finalizing, (uintptr_t)tstate);
+}
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_RUNTIME_H */
diff --git a/include/python3.11/internal/pycore_runtime_init.h b/include/python3.11/internal/pycore_runtime_init.h
new file mode 100644
index 0000000..13eae1e
--- /dev/null
+++ b/include/python3.11/internal/pycore_runtime_init.h
@@ -0,0 +1,1256 @@
+#ifndef Py_INTERNAL_RUNTIME_INIT_H
+#define Py_INTERNAL_RUNTIME_INIT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#include "pycore_object.h"
+
+
+/* The static initializers defined here should only be used
+ in the runtime init code (in pystate.c and pylifecycle.c). */
+
+
+#define _PyRuntimeState_INIT \
+ { \
+ .gilstate = { \
+ .check_enabled = 1, \
+ /* A TSS key must be initialized with Py_tss_NEEDS_INIT \
+ in accordance with the specification. */ \
+ .autoTSSkey = Py_tss_NEEDS_INIT, \
+ }, \
+ .interpreters = { \
+ /* This prevents interpreters from getting created \
+ until _PyInterpreterState_Enable() is called. */ \
+ .next_id = -1, \
+ }, \
+ .global_objects = _Py_global_objects_INIT, \
+ ._main_interpreter = _PyInterpreterState_INIT, \
+ }
+
+#ifdef HAVE_DLOPEN
+# include <dlfcn.h>
+# if HAVE_DECL_RTLD_NOW
+# define _Py_DLOPEN_FLAGS RTLD_NOW
+# else
+# define _Py_DLOPEN_FLAGS RTLD_LAZY
+# endif
+# define DLOPENFLAGS_INIT .dlopenflags = _Py_DLOPEN_FLAGS,
+#else
+# define _Py_DLOPEN_FLAGS 0
+# define DLOPENFLAGS_INIT
+#endif
+
+#define _PyInterpreterState_INIT \
+ { \
+ ._static = 1, \
+ .id_refcount = -1, \
+ DLOPENFLAGS_INIT \
+ .ceval = { \
+ .recursion_limit = Py_DEFAULT_RECURSION_LIMIT, \
+ }, \
+ .gc = { \
+ .enabled = 1, \
+ .generations = { \
+ /* .head is set in _PyGC_InitState(). */ \
+ { .threshold = 700, }, \
+ { .threshold = 10, }, \
+ { .threshold = 10, }, \
+ }, \
+ }, \
+ ._initial_thread = _PyThreadState_INIT, \
+ }
+
+#define _PyThreadState_INIT \
+ { \
+ ._static = 1, \
+ .recursion_limit = Py_DEFAULT_RECURSION_LIMIT, \
+ .context_ver = 1, \
+ }
+
+
+// global objects
+
+#define _PyLong_DIGIT_INIT(val) \
+ { \
+ _PyVarObject_IMMORTAL_INIT(&PyLong_Type, \
+ ((val) == 0 ? 0 : ((val) > 0 ? 1 : -1))), \
+ .ob_digit = { ((val) >= 0 ? (val) : -(val)) }, \
+ }
+
+#define _PyBytes_SIMPLE_INIT(CH, LEN) \
+ { \
+ _PyVarObject_IMMORTAL_INIT(&PyBytes_Type, LEN), \
+ .ob_shash = -1, \
+ .ob_sval = { CH }, \
+ }
+#define _PyBytes_CHAR_INIT(CH) \
+ { \
+ _PyBytes_SIMPLE_INIT(CH, 1) \
+ }
+
+#define _PyUnicode_ASCII_BASE_INIT(LITERAL, ASCII) \
+ { \
+ .ob_base = _PyObject_IMMORTAL_INIT(&PyUnicode_Type), \
+ .length = sizeof(LITERAL) - 1, \
+ .hash = -1, \
+ .state = { \
+ .kind = 1, \
+ .compact = 1, \
+ .ascii = ASCII, \
+ .ready = 1, \
+ }, \
+ }
+#define _PyASCIIObject_INIT(LITERAL) \
+ { \
+ ._ascii = _PyUnicode_ASCII_BASE_INIT(LITERAL, 1), \
+ ._data = LITERAL \
+ }
+#define INIT_STR(NAME, LITERAL) \
+ ._ ## NAME = _PyASCIIObject_INIT(LITERAL)
+#define INIT_ID(NAME) \
+ ._ ## NAME = _PyASCIIObject_INIT(#NAME)
+#define _PyUnicode_LATIN1_INIT(LITERAL) \
+ { \
+ ._latin1 = { \
+ ._base = _PyUnicode_ASCII_BASE_INIT(LITERAL, 0), \
+ }, \
+ ._data = LITERAL, \
+ }
+
+/* The following is auto-generated by Tools/scripts/generate_global_objects.py. */
+#define _Py_global_objects_INIT { \
+ .singletons = { \
+ .small_ints = { \
+ _PyLong_DIGIT_INIT(-5), \
+ _PyLong_DIGIT_INIT(-4), \
+ _PyLong_DIGIT_INIT(-3), \
+ _PyLong_DIGIT_INIT(-2), \
+ _PyLong_DIGIT_INIT(-1), \
+ _PyLong_DIGIT_INIT(0), \
+ _PyLong_DIGIT_INIT(1), \
+ _PyLong_DIGIT_INIT(2), \
+ _PyLong_DIGIT_INIT(3), \
+ _PyLong_DIGIT_INIT(4), \
+ _PyLong_DIGIT_INIT(5), \
+ _PyLong_DIGIT_INIT(6), \
+ _PyLong_DIGIT_INIT(7), \
+ _PyLong_DIGIT_INIT(8), \
+ _PyLong_DIGIT_INIT(9), \
+ _PyLong_DIGIT_INIT(10), \
+ _PyLong_DIGIT_INIT(11), \
+ _PyLong_DIGIT_INIT(12), \
+ _PyLong_DIGIT_INIT(13), \
+ _PyLong_DIGIT_INIT(14), \
+ _PyLong_DIGIT_INIT(15), \
+ _PyLong_DIGIT_INIT(16), \
+ _PyLong_DIGIT_INIT(17), \
+ _PyLong_DIGIT_INIT(18), \
+ _PyLong_DIGIT_INIT(19), \
+ _PyLong_DIGIT_INIT(20), \
+ _PyLong_DIGIT_INIT(21), \
+ _PyLong_DIGIT_INIT(22), \
+ _PyLong_DIGIT_INIT(23), \
+ _PyLong_DIGIT_INIT(24), \
+ _PyLong_DIGIT_INIT(25), \
+ _PyLong_DIGIT_INIT(26), \
+ _PyLong_DIGIT_INIT(27), \
+ _PyLong_DIGIT_INIT(28), \
+ _PyLong_DIGIT_INIT(29), \
+ _PyLong_DIGIT_INIT(30), \
+ _PyLong_DIGIT_INIT(31), \
+ _PyLong_DIGIT_INIT(32), \
+ _PyLong_DIGIT_INIT(33), \
+ _PyLong_DIGIT_INIT(34), \
+ _PyLong_DIGIT_INIT(35), \
+ _PyLong_DIGIT_INIT(36), \
+ _PyLong_DIGIT_INIT(37), \
+ _PyLong_DIGIT_INIT(38), \
+ _PyLong_DIGIT_INIT(39), \
+ _PyLong_DIGIT_INIT(40), \
+ _PyLong_DIGIT_INIT(41), \
+ _PyLong_DIGIT_INIT(42), \
+ _PyLong_DIGIT_INIT(43), \
+ _PyLong_DIGIT_INIT(44), \
+ _PyLong_DIGIT_INIT(45), \
+ _PyLong_DIGIT_INIT(46), \
+ _PyLong_DIGIT_INIT(47), \
+ _PyLong_DIGIT_INIT(48), \
+ _PyLong_DIGIT_INIT(49), \
+ _PyLong_DIGIT_INIT(50), \
+ _PyLong_DIGIT_INIT(51), \
+ _PyLong_DIGIT_INIT(52), \
+ _PyLong_DIGIT_INIT(53), \
+ _PyLong_DIGIT_INIT(54), \
+ _PyLong_DIGIT_INIT(55), \
+ _PyLong_DIGIT_INIT(56), \
+ _PyLong_DIGIT_INIT(57), \
+ _PyLong_DIGIT_INIT(58), \
+ _PyLong_DIGIT_INIT(59), \
+ _PyLong_DIGIT_INIT(60), \
+ _PyLong_DIGIT_INIT(61), \
+ _PyLong_DIGIT_INIT(62), \
+ _PyLong_DIGIT_INIT(63), \
+ _PyLong_DIGIT_INIT(64), \
+ _PyLong_DIGIT_INIT(65), \
+ _PyLong_DIGIT_INIT(66), \
+ _PyLong_DIGIT_INIT(67), \
+ _PyLong_DIGIT_INIT(68), \
+ _PyLong_DIGIT_INIT(69), \
+ _PyLong_DIGIT_INIT(70), \
+ _PyLong_DIGIT_INIT(71), \
+ _PyLong_DIGIT_INIT(72), \
+ _PyLong_DIGIT_INIT(73), \
+ _PyLong_DIGIT_INIT(74), \
+ _PyLong_DIGIT_INIT(75), \
+ _PyLong_DIGIT_INIT(76), \
+ _PyLong_DIGIT_INIT(77), \
+ _PyLong_DIGIT_INIT(78), \
+ _PyLong_DIGIT_INIT(79), \
+ _PyLong_DIGIT_INIT(80), \
+ _PyLong_DIGIT_INIT(81), \
+ _PyLong_DIGIT_INIT(82), \
+ _PyLong_DIGIT_INIT(83), \
+ _PyLong_DIGIT_INIT(84), \
+ _PyLong_DIGIT_INIT(85), \
+ _PyLong_DIGIT_INIT(86), \
+ _PyLong_DIGIT_INIT(87), \
+ _PyLong_DIGIT_INIT(88), \
+ _PyLong_DIGIT_INIT(89), \
+ _PyLong_DIGIT_INIT(90), \
+ _PyLong_DIGIT_INIT(91), \
+ _PyLong_DIGIT_INIT(92), \
+ _PyLong_DIGIT_INIT(93), \
+ _PyLong_DIGIT_INIT(94), \
+ _PyLong_DIGIT_INIT(95), \
+ _PyLong_DIGIT_INIT(96), \
+ _PyLong_DIGIT_INIT(97), \
+ _PyLong_DIGIT_INIT(98), \
+ _PyLong_DIGIT_INIT(99), \
+ _PyLong_DIGIT_INIT(100), \
+ _PyLong_DIGIT_INIT(101), \
+ _PyLong_DIGIT_INIT(102), \
+ _PyLong_DIGIT_INIT(103), \
+ _PyLong_DIGIT_INIT(104), \
+ _PyLong_DIGIT_INIT(105), \
+ _PyLong_DIGIT_INIT(106), \
+ _PyLong_DIGIT_INIT(107), \
+ _PyLong_DIGIT_INIT(108), \
+ _PyLong_DIGIT_INIT(109), \
+ _PyLong_DIGIT_INIT(110), \
+ _PyLong_DIGIT_INIT(111), \
+ _PyLong_DIGIT_INIT(112), \
+ _PyLong_DIGIT_INIT(113), \
+ _PyLong_DIGIT_INIT(114), \
+ _PyLong_DIGIT_INIT(115), \
+ _PyLong_DIGIT_INIT(116), \
+ _PyLong_DIGIT_INIT(117), \
+ _PyLong_DIGIT_INIT(118), \
+ _PyLong_DIGIT_INIT(119), \
+ _PyLong_DIGIT_INIT(120), \
+ _PyLong_DIGIT_INIT(121), \
+ _PyLong_DIGIT_INIT(122), \
+ _PyLong_DIGIT_INIT(123), \
+ _PyLong_DIGIT_INIT(124), \
+ _PyLong_DIGIT_INIT(125), \
+ _PyLong_DIGIT_INIT(126), \
+ _PyLong_DIGIT_INIT(127), \
+ _PyLong_DIGIT_INIT(128), \
+ _PyLong_DIGIT_INIT(129), \
+ _PyLong_DIGIT_INIT(130), \
+ _PyLong_DIGIT_INIT(131), \
+ _PyLong_DIGIT_INIT(132), \
+ _PyLong_DIGIT_INIT(133), \
+ _PyLong_DIGIT_INIT(134), \
+ _PyLong_DIGIT_INIT(135), \
+ _PyLong_DIGIT_INIT(136), \
+ _PyLong_DIGIT_INIT(137), \
+ _PyLong_DIGIT_INIT(138), \
+ _PyLong_DIGIT_INIT(139), \
+ _PyLong_DIGIT_INIT(140), \
+ _PyLong_DIGIT_INIT(141), \
+ _PyLong_DIGIT_INIT(142), \
+ _PyLong_DIGIT_INIT(143), \
+ _PyLong_DIGIT_INIT(144), \
+ _PyLong_DIGIT_INIT(145), \
+ _PyLong_DIGIT_INIT(146), \
+ _PyLong_DIGIT_INIT(147), \
+ _PyLong_DIGIT_INIT(148), \
+ _PyLong_DIGIT_INIT(149), \
+ _PyLong_DIGIT_INIT(150), \
+ _PyLong_DIGIT_INIT(151), \
+ _PyLong_DIGIT_INIT(152), \
+ _PyLong_DIGIT_INIT(153), \
+ _PyLong_DIGIT_INIT(154), \
+ _PyLong_DIGIT_INIT(155), \
+ _PyLong_DIGIT_INIT(156), \
+ _PyLong_DIGIT_INIT(157), \
+ _PyLong_DIGIT_INIT(158), \
+ _PyLong_DIGIT_INIT(159), \
+ _PyLong_DIGIT_INIT(160), \
+ _PyLong_DIGIT_INIT(161), \
+ _PyLong_DIGIT_INIT(162), \
+ _PyLong_DIGIT_INIT(163), \
+ _PyLong_DIGIT_INIT(164), \
+ _PyLong_DIGIT_INIT(165), \
+ _PyLong_DIGIT_INIT(166), \
+ _PyLong_DIGIT_INIT(167), \
+ _PyLong_DIGIT_INIT(168), \
+ _PyLong_DIGIT_INIT(169), \
+ _PyLong_DIGIT_INIT(170), \
+ _PyLong_DIGIT_INIT(171), \
+ _PyLong_DIGIT_INIT(172), \
+ _PyLong_DIGIT_INIT(173), \
+ _PyLong_DIGIT_INIT(174), \
+ _PyLong_DIGIT_INIT(175), \
+ _PyLong_DIGIT_INIT(176), \
+ _PyLong_DIGIT_INIT(177), \
+ _PyLong_DIGIT_INIT(178), \
+ _PyLong_DIGIT_INIT(179), \
+ _PyLong_DIGIT_INIT(180), \
+ _PyLong_DIGIT_INIT(181), \
+ _PyLong_DIGIT_INIT(182), \
+ _PyLong_DIGIT_INIT(183), \
+ _PyLong_DIGIT_INIT(184), \
+ _PyLong_DIGIT_INIT(185), \
+ _PyLong_DIGIT_INIT(186), \
+ _PyLong_DIGIT_INIT(187), \
+ _PyLong_DIGIT_INIT(188), \
+ _PyLong_DIGIT_INIT(189), \
+ _PyLong_DIGIT_INIT(190), \
+ _PyLong_DIGIT_INIT(191), \
+ _PyLong_DIGIT_INIT(192), \
+ _PyLong_DIGIT_INIT(193), \
+ _PyLong_DIGIT_INIT(194), \
+ _PyLong_DIGIT_INIT(195), \
+ _PyLong_DIGIT_INIT(196), \
+ _PyLong_DIGIT_INIT(197), \
+ _PyLong_DIGIT_INIT(198), \
+ _PyLong_DIGIT_INIT(199), \
+ _PyLong_DIGIT_INIT(200), \
+ _PyLong_DIGIT_INIT(201), \
+ _PyLong_DIGIT_INIT(202), \
+ _PyLong_DIGIT_INIT(203), \
+ _PyLong_DIGIT_INIT(204), \
+ _PyLong_DIGIT_INIT(205), \
+ _PyLong_DIGIT_INIT(206), \
+ _PyLong_DIGIT_INIT(207), \
+ _PyLong_DIGIT_INIT(208), \
+ _PyLong_DIGIT_INIT(209), \
+ _PyLong_DIGIT_INIT(210), \
+ _PyLong_DIGIT_INIT(211), \
+ _PyLong_DIGIT_INIT(212), \
+ _PyLong_DIGIT_INIT(213), \
+ _PyLong_DIGIT_INIT(214), \
+ _PyLong_DIGIT_INIT(215), \
+ _PyLong_DIGIT_INIT(216), \
+ _PyLong_DIGIT_INIT(217), \
+ _PyLong_DIGIT_INIT(218), \
+ _PyLong_DIGIT_INIT(219), \
+ _PyLong_DIGIT_INIT(220), \
+ _PyLong_DIGIT_INIT(221), \
+ _PyLong_DIGIT_INIT(222), \
+ _PyLong_DIGIT_INIT(223), \
+ _PyLong_DIGIT_INIT(224), \
+ _PyLong_DIGIT_INIT(225), \
+ _PyLong_DIGIT_INIT(226), \
+ _PyLong_DIGIT_INIT(227), \
+ _PyLong_DIGIT_INIT(228), \
+ _PyLong_DIGIT_INIT(229), \
+ _PyLong_DIGIT_INIT(230), \
+ _PyLong_DIGIT_INIT(231), \
+ _PyLong_DIGIT_INIT(232), \
+ _PyLong_DIGIT_INIT(233), \
+ _PyLong_DIGIT_INIT(234), \
+ _PyLong_DIGIT_INIT(235), \
+ _PyLong_DIGIT_INIT(236), \
+ _PyLong_DIGIT_INIT(237), \
+ _PyLong_DIGIT_INIT(238), \
+ _PyLong_DIGIT_INIT(239), \
+ _PyLong_DIGIT_INIT(240), \
+ _PyLong_DIGIT_INIT(241), \
+ _PyLong_DIGIT_INIT(242), \
+ _PyLong_DIGIT_INIT(243), \
+ _PyLong_DIGIT_INIT(244), \
+ _PyLong_DIGIT_INIT(245), \
+ _PyLong_DIGIT_INIT(246), \
+ _PyLong_DIGIT_INIT(247), \
+ _PyLong_DIGIT_INIT(248), \
+ _PyLong_DIGIT_INIT(249), \
+ _PyLong_DIGIT_INIT(250), \
+ _PyLong_DIGIT_INIT(251), \
+ _PyLong_DIGIT_INIT(252), \
+ _PyLong_DIGIT_INIT(253), \
+ _PyLong_DIGIT_INIT(254), \
+ _PyLong_DIGIT_INIT(255), \
+ _PyLong_DIGIT_INIT(256), \
+ }, \
+ \
+ .bytes_empty = _PyBytes_SIMPLE_INIT(0, 0), \
+ .bytes_characters = { \
+ _PyBytes_CHAR_INIT(0), \
+ _PyBytes_CHAR_INIT(1), \
+ _PyBytes_CHAR_INIT(2), \
+ _PyBytes_CHAR_INIT(3), \
+ _PyBytes_CHAR_INIT(4), \
+ _PyBytes_CHAR_INIT(5), \
+ _PyBytes_CHAR_INIT(6), \
+ _PyBytes_CHAR_INIT(7), \
+ _PyBytes_CHAR_INIT(8), \
+ _PyBytes_CHAR_INIT(9), \
+ _PyBytes_CHAR_INIT(10), \
+ _PyBytes_CHAR_INIT(11), \
+ _PyBytes_CHAR_INIT(12), \
+ _PyBytes_CHAR_INIT(13), \
+ _PyBytes_CHAR_INIT(14), \
+ _PyBytes_CHAR_INIT(15), \
+ _PyBytes_CHAR_INIT(16), \
+ _PyBytes_CHAR_INIT(17), \
+ _PyBytes_CHAR_INIT(18), \
+ _PyBytes_CHAR_INIT(19), \
+ _PyBytes_CHAR_INIT(20), \
+ _PyBytes_CHAR_INIT(21), \
+ _PyBytes_CHAR_INIT(22), \
+ _PyBytes_CHAR_INIT(23), \
+ _PyBytes_CHAR_INIT(24), \
+ _PyBytes_CHAR_INIT(25), \
+ _PyBytes_CHAR_INIT(26), \
+ _PyBytes_CHAR_INIT(27), \
+ _PyBytes_CHAR_INIT(28), \
+ _PyBytes_CHAR_INIT(29), \
+ _PyBytes_CHAR_INIT(30), \
+ _PyBytes_CHAR_INIT(31), \
+ _PyBytes_CHAR_INIT(32), \
+ _PyBytes_CHAR_INIT(33), \
+ _PyBytes_CHAR_INIT(34), \
+ _PyBytes_CHAR_INIT(35), \
+ _PyBytes_CHAR_INIT(36), \
+ _PyBytes_CHAR_INIT(37), \
+ _PyBytes_CHAR_INIT(38), \
+ _PyBytes_CHAR_INIT(39), \
+ _PyBytes_CHAR_INIT(40), \
+ _PyBytes_CHAR_INIT(41), \
+ _PyBytes_CHAR_INIT(42), \
+ _PyBytes_CHAR_INIT(43), \
+ _PyBytes_CHAR_INIT(44), \
+ _PyBytes_CHAR_INIT(45), \
+ _PyBytes_CHAR_INIT(46), \
+ _PyBytes_CHAR_INIT(47), \
+ _PyBytes_CHAR_INIT(48), \
+ _PyBytes_CHAR_INIT(49), \
+ _PyBytes_CHAR_INIT(50), \
+ _PyBytes_CHAR_INIT(51), \
+ _PyBytes_CHAR_INIT(52), \
+ _PyBytes_CHAR_INIT(53), \
+ _PyBytes_CHAR_INIT(54), \
+ _PyBytes_CHAR_INIT(55), \
+ _PyBytes_CHAR_INIT(56), \
+ _PyBytes_CHAR_INIT(57), \
+ _PyBytes_CHAR_INIT(58), \
+ _PyBytes_CHAR_INIT(59), \
+ _PyBytes_CHAR_INIT(60), \
+ _PyBytes_CHAR_INIT(61), \
+ _PyBytes_CHAR_INIT(62), \
+ _PyBytes_CHAR_INIT(63), \
+ _PyBytes_CHAR_INIT(64), \
+ _PyBytes_CHAR_INIT(65), \
+ _PyBytes_CHAR_INIT(66), \
+ _PyBytes_CHAR_INIT(67), \
+ _PyBytes_CHAR_INIT(68), \
+ _PyBytes_CHAR_INIT(69), \
+ _PyBytes_CHAR_INIT(70), \
+ _PyBytes_CHAR_INIT(71), \
+ _PyBytes_CHAR_INIT(72), \
+ _PyBytes_CHAR_INIT(73), \
+ _PyBytes_CHAR_INIT(74), \
+ _PyBytes_CHAR_INIT(75), \
+ _PyBytes_CHAR_INIT(76), \
+ _PyBytes_CHAR_INIT(77), \
+ _PyBytes_CHAR_INIT(78), \
+ _PyBytes_CHAR_INIT(79), \
+ _PyBytes_CHAR_INIT(80), \
+ _PyBytes_CHAR_INIT(81), \
+ _PyBytes_CHAR_INIT(82), \
+ _PyBytes_CHAR_INIT(83), \
+ _PyBytes_CHAR_INIT(84), \
+ _PyBytes_CHAR_INIT(85), \
+ _PyBytes_CHAR_INIT(86), \
+ _PyBytes_CHAR_INIT(87), \
+ _PyBytes_CHAR_INIT(88), \
+ _PyBytes_CHAR_INIT(89), \
+ _PyBytes_CHAR_INIT(90), \
+ _PyBytes_CHAR_INIT(91), \
+ _PyBytes_CHAR_INIT(92), \
+ _PyBytes_CHAR_INIT(93), \
+ _PyBytes_CHAR_INIT(94), \
+ _PyBytes_CHAR_INIT(95), \
+ _PyBytes_CHAR_INIT(96), \
+ _PyBytes_CHAR_INIT(97), \
+ _PyBytes_CHAR_INIT(98), \
+ _PyBytes_CHAR_INIT(99), \
+ _PyBytes_CHAR_INIT(100), \
+ _PyBytes_CHAR_INIT(101), \
+ _PyBytes_CHAR_INIT(102), \
+ _PyBytes_CHAR_INIT(103), \
+ _PyBytes_CHAR_INIT(104), \
+ _PyBytes_CHAR_INIT(105), \
+ _PyBytes_CHAR_INIT(106), \
+ _PyBytes_CHAR_INIT(107), \
+ _PyBytes_CHAR_INIT(108), \
+ _PyBytes_CHAR_INIT(109), \
+ _PyBytes_CHAR_INIT(110), \
+ _PyBytes_CHAR_INIT(111), \
+ _PyBytes_CHAR_INIT(112), \
+ _PyBytes_CHAR_INIT(113), \
+ _PyBytes_CHAR_INIT(114), \
+ _PyBytes_CHAR_INIT(115), \
+ _PyBytes_CHAR_INIT(116), \
+ _PyBytes_CHAR_INIT(117), \
+ _PyBytes_CHAR_INIT(118), \
+ _PyBytes_CHAR_INIT(119), \
+ _PyBytes_CHAR_INIT(120), \
+ _PyBytes_CHAR_INIT(121), \
+ _PyBytes_CHAR_INIT(122), \
+ _PyBytes_CHAR_INIT(123), \
+ _PyBytes_CHAR_INIT(124), \
+ _PyBytes_CHAR_INIT(125), \
+ _PyBytes_CHAR_INIT(126), \
+ _PyBytes_CHAR_INIT(127), \
+ _PyBytes_CHAR_INIT(128), \
+ _PyBytes_CHAR_INIT(129), \
+ _PyBytes_CHAR_INIT(130), \
+ _PyBytes_CHAR_INIT(131), \
+ _PyBytes_CHAR_INIT(132), \
+ _PyBytes_CHAR_INIT(133), \
+ _PyBytes_CHAR_INIT(134), \
+ _PyBytes_CHAR_INIT(135), \
+ _PyBytes_CHAR_INIT(136), \
+ _PyBytes_CHAR_INIT(137), \
+ _PyBytes_CHAR_INIT(138), \
+ _PyBytes_CHAR_INIT(139), \
+ _PyBytes_CHAR_INIT(140), \
+ _PyBytes_CHAR_INIT(141), \
+ _PyBytes_CHAR_INIT(142), \
+ _PyBytes_CHAR_INIT(143), \
+ _PyBytes_CHAR_INIT(144), \
+ _PyBytes_CHAR_INIT(145), \
+ _PyBytes_CHAR_INIT(146), \
+ _PyBytes_CHAR_INIT(147), \
+ _PyBytes_CHAR_INIT(148), \
+ _PyBytes_CHAR_INIT(149), \
+ _PyBytes_CHAR_INIT(150), \
+ _PyBytes_CHAR_INIT(151), \
+ _PyBytes_CHAR_INIT(152), \
+ _PyBytes_CHAR_INIT(153), \
+ _PyBytes_CHAR_INIT(154), \
+ _PyBytes_CHAR_INIT(155), \
+ _PyBytes_CHAR_INIT(156), \
+ _PyBytes_CHAR_INIT(157), \
+ _PyBytes_CHAR_INIT(158), \
+ _PyBytes_CHAR_INIT(159), \
+ _PyBytes_CHAR_INIT(160), \
+ _PyBytes_CHAR_INIT(161), \
+ _PyBytes_CHAR_INIT(162), \
+ _PyBytes_CHAR_INIT(163), \
+ _PyBytes_CHAR_INIT(164), \
+ _PyBytes_CHAR_INIT(165), \
+ _PyBytes_CHAR_INIT(166), \
+ _PyBytes_CHAR_INIT(167), \
+ _PyBytes_CHAR_INIT(168), \
+ _PyBytes_CHAR_INIT(169), \
+ _PyBytes_CHAR_INIT(170), \
+ _PyBytes_CHAR_INIT(171), \
+ _PyBytes_CHAR_INIT(172), \
+ _PyBytes_CHAR_INIT(173), \
+ _PyBytes_CHAR_INIT(174), \
+ _PyBytes_CHAR_INIT(175), \
+ _PyBytes_CHAR_INIT(176), \
+ _PyBytes_CHAR_INIT(177), \
+ _PyBytes_CHAR_INIT(178), \
+ _PyBytes_CHAR_INIT(179), \
+ _PyBytes_CHAR_INIT(180), \
+ _PyBytes_CHAR_INIT(181), \
+ _PyBytes_CHAR_INIT(182), \
+ _PyBytes_CHAR_INIT(183), \
+ _PyBytes_CHAR_INIT(184), \
+ _PyBytes_CHAR_INIT(185), \
+ _PyBytes_CHAR_INIT(186), \
+ _PyBytes_CHAR_INIT(187), \
+ _PyBytes_CHAR_INIT(188), \
+ _PyBytes_CHAR_INIT(189), \
+ _PyBytes_CHAR_INIT(190), \
+ _PyBytes_CHAR_INIT(191), \
+ _PyBytes_CHAR_INIT(192), \
+ _PyBytes_CHAR_INIT(193), \
+ _PyBytes_CHAR_INIT(194), \
+ _PyBytes_CHAR_INIT(195), \
+ _PyBytes_CHAR_INIT(196), \
+ _PyBytes_CHAR_INIT(197), \
+ _PyBytes_CHAR_INIT(198), \
+ _PyBytes_CHAR_INIT(199), \
+ _PyBytes_CHAR_INIT(200), \
+ _PyBytes_CHAR_INIT(201), \
+ _PyBytes_CHAR_INIT(202), \
+ _PyBytes_CHAR_INIT(203), \
+ _PyBytes_CHAR_INIT(204), \
+ _PyBytes_CHAR_INIT(205), \
+ _PyBytes_CHAR_INIT(206), \
+ _PyBytes_CHAR_INIT(207), \
+ _PyBytes_CHAR_INIT(208), \
+ _PyBytes_CHAR_INIT(209), \
+ _PyBytes_CHAR_INIT(210), \
+ _PyBytes_CHAR_INIT(211), \
+ _PyBytes_CHAR_INIT(212), \
+ _PyBytes_CHAR_INIT(213), \
+ _PyBytes_CHAR_INIT(214), \
+ _PyBytes_CHAR_INIT(215), \
+ _PyBytes_CHAR_INIT(216), \
+ _PyBytes_CHAR_INIT(217), \
+ _PyBytes_CHAR_INIT(218), \
+ _PyBytes_CHAR_INIT(219), \
+ _PyBytes_CHAR_INIT(220), \
+ _PyBytes_CHAR_INIT(221), \
+ _PyBytes_CHAR_INIT(222), \
+ _PyBytes_CHAR_INIT(223), \
+ _PyBytes_CHAR_INIT(224), \
+ _PyBytes_CHAR_INIT(225), \
+ _PyBytes_CHAR_INIT(226), \
+ _PyBytes_CHAR_INIT(227), \
+ _PyBytes_CHAR_INIT(228), \
+ _PyBytes_CHAR_INIT(229), \
+ _PyBytes_CHAR_INIT(230), \
+ _PyBytes_CHAR_INIT(231), \
+ _PyBytes_CHAR_INIT(232), \
+ _PyBytes_CHAR_INIT(233), \
+ _PyBytes_CHAR_INIT(234), \
+ _PyBytes_CHAR_INIT(235), \
+ _PyBytes_CHAR_INIT(236), \
+ _PyBytes_CHAR_INIT(237), \
+ _PyBytes_CHAR_INIT(238), \
+ _PyBytes_CHAR_INIT(239), \
+ _PyBytes_CHAR_INIT(240), \
+ _PyBytes_CHAR_INIT(241), \
+ _PyBytes_CHAR_INIT(242), \
+ _PyBytes_CHAR_INIT(243), \
+ _PyBytes_CHAR_INIT(244), \
+ _PyBytes_CHAR_INIT(245), \
+ _PyBytes_CHAR_INIT(246), \
+ _PyBytes_CHAR_INIT(247), \
+ _PyBytes_CHAR_INIT(248), \
+ _PyBytes_CHAR_INIT(249), \
+ _PyBytes_CHAR_INIT(250), \
+ _PyBytes_CHAR_INIT(251), \
+ _PyBytes_CHAR_INIT(252), \
+ _PyBytes_CHAR_INIT(253), \
+ _PyBytes_CHAR_INIT(254), \
+ _PyBytes_CHAR_INIT(255), \
+ }, \
+ \
+ .strings = { \
+ .literals = { \
+ INIT_STR(anon_dictcomp, "<dictcomp>"), \
+ INIT_STR(anon_genexpr, "<genexpr>"), \
+ INIT_STR(anon_lambda, "<lambda>"), \
+ INIT_STR(anon_listcomp, "<listcomp>"), \
+ INIT_STR(anon_module, "<module>"), \
+ INIT_STR(anon_setcomp, "<setcomp>"), \
+ INIT_STR(anon_string, "<string>"), \
+ INIT_STR(anon_unknown, "<unknown>"), \
+ INIT_STR(close_br, "}"), \
+ INIT_STR(comma_sep, ", "), \
+ INIT_STR(dbl_close_br, "}}"), \
+ INIT_STR(dbl_open_br, "{{"), \
+ INIT_STR(dbl_percent, "%%"), \
+ INIT_STR(dot, "."), \
+ INIT_STR(dot_locals, ".<locals>"), \
+ INIT_STR(empty, ""), \
+ INIT_STR(list_err, "list index out of range"), \
+ INIT_STR(newline, "\n"), \
+ INIT_STR(open_br, "{"), \
+ INIT_STR(percent, "%"), \
+ INIT_STR(utf_8, "utf-8"), \
+ }, \
+ .identifiers = { \
+ INIT_ID(False), \
+ INIT_ID(Py_Repr), \
+ INIT_ID(TextIOWrapper), \
+ INIT_ID(True), \
+ INIT_ID(WarningMessage), \
+ INIT_ID(_), \
+ INIT_ID(__IOBase_closed), \
+ INIT_ID(__abc_tpflags__), \
+ INIT_ID(__abs__), \
+ INIT_ID(__abstractmethods__), \
+ INIT_ID(__add__), \
+ INIT_ID(__aenter__), \
+ INIT_ID(__aexit__), \
+ INIT_ID(__aiter__), \
+ INIT_ID(__all__), \
+ INIT_ID(__and__), \
+ INIT_ID(__anext__), \
+ INIT_ID(__annotations__), \
+ INIT_ID(__args__), \
+ INIT_ID(__await__), \
+ INIT_ID(__bases__), \
+ INIT_ID(__bool__), \
+ INIT_ID(__build_class__), \
+ INIT_ID(__builtins__), \
+ INIT_ID(__bytes__), \
+ INIT_ID(__call__), \
+ INIT_ID(__cantrace__), \
+ INIT_ID(__class__), \
+ INIT_ID(__class_getitem__), \
+ INIT_ID(__classcell__), \
+ INIT_ID(__complex__), \
+ INIT_ID(__contains__), \
+ INIT_ID(__copy__), \
+ INIT_ID(__del__), \
+ INIT_ID(__delattr__), \
+ INIT_ID(__delete__), \
+ INIT_ID(__delitem__), \
+ INIT_ID(__dict__), \
+ INIT_ID(__dir__), \
+ INIT_ID(__divmod__), \
+ INIT_ID(__doc__), \
+ INIT_ID(__enter__), \
+ INIT_ID(__eq__), \
+ INIT_ID(__exit__), \
+ INIT_ID(__file__), \
+ INIT_ID(__float__), \
+ INIT_ID(__floordiv__), \
+ INIT_ID(__format__), \
+ INIT_ID(__fspath__), \
+ INIT_ID(__ge__), \
+ INIT_ID(__get__), \
+ INIT_ID(__getattr__), \
+ INIT_ID(__getattribute__), \
+ INIT_ID(__getinitargs__), \
+ INIT_ID(__getitem__), \
+ INIT_ID(__getnewargs__), \
+ INIT_ID(__getnewargs_ex__), \
+ INIT_ID(__getstate__), \
+ INIT_ID(__gt__), \
+ INIT_ID(__hash__), \
+ INIT_ID(__iadd__), \
+ INIT_ID(__iand__), \
+ INIT_ID(__ifloordiv__), \
+ INIT_ID(__ilshift__), \
+ INIT_ID(__imatmul__), \
+ INIT_ID(__imod__), \
+ INIT_ID(__import__), \
+ INIT_ID(__imul__), \
+ INIT_ID(__index__), \
+ INIT_ID(__init__), \
+ INIT_ID(__init_subclass__), \
+ INIT_ID(__instancecheck__), \
+ INIT_ID(__int__), \
+ INIT_ID(__invert__), \
+ INIT_ID(__ior__), \
+ INIT_ID(__ipow__), \
+ INIT_ID(__irshift__), \
+ INIT_ID(__isabstractmethod__), \
+ INIT_ID(__isub__), \
+ INIT_ID(__iter__), \
+ INIT_ID(__itruediv__), \
+ INIT_ID(__ixor__), \
+ INIT_ID(__le__), \
+ INIT_ID(__len__), \
+ INIT_ID(__length_hint__), \
+ INIT_ID(__lltrace__), \
+ INIT_ID(__loader__), \
+ INIT_ID(__lshift__), \
+ INIT_ID(__lt__), \
+ INIT_ID(__main__), \
+ INIT_ID(__matmul__), \
+ INIT_ID(__missing__), \
+ INIT_ID(__mod__), \
+ INIT_ID(__module__), \
+ INIT_ID(__mro_entries__), \
+ INIT_ID(__mul__), \
+ INIT_ID(__name__), \
+ INIT_ID(__ne__), \
+ INIT_ID(__neg__), \
+ INIT_ID(__new__), \
+ INIT_ID(__newobj__), \
+ INIT_ID(__newobj_ex__), \
+ INIT_ID(__next__), \
+ INIT_ID(__notes__), \
+ INIT_ID(__or__), \
+ INIT_ID(__orig_class__), \
+ INIT_ID(__origin__), \
+ INIT_ID(__package__), \
+ INIT_ID(__parameters__), \
+ INIT_ID(__path__), \
+ INIT_ID(__pos__), \
+ INIT_ID(__pow__), \
+ INIT_ID(__prepare__), \
+ INIT_ID(__qualname__), \
+ INIT_ID(__radd__), \
+ INIT_ID(__rand__), \
+ INIT_ID(__rdivmod__), \
+ INIT_ID(__reduce__), \
+ INIT_ID(__reduce_ex__), \
+ INIT_ID(__repr__), \
+ INIT_ID(__reversed__), \
+ INIT_ID(__rfloordiv__), \
+ INIT_ID(__rlshift__), \
+ INIT_ID(__rmatmul__), \
+ INIT_ID(__rmod__), \
+ INIT_ID(__rmul__), \
+ INIT_ID(__ror__), \
+ INIT_ID(__round__), \
+ INIT_ID(__rpow__), \
+ INIT_ID(__rrshift__), \
+ INIT_ID(__rshift__), \
+ INIT_ID(__rsub__), \
+ INIT_ID(__rtruediv__), \
+ INIT_ID(__rxor__), \
+ INIT_ID(__set__), \
+ INIT_ID(__set_name__), \
+ INIT_ID(__setattr__), \
+ INIT_ID(__setitem__), \
+ INIT_ID(__setstate__), \
+ INIT_ID(__sizeof__), \
+ INIT_ID(__slotnames__), \
+ INIT_ID(__slots__), \
+ INIT_ID(__spec__), \
+ INIT_ID(__str__), \
+ INIT_ID(__sub__), \
+ INIT_ID(__subclasscheck__), \
+ INIT_ID(__subclasshook__), \
+ INIT_ID(__truediv__), \
+ INIT_ID(__trunc__), \
+ INIT_ID(__typing_is_unpacked_typevartuple__), \
+ INIT_ID(__typing_prepare_subst__), \
+ INIT_ID(__typing_subst__), \
+ INIT_ID(__typing_unpacked_tuple_args__), \
+ INIT_ID(__warningregistry__), \
+ INIT_ID(__weakref__), \
+ INIT_ID(__xor__), \
+ INIT_ID(_abc_impl), \
+ INIT_ID(_annotation), \
+ INIT_ID(_blksize), \
+ INIT_ID(_bootstrap), \
+ INIT_ID(_dealloc_warn), \
+ INIT_ID(_finalizing), \
+ INIT_ID(_find_and_load), \
+ INIT_ID(_fix_up_module), \
+ INIT_ID(_get_sourcefile), \
+ INIT_ID(_handle_fromlist), \
+ INIT_ID(_initializing), \
+ INIT_ID(_is_text_encoding), \
+ INIT_ID(_lock_unlock_module), \
+ INIT_ID(_showwarnmsg), \
+ INIT_ID(_shutdown), \
+ INIT_ID(_slotnames), \
+ INIT_ID(_strptime_time), \
+ INIT_ID(_uninitialized_submodules), \
+ INIT_ID(_warn_unawaited_coroutine), \
+ INIT_ID(_xoptions), \
+ INIT_ID(add), \
+ INIT_ID(append), \
+ INIT_ID(big), \
+ INIT_ID(buffer), \
+ INIT_ID(builtins), \
+ INIT_ID(c_call), \
+ INIT_ID(c_exception), \
+ INIT_ID(c_return), \
+ INIT_ID(call), \
+ INIT_ID(clear), \
+ INIT_ID(close), \
+ INIT_ID(closed), \
+ INIT_ID(code), \
+ INIT_ID(copy), \
+ INIT_ID(copyreg), \
+ INIT_ID(decode), \
+ INIT_ID(default), \
+ INIT_ID(defaultaction), \
+ INIT_ID(dictcomp), \
+ INIT_ID(difference_update), \
+ INIT_ID(dispatch_table), \
+ INIT_ID(displayhook), \
+ INIT_ID(enable), \
+ INIT_ID(encode), \
+ INIT_ID(encoding), \
+ INIT_ID(end_lineno), \
+ INIT_ID(end_offset), \
+ INIT_ID(errors), \
+ INIT_ID(excepthook), \
+ INIT_ID(exception), \
+ INIT_ID(extend), \
+ INIT_ID(filename), \
+ INIT_ID(fileno), \
+ INIT_ID(fillvalue), \
+ INIT_ID(filters), \
+ INIT_ID(find_class), \
+ INIT_ID(flush), \
+ INIT_ID(genexpr), \
+ INIT_ID(get), \
+ INIT_ID(get_source), \
+ INIT_ID(getattr), \
+ INIT_ID(getstate), \
+ INIT_ID(ignore), \
+ INIT_ID(importlib), \
+ INIT_ID(inf), \
+ INIT_ID(intersection), \
+ INIT_ID(isatty), \
+ INIT_ID(isinstance), \
+ INIT_ID(items), \
+ INIT_ID(iter), \
+ INIT_ID(join), \
+ INIT_ID(keys), \
+ INIT_ID(lambda), \
+ INIT_ID(last_traceback), \
+ INIT_ID(last_type), \
+ INIT_ID(last_value), \
+ INIT_ID(latin1), \
+ INIT_ID(len), \
+ INIT_ID(line), \
+ INIT_ID(lineno), \
+ INIT_ID(listcomp), \
+ INIT_ID(little), \
+ INIT_ID(locale), \
+ INIT_ID(match), \
+ INIT_ID(metaclass), \
+ INIT_ID(mode), \
+ INIT_ID(modules), \
+ INIT_ID(mro), \
+ INIT_ID(msg), \
+ INIT_ID(n_fields), \
+ INIT_ID(n_sequence_fields), \
+ INIT_ID(n_unnamed_fields), \
+ INIT_ID(name), \
+ INIT_ID(newlines), \
+ INIT_ID(next), \
+ INIT_ID(obj), \
+ INIT_ID(offset), \
+ INIT_ID(onceregistry), \
+ INIT_ID(opcode), \
+ INIT_ID(open), \
+ INIT_ID(parent), \
+ INIT_ID(partial), \
+ INIT_ID(path), \
+ INIT_ID(peek), \
+ INIT_ID(persistent_id), \
+ INIT_ID(persistent_load), \
+ INIT_ID(print_file_and_line), \
+ INIT_ID(ps1), \
+ INIT_ID(ps2), \
+ INIT_ID(raw), \
+ INIT_ID(read), \
+ INIT_ID(read1), \
+ INIT_ID(readable), \
+ INIT_ID(readall), \
+ INIT_ID(readinto), \
+ INIT_ID(readinto1), \
+ INIT_ID(readline), \
+ INIT_ID(reducer_override), \
+ INIT_ID(reload), \
+ INIT_ID(replace), \
+ INIT_ID(reset), \
+ INIT_ID(return), \
+ INIT_ID(reversed), \
+ INIT_ID(seek), \
+ INIT_ID(seekable), \
+ INIT_ID(send), \
+ INIT_ID(setcomp), \
+ INIT_ID(setstate), \
+ INIT_ID(sort), \
+ INIT_ID(stderr), \
+ INIT_ID(stdin), \
+ INIT_ID(stdout), \
+ INIT_ID(strict), \
+ INIT_ID(symmetric_difference_update), \
+ INIT_ID(tell), \
+ INIT_ID(text), \
+ INIT_ID(threading), \
+ INIT_ID(throw), \
+ INIT_ID(top), \
+ INIT_ID(truncate), \
+ INIT_ID(unraisablehook), \
+ INIT_ID(values), \
+ INIT_ID(version), \
+ INIT_ID(warnings), \
+ INIT_ID(warnoptions), \
+ INIT_ID(writable), \
+ INIT_ID(write), \
+ INIT_ID(zipimporter), \
+ }, \
+ .ascii = { \
+ _PyASCIIObject_INIT("\x00"), \
+ _PyASCIIObject_INIT("\x01"), \
+ _PyASCIIObject_INIT("\x02"), \
+ _PyASCIIObject_INIT("\x03"), \
+ _PyASCIIObject_INIT("\x04"), \
+ _PyASCIIObject_INIT("\x05"), \
+ _PyASCIIObject_INIT("\x06"), \
+ _PyASCIIObject_INIT("\x07"), \
+ _PyASCIIObject_INIT("\x08"), \
+ _PyASCIIObject_INIT("\x09"), \
+ _PyASCIIObject_INIT("\x0a"), \
+ _PyASCIIObject_INIT("\x0b"), \
+ _PyASCIIObject_INIT("\x0c"), \
+ _PyASCIIObject_INIT("\x0d"), \
+ _PyASCIIObject_INIT("\x0e"), \
+ _PyASCIIObject_INIT("\x0f"), \
+ _PyASCIIObject_INIT("\x10"), \
+ _PyASCIIObject_INIT("\x11"), \
+ _PyASCIIObject_INIT("\x12"), \
+ _PyASCIIObject_INIT("\x13"), \
+ _PyASCIIObject_INIT("\x14"), \
+ _PyASCIIObject_INIT("\x15"), \
+ _PyASCIIObject_INIT("\x16"), \
+ _PyASCIIObject_INIT("\x17"), \
+ _PyASCIIObject_INIT("\x18"), \
+ _PyASCIIObject_INIT("\x19"), \
+ _PyASCIIObject_INIT("\x1a"), \
+ _PyASCIIObject_INIT("\x1b"), \
+ _PyASCIIObject_INIT("\x1c"), \
+ _PyASCIIObject_INIT("\x1d"), \
+ _PyASCIIObject_INIT("\x1e"), \
+ _PyASCIIObject_INIT("\x1f"), \
+ _PyASCIIObject_INIT("\x20"), \
+ _PyASCIIObject_INIT("\x21"), \
+ _PyASCIIObject_INIT("\x22"), \
+ _PyASCIIObject_INIT("\x23"), \
+ _PyASCIIObject_INIT("\x24"), \
+ _PyASCIIObject_INIT("\x25"), \
+ _PyASCIIObject_INIT("\x26"), \
+ _PyASCIIObject_INIT("\x27"), \
+ _PyASCIIObject_INIT("\x28"), \
+ _PyASCIIObject_INIT("\x29"), \
+ _PyASCIIObject_INIT("\x2a"), \
+ _PyASCIIObject_INIT("\x2b"), \
+ _PyASCIIObject_INIT("\x2c"), \
+ _PyASCIIObject_INIT("\x2d"), \
+ _PyASCIIObject_INIT("\x2e"), \
+ _PyASCIIObject_INIT("\x2f"), \
+ _PyASCIIObject_INIT("\x30"), \
+ _PyASCIIObject_INIT("\x31"), \
+ _PyASCIIObject_INIT("\x32"), \
+ _PyASCIIObject_INIT("\x33"), \
+ _PyASCIIObject_INIT("\x34"), \
+ _PyASCIIObject_INIT("\x35"), \
+ _PyASCIIObject_INIT("\x36"), \
+ _PyASCIIObject_INIT("\x37"), \
+ _PyASCIIObject_INIT("\x38"), \
+ _PyASCIIObject_INIT("\x39"), \
+ _PyASCIIObject_INIT("\x3a"), \
+ _PyASCIIObject_INIT("\x3b"), \
+ _PyASCIIObject_INIT("\x3c"), \
+ _PyASCIIObject_INIT("\x3d"), \
+ _PyASCIIObject_INIT("\x3e"), \
+ _PyASCIIObject_INIT("\x3f"), \
+ _PyASCIIObject_INIT("\x40"), \
+ _PyASCIIObject_INIT("\x41"), \
+ _PyASCIIObject_INIT("\x42"), \
+ _PyASCIIObject_INIT("\x43"), \
+ _PyASCIIObject_INIT("\x44"), \
+ _PyASCIIObject_INIT("\x45"), \
+ _PyASCIIObject_INIT("\x46"), \
+ _PyASCIIObject_INIT("\x47"), \
+ _PyASCIIObject_INIT("\x48"), \
+ _PyASCIIObject_INIT("\x49"), \
+ _PyASCIIObject_INIT("\x4a"), \
+ _PyASCIIObject_INIT("\x4b"), \
+ _PyASCIIObject_INIT("\x4c"), \
+ _PyASCIIObject_INIT("\x4d"), \
+ _PyASCIIObject_INIT("\x4e"), \
+ _PyASCIIObject_INIT("\x4f"), \
+ _PyASCIIObject_INIT("\x50"), \
+ _PyASCIIObject_INIT("\x51"), \
+ _PyASCIIObject_INIT("\x52"), \
+ _PyASCIIObject_INIT("\x53"), \
+ _PyASCIIObject_INIT("\x54"), \
+ _PyASCIIObject_INIT("\x55"), \
+ _PyASCIIObject_INIT("\x56"), \
+ _PyASCIIObject_INIT("\x57"), \
+ _PyASCIIObject_INIT("\x58"), \
+ _PyASCIIObject_INIT("\x59"), \
+ _PyASCIIObject_INIT("\x5a"), \
+ _PyASCIIObject_INIT("\x5b"), \
+ _PyASCIIObject_INIT("\x5c"), \
+ _PyASCIIObject_INIT("\x5d"), \
+ _PyASCIIObject_INIT("\x5e"), \
+ _PyASCIIObject_INIT("\x5f"), \
+ _PyASCIIObject_INIT("\x60"), \
+ _PyASCIIObject_INIT("\x61"), \
+ _PyASCIIObject_INIT("\x62"), \
+ _PyASCIIObject_INIT("\x63"), \
+ _PyASCIIObject_INIT("\x64"), \
+ _PyASCIIObject_INIT("\x65"), \
+ _PyASCIIObject_INIT("\x66"), \
+ _PyASCIIObject_INIT("\x67"), \
+ _PyASCIIObject_INIT("\x68"), \
+ _PyASCIIObject_INIT("\x69"), \
+ _PyASCIIObject_INIT("\x6a"), \
+ _PyASCIIObject_INIT("\x6b"), \
+ _PyASCIIObject_INIT("\x6c"), \
+ _PyASCIIObject_INIT("\x6d"), \
+ _PyASCIIObject_INIT("\x6e"), \
+ _PyASCIIObject_INIT("\x6f"), \
+ _PyASCIIObject_INIT("\x70"), \
+ _PyASCIIObject_INIT("\x71"), \
+ _PyASCIIObject_INIT("\x72"), \
+ _PyASCIIObject_INIT("\x73"), \
+ _PyASCIIObject_INIT("\x74"), \
+ _PyASCIIObject_INIT("\x75"), \
+ _PyASCIIObject_INIT("\x76"), \
+ _PyASCIIObject_INIT("\x77"), \
+ _PyASCIIObject_INIT("\x78"), \
+ _PyASCIIObject_INIT("\x79"), \
+ _PyASCIIObject_INIT("\x7a"), \
+ _PyASCIIObject_INIT("\x7b"), \
+ _PyASCIIObject_INIT("\x7c"), \
+ _PyASCIIObject_INIT("\x7d"), \
+ _PyASCIIObject_INIT("\x7e"), \
+ _PyASCIIObject_INIT("\x7f"), \
+ }, \
+ .latin1 = { \
+ _PyUnicode_LATIN1_INIT("\x80"), \
+ _PyUnicode_LATIN1_INIT("\x81"), \
+ _PyUnicode_LATIN1_INIT("\x82"), \
+ _PyUnicode_LATIN1_INIT("\x83"), \
+ _PyUnicode_LATIN1_INIT("\x84"), \
+ _PyUnicode_LATIN1_INIT("\x85"), \
+ _PyUnicode_LATIN1_INIT("\x86"), \
+ _PyUnicode_LATIN1_INIT("\x87"), \
+ _PyUnicode_LATIN1_INIT("\x88"), \
+ _PyUnicode_LATIN1_INIT("\x89"), \
+ _PyUnicode_LATIN1_INIT("\x8a"), \
+ _PyUnicode_LATIN1_INIT("\x8b"), \
+ _PyUnicode_LATIN1_INIT("\x8c"), \
+ _PyUnicode_LATIN1_INIT("\x8d"), \
+ _PyUnicode_LATIN1_INIT("\x8e"), \
+ _PyUnicode_LATIN1_INIT("\x8f"), \
+ _PyUnicode_LATIN1_INIT("\x90"), \
+ _PyUnicode_LATIN1_INIT("\x91"), \
+ _PyUnicode_LATIN1_INIT("\x92"), \
+ _PyUnicode_LATIN1_INIT("\x93"), \
+ _PyUnicode_LATIN1_INIT("\x94"), \
+ _PyUnicode_LATIN1_INIT("\x95"), \
+ _PyUnicode_LATIN1_INIT("\x96"), \
+ _PyUnicode_LATIN1_INIT("\x97"), \
+ _PyUnicode_LATIN1_INIT("\x98"), \
+ _PyUnicode_LATIN1_INIT("\x99"), \
+ _PyUnicode_LATIN1_INIT("\x9a"), \
+ _PyUnicode_LATIN1_INIT("\x9b"), \
+ _PyUnicode_LATIN1_INIT("\x9c"), \
+ _PyUnicode_LATIN1_INIT("\x9d"), \
+ _PyUnicode_LATIN1_INIT("\x9e"), \
+ _PyUnicode_LATIN1_INIT("\x9f"), \
+ _PyUnicode_LATIN1_INIT("\xa0"), \
+ _PyUnicode_LATIN1_INIT("\xa1"), \
+ _PyUnicode_LATIN1_INIT("\xa2"), \
+ _PyUnicode_LATIN1_INIT("\xa3"), \
+ _PyUnicode_LATIN1_INIT("\xa4"), \
+ _PyUnicode_LATIN1_INIT("\xa5"), \
+ _PyUnicode_LATIN1_INIT("\xa6"), \
+ _PyUnicode_LATIN1_INIT("\xa7"), \
+ _PyUnicode_LATIN1_INIT("\xa8"), \
+ _PyUnicode_LATIN1_INIT("\xa9"), \
+ _PyUnicode_LATIN1_INIT("\xaa"), \
+ _PyUnicode_LATIN1_INIT("\xab"), \
+ _PyUnicode_LATIN1_INIT("\xac"), \
+ _PyUnicode_LATIN1_INIT("\xad"), \
+ _PyUnicode_LATIN1_INIT("\xae"), \
+ _PyUnicode_LATIN1_INIT("\xaf"), \
+ _PyUnicode_LATIN1_INIT("\xb0"), \
+ _PyUnicode_LATIN1_INIT("\xb1"), \
+ _PyUnicode_LATIN1_INIT("\xb2"), \
+ _PyUnicode_LATIN1_INIT("\xb3"), \
+ _PyUnicode_LATIN1_INIT("\xb4"), \
+ _PyUnicode_LATIN1_INIT("\xb5"), \
+ _PyUnicode_LATIN1_INIT("\xb6"), \
+ _PyUnicode_LATIN1_INIT("\xb7"), \
+ _PyUnicode_LATIN1_INIT("\xb8"), \
+ _PyUnicode_LATIN1_INIT("\xb9"), \
+ _PyUnicode_LATIN1_INIT("\xba"), \
+ _PyUnicode_LATIN1_INIT("\xbb"), \
+ _PyUnicode_LATIN1_INIT("\xbc"), \
+ _PyUnicode_LATIN1_INIT("\xbd"), \
+ _PyUnicode_LATIN1_INIT("\xbe"), \
+ _PyUnicode_LATIN1_INIT("\xbf"), \
+ _PyUnicode_LATIN1_INIT("\xc0"), \
+ _PyUnicode_LATIN1_INIT("\xc1"), \
+ _PyUnicode_LATIN1_INIT("\xc2"), \
+ _PyUnicode_LATIN1_INIT("\xc3"), \
+ _PyUnicode_LATIN1_INIT("\xc4"), \
+ _PyUnicode_LATIN1_INIT("\xc5"), \
+ _PyUnicode_LATIN1_INIT("\xc6"), \
+ _PyUnicode_LATIN1_INIT("\xc7"), \
+ _PyUnicode_LATIN1_INIT("\xc8"), \
+ _PyUnicode_LATIN1_INIT("\xc9"), \
+ _PyUnicode_LATIN1_INIT("\xca"), \
+ _PyUnicode_LATIN1_INIT("\xcb"), \
+ _PyUnicode_LATIN1_INIT("\xcc"), \
+ _PyUnicode_LATIN1_INIT("\xcd"), \
+ _PyUnicode_LATIN1_INIT("\xce"), \
+ _PyUnicode_LATIN1_INIT("\xcf"), \
+ _PyUnicode_LATIN1_INIT("\xd0"), \
+ _PyUnicode_LATIN1_INIT("\xd1"), \
+ _PyUnicode_LATIN1_INIT("\xd2"), \
+ _PyUnicode_LATIN1_INIT("\xd3"), \
+ _PyUnicode_LATIN1_INIT("\xd4"), \
+ _PyUnicode_LATIN1_INIT("\xd5"), \
+ _PyUnicode_LATIN1_INIT("\xd6"), \
+ _PyUnicode_LATIN1_INIT("\xd7"), \
+ _PyUnicode_LATIN1_INIT("\xd8"), \
+ _PyUnicode_LATIN1_INIT("\xd9"), \
+ _PyUnicode_LATIN1_INIT("\xda"), \
+ _PyUnicode_LATIN1_INIT("\xdb"), \
+ _PyUnicode_LATIN1_INIT("\xdc"), \
+ _PyUnicode_LATIN1_INIT("\xdd"), \
+ _PyUnicode_LATIN1_INIT("\xde"), \
+ _PyUnicode_LATIN1_INIT("\xdf"), \
+ _PyUnicode_LATIN1_INIT("\xe0"), \
+ _PyUnicode_LATIN1_INIT("\xe1"), \
+ _PyUnicode_LATIN1_INIT("\xe2"), \
+ _PyUnicode_LATIN1_INIT("\xe3"), \
+ _PyUnicode_LATIN1_INIT("\xe4"), \
+ _PyUnicode_LATIN1_INIT("\xe5"), \
+ _PyUnicode_LATIN1_INIT("\xe6"), \
+ _PyUnicode_LATIN1_INIT("\xe7"), \
+ _PyUnicode_LATIN1_INIT("\xe8"), \
+ _PyUnicode_LATIN1_INIT("\xe9"), \
+ _PyUnicode_LATIN1_INIT("\xea"), \
+ _PyUnicode_LATIN1_INIT("\xeb"), \
+ _PyUnicode_LATIN1_INIT("\xec"), \
+ _PyUnicode_LATIN1_INIT("\xed"), \
+ _PyUnicode_LATIN1_INIT("\xee"), \
+ _PyUnicode_LATIN1_INIT("\xef"), \
+ _PyUnicode_LATIN1_INIT("\xf0"), \
+ _PyUnicode_LATIN1_INIT("\xf1"), \
+ _PyUnicode_LATIN1_INIT("\xf2"), \
+ _PyUnicode_LATIN1_INIT("\xf3"), \
+ _PyUnicode_LATIN1_INIT("\xf4"), \
+ _PyUnicode_LATIN1_INIT("\xf5"), \
+ _PyUnicode_LATIN1_INIT("\xf6"), \
+ _PyUnicode_LATIN1_INIT("\xf7"), \
+ _PyUnicode_LATIN1_INIT("\xf8"), \
+ _PyUnicode_LATIN1_INIT("\xf9"), \
+ _PyUnicode_LATIN1_INIT("\xfa"), \
+ _PyUnicode_LATIN1_INIT("\xfb"), \
+ _PyUnicode_LATIN1_INIT("\xfc"), \
+ _PyUnicode_LATIN1_INIT("\xfd"), \
+ _PyUnicode_LATIN1_INIT("\xfe"), \
+ _PyUnicode_LATIN1_INIT("\xff"), \
+ }, \
+ }, \
+ \
+ .tuple_empty = { \
+ .ob_base = _PyVarObject_IMMORTAL_INIT(&PyTuple_Type, 0) \
+ }, \
+ }, \
+}
+/* End auto-generated code */
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_RUNTIME_INIT_H */
diff --git a/include/python3.11/internal/pycore_signal.h b/include/python3.11/internal/pycore_signal.h
new file mode 100644
index 0000000..b921dd1
--- /dev/null
+++ b/include/python3.11/internal/pycore_signal.h
@@ -0,0 +1,35 @@
+// Define Py_NSIG constant for signal handling.
+
+#ifndef Py_INTERNAL_SIGNAL_H
+#define Py_INTERNAL_SIGNAL_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#include <signal.h> // NSIG
+
+#ifdef _SIG_MAXSIG
+ // gh-91145: On FreeBSD, <signal.h> defines NSIG as 32: it doesn't include
+ // realtime signals: [SIGRTMIN,SIGRTMAX]. Use _SIG_MAXSIG instead. For
+ // example on x86-64 FreeBSD 13, SIGRTMAX is 126 and _SIG_MAXSIG is 128.
+# define Py_NSIG _SIG_MAXSIG
+#elif defined(NSIG)
+# define Py_NSIG NSIG
+#elif defined(_NSIG)
+# define Py_NSIG _NSIG // BSD/SysV
+#elif defined(_SIGMAX)
+# define Py_NSIG (_SIGMAX + 1) // QNX
+#elif defined(SIGMAX)
+# define Py_NSIG (SIGMAX + 1) // djgpp
+#else
+# define Py_NSIG 64 // Use a reasonable default value
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif // !Py_INTERNAL_SIGNAL_H
diff --git a/include/python3.11/internal/pycore_sliceobject.h b/include/python3.11/internal/pycore_sliceobject.h
new file mode 100644
index 0000000..e81834c
--- /dev/null
+++ b/include/python3.11/internal/pycore_sliceobject.h
@@ -0,0 +1,20 @@
+#ifndef Py_INTERNAL_SLICEOBJECT_H
+#define Py_INTERNAL_SLICEOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+
+/* runtime lifecycle */
+
+extern void _PySlice_Fini(PyInterpreterState *);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_SLICEOBJECT_H */
diff --git a/include/python3.11/internal/pycore_strhex.h b/include/python3.11/internal/pycore_strhex.h
new file mode 100644
index 0000000..f427b4d
--- /dev/null
+++ b/include/python3.11/internal/pycore_strhex.h
@@ -0,0 +1,36 @@
+#ifndef Py_INTERNAL_STRHEX_H
+#define Py_INTERNAL_STRHEX_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+// Returns a str() containing the hex representation of argbuf.
+PyAPI_FUNC(PyObject*) _Py_strhex(const
+ char* argbuf,
+ const Py_ssize_t arglen);
+
+// Returns a bytes() containing the ASCII hex representation of argbuf.
+PyAPI_FUNC(PyObject*) _Py_strhex_bytes(
+ const char* argbuf,
+ const Py_ssize_t arglen);
+
+// These variants include support for a separator between every N bytes:
+PyAPI_FUNC(PyObject*) _Py_strhex_with_sep(
+ const char* argbuf,
+ const Py_ssize_t arglen,
+ PyObject* sep,
+ const int bytes_per_group);
+PyAPI_FUNC(PyObject*) _Py_strhex_bytes_with_sep(
+ const char* argbuf,
+ const Py_ssize_t arglen,
+ PyObject* sep,
+ const int bytes_per_group);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_STRHEX_H */
diff --git a/include/python3.11/internal/pycore_structseq.h b/include/python3.11/internal/pycore_structseq.h
new file mode 100644
index 0000000..0199c79
--- /dev/null
+++ b/include/python3.11/internal/pycore_structseq.h
@@ -0,0 +1,28 @@
+#ifndef Py_INTERNAL_STRUCTSEQ_H
+#define Py_INTERNAL_STRUCTSEQ_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+
+/* other API */
+
+PyAPI_FUNC(PyTypeObject *) _PyStructSequence_NewType(
+ PyStructSequence_Desc *desc,
+ unsigned long tp_flags);
+
+PyAPI_FUNC(int) _PyStructSequence_InitType(
+ PyTypeObject *type,
+ PyStructSequence_Desc *desc,
+ unsigned long tp_flags);
+
+extern void _PyStructSequence_FiniType(PyTypeObject *type);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_STRUCTSEQ_H */
diff --git a/include/python3.11/internal/pycore_symtable.h b/include/python3.11/internal/pycore_symtable.h
new file mode 100644
index 0000000..28935f4
--- /dev/null
+++ b/include/python3.11/internal/pycore_symtable.h
@@ -0,0 +1,134 @@
+#ifndef Py_INTERNAL_SYMTABLE_H
+#define Py_INTERNAL_SYMTABLE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+struct _mod; // Type defined in pycore_ast.h
+
+typedef enum _block_type { FunctionBlock, ClassBlock, ModuleBlock, AnnotationBlock }
+ _Py_block_ty;
+
+typedef enum _comprehension_type {
+ NoComprehension = 0,
+ ListComprehension = 1,
+ DictComprehension = 2,
+ SetComprehension = 3,
+ GeneratorExpression = 4 } _Py_comprehension_ty;
+
+struct _symtable_entry;
+
+struct symtable {
+ PyObject *st_filename; /* name of file being compiled,
+ decoded from the filesystem encoding */
+ struct _symtable_entry *st_cur; /* current symbol table entry */
+ struct _symtable_entry *st_top; /* symbol table entry for module */
+ PyObject *st_blocks; /* dict: map AST node addresses
+ * to symbol table entries */
+ PyObject *st_stack; /* list: stack of namespace info */
+ PyObject *st_global; /* borrowed ref to st_top->ste_symbols */
+ int st_nblocks; /* number of blocks used. kept for
+ consistency with the corresponding
+ compiler structure */
+ PyObject *st_private; /* name of current class or NULL */
+ PyFutureFeatures *st_future; /* module's future features that affect
+ the symbol table */
+ int recursion_depth; /* current recursion depth */
+ int recursion_limit; /* recursion limit */
+};
+
+typedef struct _symtable_entry {
+ PyObject_HEAD
+ PyObject *ste_id; /* int: key in ste_table->st_blocks */
+ PyObject *ste_symbols; /* dict: variable names to flags */
+ PyObject *ste_name; /* string: name of current block */
+ PyObject *ste_varnames; /* list of function parameters */
+ PyObject *ste_children; /* list of child blocks */
+ PyObject *ste_directives;/* locations of global and nonlocal statements */
+ _Py_block_ty ste_type; /* module, class or function */
+ int ste_nested; /* true if block is nested */
+ unsigned ste_free : 1; /* true if block has free variables */
+ unsigned ste_child_free : 1; /* true if a child block has free vars,
+ including free refs to globals */
+ unsigned ste_generator : 1; /* true if namespace is a generator */
+ unsigned ste_coroutine : 1; /* true if namespace is a coroutine */
+ _Py_comprehension_ty ste_comprehension; /* Kind of comprehension (if any) */
+ unsigned ste_varargs : 1; /* true if block has varargs */
+ unsigned ste_varkeywords : 1; /* true if block has varkeywords */
+ unsigned ste_returns_value : 1; /* true if namespace uses return with
+ an argument */
+ unsigned ste_needs_class_closure : 1; /* for class scopes, true if a
+ closure over __class__
+ should be created */
+ unsigned ste_comp_iter_target : 1; /* true if visiting comprehension target */
+ int ste_comp_iter_expr; /* non-zero if visiting a comprehension range expression */
+ int ste_lineno; /* first line of block */
+ int ste_col_offset; /* offset of first line of block */
+ int ste_end_lineno; /* end line of block */
+ int ste_end_col_offset; /* end offset of first line of block */
+ int ste_opt_lineno; /* lineno of last exec or import * */
+ int ste_opt_col_offset; /* offset of last exec or import * */
+ struct symtable *ste_table;
+} PySTEntryObject;
+
+extern PyTypeObject PySTEntry_Type;
+
+#define PySTEntry_Check(op) Py_IS_TYPE(op, &PySTEntry_Type)
+
+extern long _PyST_GetSymbol(PySTEntryObject *, PyObject *);
+extern int _PyST_GetScope(PySTEntryObject *, PyObject *);
+
+extern struct symtable* _PySymtable_Build(
+ struct _mod *mod,
+ PyObject *filename,
+ PyFutureFeatures *future);
+PyAPI_FUNC(PySTEntryObject *) PySymtable_Lookup(struct symtable *, void *);
+
+extern void _PySymtable_Free(struct symtable *);
+
+/* Flags for def-use information */
+
+#define DEF_GLOBAL 1 /* global stmt */
+#define DEF_LOCAL 2 /* assignment in code block */
+#define DEF_PARAM 2<<1 /* formal parameter */
+#define DEF_NONLOCAL 2<<2 /* nonlocal stmt */
+#define USE 2<<3 /* name is used */
+#define DEF_FREE 2<<4 /* name used but not defined in nested block */
+#define DEF_FREE_CLASS 2<<5 /* free variable from class's method */
+#define DEF_IMPORT 2<<6 /* assignment occurred via import */
+#define DEF_ANNOT 2<<7 /* this name is annotated */
+#define DEF_COMP_ITER 2<<8 /* this name is a comprehension iteration variable */
+
+#define DEF_BOUND (DEF_LOCAL | DEF_PARAM | DEF_IMPORT)
+
+/* GLOBAL_EXPLICIT and GLOBAL_IMPLICIT are used internally by the symbol
+ table. GLOBAL is returned from PyST_GetScope() for either of them.
+ It is stored in ste_symbols at bits 12-15.
+*/
+#define SCOPE_OFFSET 11
+#define SCOPE_MASK (DEF_GLOBAL | DEF_LOCAL | DEF_PARAM | DEF_NONLOCAL)
+
+#define LOCAL 1
+#define GLOBAL_EXPLICIT 2
+#define GLOBAL_IMPLICIT 3
+#define FREE 4
+#define CELL 5
+
+#define GENERATOR 1
+#define GENERATOR_EXPRESSION 2
+
+// Used by symtablemodule.c
+extern struct symtable* _Py_SymtableStringObjectFlags(
+ const char *str,
+ PyObject *filename,
+ int start,
+ PyCompilerFlags *flags);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_SYMTABLE_H */
diff --git a/include/python3.11/internal/pycore_sysmodule.h b/include/python3.11/internal/pycore_sysmodule.h
new file mode 100644
index 0000000..10d092c
--- /dev/null
+++ b/include/python3.11/internal/pycore_sysmodule.h
@@ -0,0 +1,26 @@
+#ifndef Py_INTERNAL_SYSMODULE_H
+#define Py_INTERNAL_SYSMODULE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+PyAPI_FUNC(int) _PySys_Audit(
+ PyThreadState *tstate,
+ const char *event,
+ const char *argFormat,
+ ...);
+
+/* We want minimal exposure of this function, so use extern rather than
+ PyAPI_FUNC() to not export the symbol. */
+extern void _PySys_ClearAuditHooks(PyThreadState *tstate);
+
+PyAPI_FUNC(int) _PySys_SetAttr(PyObject *, PyObject *);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_SYSMODULE_H */
diff --git a/include/python3.11/internal/pycore_traceback.h b/include/python3.11/internal/pycore_traceback.h
new file mode 100644
index 0000000..c393b2c
--- /dev/null
+++ b/include/python3.11/internal/pycore_traceback.h
@@ -0,0 +1,101 @@
+#ifndef Py_INTERNAL_TRACEBACK_H
+#define Py_INTERNAL_TRACEBACK_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+/* Write the Python traceback into the file 'fd'. For example:
+
+ Traceback (most recent call first):
+ File "xxx", line xxx in <xxx>
+ File "xxx", line xxx in <xxx>
+ ...
+ File "xxx", line xxx in <xxx>
+
+ This function is written for debug purpose only, to dump the traceback in
+ the worst case: after a segmentation fault, at fatal error, etc. That's why,
+ it is very limited. Strings are truncated to 100 characters and encoded to
+ ASCII with backslashreplace. It doesn't write the source code, only the
+ function name, filename and line number of each frame. Write only the first
+ 100 frames: if the traceback is truncated, write the line " ...".
+
+ This function is signal safe. */
+
+PyAPI_FUNC(void) _Py_DumpTraceback(
+ int fd,
+ PyThreadState *tstate);
+
+/* Write the traceback of all threads into the file 'fd'. current_thread can be
+ NULL.
+
+ Return NULL on success, or an error message on error.
+
+ This function is written for debug purpose only. It calls
+ _Py_DumpTraceback() for each thread, and so has the same limitations. It
+ only write the traceback of the first 100 threads: write "..." if there are
+ more threads.
+
+ If current_tstate is NULL, the function tries to get the Python thread state
+ of the current thread. It is not an error if the function is unable to get
+ the current Python thread state.
+
+ If interp is NULL, the function tries to get the interpreter state from
+ the current Python thread state, or from
+ _PyGILState_GetInterpreterStateUnsafe() in last resort.
+
+ It is better to pass NULL to interp and current_tstate, the function tries
+ different options to retrieve this information.
+
+ This function is signal safe. */
+
+PyAPI_FUNC(const char*) _Py_DumpTracebackThreads(
+ int fd,
+ PyInterpreterState *interp,
+ PyThreadState *current_tstate);
+
+/* Write a Unicode object into the file descriptor fd. Encode the string to
+ ASCII using the backslashreplace error handler.
+
+ Do nothing if text is not a Unicode object. The function accepts Unicode
+ string which is not ready (PyUnicode_WCHAR_KIND).
+
+ This function is signal safe. */
+PyAPI_FUNC(void) _Py_DumpASCII(int fd, PyObject *text);
+
+/* Format an integer as decimal into the file descriptor fd.
+
+ This function is signal safe. */
+PyAPI_FUNC(void) _Py_DumpDecimal(
+ int fd,
+ size_t value);
+
+/* Format an integer as hexadecimal with width digits into fd file descriptor.
+ The function is signal safe. */
+PyAPI_FUNC(void) _Py_DumpHexadecimal(
+ int fd,
+ uintptr_t value,
+ Py_ssize_t width);
+
+PyAPI_FUNC(PyObject*) _PyTraceBack_FromFrame(
+ PyObject *tb_next,
+ PyFrameObject *frame);
+
+#define EXCEPTION_TB_HEADER "Traceback (most recent call last):\n"
+#define EXCEPTION_GROUP_TB_HEADER "Exception Group Traceback (most recent call last):\n"
+
+/* Write the traceback tb to file f. Prefix each line with
+ indent spaces followed by the margin (if it is not NULL). */
+PyAPI_FUNC(int) _PyTraceBack_Print_Indented(
+ PyObject *tb, int indent, const char* margin,
+ const char *header_margin, const char *header, PyObject *f);
+PyAPI_FUNC(int) _Py_WriteIndentedMargin(int, const char*, PyObject *);
+PyAPI_FUNC(int) _Py_WriteIndent(int, PyObject *);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_TRACEBACK_H */
diff --git a/include/python3.11/internal/pycore_tuple.h b/include/python3.11/internal/pycore_tuple.h
new file mode 100644
index 0000000..1efe4fa
--- /dev/null
+++ b/include/python3.11/internal/pycore_tuple.h
@@ -0,0 +1,73 @@
+#ifndef Py_INTERNAL_TUPLE_H
+#define Py_INTERNAL_TUPLE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#include "tupleobject.h" /* _PyTuple_CAST() */
+
+
+/* runtime lifecycle */
+
+extern PyStatus _PyTuple_InitGlobalObjects(PyInterpreterState *);
+extern PyStatus _PyTuple_InitTypes(PyInterpreterState *);
+extern void _PyTuple_Fini(PyInterpreterState *);
+
+
+/* other API */
+
+// PyTuple_MAXSAVESIZE - largest tuple to save on free list
+// PyTuple_MAXFREELIST - maximum number of tuples of each size to save
+
+#if defined(PyTuple_MAXSAVESIZE) && PyTuple_MAXSAVESIZE <= 0
+ // A build indicated that tuple freelists should not be used.
+# define PyTuple_NFREELISTS 0
+# undef PyTuple_MAXSAVESIZE
+# undef PyTuple_MAXFREELIST
+
+#elif !defined(WITH_FREELISTS)
+# define PyTuple_NFREELISTS 0
+# undef PyTuple_MAXSAVESIZE
+# undef PyTuple_MAXFREELIST
+
+#else
+ // We are using a freelist for tuples.
+# ifndef PyTuple_MAXSAVESIZE
+# define PyTuple_MAXSAVESIZE 20
+# endif
+# define PyTuple_NFREELISTS PyTuple_MAXSAVESIZE
+# ifndef PyTuple_MAXFREELIST
+# define PyTuple_MAXFREELIST 2000
+# endif
+#endif
+
+struct _Py_tuple_state {
+#if PyTuple_NFREELISTS > 0
+ /* There is one freelist for each size from 1 to PyTuple_MAXSAVESIZE.
+ The empty tuple is handled separately.
+
+ Each tuple stored in the array is the head of the linked list
+ (and the next available tuple) for that size. The actual tuple
+ object is used as the linked list node, with its first item
+ (ob_item[0]) pointing to the next node (i.e. the previous head).
+ Each linked list is initially NULL. */
+ PyTupleObject *free_list[PyTuple_NFREELISTS];
+ int numfree[PyTuple_NFREELISTS];
+#else
+ char _unused; // Empty structs are not allowed.
+#endif
+};
+
+#define _PyTuple_ITEMS(op) (_PyTuple_CAST(op)->ob_item)
+
+extern PyObject *_PyTuple_FromArray(PyObject *const *, Py_ssize_t);
+extern PyObject *_PyTuple_FromArraySteal(PyObject *const *, Py_ssize_t);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_TUPLE_H */
diff --git a/include/python3.11/internal/pycore_typeobject.h b/include/python3.11/internal/pycore_typeobject.h
new file mode 100644
index 0000000..c480a3a
--- /dev/null
+++ b/include/python3.11/internal/pycore_typeobject.h
@@ -0,0 +1,50 @@
+#ifndef Py_INTERNAL_TYPEOBJECT_H
+#define Py_INTERNAL_TYPEOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+
+/* runtime lifecycle */
+
+extern PyStatus _PyTypes_InitState(PyInterpreterState *);
+extern PyStatus _PyTypes_InitTypes(PyInterpreterState *);
+extern void _PyTypes_FiniTypes(PyInterpreterState *);
+extern void _PyTypes_Fini(PyInterpreterState *);
+
+
+/* other API */
+
+// Type attribute lookup cache: speed up attribute and method lookups,
+// see _PyType_Lookup().
+struct type_cache_entry {
+ unsigned int version; // initialized from type->tp_version_tag
+ PyObject *name; // reference to exactly a str or None
+ PyObject *value; // borrowed reference or NULL
+};
+
+#define MCACHE_SIZE_EXP 12
+#define MCACHE_STATS 0
+
+struct type_cache {
+ struct type_cache_entry hashtable[1 << MCACHE_SIZE_EXP];
+#if MCACHE_STATS
+ size_t hits;
+ size_t misses;
+ size_t collisions;
+#endif
+};
+
+extern PyStatus _PyTypes_InitSlotDefs(void);
+
+extern void _PyStaticType_Dealloc(PyTypeObject *type);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_TYPEOBJECT_H */
diff --git a/include/python3.10/internal/pycore_ucnhash.h b/include/python3.11/internal/pycore_ucnhash.h
similarity index 100%
rename from include/python3.10/internal/pycore_ucnhash.h
rename to include/python3.11/internal/pycore_ucnhash.h
diff --git a/include/python3.11/internal/pycore_unicodeobject.h b/include/python3.11/internal/pycore_unicodeobject.h
new file mode 100644
index 0000000..4bee241
--- /dev/null
+++ b/include/python3.11/internal/pycore_unicodeobject.h
@@ -0,0 +1,62 @@
+#ifndef Py_INTERNAL_UNICODEOBJECT_H
+#define Py_INTERNAL_UNICODEOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+#include "pycore_fileutils.h" // _Py_error_handler
+
+void _PyUnicode_ExactDealloc(PyObject *op);
+
+/* runtime lifecycle */
+
+extern void _PyUnicode_InitState(PyInterpreterState *);
+extern PyStatus _PyUnicode_InitGlobalObjects(PyInterpreterState *);
+extern PyStatus _PyUnicode_InitTypes(PyInterpreterState *);
+extern void _PyUnicode_Fini(PyInterpreterState *);
+extern void _PyUnicode_FiniTypes(PyInterpreterState *);
+extern void _PyStaticUnicode_Dealloc(PyObject *);
+
+extern PyTypeObject _PyUnicodeASCIIIter_Type;
+
+/* other API */
+
+struct _Py_unicode_runtime_ids {
+ PyThread_type_lock lock;
+ // next_index value must be preserved when Py_Initialize()/Py_Finalize()
+ // is called multiple times: see _PyUnicode_FromId() implementation.
+ Py_ssize_t next_index;
+};
+
+/* fs_codec.encoding is initialized to NULL.
+ Later, it is set to a non-NULL string by _PyUnicode_InitEncodings(). */
+struct _Py_unicode_fs_codec {
+ char *encoding; // Filesystem encoding (encoded to UTF-8)
+ int utf8; // encoding=="utf-8"?
+ char *errors; // Filesystem errors (encoded to UTF-8)
+ _Py_error_handler error_handler;
+};
+
+struct _Py_unicode_ids {
+ Py_ssize_t size;
+ PyObject **array;
+};
+
+struct _Py_unicode_state {
+ struct _Py_unicode_fs_codec fs_codec;
+
+ // Unicode identifiers (_Py_Identifier): see _PyUnicode_FromId()
+ struct _Py_unicode_ids ids;
+};
+
+extern void _PyUnicode_ClearInterned(PyInterpreterState *interp);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_UNICODEOBJECT_H */
diff --git a/include/python3.11/internal/pycore_unionobject.h b/include/python3.11/internal/pycore_unionobject.h
new file mode 100644
index 0000000..a9ed565
--- /dev/null
+++ b/include/python3.11/internal/pycore_unionobject.h
@@ -0,0 +1,23 @@
+#ifndef Py_INTERNAL_UNIONOBJECT_H
+#define Py_INTERNAL_UNIONOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+extern PyTypeObject _PyUnion_Type;
+#define _PyUnion_Check(op) Py_IS_TYPE(op, &_PyUnion_Type)
+extern PyObject *_Py_union_type_or(PyObject *, PyObject *);
+
+#define _PyGenericAlias_Check(op) PyObject_TypeCheck(op, &Py_GenericAliasType)
+extern PyObject *_Py_subs_parameters(PyObject *, PyObject *, PyObject *, PyObject *);
+extern PyObject *_Py_make_parameters(PyObject *);
+extern PyObject *_Py_union_args(PyObject *self);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_UNIONOBJECT_H */
diff --git a/include/python3.11/internal/pycore_warnings.h b/include/python3.11/internal/pycore_warnings.h
new file mode 100644
index 0000000..efb4f1c
--- /dev/null
+++ b/include/python3.11/internal/pycore_warnings.h
@@ -0,0 +1,29 @@
+#ifndef Py_INTERNAL_WARNINGS_H
+#define Py_INTERNAL_WARNINGS_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+struct _warnings_runtime_state {
+ /* Both 'filters' and 'onceregistry' can be set in warnings.py;
+ get_warnings_attr() will reset these variables accordingly. */
+ PyObject *filters; /* List */
+ PyObject *once_registry; /* Dict */
+ PyObject *default_action; /* String */
+ long filters_version;
+};
+
+extern int _PyWarnings_InitState(PyInterpreterState *interp);
+
+PyAPI_FUNC(PyObject*) _PyWarnings_Init(void);
+
+extern void _PyErr_WarnUnawaitedCoroutine(PyObject *coro);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_INTERNAL_WARNINGS_H */
diff --git a/include/python3.10/intrcheck.h b/include/python3.11/intrcheck.h
similarity index 100%
rename from include/python3.10/intrcheck.h
rename to include/python3.11/intrcheck.h
diff --git a/include/python3.10/iterobject.h b/include/python3.11/iterobject.h
similarity index 100%
rename from include/python3.10/iterobject.h
rename to include/python3.11/iterobject.h
diff --git a/include/python3.11/listobject.h b/include/python3.11/listobject.h
new file mode 100644
index 0000000..eff42c1
--- /dev/null
+++ b/include/python3.11/listobject.h
@@ -0,0 +1,52 @@
+/* List object interface
+
+ Another generally useful object type is a list of object pointers.
+ This is a mutable type: the list items can be changed, and items can be
+ added or removed. Out-of-range indices or non-list objects are ignored.
+
+ WARNING: PyList_SetItem does not increment the new item's reference count,
+ but does decrement the reference count of the item it replaces, if not nil.
+ It does *decrement* the reference count if it is *not* inserted in the list.
+ Similarly, PyList_GetItem does not increment the returned item's reference
+ count.
+*/
+
+#ifndef Py_LISTOBJECT_H
+#define Py_LISTOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_DATA(PyTypeObject) PyList_Type;
+PyAPI_DATA(PyTypeObject) PyListIter_Type;
+PyAPI_DATA(PyTypeObject) PyListRevIter_Type;
+
+#define PyList_Check(op) \
+ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_LIST_SUBCLASS)
+#define PyList_CheckExact(op) Py_IS_TYPE(op, &PyList_Type)
+
+PyAPI_FUNC(PyObject *) PyList_New(Py_ssize_t size);
+PyAPI_FUNC(Py_ssize_t) PyList_Size(PyObject *);
+
+PyAPI_FUNC(PyObject *) PyList_GetItem(PyObject *, Py_ssize_t);
+PyAPI_FUNC(int) PyList_SetItem(PyObject *, Py_ssize_t, PyObject *);
+PyAPI_FUNC(int) PyList_Insert(PyObject *, Py_ssize_t, PyObject *);
+PyAPI_FUNC(int) PyList_Append(PyObject *, PyObject *);
+
+PyAPI_FUNC(PyObject *) PyList_GetSlice(PyObject *, Py_ssize_t, Py_ssize_t);
+PyAPI_FUNC(int) PyList_SetSlice(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);
+
+PyAPI_FUNC(int) PyList_Sort(PyObject *);
+PyAPI_FUNC(int) PyList_Reverse(PyObject *);
+PyAPI_FUNC(PyObject *) PyList_AsTuple(PyObject *);
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_LISTOBJECT_H
+# include "cpython/listobject.h"
+# undef Py_CPYTHON_LISTOBJECT_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_LISTOBJECT_H */
diff --git a/include/python3.11/longobject.h b/include/python3.11/longobject.h
new file mode 100644
index 0000000..81ba123
--- /dev/null
+++ b/include/python3.11/longobject.h
@@ -0,0 +1,91 @@
+#ifndef Py_LONGOBJECT_H
+#define Py_LONGOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Long (arbitrary precision) integer object interface */
+
+PyAPI_DATA(PyTypeObject) PyLong_Type;
+
+#define PyLong_Check(op) \
+ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_LONG_SUBCLASS)
+#define PyLong_CheckExact(op) Py_IS_TYPE(op, &PyLong_Type)
+
+PyAPI_FUNC(PyObject *) PyLong_FromLong(long);
+PyAPI_FUNC(PyObject *) PyLong_FromUnsignedLong(unsigned long);
+PyAPI_FUNC(PyObject *) PyLong_FromSize_t(size_t);
+PyAPI_FUNC(PyObject *) PyLong_FromSsize_t(Py_ssize_t);
+PyAPI_FUNC(PyObject *) PyLong_FromDouble(double);
+PyAPI_FUNC(long) PyLong_AsLong(PyObject *);
+PyAPI_FUNC(long) PyLong_AsLongAndOverflow(PyObject *, int *);
+PyAPI_FUNC(Py_ssize_t) PyLong_AsSsize_t(PyObject *);
+PyAPI_FUNC(size_t) PyLong_AsSize_t(PyObject *);
+PyAPI_FUNC(unsigned long) PyLong_AsUnsignedLong(PyObject *);
+PyAPI_FUNC(unsigned long) PyLong_AsUnsignedLongMask(PyObject *);
+PyAPI_FUNC(PyObject *) PyLong_GetInfo(void);
+
+/* It may be useful in the future. I've added it in the PyInt -> PyLong
+ cleanup to keep the extra information. [CH] */
+#define PyLong_AS_LONG(op) PyLong_AsLong(op)
+
+/* Issue #1983: pid_t can be longer than a C long on some systems */
+#if !defined(SIZEOF_PID_T) || SIZEOF_PID_T == SIZEOF_INT
+#define _Py_PARSE_PID "i"
+#define PyLong_FromPid PyLong_FromLong
+#define PyLong_AsPid PyLong_AsLong
+#elif SIZEOF_PID_T == SIZEOF_LONG
+#define _Py_PARSE_PID "l"
+#define PyLong_FromPid PyLong_FromLong
+#define PyLong_AsPid PyLong_AsLong
+#elif defined(SIZEOF_LONG_LONG) && SIZEOF_PID_T == SIZEOF_LONG_LONG
+#define _Py_PARSE_PID "L"
+#define PyLong_FromPid PyLong_FromLongLong
+#define PyLong_AsPid PyLong_AsLongLong
+#else
+#error "sizeof(pid_t) is neither sizeof(int), sizeof(long) or sizeof(long long)"
+#endif /* SIZEOF_PID_T */
+
+#if SIZEOF_VOID_P == SIZEOF_INT
+# define _Py_PARSE_INTPTR "i"
+# define _Py_PARSE_UINTPTR "I"
+#elif SIZEOF_VOID_P == SIZEOF_LONG
+# define _Py_PARSE_INTPTR "l"
+# define _Py_PARSE_UINTPTR "k"
+#elif defined(SIZEOF_LONG_LONG) && SIZEOF_VOID_P == SIZEOF_LONG_LONG
+# define _Py_PARSE_INTPTR "L"
+# define _Py_PARSE_UINTPTR "K"
+#else
+# error "void* different in size from int, long and long long"
+#endif /* SIZEOF_VOID_P */
+
+PyAPI_FUNC(double) PyLong_AsDouble(PyObject *);
+PyAPI_FUNC(PyObject *) PyLong_FromVoidPtr(void *);
+PyAPI_FUNC(void *) PyLong_AsVoidPtr(PyObject *);
+
+PyAPI_FUNC(PyObject *) PyLong_FromLongLong(long long);
+PyAPI_FUNC(PyObject *) PyLong_FromUnsignedLongLong(unsigned long long);
+PyAPI_FUNC(long long) PyLong_AsLongLong(PyObject *);
+PyAPI_FUNC(unsigned long long) PyLong_AsUnsignedLongLong(PyObject *);
+PyAPI_FUNC(unsigned long long) PyLong_AsUnsignedLongLongMask(PyObject *);
+PyAPI_FUNC(long long) PyLong_AsLongLongAndOverflow(PyObject *, int *);
+
+PyAPI_FUNC(PyObject *) PyLong_FromString(const char *, char **, int);
+
+/* These aren't really part of the int object, but they're handy. The
+ functions are in Python/mystrtoul.c.
+ */
+PyAPI_FUNC(unsigned long) PyOS_strtoul(const char *, char **, int);
+PyAPI_FUNC(long) PyOS_strtol(const char *, char **, int);
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_LONGOBJECT_H
+# include "cpython/longobject.h"
+# undef Py_CPYTHON_LONGOBJECT_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_LONGOBJECT_H */
diff --git a/include/python3.11/marshal.h b/include/python3.11/marshal.h
new file mode 100644
index 0000000..f8b0de8
--- /dev/null
+++ b/include/python3.11/marshal.h
@@ -0,0 +1,31 @@
+
+/* Interface for marshal.c */
+
+#ifndef Py_MARSHAL_H
+#define Py_MARSHAL_H
+#ifndef Py_LIMITED_API
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_FUNC(PyObject *) PyMarshal_ReadObjectFromString(const char *,
+ Py_ssize_t);
+PyAPI_FUNC(PyObject *) PyMarshal_WriteObjectToString(PyObject *, int);
+
+#define Py_MARSHAL_VERSION 4
+
+PyAPI_FUNC(long) PyMarshal_ReadLongFromFile(FILE *);
+PyAPI_FUNC(int) PyMarshal_ReadShortFromFile(FILE *);
+PyAPI_FUNC(PyObject *) PyMarshal_ReadObjectFromFile(FILE *);
+PyAPI_FUNC(PyObject *) PyMarshal_ReadLastObjectFromFile(FILE *);
+
+PyAPI_FUNC(void) PyMarshal_WriteLongToFile(long, FILE *, int);
+PyAPI_FUNC(void) PyMarshal_WriteObjectToFile(PyObject *, FILE *, int);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* Py_LIMITED_API */
+#endif /* !Py_MARSHAL_H */
diff --git a/include/python3.11/memoryobject.h b/include/python3.11/memoryobject.h
new file mode 100644
index 0000000..154397c
--- /dev/null
+++ b/include/python3.11/memoryobject.h
@@ -0,0 +1,72 @@
+/* Memory view object. In Python this is available as "memoryview". */
+
+#ifndef Py_MEMORYOBJECT_H
+#define Py_MEMORYOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_LIMITED_API
+PyAPI_DATA(PyTypeObject) _PyManagedBuffer_Type;
+#endif
+PyAPI_DATA(PyTypeObject) PyMemoryView_Type;
+
+#define PyMemoryView_Check(op) Py_IS_TYPE(op, &PyMemoryView_Type)
+
+#ifndef Py_LIMITED_API
+/* Get a pointer to the memoryview's private copy of the exporter's buffer. */
+#define PyMemoryView_GET_BUFFER(op) (&((PyMemoryViewObject *)(op))->view)
+/* Get a pointer to the exporting object (this may be NULL!). */
+#define PyMemoryView_GET_BASE(op) (((PyMemoryViewObject *)(op))->view.obj)
+#endif
+
+PyAPI_FUNC(PyObject *) PyMemoryView_FromObject(PyObject *base);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+PyAPI_FUNC(PyObject *) PyMemoryView_FromMemory(char *mem, Py_ssize_t size,
+ int flags);
+#endif
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030b0000
+PyAPI_FUNC(PyObject *) PyMemoryView_FromBuffer(const Py_buffer *info);
+#endif
+PyAPI_FUNC(PyObject *) PyMemoryView_GetContiguous(PyObject *base,
+ int buffertype,
+ char order);
+
+
+/* The structs are declared here so that macros can work, but they shouldn't
+ be considered public. Don't access their fields directly, use the macros
+ and functions instead! */
+#ifndef Py_LIMITED_API
+#define _Py_MANAGED_BUFFER_RELEASED 0x001 /* access to exporter blocked */
+#define _Py_MANAGED_BUFFER_FREE_FORMAT 0x002 /* free format */
+typedef struct {
+ PyObject_HEAD
+ int flags; /* state flags */
+ Py_ssize_t exports; /* number of direct memoryview exports */
+ Py_buffer master; /* snapshot buffer obtained from the original exporter */
+} _PyManagedBufferObject;
+
+
+/* memoryview state flags */
+#define _Py_MEMORYVIEW_RELEASED 0x001 /* access to master buffer blocked */
+#define _Py_MEMORYVIEW_C 0x002 /* C-contiguous layout */
+#define _Py_MEMORYVIEW_FORTRAN 0x004 /* Fortran contiguous layout */
+#define _Py_MEMORYVIEW_SCALAR 0x008 /* scalar: ndim = 0 */
+#define _Py_MEMORYVIEW_PIL 0x010 /* PIL-style layout */
+
+typedef struct {
+ PyObject_VAR_HEAD
+ _PyManagedBufferObject *mbuf; /* managed buffer */
+ Py_hash_t hash; /* hash value for read-only views */
+ int flags; /* state flags */
+ Py_ssize_t exports; /* number of buffer re-exports */
+ Py_buffer view; /* private copy of the exporter's view */
+ PyObject *weakreflist;
+ Py_ssize_t ob_array[1]; /* shape, strides, suboffsets */
+} PyMemoryViewObject;
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_MEMORYOBJECT_H */
diff --git a/include/python3.11/methodobject.h b/include/python3.11/methodobject.h
new file mode 100644
index 0000000..c971d78
--- /dev/null
+++ b/include/python3.11/methodobject.h
@@ -0,0 +1,132 @@
+
+/* Method object interface */
+
+#ifndef Py_METHODOBJECT_H
+#define Py_METHODOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* This is about the type 'builtin_function_or_method',
+ not Python methods in user-defined classes. See classobject.h
+ for the latter. */
+
+PyAPI_DATA(PyTypeObject) PyCFunction_Type;
+
+#define PyCFunction_CheckExact(op) Py_IS_TYPE(op, &PyCFunction_Type)
+#define PyCFunction_Check(op) PyObject_TypeCheck(op, &PyCFunction_Type)
+
+typedef PyObject *(*PyCFunction)(PyObject *, PyObject *);
+typedef PyObject *(*_PyCFunctionFast) (PyObject *, PyObject *const *, Py_ssize_t);
+typedef PyObject *(*PyCFunctionWithKeywords)(PyObject *, PyObject *,
+ PyObject *);
+typedef PyObject *(*_PyCFunctionFastWithKeywords) (PyObject *,
+ PyObject *const *, Py_ssize_t,
+ PyObject *);
+typedef PyObject *(*PyCMethod)(PyObject *, PyTypeObject *, PyObject *const *,
+ size_t, PyObject *);
+
+// Cast an function to the PyCFunction type to use it with PyMethodDef.
+//
+// This macro can be used to prevent compiler warnings if the first parameter
+// uses a different pointer type than PyObject* (ex: METH_VARARGS and METH_O
+// calling conventions).
+//
+// The macro can also be used for METH_FASTCALL and METH_VARARGS|METH_KEYWORDS
+// calling conventions to avoid compiler warnings because the function has more
+// than 2 parameters. The macro first casts the function to the
+// "void func(void)" type to prevent compiler warnings.
+//
+// If a function is declared with the METH_NOARGS calling convention, it must
+// have 2 parameters. Since the second parameter is unused, Py_UNUSED() can be
+// used to prevent a compiler warning. If the function has a single parameter,
+// it triggers an undefined behavior when Python calls it with 2 parameters
+// (bpo-33012).
+#define _PyCFunction_CAST(func) \
+ _Py_CAST(PyCFunction, _Py_CAST(void(*)(void), (func)))
+
+PyAPI_FUNC(PyCFunction) PyCFunction_GetFunction(PyObject *);
+PyAPI_FUNC(PyObject *) PyCFunction_GetSelf(PyObject *);
+PyAPI_FUNC(int) PyCFunction_GetFlags(PyObject *);
+
+Py_DEPRECATED(3.9) PyAPI_FUNC(PyObject *) PyCFunction_Call(PyObject *, PyObject *, PyObject *);
+
+struct PyMethodDef {
+ const char *ml_name; /* The name of the built-in function/method */
+ PyCFunction ml_meth; /* The C function that implements it */
+ int ml_flags; /* Combination of METH_xxx flags, which mostly
+ describe the args expected by the C func */
+ const char *ml_doc; /* The __doc__ attribute, or NULL */
+};
+
+/* PyCFunction_New is declared as a function for stable ABI (declaration is
+ * needed for e.g. GCC with -fvisibility=hidden), but redefined as a macro
+ * that calls PyCFunction_NewEx. */
+PyAPI_FUNC(PyObject *) PyCFunction_New(PyMethodDef *, PyObject *);
+#define PyCFunction_New(ML, SELF) PyCFunction_NewEx((ML), (SELF), NULL)
+
+/* PyCFunction_NewEx is similar: on 3.9+, this calls PyCMethod_New. */
+PyAPI_FUNC(PyObject *) PyCFunction_NewEx(PyMethodDef *, PyObject *,
+ PyObject *);
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03090000
+#define PyCFunction_NewEx(ML, SELF, MOD) PyCMethod_New((ML), (SELF), (MOD), NULL)
+PyAPI_FUNC(PyObject *) PyCMethod_New(PyMethodDef *, PyObject *,
+ PyObject *, PyTypeObject *);
+#endif
+
+
+/* Flag passed to newmethodobject */
+/* #define METH_OLDARGS 0x0000 -- unsupported now */
+#define METH_VARARGS 0x0001
+#define METH_KEYWORDS 0x0002
+/* METH_NOARGS and METH_O must not be combined with the flags above. */
+#define METH_NOARGS 0x0004
+#define METH_O 0x0008
+
+/* METH_CLASS and METH_STATIC are a little different; these control
+ the construction of methods for a class. These cannot be used for
+ functions in modules. */
+#define METH_CLASS 0x0010
+#define METH_STATIC 0x0020
+
+/* METH_COEXIST allows a method to be entered even though a slot has
+ already filled the entry. When defined, the flag allows a separate
+ method, "__contains__" for example, to coexist with a defined
+ slot like sq_contains. */
+
+#define METH_COEXIST 0x0040
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030a0000
+# define METH_FASTCALL 0x0080
+#endif
+
+/* This bit is preserved for Stackless Python */
+#ifdef STACKLESS
+# define METH_STACKLESS 0x0100
+#else
+# define METH_STACKLESS 0x0000
+#endif
+
+/* METH_METHOD means the function stores an
+ * additional reference to the class that defines it;
+ * both self and class are passed to it.
+ * It uses PyCMethodObject instead of PyCFunctionObject.
+ * May not be combined with METH_NOARGS, METH_O, METH_CLASS or METH_STATIC.
+ */
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03090000
+#define METH_METHOD 0x0200
+#endif
+
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_METHODOBJECT_H
+# include "cpython/methodobject.h"
+# undef Py_CPYTHON_METHODOBJECT_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_METHODOBJECT_H */
diff --git a/include/python3.11/modsupport.h b/include/python3.11/modsupport.h
new file mode 100644
index 0000000..0e96a5c
--- /dev/null
+++ b/include/python3.11/modsupport.h
@@ -0,0 +1,168 @@
+
+#ifndef Py_MODSUPPORT_H
+#define Py_MODSUPPORT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Module support interface */
+
+#include <stdarg.h> // va_list
+
+/* If PY_SSIZE_T_CLEAN is defined, each functions treats #-specifier
+ to mean Py_ssize_t */
+#ifdef PY_SSIZE_T_CLEAN
+#define PyArg_Parse _PyArg_Parse_SizeT
+#define PyArg_ParseTuple _PyArg_ParseTuple_SizeT
+#define PyArg_ParseTupleAndKeywords _PyArg_ParseTupleAndKeywords_SizeT
+#define PyArg_VaParse _PyArg_VaParse_SizeT
+#define PyArg_VaParseTupleAndKeywords _PyArg_VaParseTupleAndKeywords_SizeT
+#define Py_BuildValue _Py_BuildValue_SizeT
+#define Py_VaBuildValue _Py_VaBuildValue_SizeT
+#endif
+
+/* Due to a glitch in 3.2, the _SizeT versions weren't exported from the DLL. */
+#if !defined(PY_SSIZE_T_CLEAN) || !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+PyAPI_FUNC(int) PyArg_Parse(PyObject *, const char *, ...);
+PyAPI_FUNC(int) PyArg_ParseTuple(PyObject *, const char *, ...);
+PyAPI_FUNC(int) PyArg_ParseTupleAndKeywords(PyObject *, PyObject *,
+ const char *, char **, ...);
+PyAPI_FUNC(int) PyArg_VaParse(PyObject *, const char *, va_list);
+PyAPI_FUNC(int) PyArg_VaParseTupleAndKeywords(PyObject *, PyObject *,
+ const char *, char **, va_list);
+#endif
+PyAPI_FUNC(int) PyArg_ValidateKeywordArguments(PyObject *);
+PyAPI_FUNC(int) PyArg_UnpackTuple(PyObject *, const char *, Py_ssize_t, Py_ssize_t, ...);
+PyAPI_FUNC(PyObject *) Py_BuildValue(const char *, ...);
+PyAPI_FUNC(PyObject *) _Py_BuildValue_SizeT(const char *, ...);
+
+
+#define ANY_VARARGS(n) (n == PY_SSIZE_T_MAX)
+
+PyAPI_FUNC(PyObject *) Py_VaBuildValue(const char *, va_list);
+
+// Add an attribute with name 'name' and value 'obj' to the module 'mod.
+// On success, return 0 on success.
+// On error, raise an exception and return -1.
+PyAPI_FUNC(int) PyModule_AddObjectRef(PyObject *mod, const char *name, PyObject *value);
+
+// Similar to PyModule_AddObjectRef() but steal a reference to 'obj'
+// (Py_DECREF(obj)) on success (if it returns 0).
+PyAPI_FUNC(int) PyModule_AddObject(PyObject *mod, const char *, PyObject *value);
+
+PyAPI_FUNC(int) PyModule_AddIntConstant(PyObject *, const char *, long);
+PyAPI_FUNC(int) PyModule_AddStringConstant(PyObject *, const char *, const char *);
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03090000
+/* New in 3.9 */
+PyAPI_FUNC(int) PyModule_AddType(PyObject *module, PyTypeObject *type);
+#endif /* Py_LIMITED_API */
+
+#define PyModule_AddIntMacro(m, c) PyModule_AddIntConstant(m, #c, c)
+#define PyModule_AddStringMacro(m, c) PyModule_AddStringConstant(m, #c, c)
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
+/* New in 3.5 */
+PyAPI_FUNC(int) PyModule_SetDocString(PyObject *, const char *);
+PyAPI_FUNC(int) PyModule_AddFunctions(PyObject *, PyMethodDef *);
+PyAPI_FUNC(int) PyModule_ExecDef(PyObject *module, PyModuleDef *def);
+#endif
+
+#define Py_CLEANUP_SUPPORTED 0x20000
+
+#define PYTHON_API_VERSION 1013
+#define PYTHON_API_STRING "1013"
+/* The API version is maintained (independently from the Python version)
+ so we can detect mismatches between the interpreter and dynamically
+ loaded modules. These are diagnosed by an error message but
+ the module is still loaded (because the mismatch can only be tested
+ after loading the module). The error message is intended to
+ explain the core dump a few seconds later.
+
+ The symbol PYTHON_API_STRING defines the same value as a string
+ literal. *** PLEASE MAKE SURE THE DEFINITIONS MATCH. ***
+
+ Please add a line or two to the top of this log for each API
+ version change:
+
+ 22-Feb-2006 MvL 1013 PEP 353 - long indices for sequence lengths
+
+ 19-Aug-2002 GvR 1012 Changes to string object struct for
+ interning changes, saving 3 bytes.
+
+ 17-Jul-2001 GvR 1011 Descr-branch, just to be on the safe side
+
+ 25-Jan-2001 FLD 1010 Parameters added to PyCode_New() and
+ PyFrame_New(); Python 2.1a2
+
+ 14-Mar-2000 GvR 1009 Unicode API added
+
+ 3-Jan-1999 GvR 1007 Decided to change back! (Don't reuse 1008!)
+
+ 3-Dec-1998 GvR 1008 Python 1.5.2b1
+
+ 18-Jan-1997 GvR 1007 string interning and other speedups
+
+ 11-Oct-1996 GvR renamed Py_Ellipses to Py_Ellipsis :-(
+
+ 30-Jul-1996 GvR Slice and ellipses syntax added
+
+ 23-Jul-1996 GvR For 1.4 -- better safe than sorry this time :-)
+
+ 7-Nov-1995 GvR Keyword arguments (should've been done at 1.3 :-( )
+
+ 10-Jan-1995 GvR Renamed globals to new naming scheme
+
+ 9-Jan-1995 GvR Initial version (incompatible with older API)
+*/
+
+/* The PYTHON_ABI_VERSION is introduced in PEP 384. For the lifetime of
+ Python 3, it will stay at the value of 3; changes to the limited API
+ must be performed in a strictly backwards-compatible manner. */
+#define PYTHON_ABI_VERSION 3
+#define PYTHON_ABI_STRING "3"
+
+#ifdef Py_TRACE_REFS
+ /* When we are tracing reference counts, rename module creation functions so
+ modules compiled with incompatible settings will generate a
+ link-time error. */
+ #define PyModule_Create2 PyModule_Create2TraceRefs
+ #define PyModule_FromDefAndSpec2 PyModule_FromDefAndSpec2TraceRefs
+#endif
+
+PyAPI_FUNC(PyObject *) PyModule_Create2(PyModuleDef*, int apiver);
+
+#ifdef Py_LIMITED_API
+#define PyModule_Create(module) \
+ PyModule_Create2(module, PYTHON_ABI_VERSION)
+#else
+#define PyModule_Create(module) \
+ PyModule_Create2(module, PYTHON_API_VERSION)
+#endif
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
+/* New in 3.5 */
+PyAPI_FUNC(PyObject *) PyModule_FromDefAndSpec2(PyModuleDef *def,
+ PyObject *spec,
+ int module_api_version);
+
+#ifdef Py_LIMITED_API
+#define PyModule_FromDefAndSpec(module, spec) \
+ PyModule_FromDefAndSpec2(module, spec, PYTHON_ABI_VERSION)
+#else
+#define PyModule_FromDefAndSpec(module, spec) \
+ PyModule_FromDefAndSpec2(module, spec, PYTHON_API_VERSION)
+#endif /* Py_LIMITED_API */
+
+#endif /* New in 3.5 */
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_MODSUPPORT_H
+# include "cpython/modsupport.h"
+# undef Py_CPYTHON_MODSUPPORT_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_MODSUPPORT_H */
diff --git a/include/python3.11/moduleobject.h b/include/python3.11/moduleobject.h
new file mode 100644
index 0000000..75abd2c
--- /dev/null
+++ b/include/python3.11/moduleobject.h
@@ -0,0 +1,95 @@
+
+/* Module object interface */
+
+#ifndef Py_MODULEOBJECT_H
+#define Py_MODULEOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_DATA(PyTypeObject) PyModule_Type;
+
+#define PyModule_Check(op) PyObject_TypeCheck(op, &PyModule_Type)
+#define PyModule_CheckExact(op) Py_IS_TYPE(op, &PyModule_Type)
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+PyAPI_FUNC(PyObject *) PyModule_NewObject(
+ PyObject *name
+ );
+#endif
+PyAPI_FUNC(PyObject *) PyModule_New(
+ const char *name /* UTF-8 encoded string */
+ );
+PyAPI_FUNC(PyObject *) PyModule_GetDict(PyObject *);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+PyAPI_FUNC(PyObject *) PyModule_GetNameObject(PyObject *);
+#endif
+PyAPI_FUNC(const char *) PyModule_GetName(PyObject *);
+Py_DEPRECATED(3.2) PyAPI_FUNC(const char *) PyModule_GetFilename(PyObject *);
+PyAPI_FUNC(PyObject *) PyModule_GetFilenameObject(PyObject *);
+#ifndef Py_LIMITED_API
+PyAPI_FUNC(void) _PyModule_Clear(PyObject *);
+PyAPI_FUNC(void) _PyModule_ClearDict(PyObject *);
+PyAPI_FUNC(int) _PyModuleSpec_IsInitializing(PyObject *);
+#endif
+PyAPI_FUNC(PyModuleDef*) PyModule_GetDef(PyObject*);
+PyAPI_FUNC(void*) PyModule_GetState(PyObject*);
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
+/* New in 3.5 */
+PyAPI_FUNC(PyObject *) PyModuleDef_Init(PyModuleDef*);
+PyAPI_DATA(PyTypeObject) PyModuleDef_Type;
+#endif
+
+typedef struct PyModuleDef_Base {
+ PyObject_HEAD
+ PyObject* (*m_init)(void);
+ Py_ssize_t m_index;
+ PyObject* m_copy;
+} PyModuleDef_Base;
+
+#define PyModuleDef_HEAD_INIT { \
+ PyObject_HEAD_INIT(_Py_NULL) \
+ _Py_NULL, /* m_init */ \
+ 0, /* m_index */ \
+ _Py_NULL, /* m_copy */ \
+ }
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
+/* New in 3.5 */
+struct PyModuleDef_Slot {
+ int slot;
+ void *value;
+};
+
+#define Py_mod_create 1
+#define Py_mod_exec 2
+
+#ifndef Py_LIMITED_API
+#define _Py_mod_LAST_SLOT 2
+#endif
+
+#endif /* New in 3.5 */
+
+struct PyModuleDef {
+ PyModuleDef_Base m_base;
+ const char* m_name;
+ const char* m_doc;
+ Py_ssize_t m_size;
+ PyMethodDef *m_methods;
+ PyModuleDef_Slot *m_slots;
+ traverseproc m_traverse;
+ inquiry m_clear;
+ freefunc m_free;
+};
+
+
+// Internal C API
+#ifdef Py_BUILD_CORE
+extern int _PyModule_IsExtension(PyObject *obj);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_MODULEOBJECT_H */
diff --git a/include/python3.11/object.h b/include/python3.11/object.h
new file mode 100644
index 0000000..f2af428
--- /dev/null
+++ b/include/python3.11/object.h
@@ -0,0 +1,797 @@
+#ifndef Py_OBJECT_H
+#define Py_OBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Object and type object interface */
+
+/*
+Objects are structures allocated on the heap. Special rules apply to
+the use of objects to ensure they are properly garbage-collected.
+Objects are never allocated statically or on the stack; they must be
+accessed through special macros and functions only. (Type objects are
+exceptions to the first rule; the standard types are represented by
+statically initialized type objects, although work on type/class unification
+for Python 2.2 made it possible to have heap-allocated type objects too).
+
+An object has a 'reference count' that is increased or decreased when a
+pointer to the object is copied or deleted; when the reference count
+reaches zero there are no references to the object left and it can be
+removed from the heap.
+
+An object has a 'type' that determines what it represents and what kind
+of data it contains. An object's type is fixed when it is created.
+Types themselves are represented as objects; an object contains a
+pointer to the corresponding type object. The type itself has a type
+pointer pointing to the object representing the type 'type', which
+contains a pointer to itself!.
+
+Objects do not float around in memory; once allocated an object keeps
+the same size and address. Objects that must hold variable-size data
+can contain pointers to variable-size parts of the object. Not all
+objects of the same type have the same size; but the size cannot change
+after allocation. (These restrictions are made so a reference to an
+object can be simply a pointer -- moving an object would require
+updating all the pointers, and changing an object's size would require
+moving it if there was another object right next to it.)
+
+Objects are always accessed through pointers of the type 'PyObject *'.
+The type 'PyObject' is a structure that only contains the reference count
+and the type pointer. The actual memory allocated for an object
+contains other data that can only be accessed after casting the pointer
+to a pointer to a longer structure type. This longer type must start
+with the reference count and type fields; the macro PyObject_HEAD should be
+used for this (to accommodate for future changes). The implementation
+of a particular object type can cast the object pointer to the proper
+type and back.
+
+A standard interface exists for objects that contain an array of items
+whose size is determined when the object is allocated.
+*/
+
+/* Py_DEBUG implies Py_REF_DEBUG. */
+#if defined(Py_DEBUG) && !defined(Py_REF_DEBUG)
+# define Py_REF_DEBUG
+#endif
+
+#if defined(Py_LIMITED_API) && defined(Py_TRACE_REFS)
+# error Py_LIMITED_API is incompatible with Py_TRACE_REFS
+#endif
+
+#ifdef Py_TRACE_REFS
+/* Define pointers to support a doubly-linked list of all live heap objects. */
+#define _PyObject_HEAD_EXTRA \
+ PyObject *_ob_next; \
+ PyObject *_ob_prev;
+
+#define _PyObject_EXTRA_INIT _Py_NULL, _Py_NULL,
+
+#else
+# define _PyObject_HEAD_EXTRA
+# define _PyObject_EXTRA_INIT
+#endif
+
+/* PyObject_HEAD defines the initial segment of every PyObject. */
+#define PyObject_HEAD PyObject ob_base;
+
+#define PyObject_HEAD_INIT(type) \
+ { _PyObject_EXTRA_INIT \
+ 1, type },
+
+#define PyVarObject_HEAD_INIT(type, size) \
+ { PyObject_HEAD_INIT(type) size },
+
+/* PyObject_VAR_HEAD defines the initial segment of all variable-size
+ * container objects. These end with a declaration of an array with 1
+ * element, but enough space is malloc'ed so that the array actually
+ * has room for ob_size elements. Note that ob_size is an element count,
+ * not necessarily a byte count.
+ */
+#define PyObject_VAR_HEAD PyVarObject ob_base;
+#define Py_INVALID_SIZE (Py_ssize_t)-1
+
+/* Nothing is actually declared to be a PyObject, but every pointer to
+ * a Python object can be cast to a PyObject*. This is inheritance built
+ * by hand. Similarly every pointer to a variable-size Python object can,
+ * in addition, be cast to PyVarObject*.
+ */
+struct _object {
+ _PyObject_HEAD_EXTRA
+ Py_ssize_t ob_refcnt;
+ PyTypeObject *ob_type;
+};
+
+/* Cast argument to PyObject* type. */
+#define _PyObject_CAST(op) _Py_CAST(PyObject*, (op))
+
+typedef struct {
+ PyObject ob_base;
+ Py_ssize_t ob_size; /* Number of items in variable part */
+} PyVarObject;
+
+/* Cast argument to PyVarObject* type. */
+#define _PyVarObject_CAST(op) _Py_CAST(PyVarObject*, (op))
+
+
+// Test if the 'x' object is the 'y' object, the same as "x is y" in Python.
+PyAPI_FUNC(int) Py_Is(PyObject *x, PyObject *y);
+#define Py_Is(x, y) ((x) == (y))
+
+
+static inline Py_ssize_t Py_REFCNT(PyObject *ob) {
+ return ob->ob_refcnt;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define Py_REFCNT(ob) Py_REFCNT(_PyObject_CAST(ob))
+#endif
+
+
+// bpo-39573: The Py_SET_TYPE() function must be used to set an object type.
+static inline PyTypeObject* Py_TYPE(PyObject *ob) {
+ return ob->ob_type;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define Py_TYPE(ob) Py_TYPE(_PyObject_CAST(ob))
+#endif
+
+// bpo-39573: The Py_SET_SIZE() function must be used to set an object size.
+static inline Py_ssize_t Py_SIZE(PyObject *ob) {
+ PyVarObject *var_ob = _PyVarObject_CAST(ob);
+ return var_ob->ob_size;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define Py_SIZE(ob) Py_SIZE(_PyObject_CAST(ob))
+#endif
+
+
+static inline int Py_IS_TYPE(PyObject *ob, PyTypeObject *type) {
+ return Py_TYPE(ob) == type;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define Py_IS_TYPE(ob, type) Py_IS_TYPE(_PyObject_CAST(ob), type)
+#endif
+
+
+static inline void Py_SET_REFCNT(PyObject *ob, Py_ssize_t refcnt) {
+ ob->ob_refcnt = refcnt;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define Py_SET_REFCNT(ob, refcnt) Py_SET_REFCNT(_PyObject_CAST(ob), refcnt)
+#endif
+
+
+static inline void Py_SET_TYPE(PyObject *ob, PyTypeObject *type) {
+ ob->ob_type = type;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define Py_SET_TYPE(ob, type) Py_SET_TYPE(_PyObject_CAST(ob), type)
+#endif
+
+
+static inline void Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size) {
+ ob->ob_size = size;
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define Py_SET_SIZE(ob, size) Py_SET_SIZE(_PyVarObject_CAST(ob), size)
+#endif
+
+
+/*
+Type objects contain a string containing the type name (to help somewhat
+in debugging), the allocation parameters (see PyObject_New() and
+PyObject_NewVar()),
+and methods for accessing objects of the type. Methods are optional, a
+nil pointer meaning that particular kind of access is not available for
+this type. The Py_DECREF() macro uses the tp_dealloc method without
+checking for a nil pointer; it should always be implemented except if
+the implementation can guarantee that the reference count will never
+reach zero (e.g., for statically allocated type objects).
+
+NB: the methods for certain type groups are now contained in separate
+method blocks.
+*/
+
+typedef PyObject * (*unaryfunc)(PyObject *);
+typedef PyObject * (*binaryfunc)(PyObject *, PyObject *);
+typedef PyObject * (*ternaryfunc)(PyObject *, PyObject *, PyObject *);
+typedef int (*inquiry)(PyObject *);
+typedef Py_ssize_t (*lenfunc)(PyObject *);
+typedef PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t);
+typedef PyObject *(*ssizessizeargfunc)(PyObject *, Py_ssize_t, Py_ssize_t);
+typedef int(*ssizeobjargproc)(PyObject *, Py_ssize_t, PyObject *);
+typedef int(*ssizessizeobjargproc)(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);
+typedef int(*objobjargproc)(PyObject *, PyObject *, PyObject *);
+
+typedef int (*objobjproc)(PyObject *, PyObject *);
+typedef int (*visitproc)(PyObject *, void *);
+typedef int (*traverseproc)(PyObject *, visitproc, void *);
+
+
+typedef void (*freefunc)(void *);
+typedef void (*destructor)(PyObject *);
+typedef PyObject *(*getattrfunc)(PyObject *, char *);
+typedef PyObject *(*getattrofunc)(PyObject *, PyObject *);
+typedef int (*setattrfunc)(PyObject *, char *, PyObject *);
+typedef int (*setattrofunc)(PyObject *, PyObject *, PyObject *);
+typedef PyObject *(*reprfunc)(PyObject *);
+typedef Py_hash_t (*hashfunc)(PyObject *);
+typedef PyObject *(*richcmpfunc) (PyObject *, PyObject *, int);
+typedef PyObject *(*getiterfunc) (PyObject *);
+typedef PyObject *(*iternextfunc) (PyObject *);
+typedef PyObject *(*descrgetfunc) (PyObject *, PyObject *, PyObject *);
+typedef int (*descrsetfunc) (PyObject *, PyObject *, PyObject *);
+typedef int (*initproc)(PyObject *, PyObject *, PyObject *);
+typedef PyObject *(*newfunc)(PyTypeObject *, PyObject *, PyObject *);
+typedef PyObject *(*allocfunc)(PyTypeObject *, Py_ssize_t);
+
+typedef struct{
+ int slot; /* slot id, see below */
+ void *pfunc; /* function pointer */
+} PyType_Slot;
+
+typedef struct{
+ const char* name;
+ int basicsize;
+ int itemsize;
+ unsigned int flags;
+ PyType_Slot *slots; /* terminated by slot==0. */
+} PyType_Spec;
+
+PyAPI_FUNC(PyObject*) PyType_FromSpec(PyType_Spec*);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+PyAPI_FUNC(PyObject*) PyType_FromSpecWithBases(PyType_Spec*, PyObject*);
+#endif
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000
+PyAPI_FUNC(void*) PyType_GetSlot(PyTypeObject*, int);
+#endif
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03090000
+PyAPI_FUNC(PyObject*) PyType_FromModuleAndSpec(PyObject *, PyType_Spec *, PyObject *);
+PyAPI_FUNC(PyObject *) PyType_GetModule(PyTypeObject *);
+PyAPI_FUNC(void *) PyType_GetModuleState(PyTypeObject *);
+#endif
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030B0000
+PyAPI_FUNC(PyObject *) PyType_GetName(PyTypeObject *);
+PyAPI_FUNC(PyObject *) PyType_GetQualName(PyTypeObject *);
+#endif
+
+/* Generic type check */
+PyAPI_FUNC(int) PyType_IsSubtype(PyTypeObject *, PyTypeObject *);
+
+static inline int PyObject_TypeCheck(PyObject *ob, PyTypeObject *type) {
+ return Py_IS_TYPE(ob, type) || PyType_IsSubtype(Py_TYPE(ob), type);
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyObject_TypeCheck(ob, type) PyObject_TypeCheck(_PyObject_CAST(ob), type)
+#endif
+
+PyAPI_DATA(PyTypeObject) PyType_Type; /* built-in 'type' */
+PyAPI_DATA(PyTypeObject) PyBaseObject_Type; /* built-in 'object' */
+PyAPI_DATA(PyTypeObject) PySuper_Type; /* built-in 'super' */
+
+PyAPI_FUNC(unsigned long) PyType_GetFlags(PyTypeObject*);
+
+PyAPI_FUNC(int) PyType_Ready(PyTypeObject *);
+PyAPI_FUNC(PyObject *) PyType_GenericAlloc(PyTypeObject *, Py_ssize_t);
+PyAPI_FUNC(PyObject *) PyType_GenericNew(PyTypeObject *,
+ PyObject *, PyObject *);
+PyAPI_FUNC(unsigned int) PyType_ClearCache(void);
+PyAPI_FUNC(void) PyType_Modified(PyTypeObject *);
+
+/* Generic operations on objects */
+PyAPI_FUNC(PyObject *) PyObject_Repr(PyObject *);
+PyAPI_FUNC(PyObject *) PyObject_Str(PyObject *);
+PyAPI_FUNC(PyObject *) PyObject_ASCII(PyObject *);
+PyAPI_FUNC(PyObject *) PyObject_Bytes(PyObject *);
+PyAPI_FUNC(PyObject *) PyObject_RichCompare(PyObject *, PyObject *, int);
+PyAPI_FUNC(int) PyObject_RichCompareBool(PyObject *, PyObject *, int);
+PyAPI_FUNC(PyObject *) PyObject_GetAttrString(PyObject *, const char *);
+PyAPI_FUNC(int) PyObject_SetAttrString(PyObject *, const char *, PyObject *);
+PyAPI_FUNC(int) PyObject_HasAttrString(PyObject *, const char *);
+PyAPI_FUNC(PyObject *) PyObject_GetAttr(PyObject *, PyObject *);
+PyAPI_FUNC(int) PyObject_SetAttr(PyObject *, PyObject *, PyObject *);
+PyAPI_FUNC(int) PyObject_HasAttr(PyObject *, PyObject *);
+PyAPI_FUNC(PyObject *) PyObject_SelfIter(PyObject *);
+PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *);
+PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *, PyObject *, PyObject *);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+PyAPI_FUNC(int) PyObject_GenericSetDict(PyObject *, PyObject *, void *);
+#endif
+PyAPI_FUNC(Py_hash_t) PyObject_Hash(PyObject *);
+PyAPI_FUNC(Py_hash_t) PyObject_HashNotImplemented(PyObject *);
+PyAPI_FUNC(int) PyObject_IsTrue(PyObject *);
+PyAPI_FUNC(int) PyObject_Not(PyObject *);
+PyAPI_FUNC(int) PyCallable_Check(PyObject *);
+PyAPI_FUNC(void) PyObject_ClearWeakRefs(PyObject *);
+
+/* PyObject_Dir(obj) acts like Python builtins.dir(obj), returning a
+ list of strings. PyObject_Dir(NULL) is like builtins.dir(),
+ returning the names of the current locals. In this case, if there are
+ no current locals, NULL is returned, and PyErr_Occurred() is false.
+*/
+PyAPI_FUNC(PyObject *) PyObject_Dir(PyObject *);
+
+/* Pickle support. */
+#ifndef Py_LIMITED_API
+PyAPI_FUNC(PyObject *) _PyObject_GetState(PyObject *);
+#endif
+
+
+/* Helpers for printing recursive container types */
+PyAPI_FUNC(int) Py_ReprEnter(PyObject *);
+PyAPI_FUNC(void) Py_ReprLeave(PyObject *);
+
+/* Flag bits for printing: */
+#define Py_PRINT_RAW 1 /* No string quotes etc. */
+
+/*
+Type flags (tp_flags)
+
+These flags are used to change expected features and behavior for a
+particular type.
+
+Arbitration of the flag bit positions will need to be coordinated among
+all extension writers who publicly release their extensions (this will
+be fewer than you might expect!).
+
+Most flags were removed as of Python 3.0 to make room for new flags. (Some
+flags are not for backwards compatibility but to indicate the presence of an
+optional feature; these flags remain of course.)
+
+Type definitions should use Py_TPFLAGS_DEFAULT for their tp_flags value.
+
+Code can use PyType_HasFeature(type_ob, flag_value) to test whether the
+given type object has a specified feature.
+*/
+
+#ifndef Py_LIMITED_API
+
+/* Placement of dict (and values) pointers are managed by the VM, not by the type.
+ * The VM will automatically set tp_dictoffset. Should not be used for variable sized
+ * classes, such as classes that extend tuple.
+ */
+#define Py_TPFLAGS_MANAGED_DICT (1 << 4)
+
+/* Set if instances of the type object are treated as sequences for pattern matching */
+#define Py_TPFLAGS_SEQUENCE (1 << 5)
+/* Set if instances of the type object are treated as mappings for pattern matching */
+#define Py_TPFLAGS_MAPPING (1 << 6)
+#endif
+
+/* Disallow creating instances of the type: set tp_new to NULL and don't create
+ * the "__new__" key in the type dictionary. */
+#define Py_TPFLAGS_DISALLOW_INSTANTIATION (1UL << 7)
+
+/* Set if the type object is immutable: type attributes cannot be set nor deleted */
+#define Py_TPFLAGS_IMMUTABLETYPE (1UL << 8)
+
+/* Set if the type object is dynamically allocated */
+#define Py_TPFLAGS_HEAPTYPE (1UL << 9)
+
+/* Set if the type allows subclassing */
+#define Py_TPFLAGS_BASETYPE (1UL << 10)
+
+/* Set if the type implements the vectorcall protocol (PEP 590) */
+#ifndef Py_LIMITED_API
+#define Py_TPFLAGS_HAVE_VECTORCALL (1UL << 11)
+// Backwards compatibility alias for API that was provisional in Python 3.8
+#define _Py_TPFLAGS_HAVE_VECTORCALL Py_TPFLAGS_HAVE_VECTORCALL
+#endif
+
+/* Set if the type is 'ready' -- fully initialized */
+#define Py_TPFLAGS_READY (1UL << 12)
+
+/* Set while the type is being 'readied', to prevent recursive ready calls */
+#define Py_TPFLAGS_READYING (1UL << 13)
+
+/* Objects support garbage collection (see objimpl.h) */
+#define Py_TPFLAGS_HAVE_GC (1UL << 14)
+
+/* These two bits are preserved for Stackless Python, next after this is 17 */
+#ifdef STACKLESS
+#define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION (3UL << 15)
+#else
+#define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION 0
+#endif
+
+/* Objects behave like an unbound method */
+#define Py_TPFLAGS_METHOD_DESCRIPTOR (1UL << 17)
+
+/* Object has up-to-date type attribute cache */
+#define Py_TPFLAGS_VALID_VERSION_TAG (1UL << 19)
+
+/* Type is abstract and cannot be instantiated */
+#define Py_TPFLAGS_IS_ABSTRACT (1UL << 20)
+
+// This undocumented flag gives certain built-ins their unique pattern-matching
+// behavior, which allows a single positional subpattern to match against the
+// subject itself (rather than a mapped attribute on it):
+#define _Py_TPFLAGS_MATCH_SELF (1UL << 22)
+
+/* These flags are used to determine if a type is a subclass. */
+#define Py_TPFLAGS_LONG_SUBCLASS (1UL << 24)
+#define Py_TPFLAGS_LIST_SUBCLASS (1UL << 25)
+#define Py_TPFLAGS_TUPLE_SUBCLASS (1UL << 26)
+#define Py_TPFLAGS_BYTES_SUBCLASS (1UL << 27)
+#define Py_TPFLAGS_UNICODE_SUBCLASS (1UL << 28)
+#define Py_TPFLAGS_DICT_SUBCLASS (1UL << 29)
+#define Py_TPFLAGS_BASE_EXC_SUBCLASS (1UL << 30)
+#define Py_TPFLAGS_TYPE_SUBCLASS (1UL << 31)
+
+#define Py_TPFLAGS_DEFAULT ( \
+ Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \
+ 0)
+
+/* NOTE: Some of the following flags reuse lower bits (removed as part of the
+ * Python 3.0 transition). */
+
+/* The following flags are kept for compatibility; in previous
+ * versions they indicated presence of newer tp_* fields on the
+ * type struct.
+ * Starting with 3.8, binary compatibility of C extensions across
+ * feature releases of Python is not supported anymore (except when
+ * using the stable ABI, in which all classes are created dynamically,
+ * using the interpreter's memory layout.)
+ * Note that older extensions using the stable ABI set these flags,
+ * so the bits must not be repurposed.
+ */
+#define Py_TPFLAGS_HAVE_FINALIZE (1UL << 0)
+#define Py_TPFLAGS_HAVE_VERSION_TAG (1UL << 18)
+
+
+/*
+The macros Py_INCREF(op) and Py_DECREF(op) are used to increment or decrement
+reference counts. Py_DECREF calls the object's deallocator function when
+the refcount falls to 0; for
+objects that don't contain references to other objects or heap memory
+this can be the standard function free(). Both macros can be used
+wherever a void expression is allowed. The argument must not be a
+NULL pointer. If it may be NULL, use Py_XINCREF/Py_XDECREF instead.
+The macro _Py_NewReference(op) initialize reference counts to 1, and
+in special builds (Py_REF_DEBUG, Py_TRACE_REFS) performs additional
+bookkeeping appropriate to the special build.
+
+We assume that the reference count field can never overflow; this can
+be proven when the size of the field is the same as the pointer size, so
+we ignore the possibility. Provided a C int is at least 32 bits (which
+is implicitly assumed in many parts of this code), that's enough for
+about 2**31 references to an object.
+
+XXX The following became out of date in Python 2.2, but I'm not sure
+XXX what the full truth is now. Certainly, heap-allocated type objects
+XXX can and should be deallocated.
+Type objects should never be deallocated; the type pointer in an object
+is not considered to be a reference to the type object, to save
+complications in the deallocation function. (This is actually a
+decision that's up to the implementer of each new type so if you want,
+you can count such references to the type object.)
+*/
+
+#ifdef Py_REF_DEBUG
+PyAPI_DATA(Py_ssize_t) _Py_RefTotal;
+PyAPI_FUNC(void) _Py_NegativeRefcount(const char *filename, int lineno,
+ PyObject *op);
+#endif /* Py_REF_DEBUG */
+
+PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
+
+/*
+These are provided as conveniences to Python runtime embedders, so that
+they can have object code that is not dependent on Python compilation flags.
+*/
+PyAPI_FUNC(void) Py_IncRef(PyObject *);
+PyAPI_FUNC(void) Py_DecRef(PyObject *);
+
+// Similar to Py_IncRef() and Py_DecRef() but the argument must be non-NULL.
+// Private functions used by Py_INCREF() and Py_DECREF().
+PyAPI_FUNC(void) _Py_IncRef(PyObject *);
+PyAPI_FUNC(void) _Py_DecRef(PyObject *);
+
+static inline void Py_INCREF(PyObject *op)
+{
+#if defined(Py_REF_DEBUG) && defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030A0000
+ // Stable ABI for Python 3.10 built in debug mode.
+ _Py_IncRef(op);
+#else
+ // Non-limited C API and limited C API for Python 3.9 and older access
+ // directly PyObject.ob_refcnt.
+#ifdef Py_REF_DEBUG
+ _Py_RefTotal++;
+#endif
+ op->ob_refcnt++;
+#endif
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define Py_INCREF(op) Py_INCREF(_PyObject_CAST(op))
+#endif
+
+
+#if defined(Py_REF_DEBUG) && defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030A0000
+// Stable ABI for limited C API version 3.10 of Python debug build
+static inline void Py_DECREF(PyObject *op) {
+ _Py_DecRef(op);
+}
+#define Py_DECREF(op) Py_DECREF(_PyObject_CAST(op))
+
+#elif defined(Py_REF_DEBUG)
+static inline void Py_DECREF(const char *filename, int lineno, PyObject *op)
+{
+ _Py_RefTotal--;
+ if (--op->ob_refcnt != 0) {
+ if (op->ob_refcnt < 0) {
+ _Py_NegativeRefcount(filename, lineno, op);
+ }
+ }
+ else {
+ _Py_Dealloc(op);
+ }
+}
+#define Py_DECREF(op) Py_DECREF(__FILE__, __LINE__, _PyObject_CAST(op))
+
+#else
+static inline void Py_DECREF(PyObject *op)
+{
+ // Non-limited C API and limited C API for Python 3.9 and older access
+ // directly PyObject.ob_refcnt.
+ if (--op->ob_refcnt == 0) {
+ _Py_Dealloc(op);
+ }
+}
+#define Py_DECREF(op) Py_DECREF(_PyObject_CAST(op))
+#endif
+
+
+/* Safely decref `op` and set `op` to NULL, especially useful in tp_clear
+ * and tp_dealloc implementations.
+ *
+ * Note that "the obvious" code can be deadly:
+ *
+ * Py_XDECREF(op);
+ * op = NULL;
+ *
+ * Typically, `op` is something like self->containee, and `self` is done
+ * using its `containee` member. In the code sequence above, suppose
+ * `containee` is non-NULL with a refcount of 1. Its refcount falls to
+ * 0 on the first line, which can trigger an arbitrary amount of code,
+ * possibly including finalizers (like __del__ methods or weakref callbacks)
+ * coded in Python, which in turn can release the GIL and allow other threads
+ * to run, etc. Such code may even invoke methods of `self` again, or cause
+ * cyclic gc to trigger, but-- oops! --self->containee still points to the
+ * object being torn down, and it may be in an insane state while being torn
+ * down. This has in fact been a rich historic source of miserable (rare &
+ * hard-to-diagnose) segfaulting (and other) bugs.
+ *
+ * The safe way is:
+ *
+ * Py_CLEAR(op);
+ *
+ * That arranges to set `op` to NULL _before_ decref'ing, so that any code
+ * triggered as a side-effect of `op` getting torn down no longer believes
+ * `op` points to a valid object.
+ *
+ * There are cases where it's safe to use the naive code, but they're brittle.
+ * For example, if `op` points to a Python integer, you know that destroying
+ * one of those can't cause problems -- but in part that relies on that
+ * Python integers aren't currently weakly referencable. Best practice is
+ * to use Py_CLEAR() even if you can't think of a reason for why you need to.
+ */
+#define Py_CLEAR(op) \
+ do { \
+ PyObject *_py_tmp = _PyObject_CAST(op); \
+ if (_py_tmp != NULL) { \
+ (op) = NULL; \
+ Py_DECREF(_py_tmp); \
+ } \
+ } while (0)
+
+/* Function to use in case the object pointer can be NULL: */
+static inline void Py_XINCREF(PyObject *op)
+{
+ if (op != _Py_NULL) {
+ Py_INCREF(op);
+ }
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define Py_XINCREF(op) Py_XINCREF(_PyObject_CAST(op))
+#endif
+
+static inline void Py_XDECREF(PyObject *op)
+{
+ if (op != _Py_NULL) {
+ Py_DECREF(op);
+ }
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define Py_XDECREF(op) Py_XDECREF(_PyObject_CAST(op))
+#endif
+
+// Create a new strong reference to an object:
+// increment the reference count of the object and return the object.
+PyAPI_FUNC(PyObject*) Py_NewRef(PyObject *obj);
+
+// Similar to Py_NewRef(), but the object can be NULL.
+PyAPI_FUNC(PyObject*) Py_XNewRef(PyObject *obj);
+
+static inline PyObject* _Py_NewRef(PyObject *obj)
+{
+ Py_INCREF(obj);
+ return obj;
+}
+
+static inline PyObject* _Py_XNewRef(PyObject *obj)
+{
+ Py_XINCREF(obj);
+ return obj;
+}
+
+// Py_NewRef() and Py_XNewRef() are exported as functions for the stable ABI.
+// Names overridden with macros by static inline functions for best
+// performances.
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define Py_NewRef(obj) _Py_NewRef(_PyObject_CAST(obj))
+# define Py_XNewRef(obj) _Py_XNewRef(_PyObject_CAST(obj))
+#else
+# define Py_NewRef(obj) _Py_NewRef(obj)
+# define Py_XNewRef(obj) _Py_XNewRef(obj)
+#endif
+
+
+/*
+_Py_NoneStruct is an object of undefined type which can be used in contexts
+where NULL (nil) is not suitable (since NULL often means 'error').
+
+Don't forget to apply Py_INCREF() when returning this value!!!
+*/
+PyAPI_DATA(PyObject) _Py_NoneStruct; /* Don't use this directly */
+#define Py_None (&_Py_NoneStruct)
+
+// Test if an object is the None singleton, the same as "x is None" in Python.
+PyAPI_FUNC(int) Py_IsNone(PyObject *x);
+#define Py_IsNone(x) Py_Is((x), Py_None)
+
+/* Macro for returning Py_None from a function */
+#define Py_RETURN_NONE return Py_NewRef(Py_None)
+
+/*
+Py_NotImplemented is a singleton used to signal that an operation is
+not implemented for a given type combination.
+*/
+PyAPI_DATA(PyObject) _Py_NotImplementedStruct; /* Don't use this directly */
+#define Py_NotImplemented (&_Py_NotImplementedStruct)
+
+/* Macro for returning Py_NotImplemented from a function */
+#define Py_RETURN_NOTIMPLEMENTED return Py_NewRef(Py_NotImplemented)
+
+/* Rich comparison opcodes */
+#define Py_LT 0
+#define Py_LE 1
+#define Py_EQ 2
+#define Py_NE 3
+#define Py_GT 4
+#define Py_GE 5
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000
+/* Result of calling PyIter_Send */
+typedef enum {
+ PYGEN_RETURN = 0,
+ PYGEN_ERROR = -1,
+ PYGEN_NEXT = 1,
+} PySendResult;
+#endif
+
+/*
+ * Macro for implementing rich comparisons
+ *
+ * Needs to be a macro because any C-comparable type can be used.
+ */
+#define Py_RETURN_RICHCOMPARE(val1, val2, op) \
+ do { \
+ switch (op) { \
+ case Py_EQ: if ((val1) == (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
+ case Py_NE: if ((val1) != (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
+ case Py_LT: if ((val1) < (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
+ case Py_GT: if ((val1) > (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
+ case Py_LE: if ((val1) <= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
+ case Py_GE: if ((val1) >= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
+ default: \
+ Py_UNREACHABLE(); \
+ } \
+ } while (0)
+
+
+/*
+More conventions
+================
+
+Argument Checking
+-----------------
+
+Functions that take objects as arguments normally don't check for nil
+arguments, but they do check the type of the argument, and return an
+error if the function doesn't apply to the type.
+
+Failure Modes
+-------------
+
+Functions may fail for a variety of reasons, including running out of
+memory. This is communicated to the caller in two ways: an error string
+is set (see errors.h), and the function result differs: functions that
+normally return a pointer return NULL for failure, functions returning
+an integer return -1 (which could be a legal return value too!), and
+other functions return 0 for success and -1 for failure.
+Callers should always check for errors before using the result. If
+an error was set, the caller must either explicitly clear it, or pass
+the error on to its caller.
+
+Reference Counts
+----------------
+
+It takes a while to get used to the proper usage of reference counts.
+
+Functions that create an object set the reference count to 1; such new
+objects must be stored somewhere or destroyed again with Py_DECREF().
+Some functions that 'store' objects, such as PyTuple_SetItem() and
+PyList_SetItem(),
+don't increment the reference count of the object, since the most
+frequent use is to store a fresh object. Functions that 'retrieve'
+objects, such as PyTuple_GetItem() and PyDict_GetItemString(), also
+don't increment
+the reference count, since most frequently the object is only looked at
+quickly. Thus, to retrieve an object and store it again, the caller
+must call Py_INCREF() explicitly.
+
+NOTE: functions that 'consume' a reference count, like
+PyList_SetItem(), consume the reference even if the object wasn't
+successfully stored, to simplify error handling.
+
+It seems attractive to make other functions that take an object as
+argument consume a reference count; however, this may quickly get
+confusing (even the current practice is already confusing). Consider
+it carefully, it may save lots of calls to Py_INCREF() and Py_DECREF() at
+times.
+*/
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_OBJECT_H
+# include "cpython/object.h"
+# undef Py_CPYTHON_OBJECT_H
+#endif
+
+
+static inline int
+PyType_HasFeature(PyTypeObject *type, unsigned long feature)
+{
+ unsigned long flags;
+#ifdef Py_LIMITED_API
+ // PyTypeObject is opaque in the limited C API
+ flags = PyType_GetFlags(type);
+#else
+ flags = type->tp_flags;
+#endif
+ return ((flags & feature) != 0);
+}
+
+#define PyType_FastSubclass(type, flag) PyType_HasFeature(type, flag)
+
+static inline int PyType_Check(PyObject *op) {
+ return PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS);
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyType_Check(op) PyType_Check(_PyObject_CAST(op))
+#endif
+
+#define _PyType_CAST(op) \
+ (assert(PyType_Check(op)), _Py_CAST(PyTypeObject*, (op)))
+
+static inline int PyType_CheckExact(PyObject *op) {
+ return Py_IS_TYPE(op, &PyType_Type);
+}
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define PyType_CheckExact(op) PyType_CheckExact(_PyObject_CAST(op))
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif // !Py_OBJECT_H
diff --git a/include/python3.11/objimpl.h b/include/python3.11/objimpl.h
new file mode 100644
index 0000000..4fa670e
--- /dev/null
+++ b/include/python3.11/objimpl.h
@@ -0,0 +1,215 @@
+/* The PyObject_ memory family: high-level object memory interfaces.
+ See pymem.h for the low-level PyMem_ family.
+*/
+
+#ifndef Py_OBJIMPL_H
+#define Py_OBJIMPL_H
+
+#include "pymem.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* BEWARE:
+
+ Each interface exports both functions and macros. Extension modules should
+ use the functions, to ensure binary compatibility across Python versions.
+ Because the Python implementation is free to change internal details, and
+ the macros may (or may not) expose details for speed, if you do use the
+ macros you must recompile your extensions with each Python release.
+
+ Never mix calls to PyObject_ memory functions with calls to the platform
+ malloc/realloc/ calloc/free, or with calls to PyMem_.
+*/
+
+/*
+Functions and macros for modules that implement new object types.
+
+ - PyObject_New(type, typeobj) allocates memory for a new object of the given
+ type, and initializes part of it. 'type' must be the C structure type used
+ to represent the object, and 'typeobj' the address of the corresponding
+ type object. Reference count and type pointer are filled in; the rest of
+ the bytes of the object are *undefined*! The resulting expression type is
+ 'type *'. The size of the object is determined by the tp_basicsize field
+ of the type object.
+
+ - PyObject_NewVar(type, typeobj, n) is similar but allocates a variable-size
+ object with room for n items. In addition to the refcount and type pointer
+ fields, this also fills in the ob_size field.
+
+ - PyObject_Free(op) releases the memory allocated for an object. It does not
+ run a destructor -- it only frees the memory. PyObject_Free is identical.
+
+ - PyObject_Init(op, typeobj) and PyObject_InitVar(op, typeobj, n) don't
+ allocate memory. Instead of a 'type' parameter, they take a pointer to a
+ new object (allocated by an arbitrary allocator), and initialize its object
+ header fields.
+
+Note that objects created with PyObject_{New, NewVar} are allocated using the
+specialized Python allocator (implemented in obmalloc.c), if WITH_PYMALLOC is
+enabled. In addition, a special debugging allocator is used if Py_DEBUG
+macro is also defined.
+
+In case a specific form of memory management is needed (for example, if you
+must use the platform malloc heap(s), or shared memory, or C++ local storage or
+operator new), you must first allocate the object with your custom allocator,
+then pass its pointer to PyObject_{Init, InitVar} for filling in its Python-
+specific fields: reference count, type pointer, possibly others. You should
+be aware that Python has no control over these objects because they don't
+cooperate with the Python memory manager. Such objects may not be eligible
+for automatic garbage collection and you have to make sure that they are
+released accordingly whenever their destructor gets called (cf. the specific
+form of memory management you're using).
+
+Unless you have specific memory management requirements, use
+PyObject_{New, NewVar, Del}.
+*/
+
+/*
+ * Raw object memory interface
+ * ===========================
+ */
+
+/* Functions to call the same malloc/realloc/free as used by Python's
+ object allocator. If WITH_PYMALLOC is enabled, these may differ from
+ the platform malloc/realloc/free. The Python object allocator is
+ designed for fast, cache-conscious allocation of many "small" objects,
+ and with low hidden memory overhead.
+
+ PyObject_Malloc(0) returns a unique non-NULL pointer if possible.
+
+ PyObject_Realloc(NULL, n) acts like PyObject_Malloc(n).
+ PyObject_Realloc(p != NULL, 0) does not return NULL, or free the memory
+ at p.
+
+ Returned pointers must be checked for NULL explicitly; no action is
+ performed on failure other than to return NULL (no warning it printed, no
+ exception is set, etc).
+
+ For allocating objects, use PyObject_{New, NewVar} instead whenever
+ possible. The PyObject_{Malloc, Realloc, Free} family is exposed
+ so that you can exploit Python's small-block allocator for non-object
+ uses. If you must use these routines to allocate object memory, make sure
+ the object gets initialized via PyObject_{Init, InitVar} after obtaining
+ the raw memory.
+*/
+PyAPI_FUNC(void *) PyObject_Malloc(size_t size);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
+PyAPI_FUNC(void *) PyObject_Calloc(size_t nelem, size_t elsize);
+#endif
+PyAPI_FUNC(void *) PyObject_Realloc(void *ptr, size_t new_size);
+PyAPI_FUNC(void) PyObject_Free(void *ptr);
+
+
+// Deprecated aliases only kept for backward compatibility.
+// PyObject_Del and PyObject_DEL are defined with no parameter to be able to
+// use them as function pointers (ex: tp_free = PyObject_Del).
+#define PyObject_MALLOC PyObject_Malloc
+#define PyObject_REALLOC PyObject_Realloc
+#define PyObject_FREE PyObject_Free
+#define PyObject_Del PyObject_Free
+#define PyObject_DEL PyObject_Free
+
+
+/*
+ * Generic object allocator interface
+ * ==================================
+ */
+
+/* Functions */
+PyAPI_FUNC(PyObject *) PyObject_Init(PyObject *, PyTypeObject *);
+PyAPI_FUNC(PyVarObject *) PyObject_InitVar(PyVarObject *,
+ PyTypeObject *, Py_ssize_t);
+
+#define PyObject_INIT(op, typeobj) \
+ PyObject_Init(_PyObject_CAST(op), (typeobj))
+#define PyObject_INIT_VAR(op, typeobj, size) \
+ PyObject_InitVar(_PyVarObject_CAST(op), (typeobj), (size))
+
+
+PyAPI_FUNC(PyObject *) _PyObject_New(PyTypeObject *);
+PyAPI_FUNC(PyVarObject *) _PyObject_NewVar(PyTypeObject *, Py_ssize_t);
+
+#define PyObject_New(type, typeobj) ((type *)_PyObject_New(typeobj))
+
+// Alias to PyObject_New(). In Python 3.8, PyObject_NEW() called directly
+// PyObject_MALLOC() with _PyObject_SIZE().
+#define PyObject_NEW(type, typeobj) PyObject_New(type, typeobj)
+
+#define PyObject_NewVar(type, typeobj, n) \
+ ( (type *) _PyObject_NewVar((typeobj), (n)) )
+
+// Alias to PyObject_NewVar(). In Python 3.8, PyObject_NEW_VAR() called
+// directly PyObject_MALLOC() with _PyObject_VAR_SIZE().
+#define PyObject_NEW_VAR(type, typeobj, n) PyObject_NewVar(type, typeobj, n)
+
+
+/*
+ * Garbage Collection Support
+ * ==========================
+ */
+
+/* C equivalent of gc.collect(). */
+PyAPI_FUNC(Py_ssize_t) PyGC_Collect(void);
+/* C API for controlling the state of the garbage collector */
+PyAPI_FUNC(int) PyGC_Enable(void);
+PyAPI_FUNC(int) PyGC_Disable(void);
+PyAPI_FUNC(int) PyGC_IsEnabled(void);
+
+/* Test if a type has a GC head */
+#define PyType_IS_GC(t) PyType_HasFeature((t), Py_TPFLAGS_HAVE_GC)
+
+PyAPI_FUNC(PyVarObject *) _PyObject_GC_Resize(PyVarObject *, Py_ssize_t);
+#define PyObject_GC_Resize(type, op, n) \
+ ( (type *) _PyObject_GC_Resize(_PyVarObject_CAST(op), (n)) )
+
+
+
+PyAPI_FUNC(PyObject *) _PyObject_GC_New(PyTypeObject *);
+PyAPI_FUNC(PyVarObject *) _PyObject_GC_NewVar(PyTypeObject *, Py_ssize_t);
+
+/* Tell the GC to track this object.
+ *
+ * See also private _PyObject_GC_TRACK() macro. */
+PyAPI_FUNC(void) PyObject_GC_Track(void *);
+
+/* Tell the GC to stop tracking this object.
+ *
+ * See also private _PyObject_GC_UNTRACK() macro. */
+PyAPI_FUNC(void) PyObject_GC_UnTrack(void *);
+
+PyAPI_FUNC(void) PyObject_GC_Del(void *);
+
+#define PyObject_GC_New(type, typeobj) \
+ _Py_CAST(type*, _PyObject_GC_New(typeobj))
+#define PyObject_GC_NewVar(type, typeobj, n) \
+ _Py_CAST(type*, _PyObject_GC_NewVar((typeobj), (n)))
+
+PyAPI_FUNC(int) PyObject_GC_IsTracked(PyObject *);
+PyAPI_FUNC(int) PyObject_GC_IsFinalized(PyObject *);
+
+/* Utility macro to help write tp_traverse functions.
+ * To use this macro, the tp_traverse function must name its arguments
+ * "visit" and "arg". This is intended to keep tp_traverse functions
+ * looking as much alike as possible.
+ */
+#define Py_VISIT(op) \
+ do { \
+ if (op) { \
+ int vret = visit(_PyObject_CAST(op), arg); \
+ if (vret) \
+ return vret; \
+ } \
+ } while (0)
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_OBJIMPL_H
+# include "cpython/objimpl.h"
+# undef Py_CPYTHON_OBJIMPL_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_OBJIMPL_H */
diff --git a/include/python3.11/opcode.h b/include/python3.11/opcode.h
new file mode 100644
index 0000000..084d34b
--- /dev/null
+++ b/include/python3.11/opcode.h
@@ -0,0 +1,236 @@
+// Auto-generated by Tools/scripts/generate_opcode_h.py from Lib/opcode.py
+
+#ifndef Py_OPCODE_H
+#define Py_OPCODE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Instruction opcodes for compiled code */
+#define CACHE 0
+#define POP_TOP 1
+#define PUSH_NULL 2
+#define NOP 9
+#define UNARY_POSITIVE 10
+#define UNARY_NEGATIVE 11
+#define UNARY_NOT 12
+#define UNARY_INVERT 15
+#define BINARY_SUBSCR 25
+#define GET_LEN 30
+#define MATCH_MAPPING 31
+#define MATCH_SEQUENCE 32
+#define MATCH_KEYS 33
+#define PUSH_EXC_INFO 35
+#define CHECK_EXC_MATCH 36
+#define CHECK_EG_MATCH 37
+#define WITH_EXCEPT_START 49
+#define GET_AITER 50
+#define GET_ANEXT 51
+#define BEFORE_ASYNC_WITH 52
+#define BEFORE_WITH 53
+#define END_ASYNC_FOR 54
+#define STORE_SUBSCR 60
+#define DELETE_SUBSCR 61
+#define GET_ITER 68
+#define GET_YIELD_FROM_ITER 69
+#define PRINT_EXPR 70
+#define LOAD_BUILD_CLASS 71
+#define LOAD_ASSERTION_ERROR 74
+#define RETURN_GENERATOR 75
+#define LIST_TO_TUPLE 82
+#define RETURN_VALUE 83
+#define IMPORT_STAR 84
+#define SETUP_ANNOTATIONS 85
+#define YIELD_VALUE 86
+#define ASYNC_GEN_WRAP 87
+#define PREP_RERAISE_STAR 88
+#define POP_EXCEPT 89
+#define HAVE_ARGUMENT 90
+#define STORE_NAME 90
+#define DELETE_NAME 91
+#define UNPACK_SEQUENCE 92
+#define FOR_ITER 93
+#define UNPACK_EX 94
+#define STORE_ATTR 95
+#define DELETE_ATTR 96
+#define STORE_GLOBAL 97
+#define DELETE_GLOBAL 98
+#define SWAP 99
+#define LOAD_CONST 100
+#define LOAD_NAME 101
+#define BUILD_TUPLE 102
+#define BUILD_LIST 103
+#define BUILD_SET 104
+#define BUILD_MAP 105
+#define LOAD_ATTR 106
+#define COMPARE_OP 107
+#define IMPORT_NAME 108
+#define IMPORT_FROM 109
+#define JUMP_FORWARD 110
+#define JUMP_IF_FALSE_OR_POP 111
+#define JUMP_IF_TRUE_OR_POP 112
+#define POP_JUMP_FORWARD_IF_FALSE 114
+#define POP_JUMP_FORWARD_IF_TRUE 115
+#define LOAD_GLOBAL 116
+#define IS_OP 117
+#define CONTAINS_OP 118
+#define RERAISE 119
+#define COPY 120
+#define BINARY_OP 122
+#define SEND 123
+#define LOAD_FAST 124
+#define STORE_FAST 125
+#define DELETE_FAST 126
+#define POP_JUMP_FORWARD_IF_NOT_NONE 128
+#define POP_JUMP_FORWARD_IF_NONE 129
+#define RAISE_VARARGS 130
+#define GET_AWAITABLE 131
+#define MAKE_FUNCTION 132
+#define BUILD_SLICE 133
+#define JUMP_BACKWARD_NO_INTERRUPT 134
+#define MAKE_CELL 135
+#define LOAD_CLOSURE 136
+#define LOAD_DEREF 137
+#define STORE_DEREF 138
+#define DELETE_DEREF 139
+#define JUMP_BACKWARD 140
+#define CALL_FUNCTION_EX 142
+#define EXTENDED_ARG 144
+#define LIST_APPEND 145
+#define SET_ADD 146
+#define MAP_ADD 147
+#define LOAD_CLASSDEREF 148
+#define COPY_FREE_VARS 149
+#define RESUME 151
+#define MATCH_CLASS 152
+#define FORMAT_VALUE 155
+#define BUILD_CONST_KEY_MAP 156
+#define BUILD_STRING 157
+#define LOAD_METHOD 160
+#define LIST_EXTEND 162
+#define SET_UPDATE 163
+#define DICT_MERGE 164
+#define DICT_UPDATE 165
+#define PRECALL 166
+#define CALL 171
+#define KW_NAMES 172
+#define POP_JUMP_BACKWARD_IF_NOT_NONE 173
+#define POP_JUMP_BACKWARD_IF_NONE 174
+#define POP_JUMP_BACKWARD_IF_FALSE 175
+#define POP_JUMP_BACKWARD_IF_TRUE 176
+#define BINARY_OP_ADAPTIVE 3
+#define BINARY_OP_ADD_FLOAT 4
+#define BINARY_OP_ADD_INT 5
+#define BINARY_OP_ADD_UNICODE 6
+#define BINARY_OP_INPLACE_ADD_UNICODE 7
+#define BINARY_OP_MULTIPLY_FLOAT 8
+#define BINARY_OP_MULTIPLY_INT 13
+#define BINARY_OP_SUBTRACT_FLOAT 14
+#define BINARY_OP_SUBTRACT_INT 16
+#define BINARY_SUBSCR_ADAPTIVE 17
+#define BINARY_SUBSCR_DICT 18
+#define BINARY_SUBSCR_GETITEM 19
+#define BINARY_SUBSCR_LIST_INT 20
+#define BINARY_SUBSCR_TUPLE_INT 21
+#define CALL_ADAPTIVE 22
+#define CALL_PY_EXACT_ARGS 23
+#define CALL_PY_WITH_DEFAULTS 24
+#define COMPARE_OP_ADAPTIVE 26
+#define COMPARE_OP_FLOAT_JUMP 27
+#define COMPARE_OP_INT_JUMP 28
+#define COMPARE_OP_STR_JUMP 29
+#define EXTENDED_ARG_QUICK 34
+#define JUMP_BACKWARD_QUICK 38
+#define LOAD_ATTR_ADAPTIVE 39
+#define LOAD_ATTR_INSTANCE_VALUE 40
+#define LOAD_ATTR_MODULE 41
+#define LOAD_ATTR_SLOT 42
+#define LOAD_ATTR_WITH_HINT 43
+#define LOAD_CONST__LOAD_FAST 44
+#define LOAD_FAST__LOAD_CONST 45
+#define LOAD_FAST__LOAD_FAST 46
+#define LOAD_GLOBAL_ADAPTIVE 47
+#define LOAD_GLOBAL_BUILTIN 48
+#define LOAD_GLOBAL_MODULE 55
+#define LOAD_METHOD_ADAPTIVE 56
+#define LOAD_METHOD_CLASS 57
+#define LOAD_METHOD_MODULE 58
+#define LOAD_METHOD_NO_DICT 59
+#define LOAD_METHOD_WITH_DICT 62
+#define LOAD_METHOD_WITH_VALUES 63
+#define PRECALL_ADAPTIVE 64
+#define PRECALL_BOUND_METHOD 65
+#define PRECALL_BUILTIN_CLASS 66
+#define PRECALL_BUILTIN_FAST_WITH_KEYWORDS 67
+#define PRECALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS 72
+#define PRECALL_NO_KW_BUILTIN_FAST 73
+#define PRECALL_NO_KW_BUILTIN_O 76
+#define PRECALL_NO_KW_ISINSTANCE 77
+#define PRECALL_NO_KW_LEN 78
+#define PRECALL_NO_KW_LIST_APPEND 79
+#define PRECALL_NO_KW_METHOD_DESCRIPTOR_FAST 80
+#define PRECALL_NO_KW_METHOD_DESCRIPTOR_NOARGS 81
+#define PRECALL_NO_KW_METHOD_DESCRIPTOR_O 113
+#define PRECALL_NO_KW_STR_1 121
+#define PRECALL_NO_KW_TUPLE_1 127
+#define PRECALL_NO_KW_TYPE_1 141
+#define PRECALL_PYFUNC 143
+#define RESUME_QUICK 150
+#define STORE_ATTR_ADAPTIVE 153
+#define STORE_ATTR_INSTANCE_VALUE 154
+#define STORE_ATTR_SLOT 158
+#define STORE_ATTR_WITH_HINT 159
+#define STORE_FAST__LOAD_FAST 161
+#define STORE_FAST__STORE_FAST 167
+#define STORE_SUBSCR_ADAPTIVE 168
+#define STORE_SUBSCR_DICT 169
+#define STORE_SUBSCR_LIST_INT 170
+#define UNPACK_SEQUENCE_ADAPTIVE 177
+#define UNPACK_SEQUENCE_LIST 178
+#define UNPACK_SEQUENCE_TUPLE 179
+#define UNPACK_SEQUENCE_TWO_TUPLE 180
+#define DO_TRACING 255
+
+#define HAS_CONST(op) (false\
+ || ((op) == 100) \
+ || ((op) == 172) \
+ )
+
+#define NB_ADD 0
+#define NB_AND 1
+#define NB_FLOOR_DIVIDE 2
+#define NB_LSHIFT 3
+#define NB_MATRIX_MULTIPLY 4
+#define NB_MULTIPLY 5
+#define NB_REMAINDER 6
+#define NB_OR 7
+#define NB_POWER 8
+#define NB_RSHIFT 9
+#define NB_SUBTRACT 10
+#define NB_TRUE_DIVIDE 11
+#define NB_XOR 12
+#define NB_INPLACE_ADD 13
+#define NB_INPLACE_AND 14
+#define NB_INPLACE_FLOOR_DIVIDE 15
+#define NB_INPLACE_LSHIFT 16
+#define NB_INPLACE_MATRIX_MULTIPLY 17
+#define NB_INPLACE_MULTIPLY 18
+#define NB_INPLACE_REMAINDER 19
+#define NB_INPLACE_OR 20
+#define NB_INPLACE_POWER 21
+#define NB_INPLACE_RSHIFT 22
+#define NB_INPLACE_SUBTRACT 23
+#define NB_INPLACE_TRUE_DIVIDE 24
+#define NB_INPLACE_XOR 25
+
+#define HAS_ARG(op) ((op) >= HAVE_ARGUMENT)
+
+/* Reserve some bytecodes for internal use in the compiler.
+ * The value of 240 is arbitrary. */
+#define IS_ARTIFICIAL(op) ((op) > 240)
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_OPCODE_H */
diff --git a/include/python3.10/osdefs.h b/include/python3.11/osdefs.h
similarity index 100%
rename from include/python3.10/osdefs.h
rename to include/python3.11/osdefs.h
diff --git a/include/python3.10/osmodule.h b/include/python3.11/osmodule.h
similarity index 100%
rename from include/python3.10/osmodule.h
rename to include/python3.11/osmodule.h
diff --git a/include/python3.11/patchlevel.h b/include/python3.11/patchlevel.h
new file mode 100644
index 0000000..a5b73cd
--- /dev/null
+++ b/include/python3.11/patchlevel.h
@@ -0,0 +1,35 @@
+
+/* Python version identification scheme.
+
+ When the major or minor version changes, the VERSION variable in
+ configure.ac must also be changed.
+
+ There is also (independent) API version information in modsupport.h.
+*/
+
+/* Values for PY_RELEASE_LEVEL */
+#define PY_RELEASE_LEVEL_ALPHA 0xA
+#define PY_RELEASE_LEVEL_BETA 0xB
+#define PY_RELEASE_LEVEL_GAMMA 0xC /* For release candidates */
+#define PY_RELEASE_LEVEL_FINAL 0xF /* Serial should be 0 here */
+ /* Higher for patch releases */
+
+/* Version parsed out into numeric values */
+/*--start constants--*/
+#define PY_MAJOR_VERSION 3
+#define PY_MINOR_VERSION 11
+#define PY_MICRO_VERSION 4
+#define PY_RELEASE_LEVEL PY_RELEASE_LEVEL_FINAL
+#define PY_RELEASE_SERIAL 0
+
+/* Version as a string */
+#define PY_VERSION "3.11.4"
+/*--end constants--*/
+
+/* Version as a single 4-byte hex number, e.g. 0x010502B2 == 1.5.2b2.
+ Use this for numeric comparisons, e.g. #if PY_VERSION_HEX >= ... */
+#define PY_VERSION_HEX ((PY_MAJOR_VERSION << 24) | \
+ (PY_MINOR_VERSION << 16) | \
+ (PY_MICRO_VERSION << 8) | \
+ (PY_RELEASE_LEVEL << 4) | \
+ (PY_RELEASE_SERIAL << 0))
diff --git a/include/python3.11/py_curses.h b/include/python3.11/py_curses.h
new file mode 100644
index 0000000..b2c7f1b
--- /dev/null
+++ b/include/python3.11/py_curses.h
@@ -0,0 +1,99 @@
+
+#ifndef Py_CURSES_H
+#define Py_CURSES_H
+
+#ifdef __APPLE__
+/*
+** On Mac OS X 10.2 [n]curses.h and stdlib.h use different guards
+** against multiple definition of wchar_t.
+*/
+#ifdef _BSD_WCHAR_T_DEFINED_
+#define _WCHAR_T
+#endif
+#endif /* __APPLE__ */
+
+/* On FreeBSD, [n]curses.h and stdlib.h/wchar.h use different guards
+ against multiple definition of wchar_t and wint_t. */
+#if defined(__FreeBSD__) && defined(_XOPEN_SOURCE_EXTENDED)
+# ifndef __wchar_t
+# define __wchar_t
+# endif
+# ifndef __wint_t
+# define __wint_t
+# endif
+#endif
+
+#if !defined(HAVE_CURSES_IS_PAD) && defined(WINDOW_HAS_FLAGS)
+/* The following definition is necessary for ncurses 5.7; without it,
+ some of [n]curses.h set NCURSES_OPAQUE to 1, and then Python
+ can't get at the WINDOW flags field. */
+#define NCURSES_OPAQUE 0
+#endif
+
+#ifdef HAVE_NCURSES_H
+#include <ncurses.h>
+#else
+#include <curses.h>
+#endif
+
+#ifdef HAVE_NCURSES_H
+/* configure was checking <curses.h>, but we will
+ use <ncurses.h>, which has some or all these features. */
+#if !defined(WINDOW_HAS_FLAGS) && !(NCURSES_OPAQUE+0)
+#define WINDOW_HAS_FLAGS 1
+#endif
+#if !defined(HAVE_CURSES_IS_PAD) && NCURSES_VERSION_PATCH+0 >= 20090906
+#define HAVE_CURSES_IS_PAD 1
+#endif
+#ifndef MVWDELCH_IS_EXPRESSION
+#define MVWDELCH_IS_EXPRESSION 1
+#endif
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define PyCurses_API_pointers 4
+
+/* Type declarations */
+
+typedef struct {
+ PyObject_HEAD
+ WINDOW *win;
+ char *encoding;
+} PyCursesWindowObject;
+
+#define PyCursesWindow_Check(v) Py_IS_TYPE(v, &PyCursesWindow_Type)
+
+#define PyCurses_CAPSULE_NAME "_curses._C_API"
+
+
+#ifdef CURSES_MODULE
+/* This section is used when compiling _cursesmodule.c */
+
+#else
+/* This section is used in modules that use the _cursesmodule API */
+
+static void **PyCurses_API;
+
+#define PyCursesWindow_Type (*_PyType_CAST(PyCurses_API[0]))
+#define PyCursesSetupTermCalled {if (! ((int (*)(void))PyCurses_API[1]) () ) return NULL;}
+#define PyCursesInitialised {if (! ((int (*)(void))PyCurses_API[2]) () ) return NULL;}
+#define PyCursesInitialisedColor {if (! ((int (*)(void))PyCurses_API[3]) () ) return NULL;}
+
+#define import_curses() \
+ PyCurses_API = (void **)PyCapsule_Import(PyCurses_CAPSULE_NAME, 1);
+
+#endif
+
+/* general error messages */
+static const char catchall_ERR[] = "curses function returned ERR";
+static const char catchall_NULL[] = "curses function returned NULL";
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !defined(Py_CURSES_H) */
+
diff --git a/include/python3.11/pybuffer.h b/include/python3.11/pybuffer.h
new file mode 100644
index 0000000..6893505
--- /dev/null
+++ b/include/python3.11/pybuffer.h
@@ -0,0 +1,142 @@
+/* Public Py_buffer API */
+
+#ifndef Py_BUFFER_H
+#define Py_BUFFER_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030b0000
+
+/* === New Buffer API ============================================
+ * Limited API and stable ABI since Python 3.11
+ *
+ * Py_buffer struct layout and size is now part of the stable abi3. The
+ * struct layout and size must not be changed in any way, as it would
+ * break the ABI.
+ *
+ */
+
+typedef struct {
+ void *buf;
+ PyObject *obj; /* owned reference */
+ Py_ssize_t len;
+ Py_ssize_t itemsize; /* This is Py_ssize_t so it can be
+ pointed to by strides in simple case.*/
+ int readonly;
+ int ndim;
+ char *format;
+ Py_ssize_t *shape;
+ Py_ssize_t *strides;
+ Py_ssize_t *suboffsets;
+ void *internal;
+} Py_buffer;
+
+/* Return 1 if the getbuffer function is available, otherwise return 0. */
+PyAPI_FUNC(int) PyObject_CheckBuffer(PyObject *obj);
+
+/* This is a C-API version of the getbuffer function call. It checks
+ to make sure object has the required function pointer and issues the
+ call.
+
+ Returns -1 and raises an error on failure and returns 0 on success. */
+PyAPI_FUNC(int) PyObject_GetBuffer(PyObject *obj, Py_buffer *view,
+ int flags);
+
+/* Get the memory area pointed to by the indices for the buffer given.
+ Note that view->ndim is the assumed size of indices. */
+PyAPI_FUNC(void *) PyBuffer_GetPointer(const Py_buffer *view, const Py_ssize_t *indices);
+
+/* Return the implied itemsize of the data-format area from a
+ struct-style description. */
+PyAPI_FUNC(Py_ssize_t) PyBuffer_SizeFromFormat(const char *format);
+
+/* Implementation in memoryobject.c */
+PyAPI_FUNC(int) PyBuffer_ToContiguous(void *buf, const Py_buffer *view,
+ Py_ssize_t len, char order);
+
+PyAPI_FUNC(int) PyBuffer_FromContiguous(const Py_buffer *view, const void *buf,
+ Py_ssize_t len, char order);
+
+/* Copy len bytes of data from the contiguous chunk of memory
+ pointed to by buf into the buffer exported by obj. Return
+ 0 on success and return -1 and raise a PyBuffer_Error on
+ error (i.e. the object does not have a buffer interface or
+ it is not working).
+
+ If fort is 'F', then if the object is multi-dimensional,
+ then the data will be copied into the array in
+ Fortran-style (first dimension varies the fastest). If
+ fort is 'C', then the data will be copied into the array
+ in C-style (last dimension varies the fastest). If fort
+ is 'A', then it does not matter and the copy will be made
+ in whatever way is more efficient. */
+PyAPI_FUNC(int) PyObject_CopyData(PyObject *dest, PyObject *src);
+
+/* Copy the data from the src buffer to the buffer of destination. */
+PyAPI_FUNC(int) PyBuffer_IsContiguous(const Py_buffer *view, char fort);
+
+/*Fill the strides array with byte-strides of a contiguous
+ (Fortran-style if fort is 'F' or C-style otherwise)
+ array of the given shape with the given number of bytes
+ per element. */
+PyAPI_FUNC(void) PyBuffer_FillContiguousStrides(int ndims,
+ Py_ssize_t *shape,
+ Py_ssize_t *strides,
+ int itemsize,
+ char fort);
+
+/* Fills in a buffer-info structure correctly for an exporter
+ that can only share a contiguous chunk of memory of
+ "unsigned bytes" of the given length.
+
+ Returns 0 on success and -1 (with raising an error) on error. */
+PyAPI_FUNC(int) PyBuffer_FillInfo(Py_buffer *view, PyObject *o, void *buf,
+ Py_ssize_t len, int readonly,
+ int flags);
+
+/* Releases a Py_buffer obtained from getbuffer ParseTuple's "s*". */
+PyAPI_FUNC(void) PyBuffer_Release(Py_buffer *view);
+
+/* Maximum number of dimensions */
+#define PyBUF_MAX_NDIM 64
+
+/* Flags for getting buffers */
+#define PyBUF_SIMPLE 0
+#define PyBUF_WRITABLE 0x0001
+
+#ifndef Py_LIMITED_API
+/* we used to include an E, backwards compatible alias */
+#define PyBUF_WRITEABLE PyBUF_WRITABLE
+#endif
+
+#define PyBUF_FORMAT 0x0004
+#define PyBUF_ND 0x0008
+#define PyBUF_STRIDES (0x0010 | PyBUF_ND)
+#define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES)
+#define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES)
+#define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES)
+#define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES)
+
+#define PyBUF_CONTIG (PyBUF_ND | PyBUF_WRITABLE)
+#define PyBUF_CONTIG_RO (PyBUF_ND)
+
+#define PyBUF_STRIDED (PyBUF_STRIDES | PyBUF_WRITABLE)
+#define PyBUF_STRIDED_RO (PyBUF_STRIDES)
+
+#define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_WRITABLE | PyBUF_FORMAT)
+#define PyBUF_RECORDS_RO (PyBUF_STRIDES | PyBUF_FORMAT)
+
+#define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_WRITABLE | PyBUF_FORMAT)
+#define PyBUF_FULL_RO (PyBUF_INDIRECT | PyBUF_FORMAT)
+
+
+#define PyBUF_READ 0x100
+#define PyBUF_WRITE 0x200
+
+#endif /* !Py_LIMITED_API || Py_LIMITED_API >= 3.11 */
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* Py_BUFFER_H */
diff --git a/include/python3.10/pycapsule.h b/include/python3.11/pycapsule.h
similarity index 100%
rename from include/python3.10/pycapsule.h
rename to include/python3.11/pycapsule.h
diff --git a/include/python3.11/pyconfig.h b/include/python3.11/pyconfig.h
new file mode 100644
index 0000000..1168c78
--- /dev/null
+++ b/include/python3.11/pyconfig.h
@@ -0,0 +1,1853 @@
+/* pyconfig.h. Generated from pyconfig.h.in by configure. */
+/* pyconfig.h.in. Generated from configure.ac by autoheader. */
+
+
+#ifndef Py_PYCONFIG_H
+#define Py_PYCONFIG_H
+
+
+/* Define if building universal (internal helper macro) */
+/* #undef AC_APPLE_UNIVERSAL_BUILD */
+
+/* BUILD_GNU_TYPE + AIX_BUILDDATE are used to construct the PEP425 tag of the
+ build system. */
+/* #undef AIX_BUILDDATE */
+
+/* Define for AIX if your compiler is a genuine IBM xlC/xlC_r and you want
+ support for AIX C++ shared extension modules. */
+/* #undef AIX_GENUINE_CPLUSPLUS */
+
+/* The normal alignment of `long', in bytes. */
+#define ALIGNOF_LONG 8
+
+/* The normal alignment of `size_t', in bytes. */
+#define ALIGNOF_SIZE_T 8
+
+/* Alternative SOABI used in debug build to load C extensions built in release
+ mode */
+/* #undef ALT_SOABI */
+
+/* The Android API level. */
+/* #undef ANDROID_API_LEVEL */
+
+/* Define if C doubles are 64-bit IEEE 754 binary format, stored in ARM
+ mixed-endian order (byte order 45670123) */
+/* #undef DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754 */
+
+/* Define if C doubles are 64-bit IEEE 754 binary format, stored with the most
+ significant byte first */
+/* #undef DOUBLE_IS_BIG_ENDIAN_IEEE754 */
+
+/* Define if C doubles are 64-bit IEEE 754 binary format, stored with the
+ least significant byte first */
+#define DOUBLE_IS_LITTLE_ENDIAN_IEEE754 1
+
+/* Define if --enable-ipv6 is specified */
+#define ENABLE_IPV6 1
+
+/* Define to 1 if your system stores words within floats with the most
+ significant word first */
+/* #undef FLOAT_WORDS_BIGENDIAN */
+
+/* Define if getpgrp() must be called as getpgrp(0). */
+/* #undef GETPGRP_HAVE_ARG */
+
+/* Define if you have the 'accept' function. */
+#define HAVE_ACCEPT 1
+
+/* Define to 1 if you have the `accept4' function. */
+#define HAVE_ACCEPT4 1
+
+/* Define to 1 if you have the `acosh' function. */
+#define HAVE_ACOSH 1
+
+/* struct addrinfo (netdb.h) */
+#define HAVE_ADDRINFO 1
+
+/* Define to 1 if you have the `alarm' function. */
+#define HAVE_ALARM 1
+
+/* Define if aligned memory access is required */
+/* #undef HAVE_ALIGNED_REQUIRED */
+
+/* Define to 1 if you have the <alloca.h> header file. */
+#define HAVE_ALLOCA_H 1
+
+/* Define this if your time.h defines altzone. */
+/* #undef HAVE_ALTZONE */
+
+/* Define to 1 if you have the `asinh' function. */
+#define HAVE_ASINH 1
+
+/* Define to 1 if you have the <asm/types.h> header file. */
+#define HAVE_ASM_TYPES_H 1
+
+/* Define to 1 if you have the `atanh' function. */
+#define HAVE_ATANH 1
+
+/* Define if you have the 'bind' function. */
+#define HAVE_BIND 1
+
+/* Define to 1 if you have the `bind_textdomain_codeset' function. */
+#define HAVE_BIND_TEXTDOMAIN_CODESET 1
+
+/* Define to 1 if you have the <bluetooth/bluetooth.h> header file. */
+/* #undef HAVE_BLUETOOTH_BLUETOOTH_H */
+
+/* Define to 1 if you have the <bluetooth.h> header file. */
+/* #undef HAVE_BLUETOOTH_H */
+
+/* Define if mbstowcs(NULL, "text", 0) does not return the number of wide
+ chars that would be converted. */
+/* #undef HAVE_BROKEN_MBSTOWCS */
+
+/* Define if nice() returns success/failure instead of the new priority. */
+/* #undef HAVE_BROKEN_NICE */
+
+/* Define if the system reports an invalid PIPE_BUF value. */
+/* #undef HAVE_BROKEN_PIPE_BUF */
+
+/* Define if poll() sets errno on invalid file descriptors. */
+/* #undef HAVE_BROKEN_POLL */
+
+/* Define if the Posix semaphores do not work on your system */
+/* #undef HAVE_BROKEN_POSIX_SEMAPHORES */
+
+/* Define if pthread_sigmask() does not work on your system. */
+/* #undef HAVE_BROKEN_PTHREAD_SIGMASK */
+
+/* define to 1 if your sem_getvalue is broken. */
+/* #undef HAVE_BROKEN_SEM_GETVALUE */
+
+/* Define if 'unsetenv' does not return an int. */
+/* #undef HAVE_BROKEN_UNSETENV */
+
+/* Has builtin __atomic_load_n() and __atomic_store_n() functions */
+#define HAVE_BUILTIN_ATOMIC 1
+
+/* Define to 1 if you have the <bzlib.h> header file. */
+#define HAVE_BZLIB_H 1
+
+/* Define to 1 if you have the 'chflags' function. */
+/* #undef HAVE_CHFLAGS */
+
+/* Define to 1 if you have the `chmod' function. */
+#define HAVE_CHMOD 1
+
+/* Define to 1 if you have the `chown' function. */
+#define HAVE_CHOWN 1
+
+/* Define if you have the 'chroot' function. */
+#define HAVE_CHROOT 1
+
+/* Define to 1 if you have the `clock' function. */
+#define HAVE_CLOCK 1
+
+/* Define to 1 if you have the `clock_getres' function. */
+#define HAVE_CLOCK_GETRES 1
+
+/* Define to 1 if you have the `clock_gettime' function. */
+#define HAVE_CLOCK_GETTIME 1
+
+/* Define to 1 if you have the `clock_nanosleep' function. */
+#define HAVE_CLOCK_NANOSLEEP 1
+
+/* Define to 1 if you have the `clock_settime' function. */
+#define HAVE_CLOCK_SETTIME 1
+
+/* Define to 1 if you have the `close_range' function. */
+/* #undef HAVE_CLOSE_RANGE */
+
+/* Define if the C compiler supports computed gotos. */
+#define HAVE_COMPUTED_GOTOS 1
+
+/* Define to 1 if you have the `confstr' function. */
+#define HAVE_CONFSTR 1
+
+/* Define to 1 if you have the <conio.h> header file. */
+/* #undef HAVE_CONIO_H */
+
+/* Define if you have the 'connect' function. */
+#define HAVE_CONNECT 1
+
+/* Define to 1 if you have the `copy_file_range' function. */
+/* #undef HAVE_COPY_FILE_RANGE */
+
+/* Define to 1 if you have the <crypt.h> header file. */
+#define HAVE_CRYPT_H 1
+
+/* Define if you have the crypt_r() function. */
+#define HAVE_CRYPT_R 1
+
+/* Define to 1 if you have the `ctermid' function. */
+#define HAVE_CTERMID 1
+
+/* Define if you have the 'ctermid_r' function. */
+/* #undef HAVE_CTERMID_R */
+
+/* Define if you have the 'filter' function. */
+#define HAVE_CURSES_FILTER 1
+
+/* Define to 1 if you have the <curses.h> header file. */
+#define HAVE_CURSES_H 1
+
+/* Define if you have the 'has_key' function. */
+#define HAVE_CURSES_HAS_KEY 1
+
+/* Define if you have the 'immedok' function. */
+#define HAVE_CURSES_IMMEDOK 1
+
+/* Define if you have the 'is_pad' function. */
+#define HAVE_CURSES_IS_PAD 1
+
+/* Define if you have the 'is_term_resized' function. */
+#define HAVE_CURSES_IS_TERM_RESIZED 1
+
+/* Define if you have the 'resizeterm' function. */
+#define HAVE_CURSES_RESIZETERM 1
+
+/* Define if you have the 'resize_term' function. */
+#define HAVE_CURSES_RESIZE_TERM 1
+
+/* Define if you have the 'syncok' function. */
+#define HAVE_CURSES_SYNCOK 1
+
+/* Define if you have the 'typeahead' function. */
+#define HAVE_CURSES_TYPEAHEAD 1
+
+/* Define if you have the 'use_env' function. */
+#define HAVE_CURSES_USE_ENV 1
+
+/* Define if you have the 'wchgat' function. */
+#define HAVE_CURSES_WCHGAT 1
+
+/* Define to 1 if you have the <db.h> header file. */
+/* #undef HAVE_DB_H */
+
+/* Define to 1 if you have the declaration of `RTLD_DEEPBIND', and to 0 if you
+ don't. */
+#define HAVE_DECL_RTLD_DEEPBIND 1
+
+/* Define to 1 if you have the declaration of `RTLD_GLOBAL', and to 0 if you
+ don't. */
+#define HAVE_DECL_RTLD_GLOBAL 1
+
+/* Define to 1 if you have the declaration of `RTLD_LAZY', and to 0 if you
+ don't. */
+#define HAVE_DECL_RTLD_LAZY 1
+
+/* Define to 1 if you have the declaration of `RTLD_LOCAL', and to 0 if you
+ don't. */
+#define HAVE_DECL_RTLD_LOCAL 1
+
+/* Define to 1 if you have the declaration of `RTLD_MEMBER', and to 0 if you
+ don't. */
+#define HAVE_DECL_RTLD_MEMBER 0
+
+/* Define to 1 if you have the declaration of `RTLD_NODELETE', and to 0 if you
+ don't. */
+#define HAVE_DECL_RTLD_NODELETE 1
+
+/* Define to 1 if you have the declaration of `RTLD_NOLOAD', and to 0 if you
+ don't. */
+#define HAVE_DECL_RTLD_NOLOAD 1
+
+/* Define to 1 if you have the declaration of `RTLD_NOW', and to 0 if you
+ don't. */
+#define HAVE_DECL_RTLD_NOW 1
+
+/* Define to 1 if you have the declaration of `tzname', and to 0 if you don't.
+ */
+/* #undef HAVE_DECL_TZNAME */
+
+/* Define to 1 if you have the device macros. */
+#define HAVE_DEVICE_MACROS 1
+
+/* Define to 1 if you have the /dev/ptc device file. */
+/* #undef HAVE_DEV_PTC */
+
+/* Define to 1 if you have the /dev/ptmx device file. */
+#define HAVE_DEV_PTMX 1
+
+/* Define to 1 if you have the <direct.h> header file. */
+/* #undef HAVE_DIRECT_H */
+
+/* Define to 1 if the dirent structure has a d_type field */
+#define HAVE_DIRENT_D_TYPE 1
+
+/* Define to 1 if you have the <dirent.h> header file, and it defines `DIR'.
+ */
+#define HAVE_DIRENT_H 1
+
+/* Define if you have the 'dirfd' function or macro. */
+#define HAVE_DIRFD 1
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H 1
+
+/* Define to 1 if you have the `dlopen' function. */
+#define HAVE_DLOPEN 1
+
+/* Define to 1 if you have the `dup' function. */
+#define HAVE_DUP 1
+
+/* Define to 1 if you have the `dup2' function. */
+#define HAVE_DUP2 1
+
+/* Define to 1 if you have the `dup3' function. */
+#define HAVE_DUP3 1
+
+/* Define if you have the '_dyld_shared_cache_contains_path' function. */
+/* #undef HAVE_DYLD_SHARED_CACHE_CONTAINS_PATH */
+
+/* Defined when any dynamic module loading is enabled. */
+#define HAVE_DYNAMIC_LOADING 1
+
+/* Define to 1 if you have the <endian.h> header file. */
+#define HAVE_ENDIAN_H 1
+
+/* Define if you have the 'epoll_create' function. */
+#define HAVE_EPOLL 1
+
+/* Define if you have the 'epoll_create1' function. */
+#define HAVE_EPOLL_CREATE1 1
+
+/* Define to 1 if you have the `erf' function. */
+#define HAVE_ERF 1
+
+/* Define to 1 if you have the `erfc' function. */
+#define HAVE_ERFC 1
+
+/* Define to 1 if you have the <errno.h> header file. */
+#define HAVE_ERRNO_H 1
+
+/* Define if you have the 'eventfd' function. */
+#define HAVE_EVENTFD 1
+
+/* Define to 1 if you have the `execv' function. */
+#define HAVE_EXECV 1
+
+/* Define to 1 if you have the `explicit_bzero' function. */
+/* #undef HAVE_EXPLICIT_BZERO */
+
+/* Define to 1 if you have the `explicit_memset' function. */
+/* #undef HAVE_EXPLICIT_MEMSET */
+
+/* Define to 1 if you have the `expm1' function. */
+#define HAVE_EXPM1 1
+
+/* Define to 1 if you have the `faccessat' function. */
+#define HAVE_FACCESSAT 1
+
+/* Define if you have the 'fchdir' function. */
+#define HAVE_FCHDIR 1
+
+/* Define to 1 if you have the `fchmod' function. */
+#define HAVE_FCHMOD 1
+
+/* Define to 1 if you have the `fchmodat' function. */
+#define HAVE_FCHMODAT 1
+
+/* Define to 1 if you have the `fchown' function. */
+#define HAVE_FCHOWN 1
+
+/* Define to 1 if you have the `fchownat' function. */
+#define HAVE_FCHOWNAT 1
+
+/* Define to 1 if you have the <fcntl.h> header file. */
+#define HAVE_FCNTL_H 1
+
+/* Define if you have the 'fdatasync' function. */
+#define HAVE_FDATASYNC 1
+
+/* Define to 1 if you have the `fdopendir' function. */
+#define HAVE_FDOPENDIR 1
+
+/* Define to 1 if you have the `fdwalk' function. */
+/* #undef HAVE_FDWALK */
+
+/* Define to 1 if you have the `fexecve' function. */
+#define HAVE_FEXECVE 1
+
+/* Define to 1 if you have the `flock' function. */
+#define HAVE_FLOCK 1
+
+/* Define to 1 if you have the `fork' function. */
+#define HAVE_FORK 1
+
+/* Define to 1 if you have the `fork1' function. */
+/* #undef HAVE_FORK1 */
+
+/* Define to 1 if you have the `forkpty' function. */
+#define HAVE_FORKPTY 1
+
+/* Define to 1 if you have the `fpathconf' function. */
+#define HAVE_FPATHCONF 1
+
+/* Define to 1 if you have the `fseek64' function. */
+/* #undef HAVE_FSEEK64 */
+
+/* Define to 1 if you have the `fseeko' function. */
+#define HAVE_FSEEKO 1
+
+/* Define to 1 if you have the `fstatat' function. */
+#define HAVE_FSTATAT 1
+
+/* Define to 1 if you have the `fstatvfs' function. */
+#define HAVE_FSTATVFS 1
+
+/* Define if you have the 'fsync' function. */
+#define HAVE_FSYNC 1
+
+/* Define to 1 if you have the `ftell64' function. */
+/* #undef HAVE_FTELL64 */
+
+/* Define to 1 if you have the `ftello' function. */
+#define HAVE_FTELLO 1
+
+/* Define to 1 if you have the `ftime' function. */
+#define HAVE_FTIME 1
+
+/* Define to 1 if you have the `ftruncate' function. */
+#define HAVE_FTRUNCATE 1
+
+/* Define to 1 if you have the `futimens' function. */
+#define HAVE_FUTIMENS 1
+
+/* Define to 1 if you have the `futimes' function. */
+#define HAVE_FUTIMES 1
+
+/* Define to 1 if you have the `futimesat' function. */
+#define HAVE_FUTIMESAT 1
+
+/* Define to 1 if you have the `gai_strerror' function. */
+#define HAVE_GAI_STRERROR 1
+
+/* Define if we can use gcc inline assembler to get and set mc68881 fpcr */
+/* #undef HAVE_GCC_ASM_FOR_MC68881 */
+
+/* Define if we can use x64 gcc inline assembler */
+#define HAVE_GCC_ASM_FOR_X64 1
+
+/* Define if we can use gcc inline assembler to get and set x87 control word
+ */
+#define HAVE_GCC_ASM_FOR_X87 1
+
+/* Define if your compiler provides __uint128_t */
+#define HAVE_GCC_UINT128_T 1
+
+/* Define to 1 if you have the <gdbm-ndbm.h> header file. */
+/* #undef HAVE_GDBM_DASH_NDBM_H */
+
+/* Define to 1 if you have the <gdbm.h> header file. */
+/* #undef HAVE_GDBM_H */
+
+/* Define to 1 if you have the <gdbm/ndbm.h> header file. */
+/* #undef HAVE_GDBM_NDBM_H */
+
+/* Define if you have the getaddrinfo function. */
+#define HAVE_GETADDRINFO 1
+
+/* Define this if you have flockfile(), getc_unlocked(), and funlockfile() */
+#define HAVE_GETC_UNLOCKED 1
+
+/* Define to 1 if you have the `getegid' function. */
+#define HAVE_GETEGID 1
+
+/* Define to 1 if you have the `getentropy' function. */
+/* #undef HAVE_GETENTROPY */
+
+/* Define to 1 if you have the `geteuid' function. */
+#define HAVE_GETEUID 1
+
+/* Define to 1 if you have the `getgid' function. */
+#define HAVE_GETGID 1
+
+/* Define to 1 if you have the `getgrgid' function. */
+#define HAVE_GETGRGID 1
+
+/* Define to 1 if you have the `getgrgid_r' function. */
+#define HAVE_GETGRGID_R 1
+
+/* Define to 1 if you have the `getgrnam_r' function. */
+#define HAVE_GETGRNAM_R 1
+
+/* Define to 1 if you have the `getgrouplist' function. */
+#define HAVE_GETGROUPLIST 1
+
+/* Define to 1 if you have the `getgroups' function. */
+#define HAVE_GETGROUPS 1
+
+/* Define if you have the 'gethostbyaddr' function. */
+#define HAVE_GETHOSTBYADDR 1
+
+/* Define to 1 if you have the `gethostbyname' function. */
+#define HAVE_GETHOSTBYNAME 1
+
+/* Define this if you have some version of gethostbyname_r() */
+#define HAVE_GETHOSTBYNAME_R 1
+
+/* Define this if you have the 3-arg version of gethostbyname_r(). */
+/* #undef HAVE_GETHOSTBYNAME_R_3_ARG */
+
+/* Define this if you have the 5-arg version of gethostbyname_r(). */
+/* #undef HAVE_GETHOSTBYNAME_R_5_ARG */
+
+/* Define this if you have the 6-arg version of gethostbyname_r(). */
+#define HAVE_GETHOSTBYNAME_R_6_ARG 1
+
+/* Define to 1 if you have the `gethostname' function. */
+#define HAVE_GETHOSTNAME 1
+
+/* Define to 1 if you have the `getitimer' function. */
+#define HAVE_GETITIMER 1
+
+/* Define to 1 if you have the `getloadavg' function. */
+#define HAVE_GETLOADAVG 1
+
+/* Define to 1 if you have the `getlogin' function. */
+#define HAVE_GETLOGIN 1
+
+/* Define to 1 if you have the `getnameinfo' function. */
+#define HAVE_GETNAMEINFO 1
+
+/* Define if you have the 'getpagesize' function. */
+#define HAVE_GETPAGESIZE 1
+
+/* Define if you have the 'getpeername' function. */
+#define HAVE_GETPEERNAME 1
+
+/* Define to 1 if you have the `getpgid' function. */
+#define HAVE_GETPGID 1
+
+/* Define to 1 if you have the `getpgrp' function. */
+#define HAVE_GETPGRP 1
+
+/* Define to 1 if you have the `getpid' function. */
+#define HAVE_GETPID 1
+
+/* Define to 1 if you have the `getppid' function. */
+#define HAVE_GETPPID 1
+
+/* Define to 1 if you have the `getpriority' function. */
+#define HAVE_GETPRIORITY 1
+
+/* Define if you have the 'getprotobyname' function. */
+#define HAVE_GETPROTOBYNAME 1
+
+/* Define to 1 if you have the `getpwent' function. */
+#define HAVE_GETPWENT 1
+
+/* Define to 1 if you have the `getpwnam_r' function. */
+#define HAVE_GETPWNAM_R 1
+
+/* Define to 1 if you have the `getpwuid' function. */
+#define HAVE_GETPWUID 1
+
+/* Define to 1 if you have the `getpwuid_r' function. */
+#define HAVE_GETPWUID_R 1
+
+/* Define to 1 if the getrandom() function is available */
+/* #undef HAVE_GETRANDOM */
+
+/* Define to 1 if the Linux getrandom() syscall is available */
+#define HAVE_GETRANDOM_SYSCALL 1
+
+/* Define to 1 if you have the `getresgid' function. */
+#define HAVE_GETRESGID 1
+
+/* Define to 1 if you have the `getresuid' function. */
+#define HAVE_GETRESUID 1
+
+/* Define to 1 if you have the `getrusage' function. */
+#define HAVE_GETRUSAGE 1
+
+/* Define if you have the 'getservbyname' function. */
+#define HAVE_GETSERVBYNAME 1
+
+/* Define if you have the 'getservbyport' function. */
+#define HAVE_GETSERVBYPORT 1
+
+/* Define to 1 if you have the `getsid' function. */
+#define HAVE_GETSID 1
+
+/* Define if you have the 'getsockname' function. */
+#define HAVE_GETSOCKNAME 1
+
+/* Define to 1 if you have the `getspent' function. */
+#define HAVE_GETSPENT 1
+
+/* Define to 1 if you have the `getspnam' function. */
+#define HAVE_GETSPNAM 1
+
+/* Define to 1 if you have the `getuid' function. */
+#define HAVE_GETUID 1
+
+/* Define to 1 if you have the `getwd' function. */
+#define HAVE_GETWD 1
+
+/* Define if glibc has incorrect _FORTIFY_SOURCE wrappers for memmove and
+ bcopy. */
+/* #undef HAVE_GLIBC_MEMMOVE_BUG */
+
+/* Define to 1 if you have the <grp.h> header file. */
+#define HAVE_GRP_H 1
+
+/* Define if you have the 'hstrerror' function. */
+#define HAVE_HSTRERROR 1
+
+/* Define this if you have le64toh() */
+#define HAVE_HTOLE64 1
+
+/* Define to 1 if you have the <ieeefp.h> header file. */
+/* #undef HAVE_IEEEFP_H */
+
+/* Define to 1 if you have the `if_nameindex' function. */
+#define HAVE_IF_NAMEINDEX 1
+
+/* Define if you have the 'inet_aton' function. */
+#define HAVE_INET_ATON 1
+
+/* Define if you have the 'inet_ntoa' function. */
+#define HAVE_INET_NTOA 1
+
+/* Define if you have the 'inet_pton' function. */
+#define HAVE_INET_PTON 1
+
+/* Define to 1 if you have the `initgroups' function. */
+#define HAVE_INITGROUPS 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the <io.h> header file. */
+/* #undef HAVE_IO_H */
+
+/* Define if gcc has the ipa-pure-const bug. */
+/* #undef HAVE_IPA_PURE_CONST_BUG */
+
+/* Define to 1 if you have the `kill' function. */
+#define HAVE_KILL 1
+
+/* Define to 1 if you have the `killpg' function. */
+#define HAVE_KILLPG 1
+
+/* Define if you have the 'kqueue' function. */
+/* #undef HAVE_KQUEUE */
+
+/* Define to 1 if you have the <langinfo.h> header file. */
+#define HAVE_LANGINFO_H 1
+
+/* Defined to enable large file support when an off_t is bigger than a long
+ and long long is at least as big as an off_t. You may need to add some
+ flags for configuration and compilation to enable this mode. (For Solaris
+ and Linux, the necessary defines are already defined.) */
+/* #undef HAVE_LARGEFILE_SUPPORT */
+
+/* Define to 1 if you have the 'lchflags' function. */
+/* #undef HAVE_LCHFLAGS */
+
+/* Define to 1 if you have the `lchmod' function. */
+/* #undef HAVE_LCHMOD */
+
+/* Define to 1 if you have the `lchown' function. */
+#define HAVE_LCHOWN 1
+
+/* Define to 1 if you want to build _blake2 module with libb2 */
+/* #undef HAVE_LIBB2 */
+
+/* Define to 1 if you have the `db' library (-ldb). */
+/* #undef HAVE_LIBDB */
+
+/* Define to 1 if you have the `dl' library (-ldl). */
+#define HAVE_LIBDL 1
+
+/* Define to 1 if you have the `dld' library (-ldld). */
+/* #undef HAVE_LIBDLD */
+
+/* Define to 1 if you have the `gdbm_compat' library (-lgdbm_compat). */
+/* #undef HAVE_LIBGDBM_COMPAT */
+
+/* Define to 1 if you have the `ieee' library (-lieee). */
+/* #undef HAVE_LIBIEEE */
+
+/* Define to 1 if you have the <libintl.h> header file. */
+#define HAVE_LIBINTL_H 1
+
+/* Define to 1 if you have the `ndbm' library (-lndbm). */
+/* #undef HAVE_LIBNDBM */
+
+/* Define to build the readline module. */
+/* #undef HAVE_LIBREADLINE */
+
+/* Define to 1 if you have the `resolv' library (-lresolv). */
+/* #undef HAVE_LIBRESOLV */
+
+/* Define to 1 if you have the `sendfile' library (-lsendfile). */
+/* #undef HAVE_LIBSENDFILE */
+
+/* Define to 1 if you have the `sqlite3' library (-lsqlite3). */
+/* #undef HAVE_LIBSQLITE3 */
+
+/* Define to 1 if you have the <libutil.h> header file. */
+/* #undef HAVE_LIBUTIL_H */
+
+/* Define if you have the 'link' function. */
+#define HAVE_LINK 1
+
+/* Define to 1 if you have the `linkat' function. */
+#define HAVE_LINKAT 1
+
+/* Define to 1 if you have the <linux/auxvec.h> header file. */
+#define HAVE_LINUX_AUXVEC_H 1
+
+/* Define to 1 if you have the <linux/can/bcm.h> header file. */
+#define HAVE_LINUX_CAN_BCM_H 1
+
+/* Define to 1 if you have the <linux/can.h> header file. */
+#define HAVE_LINUX_CAN_H 1
+
+/* Define to 1 if you have the <linux/can/j1939.h> header file. */
+/* #undef HAVE_LINUX_CAN_J1939_H */
+
+/* Define if compiling using Linux 3.6 or later. */
+#define HAVE_LINUX_CAN_RAW_FD_FRAMES 1
+
+/* Define to 1 if you have the <linux/can/raw.h> header file. */
+#define HAVE_LINUX_CAN_RAW_H 1
+
+/* Define if compiling using Linux 4.1 or later. */
+#define HAVE_LINUX_CAN_RAW_JOIN_FILTERS 1
+
+/* Define to 1 if you have the <linux/memfd.h> header file. */
+#define HAVE_LINUX_MEMFD_H 1
+
+/* Define to 1 if you have the <linux/netlink.h> header file. */
+#define HAVE_LINUX_NETLINK_H 1
+
+/* Define to 1 if you have the <linux/qrtr.h> header file. */
+/* #undef HAVE_LINUX_QRTR_H */
+
+/* Define to 1 if you have the <linux/random.h> header file. */
+#define HAVE_LINUX_RANDOM_H 1
+
+/* Define to 1 if you have the <linux/soundcard.h> header file. */
+#define HAVE_LINUX_SOUNDCARD_H 1
+
+/* Define to 1 if you have the <linux/tipc.h> header file. */
+#define HAVE_LINUX_TIPC_H 1
+
+/* Define to 1 if you have the <linux/vm_sockets.h> header file. */
+#define HAVE_LINUX_VM_SOCKETS_H 1
+
+/* Define to 1 if you have the <linux/wait.h> header file. */
+#define HAVE_LINUX_WAIT_H 1
+
+/* Define if you have the 'listen' function. */
+#define HAVE_LISTEN 1
+
+/* Define to 1 if you have the `lockf' function. */
+#define HAVE_LOCKF 1
+
+/* Define to 1 if you have the `log1p' function. */
+#define HAVE_LOG1P 1
+
+/* Define to 1 if you have the `log2' function. */
+#define HAVE_LOG2 1
+
+/* Define to 1 if you have the `login_tty' function. */
+#define HAVE_LOGIN_TTY 1
+
+/* Define to 1 if the system has the type `long double'. */
+#define HAVE_LONG_DOUBLE 1
+
+/* Define to 1 if you have the `lstat' function. */
+#define HAVE_LSTAT 1
+
+/* Define to 1 if you have the `lutimes' function. */
+#define HAVE_LUTIMES 1
+
+/* Define to 1 if you have the <lzma.h> header file. */
+/* #undef HAVE_LZMA_H */
+
+/* Define to 1 if you have the `madvise' function. */
+#define HAVE_MADVISE 1
+
+/* Define this if you have the makedev macro. */
+#define HAVE_MAKEDEV 1
+
+/* Define to 1 if you have the `mbrtowc' function. */
+#define HAVE_MBRTOWC 1
+
+/* Define if you have the 'memfd_create' function. */
+/* #undef HAVE_MEMFD_CREATE */
+
+/* Define to 1 if you have the <memory.h> header file. */
+/* #undef HAVE_MEMORY_H */
+
+/* Define to 1 if you have the `memrchr' function. */
+#define HAVE_MEMRCHR 1
+
+/* Define to 1 if you have the `mkdirat' function. */
+#define HAVE_MKDIRAT 1
+
+/* Define to 1 if you have the `mkfifo' function. */
+#define HAVE_MKFIFO 1
+
+/* Define to 1 if you have the `mkfifoat' function. */
+#define HAVE_MKFIFOAT 1
+
+/* Define to 1 if you have the `mknod' function. */
+#define HAVE_MKNOD 1
+
+/* Define to 1 if you have the `mknodat' function. */
+#define HAVE_MKNODAT 1
+
+/* Define to 1 if you have the `mktime' function. */
+#define HAVE_MKTIME 1
+
+/* Define to 1 if you have the `mmap' function. */
+#define HAVE_MMAP 1
+
+/* Define to 1 if you have the `mremap' function. */
+#define HAVE_MREMAP 1
+
+/* Define to 1 if you have the `nanosleep' function. */
+#define HAVE_NANOSLEEP 1
+
+/* Define to 1 if you have the <ncurses.h> header file. */
+#define HAVE_NCURSES_H 1
+
+/* Define to 1 if you have the <ndbm.h> header file. */
+/* #undef HAVE_NDBM_H */
+
+/* Define to 1 if you have the <ndir.h> header file, and it defines `DIR'. */
+/* #undef HAVE_NDIR_H */
+
+/* Define to 1 if you have the <netcan/can.h> header file. */
+/* #undef HAVE_NETCAN_CAN_H */
+
+/* Define to 1 if you have the <netdb.h> header file. */
+#define HAVE_NETDB_H 1
+
+/* Define to 1 if you have the <netinet/in.h> header file. */
+#define HAVE_NETINET_IN_H 1
+
+/* Define to 1 if you have the <netpacket/packet.h> header file. */
+#define HAVE_NETPACKET_PACKET_H 1
+
+/* Define to 1 if you have the <net/if.h> header file. */
+#define HAVE_NET_IF_H 1
+
+/* Define to 1 if you have the `nice' function. */
+#define HAVE_NICE 1
+
+/* Define if the internal form of wchar_t in non-Unicode locales is not
+ Unicode. */
+/* #undef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION */
+
+/* Define to 1 if you have the `openat' function. */
+#define HAVE_OPENAT 1
+
+/* Define to 1 if you have the `opendir' function. */
+#define HAVE_OPENDIR 1
+
+/* Define to 1 if you have the `openpty' function. */
+#define HAVE_OPENPTY 1
+
+/* Define to 1 if you have the `pathconf' function. */
+#define HAVE_PATHCONF 1
+
+/* Define to 1 if you have the `pause' function. */
+#define HAVE_PAUSE 1
+
+/* Define to 1 if you have the `pipe' function. */
+#define HAVE_PIPE 1
+
+/* Define to 1 if you have the `pipe2' function. */
+#define HAVE_PIPE2 1
+
+/* Define to 1 if you have the `plock' function. */
+/* #undef HAVE_PLOCK */
+
+/* Define to 1 if you have the `poll' function. */
+#define HAVE_POLL 1
+
+/* Define to 1 if you have the <poll.h> header file. */
+#define HAVE_POLL_H 1
+
+/* Define to 1 if you have the `posix_fadvise' function. */
+#define HAVE_POSIX_FADVISE 1
+
+/* Define to 1 if you have the `posix_fallocate' function. */
+#define HAVE_POSIX_FALLOCATE 1
+
+/* Define to 1 if you have the `posix_spawn' function. */
+#define HAVE_POSIX_SPAWN 1
+
+/* Define to 1 if you have the `posix_spawnp' function. */
+#define HAVE_POSIX_SPAWNP 1
+
+/* Define to 1 if you have the `pread' function. */
+#define HAVE_PREAD 1
+
+/* Define to 1 if you have the `preadv' function. */
+#define HAVE_PREADV 1
+
+/* Define to 1 if you have the `preadv2' function. */
+/* #undef HAVE_PREADV2 */
+
+/* Define if you have the 'prlimit' function. */
+#define HAVE_PRLIMIT 1
+
+/* Define to 1 if you have the <process.h> header file. */
+/* #undef HAVE_PROCESS_H */
+
+/* Define if your compiler supports function prototype */
+#define HAVE_PROTOTYPES 1
+
+/* Define to 1 if you have the `pthread_condattr_setclock' function. */
+#define HAVE_PTHREAD_CONDATTR_SETCLOCK 1
+
+/* Defined for Solaris 2.6 bug in pthread header. */
+/* #undef HAVE_PTHREAD_DESTRUCTOR */
+
+/* Define to 1 if you have the `pthread_getcpuclockid' function. */
+#define HAVE_PTHREAD_GETCPUCLOCKID 1
+
+/* Define to 1 if you have the <pthread.h> header file. */
+#define HAVE_PTHREAD_H 1
+
+/* Define to 1 if you have the `pthread_init' function. */
+/* #undef HAVE_PTHREAD_INIT */
+
+/* Define to 1 if you have the `pthread_kill' function. */
+#define HAVE_PTHREAD_KILL 1
+
+/* Define to 1 if you have the `pthread_sigmask' function. */
+#define HAVE_PTHREAD_SIGMASK 1
+
+/* Define if platform requires stubbed pthreads support */
+/* #undef HAVE_PTHREAD_STUBS */
+
+/* Define to 1 if you have the <pty.h> header file. */
+#define HAVE_PTY_H 1
+
+/* Define to 1 if you have the `pwrite' function. */
+#define HAVE_PWRITE 1
+
+/* Define to 1 if you have the `pwritev' function. */
+#define HAVE_PWRITEV 1
+
+/* Define to 1 if you have the `pwritev2' function. */
+/* #undef HAVE_PWRITEV2 */
+
+/* Define to 1 if you have the `readlink' function. */
+#define HAVE_READLINK 1
+
+/* Define to 1 if you have the `readlinkat' function. */
+#define HAVE_READLINKAT 1
+
+/* Define to 1 if you have the `readv' function. */
+#define HAVE_READV 1
+
+/* Define to 1 if you have the `realpath' function. */
+#define HAVE_REALPATH 1
+
+/* Define if you have the 'recvfrom' function. */
+#define HAVE_RECVFROM 1
+
+/* Define to 1 if you have the `renameat' function. */
+#define HAVE_RENAMEAT 1
+
+/* Define if readline supports append_history */
+/* #undef HAVE_RL_APPEND_HISTORY */
+
+/* Define if you can turn off readline's signal handling. */
+/* #undef HAVE_RL_CATCH_SIGNAL */
+
+/* Define if you have readline 2.2 */
+/* #undef HAVE_RL_COMPLETION_APPEND_CHARACTER */
+
+/* Define if you have readline 4.0 */
+/* #undef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK */
+
+/* Define if you have readline 4.2 */
+/* #undef HAVE_RL_COMPLETION_MATCHES */
+
+/* Define if you have rl_completion_suppress_append */
+/* #undef HAVE_RL_COMPLETION_SUPPRESS_APPEND */
+
+/* Define if you have readline 4.0 */
+/* #undef HAVE_RL_PRE_INPUT_HOOK */
+
+/* Define if you have readline 4.0 */
+/* #undef HAVE_RL_RESIZE_TERMINAL */
+
+/* Define to 1 if you have the <rpc/rpc.h> header file. */
+#define HAVE_RPC_RPC_H 1
+
+/* Define to 1 if you have the `rtpSpawn' function. */
+/* #undef HAVE_RTPSPAWN */
+
+/* Define to 1 if you have the `sched_get_priority_max' function. */
+#define HAVE_SCHED_GET_PRIORITY_MAX 1
+
+/* Define to 1 if you have the <sched.h> header file. */
+#define HAVE_SCHED_H 1
+
+/* Define to 1 if you have the `sched_rr_get_interval' function. */
+#define HAVE_SCHED_RR_GET_INTERVAL 1
+
+/* Define to 1 if you have the `sched_setaffinity' function. */
+#define HAVE_SCHED_SETAFFINITY 1
+
+/* Define to 1 if you have the `sched_setparam' function. */
+#define HAVE_SCHED_SETPARAM 1
+
+/* Define to 1 if you have the `sched_setscheduler' function. */
+#define HAVE_SCHED_SETSCHEDULER 1
+
+/* Define to 1 if you have the `sem_clockwait' function. */
+/* #undef HAVE_SEM_CLOCKWAIT */
+
+/* Define to 1 if you have the `sem_getvalue' function. */
+#define HAVE_SEM_GETVALUE 1
+
+/* Define to 1 if you have the `sem_open' function. */
+#define HAVE_SEM_OPEN 1
+
+/* Define to 1 if you have the `sem_timedwait' function. */
+#define HAVE_SEM_TIMEDWAIT 1
+
+/* Define to 1 if you have the `sem_unlink' function. */
+#define HAVE_SEM_UNLINK 1
+
+/* Define to 1 if you have the `sendfile' function. */
+#define HAVE_SENDFILE 1
+
+/* Define if you have the 'sendto' function. */
+#define HAVE_SENDTO 1
+
+/* Define to 1 if you have the `setegid' function. */
+#define HAVE_SETEGID 1
+
+/* Define to 1 if you have the `seteuid' function. */
+#define HAVE_SETEUID 1
+
+/* Define to 1 if you have the `setgid' function. */
+#define HAVE_SETGID 1
+
+/* Define if you have the 'setgroups' function. */
+#define HAVE_SETGROUPS 1
+
+/* Define to 1 if you have the `sethostname' function. */
+#define HAVE_SETHOSTNAME 1
+
+/* Define to 1 if you have the `setitimer' function. */
+#define HAVE_SETITIMER 1
+
+/* Define to 1 if you have the <setjmp.h> header file. */
+#define HAVE_SETJMP_H 1
+
+/* Define to 1 if you have the `setlocale' function. */
+#define HAVE_SETLOCALE 1
+
+/* Define to 1 if you have the `setpgid' function. */
+#define HAVE_SETPGID 1
+
+/* Define to 1 if you have the `setpgrp' function. */
+#define HAVE_SETPGRP 1
+
+/* Define to 1 if you have the `setpriority' function. */
+#define HAVE_SETPRIORITY 1
+
+/* Define to 1 if you have the `setregid' function. */
+#define HAVE_SETREGID 1
+
+/* Define to 1 if you have the `setresgid' function. */
+#define HAVE_SETRESGID 1
+
+/* Define to 1 if you have the `setresuid' function. */
+#define HAVE_SETRESUID 1
+
+/* Define to 1 if you have the `setreuid' function. */
+#define HAVE_SETREUID 1
+
+/* Define to 1 if you have the `setsid' function. */
+#define HAVE_SETSID 1
+
+/* Define if you have the 'setsockopt' function. */
+#define HAVE_SETSOCKOPT 1
+
+/* Define to 1 if you have the `setuid' function. */
+#define HAVE_SETUID 1
+
+/* Define to 1 if you have the `setvbuf' function. */
+#define HAVE_SETVBUF 1
+
+/* Define to 1 if you have the <shadow.h> header file. */
+#define HAVE_SHADOW_H 1
+
+/* Define to 1 if you have the `shm_open' function. */
+#define HAVE_SHM_OPEN 1
+
+/* Define to 1 if you have the `shm_unlink' function. */
+#define HAVE_SHM_UNLINK 1
+
+/* Define to 1 if you have the `shutdown' function. */
+#define HAVE_SHUTDOWN 1
+
+/* Define to 1 if you have the `sigaction' function. */
+#define HAVE_SIGACTION 1
+
+/* Define to 1 if you have the `sigaltstack' function. */
+#define HAVE_SIGALTSTACK 1
+
+/* Define to 1 if you have the `sigfillset' function. */
+#define HAVE_SIGFILLSET 1
+
+/* Define to 1 if `si_band' is a member of `siginfo_t'. */
+#define HAVE_SIGINFO_T_SI_BAND 1
+
+/* Define to 1 if you have the `siginterrupt' function. */
+#define HAVE_SIGINTERRUPT 1
+
+/* Define to 1 if you have the <signal.h> header file. */
+#define HAVE_SIGNAL_H 1
+
+/* Define to 1 if you have the `sigpending' function. */
+#define HAVE_SIGPENDING 1
+
+/* Define to 1 if you have the `sigrelse' function. */
+#define HAVE_SIGRELSE 1
+
+/* Define to 1 if you have the `sigtimedwait' function. */
+#define HAVE_SIGTIMEDWAIT 1
+
+/* Define to 1 if you have the `sigwait' function. */
+#define HAVE_SIGWAIT 1
+
+/* Define to 1 if you have the `sigwaitinfo' function. */
+#define HAVE_SIGWAITINFO 1
+
+/* Define to 1 if you have the `snprintf' function. */
+#define HAVE_SNPRINTF 1
+
+/* struct sockaddr_alg (linux/if_alg.h) */
+#define HAVE_SOCKADDR_ALG 1
+
+/* Define if sockaddr has sa_len member */
+/* #undef HAVE_SOCKADDR_SA_LEN */
+
+/* struct sockaddr_storage (sys/socket.h) */
+#define HAVE_SOCKADDR_STORAGE 1
+
+/* Define if you have the 'socket' function. */
+#define HAVE_SOCKET 1
+
+/* Define if you have the 'socketpair' function. */
+#define HAVE_SOCKETPAIR 1
+
+/* Define to 1 if you have the <spawn.h> header file. */
+#define HAVE_SPAWN_H 1
+
+/* Define to 1 if you have the `splice' function. */
+#define HAVE_SPLICE 1
+
+/* Define if your compiler provides ssize_t */
+#define HAVE_SSIZE_T 1
+
+/* Define to 1 if you have the `statvfs' function. */
+#define HAVE_STATVFS 1
+
+/* Define if you have struct stat.st_mtim.tv_nsec */
+#define HAVE_STAT_TV_NSEC 1
+
+/* Define if you have struct stat.st_mtimensec */
+/* #undef HAVE_STAT_TV_NSEC2 */
+
+/* Define if your compiler supports variable length function prototypes (e.g.
+ void fprintf(FILE *, char *, ...);) *and* <stdarg.h> */
+#define HAVE_STDARG_PROTOTYPES 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Has stdatomic.h with atomic_int and atomic_uintptr_t */
+/* #undef HAVE_STD_ATOMIC */
+
+/* Define to 1 if you have the `strftime' function. */
+#define HAVE_STRFTIME 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the `strlcpy' function. */
+/* #undef HAVE_STRLCPY */
+
+/* Define to 1 if you have the <stropts.h> header file. */
+/* #undef HAVE_STROPTS_H */
+
+/* Define to 1 if you have the `strsignal' function. */
+#define HAVE_STRSIGNAL 1
+
+/* Define to 1 if `pw_gecos' is a member of `struct passwd'. */
+#define HAVE_STRUCT_PASSWD_PW_GECOS 1
+
+/* Define to 1 if `pw_passwd' is a member of `struct passwd'. */
+#define HAVE_STRUCT_PASSWD_PW_PASSWD 1
+
+/* Define to 1 if `st_birthtime' is a member of `struct stat'. */
+/* #undef HAVE_STRUCT_STAT_ST_BIRTHTIME */
+
+/* Define to 1 if `st_blksize' is a member of `struct stat'. */
+#define HAVE_STRUCT_STAT_ST_BLKSIZE 1
+
+/* Define to 1 if `st_blocks' is a member of `struct stat'. */
+#define HAVE_STRUCT_STAT_ST_BLOCKS 1
+
+/* Define to 1 if `st_flags' is a member of `struct stat'. */
+/* #undef HAVE_STRUCT_STAT_ST_FLAGS */
+
+/* Define to 1 if `st_gen' is a member of `struct stat'. */
+/* #undef HAVE_STRUCT_STAT_ST_GEN */
+
+/* Define to 1 if `st_rdev' is a member of `struct stat'. */
+#define HAVE_STRUCT_STAT_ST_RDEV 1
+
+/* Define to 1 if `tm_zone' is a member of `struct tm'. */
+#define HAVE_STRUCT_TM_TM_ZONE 1
+
+/* Define if you have the 'symlink' function. */
+#define HAVE_SYMLINK 1
+
+/* Define to 1 if you have the `symlinkat' function. */
+#define HAVE_SYMLINKAT 1
+
+/* Define to 1 if you have the `sync' function. */
+#define HAVE_SYNC 1
+
+/* Define to 1 if you have the `sysconf' function. */
+#define HAVE_SYSCONF 1
+
+/* Define to 1 if you have the <sysexits.h> header file. */
+#define HAVE_SYSEXITS_H 1
+
+/* Define to 1 if you have the <syslog.h> header file. */
+#define HAVE_SYSLOG_H 1
+
+/* Define to 1 if you have the `system' function. */
+#define HAVE_SYSTEM 1
+
+/* Define to 1 if you have the <sys/audioio.h> header file. */
+/* #undef HAVE_SYS_AUDIOIO_H */
+
+/* Define to 1 if you have the <sys/auxv.h> header file. */
+#define HAVE_SYS_AUXV_H 1
+
+/* Define to 1 if you have the <sys/bsdtty.h> header file. */
+/* #undef HAVE_SYS_BSDTTY_H */
+
+/* Define to 1 if you have the <sys/devpoll.h> header file. */
+/* #undef HAVE_SYS_DEVPOLL_H */
+
+/* Define to 1 if you have the <sys/dir.h> header file, and it defines `DIR'.
+ */
+/* #undef HAVE_SYS_DIR_H */
+
+/* Define to 1 if you have the <sys/endian.h> header file. */
+/* #undef HAVE_SYS_ENDIAN_H */
+
+/* Define to 1 if you have the <sys/epoll.h> header file. */
+#define HAVE_SYS_EPOLL_H 1
+
+/* Define to 1 if you have the <sys/eventfd.h> header file. */
+#define HAVE_SYS_EVENTFD_H 1
+
+/* Define to 1 if you have the <sys/event.h> header file. */
+/* #undef HAVE_SYS_EVENT_H */
+
+/* Define to 1 if you have the <sys/file.h> header file. */
+#define HAVE_SYS_FILE_H 1
+
+/* Define to 1 if you have the <sys/ioctl.h> header file. */
+#define HAVE_SYS_IOCTL_H 1
+
+/* Define to 1 if you have the <sys/kern_control.h> header file. */
+/* #undef HAVE_SYS_KERN_CONTROL_H */
+
+/* Define to 1 if you have the <sys/loadavg.h> header file. */
+/* #undef HAVE_SYS_LOADAVG_H */
+
+/* Define to 1 if you have the <sys/lock.h> header file. */
+/* #undef HAVE_SYS_LOCK_H */
+
+/* Define to 1 if you have the <sys/memfd.h> header file. */
+/* #undef HAVE_SYS_MEMFD_H */
+
+/* Define to 1 if you have the <sys/mkdev.h> header file. */
+/* #undef HAVE_SYS_MKDEV_H */
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#define HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/modem.h> header file. */
+/* #undef HAVE_SYS_MODEM_H */
+
+/* Define to 1 if you have the <sys/ndir.h> header file, and it defines `DIR'.
+ */
+/* #undef HAVE_SYS_NDIR_H */
+
+/* Define to 1 if you have the <sys/param.h> header file. */
+#define HAVE_SYS_PARAM_H 1
+
+/* Define to 1 if you have the <sys/poll.h> header file. */
+#define HAVE_SYS_POLL_H 1
+
+/* Define to 1 if you have the <sys/random.h> header file. */
+/* #undef HAVE_SYS_RANDOM_H */
+
+/* Define to 1 if you have the <sys/resource.h> header file. */
+#define HAVE_SYS_RESOURCE_H 1
+
+/* Define to 1 if you have the <sys/select.h> header file. */
+#define HAVE_SYS_SELECT_H 1
+
+/* Define to 1 if you have the <sys/sendfile.h> header file. */
+#define HAVE_SYS_SENDFILE_H 1
+
+/* Define to 1 if you have the <sys/socket.h> header file. */
+#define HAVE_SYS_SOCKET_H 1
+
+/* Define to 1 if you have the <sys/soundcard.h> header file. */
+#define HAVE_SYS_SOUNDCARD_H 1
+
+/* Define to 1 if you have the <sys/statvfs.h> header file. */
+#define HAVE_SYS_STATVFS_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/syscall.h> header file. */
+#define HAVE_SYS_SYSCALL_H 1
+
+/* Define to 1 if you have the <sys/sysmacros.h> header file. */
+#define HAVE_SYS_SYSMACROS_H 1
+
+/* Define to 1 if you have the <sys/sys_domain.h> header file. */
+/* #undef HAVE_SYS_SYS_DOMAIN_H */
+
+/* Define to 1 if you have the <sys/termio.h> header file. */
+/* #undef HAVE_SYS_TERMIO_H */
+
+/* Define to 1 if you have the <sys/times.h> header file. */
+#define HAVE_SYS_TIMES_H 1
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+#define HAVE_SYS_TIME_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <sys/uio.h> header file. */
+#define HAVE_SYS_UIO_H 1
+
+/* Define to 1 if you have the <sys/un.h> header file. */
+#define HAVE_SYS_UN_H 1
+
+/* Define to 1 if you have the <sys/utsname.h> header file. */
+#define HAVE_SYS_UTSNAME_H 1
+
+/* Define to 1 if you have the <sys/wait.h> header file. */
+#define HAVE_SYS_WAIT_H 1
+
+/* Define to 1 if you have the <sys/xattr.h> header file. */
+#define HAVE_SYS_XATTR_H 1
+
+/* Define to 1 if you have the `tcgetpgrp' function. */
+#define HAVE_TCGETPGRP 1
+
+/* Define to 1 if you have the `tcsetpgrp' function. */
+#define HAVE_TCSETPGRP 1
+
+/* Define to 1 if you have the `tempnam' function. */
+#define HAVE_TEMPNAM 1
+
+/* Define to 1 if you have the <termios.h> header file. */
+#define HAVE_TERMIOS_H 1
+
+/* Define to 1 if you have the <term.h> header file. */
+#define HAVE_TERM_H 1
+
+/* Define to 1 if you have the `timegm' function. */
+#define HAVE_TIMEGM 1
+
+/* Define to 1 if you have the `times' function. */
+#define HAVE_TIMES 1
+
+/* Define to 1 if you have the `tmpfile' function. */
+#define HAVE_TMPFILE 1
+
+/* Define to 1 if you have the `tmpnam' function. */
+#define HAVE_TMPNAM 1
+
+/* Define to 1 if you have the `tmpnam_r' function. */
+#define HAVE_TMPNAM_R 1
+
+/* Define to 1 if your `struct tm' has `tm_zone'. Deprecated, use
+ `HAVE_STRUCT_TM_TM_ZONE' instead. */
+#define HAVE_TM_ZONE 1
+
+/* Define to 1 if you have the `truncate' function. */
+#define HAVE_TRUNCATE 1
+
+/* Define to 1 if you have the `ttyname' function. */
+#define HAVE_TTYNAME 1
+
+/* Define to 1 if you don't have `tm_zone' but do have the external array
+ `tzname'. */
+/* #undef HAVE_TZNAME */
+
+/* Define to 1 if you have the `umask' function. */
+#define HAVE_UMASK 1
+
+/* Define to 1 if you have the `uname' function. */
+#define HAVE_UNAME 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Define to 1 if you have the `unlinkat' function. */
+#define HAVE_UNLINKAT 1
+
+/* Define if you have a useable wchar_t type defined in wchar.h; useable means
+ wchar_t must be an unsigned type with at least 16 bits. (see
+ Include/unicodeobject.h). */
+/* #undef HAVE_USABLE_WCHAR_T */
+
+/* Define to 1 if you have the <util.h> header file. */
+/* #undef HAVE_UTIL_H */
+
+/* Define to 1 if you have the `utimensat' function. */
+#define HAVE_UTIMENSAT 1
+
+/* Define to 1 if you have the `utimes' function. */
+#define HAVE_UTIMES 1
+
+/* Define to 1 if you have the <utime.h> header file. */
+#define HAVE_UTIME_H 1
+
+/* Define to 1 if you have the <utmp.h> header file. */
+#define HAVE_UTMP_H 1
+
+/* Define to 1 if you have the `uuid_create' function. */
+/* #undef HAVE_UUID_CREATE */
+
+/* Define to 1 if you have the `uuid_enc_be' function. */
+/* #undef HAVE_UUID_ENC_BE */
+
+/* Define if uuid_generate_time_safe() exists. */
+/* #undef HAVE_UUID_GENERATE_TIME_SAFE */
+
+/* Define to 1 if you have the <uuid.h> header file. */
+/* #undef HAVE_UUID_H */
+
+/* Define to 1 if you have the <uuid/uuid.h> header file. */
+/* #undef HAVE_UUID_UUID_H */
+
+/* Define to 1 if you have the `vfork' function. */
+#define HAVE_VFORK 1
+
+/* Define to 1 if you have the `wait' function. */
+#define HAVE_WAIT 1
+
+/* Define to 1 if you have the `wait3' function. */
+#define HAVE_WAIT3 1
+
+/* Define to 1 if you have the `wait4' function. */
+#define HAVE_WAIT4 1
+
+/* Define to 1 if you have the `waitid' function. */
+#define HAVE_WAITID 1
+
+/* Define to 1 if you have the `waitpid' function. */
+#define HAVE_WAITPID 1
+
+/* Define if the compiler provides a wchar.h header file. */
+#define HAVE_WCHAR_H 1
+
+/* Define to 1 if you have the `wcscoll' function. */
+#define HAVE_WCSCOLL 1
+
+/* Define to 1 if you have the `wcsftime' function. */
+#define HAVE_WCSFTIME 1
+
+/* Define to 1 if you have the `wcsxfrm' function. */
+#define HAVE_WCSXFRM 1
+
+/* Define to 1 if you have the `wmemcmp' function. */
+#define HAVE_WMEMCMP 1
+
+/* Define if tzset() actually switches the local timezone in a meaningful way.
+ */
+#define HAVE_WORKING_TZSET 1
+
+/* Define to 1 if you have the `writev' function. */
+#define HAVE_WRITEV 1
+
+/* Define if the zlib library has inflateCopy */
+#define HAVE_ZLIB_COPY 1
+
+/* Define to 1 if you have the <zlib.h> header file. */
+/* #undef HAVE_ZLIB_H */
+
+/* Define to 1 if you have the `_getpty' function. */
+/* #undef HAVE__GETPTY */
+
+/* Define to 1 if `major', `minor', and `makedev' are declared in <mkdev.h>.
+ */
+/* #undef MAJOR_IN_MKDEV */
+
+/* Define to 1 if `major', `minor', and `makedev' are declared in
+ <sysmacros.h>. */
+#define MAJOR_IN_SYSMACROS 1
+
+/* Define if mvwdelch in curses.h is an expression. */
+#define MVWDELCH_IS_EXPRESSION 1
+
+/* Define to the address where bug reports for this package should be sent. */
+/* #undef PACKAGE_BUGREPORT */
+
+/* Define to the full name of this package. */
+/* #undef PACKAGE_NAME */
+
+/* Define to the full name and version of this package. */
+/* #undef PACKAGE_STRING */
+
+/* Define to the one symbol short name of this package. */
+/* #undef PACKAGE_TARNAME */
+
+/* Define to the home page for this package. */
+/* #undef PACKAGE_URL */
+
+/* Define to the version of this package. */
+/* #undef PACKAGE_VERSION */
+
+/* Define if POSIX semaphores aren't enabled on your system */
+/* #undef POSIX_SEMAPHORES_NOT_ENABLED */
+
+/* Define if pthread_key_t is compatible with int. */
+#define PTHREAD_KEY_T_IS_COMPATIBLE_WITH_INT 1
+
+/* Defined if PTHREAD_SCOPE_SYSTEM supported. */
+#define PTHREAD_SYSTEM_SCHED_SUPPORTED 1
+
+/* Define as the preferred size in bits of long digits */
+/* #undef PYLONG_BITS_IN_DIGIT */
+
+/* enabled builtin hash modules */
+#define PY_BUILTIN_HASHLIB_HASHES "md5,sha1,sha256,sha512,sha3,blake2"
+
+/* Define if you want to coerce the C locale to a UTF-8 based locale */
+#define PY_COERCE_C_LOCALE 1
+
+/* Define to printf format modifier for Py_ssize_t */
+#define PY_FORMAT_SIZE_T "z"
+
+/* Define to 1 to build the sqlite module with loadable extensions support. */
+/* #undef PY_SQLITE_ENABLE_LOAD_EXTENSION */
+
+/* Define if SQLite was compiled with the serialize API */
+/* #undef PY_SQLITE_HAVE_SERIALIZE */
+
+/* Default cipher suites list for ssl module. 1: Python's preferred selection,
+ 2: leave OpenSSL defaults untouched, 0: custom string */
+#define PY_SSL_DEFAULT_CIPHERS 1
+
+/* Cipher suite string for PY_SSL_DEFAULT_CIPHERS=0 */
+/* #undef PY_SSL_DEFAULT_CIPHER_STRING */
+
+/* PEP 11 Support tier (1, 2, 3 or 0 for unsupported) */
+#define PY_SUPPORT_TIER 1
+
+/* Define if you want to build an interpreter with many run-time checks. */
+/* #undef Py_DEBUG */
+
+/* Defined if Python is built as a shared library. */
+#define Py_ENABLE_SHARED 1
+
+/* Define hash algorithm for str, bytes and memoryview. SipHash24: 1, FNV: 2,
+ SipHash13: 3, externally defined: 0 */
+/* #undef Py_HASH_ALGORITHM */
+
+/* Define if you want to enable internal statistics gathering. */
+/* #undef Py_STATS */
+
+/* Define if you want to enable tracing references for debugging purpose */
+/* #undef Py_TRACE_REFS */
+
+/* assume C89 semantics that RETSIGTYPE is always void */
+#define RETSIGTYPE void
+
+/* Define if setpgrp() must be called as setpgrp(0, 0). */
+/* #undef SETPGRP_HAVE_ARG */
+
+/* Define if i>>j for signed int i does not extend the sign bit when i < 0 */
+/* #undef SIGNED_RIGHT_SHIFT_ZERO_FILLS */
+
+/* The size of `double', as computed by sizeof. */
+#define SIZEOF_DOUBLE 8
+
+/* The size of `float', as computed by sizeof. */
+#define SIZEOF_FLOAT 4
+
+/* The size of `fpos_t', as computed by sizeof. */
+#define SIZEOF_FPOS_T 16
+
+/* The size of `int', as computed by sizeof. */
+#define SIZEOF_INT 4
+
+/* The size of `long', as computed by sizeof. */
+#define SIZEOF_LONG 8
+
+/* The size of `long double', as computed by sizeof. */
+#define SIZEOF_LONG_DOUBLE 16
+
+/* The size of `long long', as computed by sizeof. */
+#define SIZEOF_LONG_LONG 8
+
+/* The size of `off_t', as computed by sizeof. */
+#define SIZEOF_OFF_T 8
+
+/* The size of `pid_t', as computed by sizeof. */
+#define SIZEOF_PID_T 4
+
+/* The size of `pthread_key_t', as computed by sizeof. */
+#define SIZEOF_PTHREAD_KEY_T 4
+
+/* The size of `pthread_t', as computed by sizeof. */
+#define SIZEOF_PTHREAD_T 8
+
+/* The size of `short', as computed by sizeof. */
+#define SIZEOF_SHORT 2
+
+/* The size of `size_t', as computed by sizeof. */
+#define SIZEOF_SIZE_T 8
+
+/* The size of `time_t', as computed by sizeof. */
+#define SIZEOF_TIME_T 8
+
+/* The size of `uintptr_t', as computed by sizeof. */
+#define SIZEOF_UINTPTR_T 8
+
+/* The size of `void *', as computed by sizeof. */
+#define SIZEOF_VOID_P 8
+
+/* The size of `wchar_t', as computed by sizeof. */
+#define SIZEOF_WCHAR_T 4
+
+/* The size of `_Bool', as computed by sizeof. */
+#define SIZEOF__BOOL 1
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define if you can safely include both <sys/select.h> and <sys/time.h>
+ (which you can't on SCO ODT 3.0). */
+#define SYS_SELECT_WITH_SYS_TIME 1
+
+/* Custom thread stack size depending on chosen sanitizer runtimes. */
+/* #undef THREAD_STACK_SIZE */
+
+/* Library needed by timemodule.c: librt may be needed for clock_gettime() */
+/* #undef TIMEMODULE_LIB */
+
+/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
+#define TIME_WITH_SYS_TIME 1
+
+/* Define to 1 if your <sys/time.h> declares `struct tm'. */
+/* #undef TM_IN_SYS_TIME */
+
+/* Define if you want to use computed gotos in ceval.c. */
+/* #undef USE_COMPUTED_GOTOS */
+
+/* Enable extensions on AIX 3, Interix. */
+#ifndef _ALL_SOURCE
+# define _ALL_SOURCE 1
+#endif
+/* Enable GNU extensions on systems that have them. */
+#ifndef _GNU_SOURCE
+# define _GNU_SOURCE 1
+#endif
+/* Enable threading extensions on Solaris. */
+#ifndef _POSIX_PTHREAD_SEMANTICS
+# define _POSIX_PTHREAD_SEMANTICS 1
+#endif
+/* Enable extensions on HP NonStop. */
+#ifndef _TANDEM_SOURCE
+# define _TANDEM_SOURCE 1
+#endif
+/* Enable general extensions on Solaris. */
+#ifndef __EXTENSIONS__
+# define __EXTENSIONS__ 1
+#endif
+
+
+/* Define if WINDOW in curses.h offers a field _flags. */
+#define WINDOW_HAS_FLAGS 1
+
+/* Define if you want build the _decimal module using a coroutine-local rather
+ than a thread-local context */
+#define WITH_DECIMAL_CONTEXTVAR 1
+
+/* Define if you want documentation strings in extension modules */
+#define WITH_DOC_STRINGS 1
+
+/* Define if you want to compile in DTrace support */
+/* #undef WITH_DTRACE */
+
+/* Define if you want to use the new-style (Openstep, Rhapsody, MacOS) dynamic
+ linker (dyld) instead of the old-style (NextStep) dynamic linker (rld).
+ Dyld is necessary to support frameworks. */
+/* #undef WITH_DYLD */
+
+/* Define to build the readline module against Editline. */
+/* #undef WITH_EDITLINE */
+
+/* Define if you want to compile in object freelists optimization */
+#define WITH_FREELISTS 1
+
+/* Define to 1 if libintl is needed for locale functions. */
+/* #undef WITH_LIBINTL */
+
+/* Define if you want to produce an OpenStep/Rhapsody framework (shared
+ library plus accessory files). */
+/* #undef WITH_NEXT_FRAMEWORK */
+
+/* Define if you want to compile in Python-specific mallocs */
+#define WITH_PYMALLOC 1
+
+/* Define if you want pymalloc to be disabled when running under valgrind */
+/* #undef WITH_VALGRIND */
+
+/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
+ significant byte first (like Motorola and SPARC, unlike Intel). */
+#if defined AC_APPLE_UNIVERSAL_BUILD
+# if defined __BIG_ENDIAN__
+# define WORDS_BIGENDIAN 1
+# endif
+#else
+# ifndef WORDS_BIGENDIAN
+/* # undef WORDS_BIGENDIAN */
+# endif
+#endif
+
+/* Define if arithmetic is subject to x87-style double rounding issue */
+/* #undef X87_DOUBLE_ROUNDING */
+
+/* Define on OpenBSD to activate all library features */
+/* #undef _BSD_SOURCE */
+
+/* Define on Darwin to activate all library features */
+#define _DARWIN_C_SOURCE 1
+
+/* This must be set to 64 on some systems to enable large file support. */
+#define _FILE_OFFSET_BITS 64
+
+/* Define to include mbstate_t for mbrtowc */
+/* #undef _INCLUDE__STDC_A1_SOURCE */
+
+/* This must be defined on some systems to enable large file support. */
+#define _LARGEFILE_SOURCE 1
+
+/* This must be defined on AIX systems to enable large file support. */
+/* #undef _LARGE_FILES */
+
+/* Define to 1 if on MINIX. */
+/* #undef _MINIX */
+
+/* Define on NetBSD to activate all library features */
+#define _NETBSD_SOURCE 1
+
+/* Define to 2 if the system does not provide POSIX.1 features except with
+ this defined. */
+/* #undef _POSIX_1_SOURCE */
+
+/* Define to activate features from IEEE Stds 1003.1-2008 */
+#define _POSIX_C_SOURCE 200809L
+
+/* Define to 1 if you need to in order for `stat' and other things to work. */
+/* #undef _POSIX_SOURCE */
+
+/* Define if you have POSIX threads, and your system does not define that. */
+/* #undef _POSIX_THREADS */
+
+/* framework name */
+#define _PYTHONFRAMEWORK ""
+
+/* Define to force use of thread-safe errno, h_errno, and other functions */
+/* #undef _REENTRANT */
+
+/* Define to 1 if you want to emulate getpid() on WASI */
+/* #undef _WASI_EMULATED_GETPID */
+
+/* Define to 1 if you want to emulate process clocks on WASI */
+/* #undef _WASI_EMULATED_PROCESS_CLOCKS */
+
+/* Define to 1 if you want to emulate signals on WASI */
+/* #undef _WASI_EMULATED_SIGNAL */
+
+/* Define to the level of X/Open that your system supports */
+#define _XOPEN_SOURCE 700
+
+/* Define to activate Unix95-and-earlier features */
+#define _XOPEN_SOURCE_EXTENDED 1
+
+/* Define on FreeBSD to activate all library features */
+#define __BSD_VISIBLE 1
+
+/* Define to 'long' if <time.h> doesn't define. */
+/* #undef clock_t */
+
+/* Define to empty if `const' does not conform to ANSI C. */
+/* #undef const */
+
+/* Define to `int' if <sys/types.h> doesn't define. */
+/* #undef gid_t */
+
+/* Define to `int' if <sys/types.h> does not define. */
+/* #undef mode_t */
+
+/* Define to `long int' if <sys/types.h> does not define. */
+/* #undef off_t */
+
+/* Define to `int' if <sys/types.h> does not define. */
+/* #undef pid_t */
+
+/* Define to empty if the keyword does not work. */
+/* #undef signed */
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+/* Define to `int' if <sys/socket.h> does not define. */
+/* #undef socklen_t */
+
+/* Define to `int' if <sys/types.h> doesn't define. */
+/* #undef uid_t */
+
+
+/* Define the macros needed if on a UnixWare 7.x system. */
+#if defined(__USLC__) && defined(__SCO_VERSION__)
+#define STRICT_SYSV_CURSES /* Don't use ncurses extensions */
+#endif
+
+#endif /*Py_PYCONFIG_H*/
+
diff --git a/include/python3.10/pydtrace.h b/include/python3.11/pydtrace.h
similarity index 100%
rename from include/python3.10/pydtrace.h
rename to include/python3.11/pydtrace.h
diff --git a/include/python3.11/pyerrors.h b/include/python3.11/pyerrors.h
new file mode 100644
index 0000000..34e3de3
--- /dev/null
+++ b/include/python3.11/pyerrors.h
@@ -0,0 +1,331 @@
+#ifndef Py_ERRORS_H
+#define Py_ERRORS_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdarg.h> // va_list
+
+/* Error handling definitions */
+
+PyAPI_FUNC(void) PyErr_SetNone(PyObject *);
+PyAPI_FUNC(void) PyErr_SetObject(PyObject *, PyObject *);
+PyAPI_FUNC(void) PyErr_SetString(
+ PyObject *exception,
+ const char *string /* decoded from utf-8 */
+ );
+PyAPI_FUNC(PyObject *) PyErr_Occurred(void);
+PyAPI_FUNC(void) PyErr_Clear(void);
+PyAPI_FUNC(void) PyErr_Fetch(PyObject **, PyObject **, PyObject **);
+PyAPI_FUNC(void) PyErr_Restore(PyObject *, PyObject *, PyObject *);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030b0000
+PyAPI_FUNC(PyObject*) PyErr_GetHandledException(void);
+PyAPI_FUNC(void) PyErr_SetHandledException(PyObject *);
+#endif
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+PyAPI_FUNC(void) PyErr_GetExcInfo(PyObject **, PyObject **, PyObject **);
+PyAPI_FUNC(void) PyErr_SetExcInfo(PyObject *, PyObject *, PyObject *);
+#endif
+
+/* Defined in Python/pylifecycle.c
+
+ The Py_FatalError() function is replaced with a macro which logs
+ automatically the name of the current function, unless the Py_LIMITED_API
+ macro is defined. */
+PyAPI_FUNC(void) _Py_NO_RETURN Py_FatalError(const char *message);
+
+/* Error testing and normalization */
+PyAPI_FUNC(int) PyErr_GivenExceptionMatches(PyObject *, PyObject *);
+PyAPI_FUNC(int) PyErr_ExceptionMatches(PyObject *);
+PyAPI_FUNC(void) PyErr_NormalizeException(PyObject**, PyObject**, PyObject**);
+
+/* Traceback manipulation (PEP 3134) */
+PyAPI_FUNC(int) PyException_SetTraceback(PyObject *, PyObject *);
+PyAPI_FUNC(PyObject *) PyException_GetTraceback(PyObject *);
+
+/* Cause manipulation (PEP 3134) */
+PyAPI_FUNC(PyObject *) PyException_GetCause(PyObject *);
+PyAPI_FUNC(void) PyException_SetCause(PyObject *, PyObject *);
+
+/* Context manipulation (PEP 3134) */
+PyAPI_FUNC(PyObject *) PyException_GetContext(PyObject *);
+PyAPI_FUNC(void) PyException_SetContext(PyObject *, PyObject *);
+
+/* */
+
+#define PyExceptionClass_Check(x) \
+ (PyType_Check((x)) && \
+ PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS))
+
+#define PyExceptionInstance_Check(x) \
+ PyType_FastSubclass(Py_TYPE(x), Py_TPFLAGS_BASE_EXC_SUBCLASS)
+
+PyAPI_FUNC(const char *) PyExceptionClass_Name(PyObject *);
+
+#define PyExceptionInstance_Class(x) ((PyObject*)Py_TYPE(x))
+
+#define _PyBaseExceptionGroup_Check(x) \
+ PyObject_TypeCheck(x, (PyTypeObject *)PyExc_BaseExceptionGroup)
+
+/* Predefined exceptions */
+
+PyAPI_DATA(PyObject *) PyExc_BaseException;
+PyAPI_DATA(PyObject *) PyExc_Exception;
+PyAPI_DATA(PyObject *) PyExc_BaseExceptionGroup;
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
+PyAPI_DATA(PyObject *) PyExc_StopAsyncIteration;
+#endif
+PyAPI_DATA(PyObject *) PyExc_StopIteration;
+PyAPI_DATA(PyObject *) PyExc_GeneratorExit;
+PyAPI_DATA(PyObject *) PyExc_ArithmeticError;
+PyAPI_DATA(PyObject *) PyExc_LookupError;
+
+PyAPI_DATA(PyObject *) PyExc_AssertionError;
+PyAPI_DATA(PyObject *) PyExc_AttributeError;
+PyAPI_DATA(PyObject *) PyExc_BufferError;
+PyAPI_DATA(PyObject *) PyExc_EOFError;
+PyAPI_DATA(PyObject *) PyExc_FloatingPointError;
+PyAPI_DATA(PyObject *) PyExc_OSError;
+PyAPI_DATA(PyObject *) PyExc_ImportError;
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000
+PyAPI_DATA(PyObject *) PyExc_ModuleNotFoundError;
+#endif
+PyAPI_DATA(PyObject *) PyExc_IndexError;
+PyAPI_DATA(PyObject *) PyExc_KeyError;
+PyAPI_DATA(PyObject *) PyExc_KeyboardInterrupt;
+PyAPI_DATA(PyObject *) PyExc_MemoryError;
+PyAPI_DATA(PyObject *) PyExc_NameError;
+PyAPI_DATA(PyObject *) PyExc_OverflowError;
+PyAPI_DATA(PyObject *) PyExc_RuntimeError;
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
+PyAPI_DATA(PyObject *) PyExc_RecursionError;
+#endif
+PyAPI_DATA(PyObject *) PyExc_NotImplementedError;
+PyAPI_DATA(PyObject *) PyExc_SyntaxError;
+PyAPI_DATA(PyObject *) PyExc_IndentationError;
+PyAPI_DATA(PyObject *) PyExc_TabError;
+PyAPI_DATA(PyObject *) PyExc_ReferenceError;
+PyAPI_DATA(PyObject *) PyExc_SystemError;
+PyAPI_DATA(PyObject *) PyExc_SystemExit;
+PyAPI_DATA(PyObject *) PyExc_TypeError;
+PyAPI_DATA(PyObject *) PyExc_UnboundLocalError;
+PyAPI_DATA(PyObject *) PyExc_UnicodeError;
+PyAPI_DATA(PyObject *) PyExc_UnicodeEncodeError;
+PyAPI_DATA(PyObject *) PyExc_UnicodeDecodeError;
+PyAPI_DATA(PyObject *) PyExc_UnicodeTranslateError;
+PyAPI_DATA(PyObject *) PyExc_ValueError;
+PyAPI_DATA(PyObject *) PyExc_ZeroDivisionError;
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+PyAPI_DATA(PyObject *) PyExc_BlockingIOError;
+PyAPI_DATA(PyObject *) PyExc_BrokenPipeError;
+PyAPI_DATA(PyObject *) PyExc_ChildProcessError;
+PyAPI_DATA(PyObject *) PyExc_ConnectionError;
+PyAPI_DATA(PyObject *) PyExc_ConnectionAbortedError;
+PyAPI_DATA(PyObject *) PyExc_ConnectionRefusedError;
+PyAPI_DATA(PyObject *) PyExc_ConnectionResetError;
+PyAPI_DATA(PyObject *) PyExc_FileExistsError;
+PyAPI_DATA(PyObject *) PyExc_FileNotFoundError;
+PyAPI_DATA(PyObject *) PyExc_InterruptedError;
+PyAPI_DATA(PyObject *) PyExc_IsADirectoryError;
+PyAPI_DATA(PyObject *) PyExc_NotADirectoryError;
+PyAPI_DATA(PyObject *) PyExc_PermissionError;
+PyAPI_DATA(PyObject *) PyExc_ProcessLookupError;
+PyAPI_DATA(PyObject *) PyExc_TimeoutError;
+#endif
+
+
+/* Compatibility aliases */
+PyAPI_DATA(PyObject *) PyExc_EnvironmentError;
+PyAPI_DATA(PyObject *) PyExc_IOError;
+#ifdef MS_WINDOWS
+PyAPI_DATA(PyObject *) PyExc_WindowsError;
+#endif
+
+/* Predefined warning categories */
+PyAPI_DATA(PyObject *) PyExc_Warning;
+PyAPI_DATA(PyObject *) PyExc_UserWarning;
+PyAPI_DATA(PyObject *) PyExc_DeprecationWarning;
+PyAPI_DATA(PyObject *) PyExc_PendingDeprecationWarning;
+PyAPI_DATA(PyObject *) PyExc_SyntaxWarning;
+PyAPI_DATA(PyObject *) PyExc_RuntimeWarning;
+PyAPI_DATA(PyObject *) PyExc_FutureWarning;
+PyAPI_DATA(PyObject *) PyExc_ImportWarning;
+PyAPI_DATA(PyObject *) PyExc_UnicodeWarning;
+PyAPI_DATA(PyObject *) PyExc_BytesWarning;
+PyAPI_DATA(PyObject *) PyExc_EncodingWarning;
+PyAPI_DATA(PyObject *) PyExc_ResourceWarning;
+
+
+/* Convenience functions */
+
+PyAPI_FUNC(int) PyErr_BadArgument(void);
+PyAPI_FUNC(PyObject *) PyErr_NoMemory(void);
+PyAPI_FUNC(PyObject *) PyErr_SetFromErrno(PyObject *);
+PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilenameObject(
+ PyObject *, PyObject *);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000
+PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilenameObjects(
+ PyObject *, PyObject *, PyObject *);
+#endif
+PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilename(
+ PyObject *exc,
+ const char *filename /* decoded from the filesystem encoding */
+ );
+
+PyAPI_FUNC(PyObject *) PyErr_Format(
+ PyObject *exception,
+ const char *format, /* ASCII-encoded string */
+ ...
+ );
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
+PyAPI_FUNC(PyObject *) PyErr_FormatV(
+ PyObject *exception,
+ const char *format,
+ va_list vargs);
+#endif
+
+#ifdef MS_WINDOWS
+PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithFilename(
+ int ierr,
+ const char *filename /* decoded from the filesystem encoding */
+ );
+PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErr(int);
+PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilenameObject(
+ PyObject *,int, PyObject *);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000
+PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilenameObjects(
+ PyObject *,int, PyObject *, PyObject *);
+#endif
+PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilename(
+ PyObject *exc,
+ int ierr,
+ const char *filename /* decoded from the filesystem encoding */
+ );
+PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErr(PyObject *, int);
+#endif /* MS_WINDOWS */
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000
+PyAPI_FUNC(PyObject *) PyErr_SetImportErrorSubclass(PyObject *, PyObject *,
+ PyObject *, PyObject *);
+#endif
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+PyAPI_FUNC(PyObject *) PyErr_SetImportError(PyObject *, PyObject *,
+ PyObject *);
+#endif
+
+/* Export the old function so that the existing API remains available: */
+PyAPI_FUNC(void) PyErr_BadInternalCall(void);
+PyAPI_FUNC(void) _PyErr_BadInternalCall(const char *filename, int lineno);
+/* Mask the old API with a call to the new API for code compiled under
+ Python 2.0: */
+#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
+
+/* Function to create a new exception */
+PyAPI_FUNC(PyObject *) PyErr_NewException(
+ const char *name, PyObject *base, PyObject *dict);
+PyAPI_FUNC(PyObject *) PyErr_NewExceptionWithDoc(
+ const char *name, const char *doc, PyObject *base, PyObject *dict);
+PyAPI_FUNC(void) PyErr_WriteUnraisable(PyObject *);
+
+
+/* In signalmodule.c */
+PyAPI_FUNC(int) PyErr_CheckSignals(void);
+PyAPI_FUNC(void) PyErr_SetInterrupt(void);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000
+PyAPI_FUNC(int) PyErr_SetInterruptEx(int signum);
+#endif
+
+/* Support for adding program text to SyntaxErrors */
+PyAPI_FUNC(void) PyErr_SyntaxLocation(
+ const char *filename, /* decoded from the filesystem encoding */
+ int lineno);
+PyAPI_FUNC(void) PyErr_SyntaxLocationEx(
+ const char *filename, /* decoded from the filesystem encoding */
+ int lineno,
+ int col_offset);
+PyAPI_FUNC(PyObject *) PyErr_ProgramText(
+ const char *filename, /* decoded from the filesystem encoding */
+ int lineno);
+
+/* The following functions are used to create and modify unicode
+ exceptions from C */
+
+/* create a UnicodeDecodeError object */
+PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_Create(
+ const char *encoding, /* UTF-8 encoded string */
+ const char *object,
+ Py_ssize_t length,
+ Py_ssize_t start,
+ Py_ssize_t end,
+ const char *reason /* UTF-8 encoded string */
+ );
+
+/* get the encoding attribute */
+PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_GetEncoding(PyObject *);
+PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_GetEncoding(PyObject *);
+
+/* get the object attribute */
+PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_GetObject(PyObject *);
+PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_GetObject(PyObject *);
+PyAPI_FUNC(PyObject *) PyUnicodeTranslateError_GetObject(PyObject *);
+
+/* get the value of the start attribute (the int * may not be NULL)
+ return 0 on success, -1 on failure */
+PyAPI_FUNC(int) PyUnicodeEncodeError_GetStart(PyObject *, Py_ssize_t *);
+PyAPI_FUNC(int) PyUnicodeDecodeError_GetStart(PyObject *, Py_ssize_t *);
+PyAPI_FUNC(int) PyUnicodeTranslateError_GetStart(PyObject *, Py_ssize_t *);
+
+/* assign a new value to the start attribute
+ return 0 on success, -1 on failure */
+PyAPI_FUNC(int) PyUnicodeEncodeError_SetStart(PyObject *, Py_ssize_t);
+PyAPI_FUNC(int) PyUnicodeDecodeError_SetStart(PyObject *, Py_ssize_t);
+PyAPI_FUNC(int) PyUnicodeTranslateError_SetStart(PyObject *, Py_ssize_t);
+
+/* get the value of the end attribute (the int *may not be NULL)
+ return 0 on success, -1 on failure */
+PyAPI_FUNC(int) PyUnicodeEncodeError_GetEnd(PyObject *, Py_ssize_t *);
+PyAPI_FUNC(int) PyUnicodeDecodeError_GetEnd(PyObject *, Py_ssize_t *);
+PyAPI_FUNC(int) PyUnicodeTranslateError_GetEnd(PyObject *, Py_ssize_t *);
+
+/* assign a new value to the end attribute
+ return 0 on success, -1 on failure */
+PyAPI_FUNC(int) PyUnicodeEncodeError_SetEnd(PyObject *, Py_ssize_t);
+PyAPI_FUNC(int) PyUnicodeDecodeError_SetEnd(PyObject *, Py_ssize_t);
+PyAPI_FUNC(int) PyUnicodeTranslateError_SetEnd(PyObject *, Py_ssize_t);
+
+/* get the value of the reason attribute */
+PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_GetReason(PyObject *);
+PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_GetReason(PyObject *);
+PyAPI_FUNC(PyObject *) PyUnicodeTranslateError_GetReason(PyObject *);
+
+/* assign a new value to the reason attribute
+ return 0 on success, -1 on failure */
+PyAPI_FUNC(int) PyUnicodeEncodeError_SetReason(
+ PyObject *exc,
+ const char *reason /* UTF-8 encoded string */
+ );
+PyAPI_FUNC(int) PyUnicodeDecodeError_SetReason(
+ PyObject *exc,
+ const char *reason /* UTF-8 encoded string */
+ );
+PyAPI_FUNC(int) PyUnicodeTranslateError_SetReason(
+ PyObject *exc,
+ const char *reason /* UTF-8 encoded string */
+ );
+
+PyAPI_FUNC(int) PyOS_snprintf(char *str, size_t size, const char *format, ...)
+ Py_GCC_ATTRIBUTE((format(printf, 3, 4)));
+PyAPI_FUNC(int) PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va)
+ Py_GCC_ATTRIBUTE((format(printf, 3, 0)));
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_ERRORS_H
+# include "cpython/pyerrors.h"
+# undef Py_CPYTHON_ERRORS_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_ERRORS_H */
diff --git a/include/python3.10/pyexpat.h b/include/python3.11/pyexpat.h
similarity index 100%
rename from include/python3.10/pyexpat.h
rename to include/python3.11/pyexpat.h
diff --git a/include/python3.11/pyframe.h b/include/python3.11/pyframe.h
new file mode 100644
index 0000000..13d5231
--- /dev/null
+++ b/include/python3.11/pyframe.h
@@ -0,0 +1,26 @@
+/* Limited C API of PyFrame API
+ *
+ * Include "frameobject.h" to get the PyFrameObject structure.
+ */
+
+#ifndef Py_PYFRAME_H
+#define Py_PYFRAME_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Return the line of code the frame is currently executing. */
+PyAPI_FUNC(int) PyFrame_GetLineNumber(PyFrameObject *);
+
+PyAPI_FUNC(PyCodeObject *) PyFrame_GetCode(PyFrameObject *frame);
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_PYFRAME_H
+# include "cpython/pyframe.h"
+# undef Py_CPYTHON_PYFRAME_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_PYFRAME_H */
diff --git a/include/python3.11/pyhash.h b/include/python3.11/pyhash.h
new file mode 100644
index 0000000..182d223
--- /dev/null
+++ b/include/python3.11/pyhash.h
@@ -0,0 +1,144 @@
+#ifndef Py_HASH_H
+
+#define Py_HASH_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Helpers for hash functions */
+#ifndef Py_LIMITED_API
+PyAPI_FUNC(Py_hash_t) _Py_HashDouble(PyObject *, double);
+PyAPI_FUNC(Py_hash_t) _Py_HashPointer(const void*);
+// Similar to _Py_HashPointer(), but don't replace -1 with -2
+PyAPI_FUNC(Py_hash_t) _Py_HashPointerRaw(const void*);
+PyAPI_FUNC(Py_hash_t) _Py_HashBytes(const void*, Py_ssize_t);
+#endif
+
+/* Prime multiplier used in string and various other hashes. */
+#define _PyHASH_MULTIPLIER 1000003UL /* 0xf4243 */
+
+/* Parameters used for the numeric hash implementation. See notes for
+ _Py_HashDouble in Python/pyhash.c. Numeric hashes are based on
+ reduction modulo the prime 2**_PyHASH_BITS - 1. */
+
+#if SIZEOF_VOID_P >= 8
+# define _PyHASH_BITS 61
+#else
+# define _PyHASH_BITS 31
+#endif
+
+#define _PyHASH_MODULUS (((size_t)1 << _PyHASH_BITS) - 1)
+#define _PyHASH_INF 314159
+#define _PyHASH_IMAG _PyHASH_MULTIPLIER
+
+
+/* hash secret
+ *
+ * memory layout on 64 bit systems
+ * cccccccc cccccccc cccccccc uc -- unsigned char[24]
+ * pppppppp ssssssss ........ fnv -- two Py_hash_t
+ * k0k0k0k0 k1k1k1k1 ........ siphash -- two uint64_t
+ * ........ ........ ssssssss djbx33a -- 16 bytes padding + one Py_hash_t
+ * ........ ........ eeeeeeee pyexpat XML hash salt
+ *
+ * memory layout on 32 bit systems
+ * cccccccc cccccccc cccccccc uc
+ * ppppssss ........ ........ fnv -- two Py_hash_t
+ * k0k0k0k0 k1k1k1k1 ........ siphash -- two uint64_t (*)
+ * ........ ........ ssss.... djbx33a -- 16 bytes padding + one Py_hash_t
+ * ........ ........ eeee.... pyexpat XML hash salt
+ *
+ * (*) The siphash member may not be available on 32 bit platforms without
+ * an unsigned int64 data type.
+ */
+#ifndef Py_LIMITED_API
+typedef union {
+ /* ensure 24 bytes */
+ unsigned char uc[24];
+ /* two Py_hash_t for FNV */
+ struct {
+ Py_hash_t prefix;
+ Py_hash_t suffix;
+ } fnv;
+ /* two uint64 for SipHash24 */
+ struct {
+ uint64_t k0;
+ uint64_t k1;
+ } siphash;
+ /* a different (!) Py_hash_t for small string optimization */
+ struct {
+ unsigned char padding[16];
+ Py_hash_t suffix;
+ } djbx33a;
+ struct {
+ unsigned char padding[16];
+ Py_hash_t hashsalt;
+ } expat;
+} _Py_HashSecret_t;
+PyAPI_DATA(_Py_HashSecret_t) _Py_HashSecret;
+
+#ifdef Py_DEBUG
+PyAPI_DATA(int) _Py_HashSecret_Initialized;
+#endif
+
+
+/* hash function definition */
+typedef struct {
+ Py_hash_t (*const hash)(const void *, Py_ssize_t);
+ const char *name;
+ const int hash_bits;
+ const int seed_bits;
+} PyHash_FuncDef;
+
+PyAPI_FUNC(PyHash_FuncDef*) PyHash_GetFuncDef(void);
+#endif
+
+
+/* cutoff for small string DJBX33A optimization in range [1, cutoff).
+ *
+ * About 50% of the strings in a typical Python application are smaller than
+ * 6 to 7 chars. However DJBX33A is vulnerable to hash collision attacks.
+ * NEVER use DJBX33A for long strings!
+ *
+ * A Py_HASH_CUTOFF of 0 disables small string optimization. 32 bit platforms
+ * should use a smaller cutoff because it is easier to create colliding
+ * strings. A cutoff of 7 on 64bit platforms and 5 on 32bit platforms should
+ * provide a decent safety margin.
+ */
+#ifndef Py_HASH_CUTOFF
+# define Py_HASH_CUTOFF 0
+#elif (Py_HASH_CUTOFF > 7 || Py_HASH_CUTOFF < 0)
+# error Py_HASH_CUTOFF must in range 0...7.
+#endif /* Py_HASH_CUTOFF */
+
+
+/* hash algorithm selection
+ *
+ * The values for Py_HASH_* are hard-coded in the
+ * configure script.
+ *
+ * - FNV and SIPHASH* are available on all platforms and architectures.
+ * - With EXTERNAL embedders can provide an alternative implementation with::
+ *
+ * PyHash_FuncDef PyHash_Func = {...};
+ *
+ * XXX: Figure out __declspec() for extern PyHash_FuncDef.
+ */
+#define Py_HASH_EXTERNAL 0
+#define Py_HASH_SIPHASH24 1
+#define Py_HASH_FNV 2
+#define Py_HASH_SIPHASH13 3
+
+#ifndef Py_HASH_ALGORITHM
+# ifndef HAVE_ALIGNED_REQUIRED
+# define Py_HASH_ALGORITHM Py_HASH_SIPHASH13
+# else
+# define Py_HASH_ALGORITHM Py_HASH_FNV
+# endif /* uint64_t && uint32_t && aligned */
+#endif /* Py_HASH_ALGORITHM */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !Py_HASH_H */
diff --git a/include/python3.11/pylifecycle.h b/include/python3.11/pylifecycle.h
new file mode 100644
index 0000000..e4c3b09
--- /dev/null
+++ b/include/python3.11/pylifecycle.h
@@ -0,0 +1,78 @@
+
+/* Interfaces to configure, query, create & destroy the Python runtime */
+
+#ifndef Py_PYLIFECYCLE_H
+#define Py_PYLIFECYCLE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Initialization and finalization */
+PyAPI_FUNC(void) Py_Initialize(void);
+PyAPI_FUNC(void) Py_InitializeEx(int);
+PyAPI_FUNC(void) Py_Finalize(void);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000
+PyAPI_FUNC(int) Py_FinalizeEx(void);
+#endif
+PyAPI_FUNC(int) Py_IsInitialized(void);
+
+/* Subinterpreter support */
+PyAPI_FUNC(PyThreadState *) Py_NewInterpreter(void);
+PyAPI_FUNC(void) Py_EndInterpreter(PyThreadState *);
+
+
+/* Py_PyAtExit is for the atexit module, Py_AtExit is for low-level
+ * exit functions.
+ */
+PyAPI_FUNC(int) Py_AtExit(void (*func)(void));
+
+PyAPI_FUNC(void) _Py_NO_RETURN Py_Exit(int);
+
+/* Bootstrap __main__ (defined in Modules/main.c) */
+PyAPI_FUNC(int) Py_Main(int argc, wchar_t **argv);
+PyAPI_FUNC(int) Py_BytesMain(int argc, char **argv);
+
+/* In pathconfig.c */
+Py_DEPRECATED(3.11) PyAPI_FUNC(void) Py_SetProgramName(const wchar_t *);
+PyAPI_FUNC(wchar_t *) Py_GetProgramName(void);
+
+Py_DEPRECATED(3.11) PyAPI_FUNC(void) Py_SetPythonHome(const wchar_t *);
+PyAPI_FUNC(wchar_t *) Py_GetPythonHome(void);
+
+PyAPI_FUNC(wchar_t *) Py_GetProgramFullPath(void);
+
+PyAPI_FUNC(wchar_t *) Py_GetPrefix(void);
+PyAPI_FUNC(wchar_t *) Py_GetExecPrefix(void);
+PyAPI_FUNC(wchar_t *) Py_GetPath(void);
+Py_DEPRECATED(3.11) PyAPI_FUNC(void) Py_SetPath(const wchar_t *);
+#ifdef MS_WINDOWS
+int _Py_CheckPython3(void);
+#endif
+
+/* In their own files */
+PyAPI_FUNC(const char *) Py_GetVersion(void);
+PyAPI_FUNC(const char *) Py_GetPlatform(void);
+PyAPI_FUNC(const char *) Py_GetCopyright(void);
+PyAPI_FUNC(const char *) Py_GetCompiler(void);
+PyAPI_FUNC(const char *) Py_GetBuildInfo(void);
+
+/* Signals */
+typedef void (*PyOS_sighandler_t)(int);
+PyAPI_FUNC(PyOS_sighandler_t) PyOS_getsig(int);
+PyAPI_FUNC(PyOS_sighandler_t) PyOS_setsig(int, PyOS_sighandler_t);
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030B0000
+PyAPI_DATA(const unsigned long) Py_Version;
+#endif
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_PYLIFECYCLE_H
+# include "cpython/pylifecycle.h"
+# undef Py_CPYTHON_PYLIFECYCLE_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_PYLIFECYCLE_H */
diff --git a/include/python3.10/pymacconfig.h b/include/python3.11/pymacconfig.h
similarity index 100%
rename from include/python3.10/pymacconfig.h
rename to include/python3.11/pymacconfig.h
diff --git a/include/python3.11/pymacro.h b/include/python3.11/pymacro.h
new file mode 100644
index 0000000..5840966
--- /dev/null
+++ b/include/python3.11/pymacro.h
@@ -0,0 +1,158 @@
+#ifndef Py_PYMACRO_H
+#define Py_PYMACRO_H
+
+// gh-91782: On FreeBSD 12, if the _POSIX_C_SOURCE and _XOPEN_SOURCE macros are
+// defined, <sys/cdefs.h> disables C11 support and <assert.h> does not define
+// the static_assert() macro.
+// https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=255290
+//
+// macOS <= 10.10 doesn't define static_assert in assert.h at all despite
+// having C11 compiler support.
+//
+// static_assert is defined in glibc from version 2.16. Compiler support for
+// the C11 _Static_assert keyword is in gcc >= 4.6.
+//
+// MSVC makes static_assert a keyword in C11-17, contrary to the standards.
+//
+// In C++11 and C2x, static_assert is a keyword, redefining is undefined
+// behaviour. So only define if building as C (if __STDC_VERSION__ is defined),
+// not C++, and only for C11-17.
+#if !defined(static_assert) && (defined(__GNUC__) || defined(__clang__)) \
+ && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L \
+ && __STDC_VERSION__ <= 201710L
+# define static_assert _Static_assert
+#endif
+
+/* Minimum value between x and y */
+#define Py_MIN(x, y) (((x) > (y)) ? (y) : (x))
+
+/* Maximum value between x and y */
+#define Py_MAX(x, y) (((x) > (y)) ? (x) : (y))
+
+/* Absolute value of the number x */
+#define Py_ABS(x) ((x) < 0 ? -(x) : (x))
+
+#define _Py_XSTRINGIFY(x) #x
+
+/* Convert the argument to a string. For example, Py_STRINGIFY(123) is replaced
+ with "123" by the preprocessor. Defines are also replaced by their value.
+ For example Py_STRINGIFY(__LINE__) is replaced by the line number, not
+ by "__LINE__". */
+#define Py_STRINGIFY(x) _Py_XSTRINGIFY(x)
+
+/* Get the size of a structure member in bytes */
+#define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member)
+
+/* Argument must be a char or an int in [-128, 127] or [0, 255]. */
+#define Py_CHARMASK(c) ((unsigned char)((c) & 0xff))
+
+/* Assert a build-time dependency, as an expression.
+
+ Your compile will fail if the condition isn't true, or can't be evaluated
+ by the compiler. This can be used in an expression: its value is 0.
+
+ Example:
+
+ #define foo_to_char(foo) \
+ ((char *)(foo) \
+ + Py_BUILD_ASSERT_EXPR(offsetof(struct foo, string) == 0))
+
+ Written by Rusty Russell, public domain, http://ccodearchive.net/ */
+#define Py_BUILD_ASSERT_EXPR(cond) \
+ (sizeof(char [1 - 2*!(cond)]) - 1)
+
+#define Py_BUILD_ASSERT(cond) do { \
+ (void)Py_BUILD_ASSERT_EXPR(cond); \
+ } while(0)
+
+/* Get the number of elements in a visible array
+
+ This does not work on pointers, or arrays declared as [], or function
+ parameters. With correct compiler support, such usage will cause a build
+ error (see Py_BUILD_ASSERT_EXPR).
+
+ Written by Rusty Russell, public domain, http://ccodearchive.net/
+
+ Requires at GCC 3.1+ */
+#if (defined(__GNUC__) && !defined(__STRICT_ANSI__) && \
+ (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)) || (__GNUC__ >= 4)))
+/* Two gcc extensions.
+ &a[0] degrades to a pointer: a different type from an array */
+#define Py_ARRAY_LENGTH(array) \
+ (sizeof(array) / sizeof((array)[0]) \
+ + Py_BUILD_ASSERT_EXPR(!__builtin_types_compatible_p(typeof(array), \
+ typeof(&(array)[0]))))
+#else
+#define Py_ARRAY_LENGTH(array) \
+ (sizeof(array) / sizeof((array)[0]))
+#endif
+
+
+/* Define macros for inline documentation. */
+#define PyDoc_VAR(name) static const char name[]
+#define PyDoc_STRVAR(name,str) PyDoc_VAR(name) = PyDoc_STR(str)
+#ifdef WITH_DOC_STRINGS
+#define PyDoc_STR(str) str
+#else
+#define PyDoc_STR(str) ""
+#endif
+
+/* Below "a" is a power of 2. */
+/* Round down size "n" to be a multiple of "a". */
+#define _Py_SIZE_ROUND_DOWN(n, a) ((size_t)(n) & ~(size_t)((a) - 1))
+/* Round up size "n" to be a multiple of "a". */
+#define _Py_SIZE_ROUND_UP(n, a) (((size_t)(n) + \
+ (size_t)((a) - 1)) & ~(size_t)((a) - 1))
+/* Round pointer "p" down to the closest "a"-aligned address <= "p". */
+#define _Py_ALIGN_DOWN(p, a) ((void *)((uintptr_t)(p) & ~(uintptr_t)((a) - 1)))
+/* Round pointer "p" up to the closest "a"-aligned address >= "p". */
+#define _Py_ALIGN_UP(p, a) ((void *)(((uintptr_t)(p) + \
+ (uintptr_t)((a) - 1)) & ~(uintptr_t)((a) - 1)))
+/* Check if pointer "p" is aligned to "a"-bytes boundary. */
+#define _Py_IS_ALIGNED(p, a) (!((uintptr_t)(p) & (uintptr_t)((a) - 1)))
+
+/* Use this for unused arguments in a function definition to silence compiler
+ * warnings. Example:
+ *
+ * int func(int a, int Py_UNUSED(b)) { return a; }
+ */
+#if defined(__GNUC__) || defined(__clang__)
+# define Py_UNUSED(name) _unused_ ## name __attribute__((unused))
+#else
+# define Py_UNUSED(name) _unused_ ## name
+#endif
+
+#if defined(RANDALL_WAS_HERE)
+# define Py_UNREACHABLE() \
+ Py_FatalError( \
+ "If you're seeing this, the code is in what I thought was\n" \
+ "an unreachable state.\n\n" \
+ "I could give you advice for what to do, but honestly, why\n" \
+ "should you trust me? I clearly screwed this up. I'm writing\n" \
+ "a message that should never appear, yet I know it will\n" \
+ "probably appear someday.\n\n" \
+ "On a deep level, I know I'm not up to this task.\n" \
+ "I'm so sorry.\n" \
+ "https://xkcd.com/2200")
+#elif defined(Py_DEBUG)
+# define Py_UNREACHABLE() \
+ Py_FatalError( \
+ "We've reached an unreachable state. Anything is possible.\n" \
+ "The limits were in our heads all along. Follow your dreams.\n" \
+ "https://xkcd.com/2200")
+#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
+# define Py_UNREACHABLE() __builtin_unreachable()
+#elif defined(__clang__) || defined(__INTEL_COMPILER)
+# define Py_UNREACHABLE() __builtin_unreachable()
+#elif defined(_MSC_VER)
+# define Py_UNREACHABLE() __assume(0)
+#else
+# define Py_UNREACHABLE() \
+ Py_FatalError("Unreachable C code path reached")
+#endif
+
+// Prevent using an expression as a l-value.
+// For example, "int x; _Py_RVALUE(x) = 1;" fails with a compiler error.
+#define _Py_RVALUE(EXPR) ((void)0, (EXPR))
+
+#endif /* Py_PYMACRO_H */
diff --git a/include/python3.11/pymath.h b/include/python3.11/pymath.h
new file mode 100644
index 0000000..772b67e
--- /dev/null
+++ b/include/python3.11/pymath.h
@@ -0,0 +1,65 @@
+// Symbols and macros to supply platform-independent interfaces to mathematical
+// functions and constants.
+
+#ifndef Py_PYMATH_H
+#define Py_PYMATH_H
+
+/* High precision definition of pi and e (Euler)
+ * The values are taken from libc6's math.h.
+ */
+#ifndef Py_MATH_PIl
+#define Py_MATH_PIl 3.1415926535897932384626433832795029L
+#endif
+#ifndef Py_MATH_PI
+#define Py_MATH_PI 3.14159265358979323846
+#endif
+
+#ifndef Py_MATH_El
+#define Py_MATH_El 2.7182818284590452353602874713526625L
+#endif
+
+#ifndef Py_MATH_E
+#define Py_MATH_E 2.7182818284590452354
+#endif
+
+/* Tau (2pi) to 40 digits, taken from tauday.com/tau-digits. */
+#ifndef Py_MATH_TAU
+#define Py_MATH_TAU 6.2831853071795864769252867665590057683943L
+#endif
+
+// Py_IS_NAN(X)
+// Return 1 if float or double arg is a NaN, else 0.
+#define Py_IS_NAN(X) isnan(X)
+
+// Py_IS_INFINITY(X)
+// Return 1 if float or double arg is an infinity, else 0.
+#define Py_IS_INFINITY(X) isinf(X)
+
+// Py_IS_FINITE(X)
+// Return 1 if float or double arg is neither infinite nor NAN, else 0.
+#define Py_IS_FINITE(X) isfinite(X)
+
+/* HUGE_VAL is supposed to expand to a positive double infinity. Python
+ * uses Py_HUGE_VAL instead because some platforms are broken in this
+ * respect. We used to embed code in pyport.h to try to worm around that,
+ * but different platforms are broken in conflicting ways. If you're on
+ * a platform where HUGE_VAL is defined incorrectly, fiddle your Python
+ * config to #define Py_HUGE_VAL to something that works on your platform.
+ */
+#ifndef Py_HUGE_VAL
+# define Py_HUGE_VAL HUGE_VAL
+#endif
+
+// Py_NAN: Value that evaluates to a quiet Not-a-Number (NaN).
+#if !defined(Py_NAN)
+# if _Py__has_builtin(__builtin_nan)
+ // Built-in implementation of the ISO C99 function nan(): quiet NaN.
+# define Py_NAN (__builtin_nan(""))
+#else
+ // Use C99 NAN constant: quiet Not-A-Number.
+ // NAN is a float, Py_NAN is a double: cast to double.
+# define Py_NAN ((double)NAN)
+# endif
+#endif
+
+#endif /* Py_PYMATH_H */
diff --git a/include/python3.11/pymem.h b/include/python3.11/pymem.h
new file mode 100644
index 0000000..c15ad10
--- /dev/null
+++ b/include/python3.11/pymem.h
@@ -0,0 +1,104 @@
+/* The PyMem_ family: low-level memory allocation interfaces.
+ See objimpl.h for the PyObject_ memory family.
+*/
+
+#ifndef Py_PYMEM_H
+#define Py_PYMEM_H
+
+#include "pyport.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* BEWARE:
+
+ Each interface exports both functions and macros. Extension modules should
+ use the functions, to ensure binary compatibility across Python versions.
+ Because the Python implementation is free to change internal details, and
+ the macros may (or may not) expose details for speed, if you do use the
+ macros you must recompile your extensions with each Python release.
+
+ Never mix calls to PyMem_ with calls to the platform malloc/realloc/
+ calloc/free. For example, on Windows different DLLs may end up using
+ different heaps, and if you use PyMem_Malloc you'll get the memory from the
+ heap used by the Python DLL; it could be a disaster if you free()'ed that
+ directly in your own extension. Using PyMem_Free instead ensures Python
+ can return the memory to the proper heap. As another example, in
+ a debug build (Py_DEBUG macro), Python wraps all calls to all PyMem_ and
+ PyObject_ memory functions in special debugging wrappers that add additional
+ debugging info to dynamic memory blocks. The system routines have no idea
+ what to do with that stuff, and the Python wrappers have no idea what to do
+ with raw blocks obtained directly by the system routines then.
+
+ The GIL must be held when using these APIs.
+*/
+
+/*
+ * Raw memory interface
+ * ====================
+ */
+
+/* Functions
+
+ Functions supplying platform-independent semantics for malloc/realloc/
+ free. These functions make sure that allocating 0 bytes returns a distinct
+ non-NULL pointer (whenever possible -- if we're flat out of memory, NULL
+ may be returned), even if the platform malloc and realloc don't.
+ Returned pointers must be checked for NULL explicitly. No action is
+ performed on failure (no exception is set, no warning is printed, etc).
+*/
+
+PyAPI_FUNC(void *) PyMem_Malloc(size_t size);
+PyAPI_FUNC(void *) PyMem_Calloc(size_t nelem, size_t elsize);
+PyAPI_FUNC(void *) PyMem_Realloc(void *ptr, size_t new_size);
+PyAPI_FUNC(void) PyMem_Free(void *ptr);
+
+/*
+ * Type-oriented memory interface
+ * ==============================
+ *
+ * Allocate memory for n objects of the given type. Returns a new pointer
+ * or NULL if the request was too large or memory allocation failed. Use
+ * these macros rather than doing the multiplication yourself so that proper
+ * overflow checking is always done.
+ */
+
+#define PyMem_New(type, n) \
+ ( ((size_t)(n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \
+ ( (type *) PyMem_Malloc((n) * sizeof(type)) ) )
+
+/*
+ * The value of (p) is always clobbered by this macro regardless of success.
+ * The caller MUST check if (p) is NULL afterwards and deal with the memory
+ * error if so. This means the original value of (p) MUST be saved for the
+ * caller's memory error handler to not lose track of it.
+ */
+#define PyMem_Resize(p, type, n) \
+ ( (p) = ((size_t)(n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \
+ (type *) PyMem_Realloc((p), (n) * sizeof(type)) )
+
+
+// Deprecated aliases only kept for backward compatibility.
+// PyMem_Del and PyMem_DEL are defined with no parameter to be able to use
+// them as function pointers (ex: dealloc = PyMem_Del).
+#define PyMem_MALLOC(n) PyMem_Malloc(n)
+#define PyMem_NEW(type, n) PyMem_New(type, n)
+#define PyMem_REALLOC(p, n) PyMem_Realloc(p, n)
+#define PyMem_RESIZE(p, type, n) PyMem_Resize(p, type, n)
+#define PyMem_FREE(p) PyMem_Free(p)
+#define PyMem_Del PyMem_Free
+#define PyMem_DEL PyMem_Free
+
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_PYMEM_H
+# include "cpython/pymem.h"
+# undef Py_CPYTHON_PYMEM_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !Py_PYMEM_H */
diff --git a/include/python3.11/pyport.h b/include/python3.11/pyport.h
new file mode 100644
index 0000000..93250f4
--- /dev/null
+++ b/include/python3.11/pyport.h
@@ -0,0 +1,742 @@
+#ifndef Py_PYPORT_H
+#define Py_PYPORT_H
+
+#include "pyconfig.h" /* include for defines */
+
+#include <inttypes.h>
+
+#include <limits.h>
+#ifndef UCHAR_MAX
+# error "limits.h must define UCHAR_MAX"
+#endif
+#if UCHAR_MAX != 255
+# error "Python's source code assumes C's unsigned char is an 8-bit type"
+#endif
+
+
+// Macro to use C++ static_cast<> in the Python C API.
+#ifdef __cplusplus
+# define _Py_STATIC_CAST(type, expr) static_cast<type>(expr)
+#else
+# define _Py_STATIC_CAST(type, expr) ((type)(expr))
+#endif
+// Macro to use the more powerful/dangerous C-style cast even in C++.
+#define _Py_CAST(type, expr) ((type)(expr))
+
+// Static inline functions should use _Py_NULL rather than using directly NULL
+// to prevent C++ compiler warnings. On C++11 and newer, _Py_NULL is defined as
+// nullptr.
+#if defined(__cplusplus) && __cplusplus >= 201103
+# define _Py_NULL nullptr
+#else
+# define _Py_NULL NULL
+#endif
+
+
+/* Defines to build Python and its standard library:
+ *
+ * - Py_BUILD_CORE: Build Python core. Give access to Python internals, but
+ * should not be used by third-party modules.
+ * - Py_BUILD_CORE_BUILTIN: Build a Python stdlib module as a built-in module.
+ * - Py_BUILD_CORE_MODULE: Build a Python stdlib module as a dynamic library.
+ *
+ * Py_BUILD_CORE_BUILTIN and Py_BUILD_CORE_MODULE imply Py_BUILD_CORE.
+ *
+ * On Windows, Py_BUILD_CORE_MODULE exports "PyInit_xxx" symbol, whereas
+ * Py_BUILD_CORE_BUILTIN does not.
+ */
+#if defined(Py_BUILD_CORE_BUILTIN) && !defined(Py_BUILD_CORE)
+# define Py_BUILD_CORE
+#endif
+#if defined(Py_BUILD_CORE_MODULE) && !defined(Py_BUILD_CORE)
+# define Py_BUILD_CORE
+#endif
+
+
+/**************************************************************************
+Symbols and macros to supply platform-independent interfaces to basic
+C language & library operations whose spellings vary across platforms.
+
+Please try to make documentation here as clear as possible: by definition,
+the stuff here is trying to illuminate C's darkest corners.
+
+Config #defines referenced here:
+
+SIGNED_RIGHT_SHIFT_ZERO_FILLS
+Meaning: To be defined iff i>>j does not extend the sign bit when i is a
+ signed integral type and i < 0.
+Used in: Py_ARITHMETIC_RIGHT_SHIFT
+
+Py_DEBUG
+Meaning: Extra checks compiled in for debug mode.
+Used in: Py_SAFE_DOWNCAST
+
+**************************************************************************/
+
+/* typedefs for some C9X-defined synonyms for integral types.
+ *
+ * The names in Python are exactly the same as the C9X names, except with a
+ * Py_ prefix. Until C9X is universally implemented, this is the only way
+ * to ensure that Python gets reliable names that don't conflict with names
+ * in non-Python code that are playing their own tricks to define the C9X
+ * names.
+ *
+ * NOTE: don't go nuts here! Python has no use for *most* of the C9X
+ * integral synonyms. Only define the ones we actually need.
+ */
+
+/* long long is required. Ensure HAVE_LONG_LONG is defined for compatibility. */
+#ifndef HAVE_LONG_LONG
+#define HAVE_LONG_LONG 1
+#endif
+#ifndef PY_LONG_LONG
+#define PY_LONG_LONG long long
+/* If LLONG_MAX is defined in limits.h, use that. */
+#define PY_LLONG_MIN LLONG_MIN
+#define PY_LLONG_MAX LLONG_MAX
+#define PY_ULLONG_MAX ULLONG_MAX
+#endif
+
+#define PY_UINT32_T uint32_t
+#define PY_UINT64_T uint64_t
+
+/* Signed variants of the above */
+#define PY_INT32_T int32_t
+#define PY_INT64_T int64_t
+
+/* PYLONG_BITS_IN_DIGIT describes the number of bits per "digit" (limb) in the
+ * PyLongObject implementation (longintrepr.h). It's currently either 30 or 15,
+ * defaulting to 30. The 15-bit digit option may be removed in the future.
+ */
+#ifndef PYLONG_BITS_IN_DIGIT
+#define PYLONG_BITS_IN_DIGIT 30
+#endif
+
+/* uintptr_t is the C9X name for an unsigned integral type such that a
+ * legitimate void* can be cast to uintptr_t and then back to void* again
+ * without loss of information. Similarly for intptr_t, wrt a signed
+ * integral type.
+ */
+typedef uintptr_t Py_uintptr_t;
+typedef intptr_t Py_intptr_t;
+
+/* Py_ssize_t is a signed integral type such that sizeof(Py_ssize_t) ==
+ * sizeof(size_t). C99 doesn't define such a thing directly (size_t is an
+ * unsigned integral type). See PEP 353 for details.
+ * PY_SSIZE_T_MAX is the largest positive value of type Py_ssize_t.
+ */
+#ifdef HAVE_PY_SSIZE_T
+
+#elif HAVE_SSIZE_T
+typedef ssize_t Py_ssize_t;
+# define PY_SSIZE_T_MAX SSIZE_MAX
+#elif SIZEOF_VOID_P == SIZEOF_SIZE_T
+typedef Py_intptr_t Py_ssize_t;
+# define PY_SSIZE_T_MAX INTPTR_MAX
+#else
+# error "Python needs a typedef for Py_ssize_t in pyport.h."
+#endif
+
+/* Smallest negative value of type Py_ssize_t. */
+#define PY_SSIZE_T_MIN (-PY_SSIZE_T_MAX-1)
+
+/* Py_hash_t is the same size as a pointer. */
+#define SIZEOF_PY_HASH_T SIZEOF_SIZE_T
+typedef Py_ssize_t Py_hash_t;
+/* Py_uhash_t is the unsigned equivalent needed to calculate numeric hash. */
+#define SIZEOF_PY_UHASH_T SIZEOF_SIZE_T
+typedef size_t Py_uhash_t;
+
+/* Now PY_SSIZE_T_CLEAN is mandatory. This is just for backward compatibility. */
+typedef Py_ssize_t Py_ssize_clean_t;
+
+/* Largest possible value of size_t. */
+#define PY_SIZE_MAX SIZE_MAX
+
+/* Macro kept for backward compatibility: use "z" in new code.
+ *
+ * PY_FORMAT_SIZE_T is a platform-specific modifier for use in a printf
+ * format to convert an argument with the width of a size_t or Py_ssize_t.
+ * C99 introduced "z" for this purpose, but old MSVCs had not supported it.
+ * Since MSVC supports "z" since (at least) 2015, we can just use "z"
+ * for new code.
+ *
+ * These "high level" Python format functions interpret "z" correctly on
+ * all platforms (Python interprets the format string itself, and does whatever
+ * the platform C requires to convert a size_t/Py_ssize_t argument):
+ *
+ * PyBytes_FromFormat
+ * PyErr_Format
+ * PyBytes_FromFormatV
+ * PyUnicode_FromFormatV
+ *
+ * Lower-level uses require that you interpolate the correct format modifier
+ * yourself (e.g., calling printf, fprintf, sprintf, PyOS_snprintf); for
+ * example,
+ *
+ * Py_ssize_t index;
+ * fprintf(stderr, "index %" PY_FORMAT_SIZE_T "d sucks\n", index);
+ *
+ * That will expand to %zd or to something else correct for a Py_ssize_t on
+ * the platform.
+ */
+#ifndef PY_FORMAT_SIZE_T
+# define PY_FORMAT_SIZE_T "z"
+#endif
+
+/* Py_LOCAL can be used instead of static to get the fastest possible calling
+ * convention for functions that are local to a given module.
+ *
+ * Py_LOCAL_INLINE does the same thing, and also explicitly requests inlining,
+ * for platforms that support that.
+ *
+ * NOTE: You can only use this for functions that are entirely local to a
+ * module; functions that are exported via method tables, callbacks, etc,
+ * should keep using static.
+ */
+
+#if defined(_MSC_VER)
+ /* ignore warnings if the compiler decides not to inline a function */
+# pragma warning(disable: 4710)
+ /* fastest possible local call under MSVC */
+# define Py_LOCAL(type) static type __fastcall
+# define Py_LOCAL_INLINE(type) static __inline type __fastcall
+#else
+# define Py_LOCAL(type) static type
+# define Py_LOCAL_INLINE(type) static inline type
+#endif
+
+// bpo-28126: Py_MEMCPY is kept for backwards compatibility,
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
+# define Py_MEMCPY memcpy
+#endif
+
+#ifdef HAVE_IEEEFP_H
+#include <ieeefp.h> /* needed for 'finite' declaration on some platforms */
+#endif
+
+#include <math.h> /* Moved here from the math section, before extern "C" */
+
+/********************************************
+ * WRAPPER FOR <time.h> and/or <sys/time.h> *
+ ********************************************/
+
+#ifdef HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <time.h>
+
+/******************************
+ * WRAPPER FOR <sys/select.h> *
+ ******************************/
+
+/* NB caller must include <sys/types.h> */
+
+#ifdef HAVE_SYS_SELECT_H
+#include <sys/select.h>
+#endif /* !HAVE_SYS_SELECT_H */
+
+/*******************************
+ * stat() and fstat() fiddling *
+ *******************************/
+
+#ifdef HAVE_SYS_STAT_H
+#include <sys/stat.h>
+#elif defined(HAVE_STAT_H)
+#include <stat.h>
+#endif
+
+#ifndef S_IFMT
+/* VisualAge C/C++ Failed to Define MountType Field in sys/stat.h */
+#define S_IFMT 0170000
+#endif
+
+#ifndef S_IFLNK
+/* Windows doesn't define S_IFLNK but posixmodule.c maps
+ * IO_REPARSE_TAG_SYMLINK to S_IFLNK */
+# define S_IFLNK 0120000
+#endif
+
+#ifndef S_ISREG
+#define S_ISREG(x) (((x) & S_IFMT) == S_IFREG)
+#endif
+
+#ifndef S_ISDIR
+#define S_ISDIR(x) (((x) & S_IFMT) == S_IFDIR)
+#endif
+
+#ifndef S_ISCHR
+#define S_ISCHR(x) (((x) & S_IFMT) == S_IFCHR)
+#endif
+
+#ifdef __cplusplus
+/* Move this down here since some C++ #include's don't like to be included
+ inside an extern "C" */
+extern "C" {
+#endif
+
+
+/* Py_ARITHMETIC_RIGHT_SHIFT
+ * C doesn't define whether a right-shift of a signed integer sign-extends
+ * or zero-fills. Here a macro to force sign extension:
+ * Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J)
+ * Return I >> J, forcing sign extension. Arithmetically, return the
+ * floor of I/2**J.
+ * Requirements:
+ * I should have signed integer type. In the terminology of C99, this can
+ * be either one of the five standard signed integer types (signed char,
+ * short, int, long, long long) or an extended signed integer type.
+ * J is an integer >= 0 and strictly less than the number of bits in the
+ * type of I (because C doesn't define what happens for J outside that
+ * range either).
+ * TYPE used to specify the type of I, but is now ignored. It's been left
+ * in for backwards compatibility with versions <= 2.6 or 3.0.
+ * Caution:
+ * I may be evaluated more than once.
+ */
+#ifdef SIGNED_RIGHT_SHIFT_ZERO_FILLS
+#define Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J) \
+ ((I) < 0 ? -1-((-1-(I)) >> (J)) : (I) >> (J))
+#else
+#define Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J) ((I) >> (J))
+#endif
+
+/* Py_FORCE_EXPANSION(X)
+ * "Simply" returns its argument. However, macro expansions within the
+ * argument are evaluated. This unfortunate trickery is needed to get
+ * token-pasting to work as desired in some cases.
+ */
+#define Py_FORCE_EXPANSION(X) X
+
+/* Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW)
+ * Cast VALUE to type NARROW from type WIDE. In Py_DEBUG mode, this
+ * assert-fails if any information is lost.
+ * Caution:
+ * VALUE may be evaluated more than once.
+ */
+#ifdef Py_DEBUG
+# define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) \
+ (assert(_Py_STATIC_CAST(WIDE, _Py_STATIC_CAST(NARROW, (VALUE))) == (VALUE)), \
+ _Py_STATIC_CAST(NARROW, (VALUE)))
+#else
+# define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) _Py_STATIC_CAST(NARROW, (VALUE))
+#endif
+
+
+/* Py_DEPRECATED(version)
+ * Declare a variable, type, or function deprecated.
+ * The macro must be placed before the declaration.
+ * Usage:
+ * Py_DEPRECATED(3.3) extern int old_var;
+ * Py_DEPRECATED(3.4) typedef int T1;
+ * Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);
+ */
+#if defined(__GNUC__) \
+ && ((__GNUC__ >= 4) || (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1))
+#define Py_DEPRECATED(VERSION_UNUSED) __attribute__((__deprecated__))
+#elif defined(_MSC_VER)
+#define Py_DEPRECATED(VERSION) __declspec(deprecated( \
+ "deprecated in " #VERSION))
+#else
+#define Py_DEPRECATED(VERSION_UNUSED)
+#endif
+
+#if defined(__clang__)
+#define _Py_COMP_DIAG_PUSH _Pragma("clang diagnostic push")
+#define _Py_COMP_DIAG_IGNORE_DEPR_DECLS \
+ _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
+#define _Py_COMP_DIAG_POP _Pragma("clang diagnostic pop")
+#elif defined(__GNUC__) \
+ && ((__GNUC__ >= 5) || (__GNUC__ == 4) && (__GNUC_MINOR__ >= 6))
+#define _Py_COMP_DIAG_PUSH _Pragma("GCC diagnostic push")
+#define _Py_COMP_DIAG_IGNORE_DEPR_DECLS \
+ _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
+#define _Py_COMP_DIAG_POP _Pragma("GCC diagnostic pop")
+#elif defined(_MSC_VER)
+#define _Py_COMP_DIAG_PUSH __pragma(warning(push))
+#define _Py_COMP_DIAG_IGNORE_DEPR_DECLS __pragma(warning(disable: 4996))
+#define _Py_COMP_DIAG_POP __pragma(warning(pop))
+#else
+#define _Py_COMP_DIAG_PUSH
+#define _Py_COMP_DIAG_IGNORE_DEPR_DECLS
+#define _Py_COMP_DIAG_POP
+#endif
+
+/* _Py_HOT_FUNCTION
+ * The hot attribute on a function is used to inform the compiler that the
+ * function is a hot spot of the compiled program. The function is optimized
+ * more aggressively and on many target it is placed into special subsection of
+ * the text section so all hot functions appears close together improving
+ * locality.
+ *
+ * Usage:
+ * int _Py_HOT_FUNCTION x(void) { return 3; }
+ *
+ * Issue #28618: This attribute must not be abused, otherwise it can have a
+ * negative effect on performance. Only the functions were Python spend most of
+ * its time must use it. Use a profiler when running performance benchmark
+ * suite to find these functions.
+ */
+#if defined(__GNUC__) \
+ && ((__GNUC__ >= 5) || (__GNUC__ == 4) && (__GNUC_MINOR__ >= 3))
+#define _Py_HOT_FUNCTION __attribute__((hot))
+#else
+#define _Py_HOT_FUNCTION
+#endif
+
+// Ask the compiler to always inline a static inline function. The compiler can
+// ignore it and decides to not inline the function.
+//
+// It can be used to inline performance critical static inline functions when
+// building Python in debug mode with function inlining disabled. For example,
+// MSC disables function inlining when building in debug mode.
+//
+// Marking blindly a static inline function with Py_ALWAYS_INLINE can result in
+// worse performances (due to increased code size for example). The compiler is
+// usually smarter than the developer for the cost/benefit analysis.
+//
+// If Python is built in debug mode (if the Py_DEBUG macro is defined), the
+// Py_ALWAYS_INLINE macro does nothing.
+//
+// It must be specified before the function return type. Usage:
+//
+// static inline Py_ALWAYS_INLINE int random(void) { return 4; }
+#if defined(Py_DEBUG)
+ // If Python is built in debug mode, usually compiler optimizations are
+ // disabled. In this case, Py_ALWAYS_INLINE can increase a lot the stack
+ // memory usage. For example, forcing inlining using gcc -O0 increases the
+ // stack usage from 6 KB to 15 KB per Python function call.
+# define Py_ALWAYS_INLINE
+#elif defined(__GNUC__) || defined(__clang__) || defined(__INTEL_COMPILER)
+# define Py_ALWAYS_INLINE __attribute__((always_inline))
+#elif defined(_MSC_VER)
+# define Py_ALWAYS_INLINE __forceinline
+#else
+# define Py_ALWAYS_INLINE
+#endif
+
+// Py_NO_INLINE
+// Disable inlining on a function. For example, it reduces the C stack
+// consumption: useful on LTO+PGO builds which heavily inline code (see
+// bpo-33720).
+//
+// Usage:
+//
+// Py_NO_INLINE static int random(void) { return 4; }
+#if defined(__GNUC__) || defined(__clang__) || defined(__INTEL_COMPILER)
+# define Py_NO_INLINE __attribute__ ((noinline))
+#elif defined(_MSC_VER)
+# define Py_NO_INLINE __declspec(noinline)
+#else
+# define Py_NO_INLINE
+#endif
+
+/**************************************************************************
+Prototypes that are missing from the standard include files on some systems
+(and possibly only some versions of such systems.)
+
+Please be conservative with adding new ones, document them and enclose them
+in platform-specific #ifdefs.
+**************************************************************************/
+
+#ifdef SOLARIS
+/* Unchecked */
+extern int gethostname(char *, int);
+#endif
+
+#ifdef HAVE__GETPTY
+#include <sys/types.h> /* we need to import mode_t */
+extern char * _getpty(int *, int, mode_t, int);
+#endif
+
+/* On QNX 6, struct termio must be declared by including sys/termio.h
+ if TCGETA, TCSETA, TCSETAW, or TCSETAF are used. sys/termio.h must
+ be included before termios.h or it will generate an error. */
+#if defined(HAVE_SYS_TERMIO_H) && !defined(__hpux)
+#include <sys/termio.h>
+#endif
+
+
+/* On 4.4BSD-descendants, ctype functions serves the whole range of
+ * wchar_t character set rather than single byte code points only.
+ * This characteristic can break some operations of string object
+ * including str.upper() and str.split() on UTF-8 locales. This
+ * workaround was provided by Tim Robbins of FreeBSD project.
+ */
+
+#if defined(__APPLE__)
+# define _PY_PORT_CTYPE_UTF8_ISSUE
+#endif
+
+#ifdef _PY_PORT_CTYPE_UTF8_ISSUE
+#ifndef __cplusplus
+ /* The workaround below is unsafe in C++ because
+ * the <locale> defines these symbols as real functions,
+ * with a slightly different signature.
+ * See issue #10910
+ */
+#include <ctype.h>
+#include <wctype.h>
+#undef isalnum
+#define isalnum(c) iswalnum(btowc(c))
+#undef isalpha
+#define isalpha(c) iswalpha(btowc(c))
+#undef islower
+#define islower(c) iswlower(btowc(c))
+#undef isspace
+#define isspace(c) iswspace(btowc(c))
+#undef isupper
+#define isupper(c) iswupper(btowc(c))
+#undef tolower
+#define tolower(c) towlower(btowc(c))
+#undef toupper
+#define toupper(c) towupper(btowc(c))
+#endif
+#endif
+
+
+/* Declarations for symbol visibility.
+
+ PyAPI_FUNC(type): Declares a public Python API function and return type
+ PyAPI_DATA(type): Declares public Python data and its type
+ PyMODINIT_FUNC: A Python module init function. If these functions are
+ inside the Python core, they are private to the core.
+ If in an extension module, it may be declared with
+ external linkage depending on the platform.
+
+ As a number of platforms support/require "__declspec(dllimport/dllexport)",
+ we support a HAVE_DECLSPEC_DLL macro to save duplication.
+*/
+
+/*
+ All windows ports, except cygwin, are handled in PC/pyconfig.h.
+
+ Cygwin is the only other autoconf platform requiring special
+ linkage handling and it uses __declspec().
+*/
+#if defined(__CYGWIN__)
+# define HAVE_DECLSPEC_DLL
+#endif
+
+#include "exports.h"
+
+/* only get special linkage if built as shared or platform is Cygwin */
+#if defined(Py_ENABLE_SHARED) || defined(__CYGWIN__)
+# if defined(HAVE_DECLSPEC_DLL)
+# if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
+# define PyAPI_FUNC(RTYPE) Py_EXPORTED_SYMBOL RTYPE
+# define PyAPI_DATA(RTYPE) extern Py_EXPORTED_SYMBOL RTYPE
+ /* module init functions inside the core need no external linkage */
+ /* except for Cygwin to handle embedding */
+# if defined(__CYGWIN__)
+# define PyMODINIT_FUNC Py_EXPORTED_SYMBOL PyObject*
+# else /* __CYGWIN__ */
+# define PyMODINIT_FUNC PyObject*
+# endif /* __CYGWIN__ */
+# else /* Py_BUILD_CORE */
+ /* Building an extension module, or an embedded situation */
+ /* public Python functions and data are imported */
+ /* Under Cygwin, auto-import functions to prevent compilation */
+ /* failures similar to those described at the bottom of 4.1: */
+ /* http://docs.python.org/extending/windows.html#a-cookbook-approach */
+# if !defined(__CYGWIN__)
+# define PyAPI_FUNC(RTYPE) Py_IMPORTED_SYMBOL RTYPE
+# endif /* !__CYGWIN__ */
+# define PyAPI_DATA(RTYPE) extern Py_IMPORTED_SYMBOL RTYPE
+ /* module init functions outside the core must be exported */
+# if defined(__cplusplus)
+# define PyMODINIT_FUNC extern "C" Py_EXPORTED_SYMBOL PyObject*
+# else /* __cplusplus */
+# define PyMODINIT_FUNC Py_EXPORTED_SYMBOL PyObject*
+# endif /* __cplusplus */
+# endif /* Py_BUILD_CORE */
+# endif /* HAVE_DECLSPEC_DLL */
+#endif /* Py_ENABLE_SHARED */
+
+/* If no external linkage macros defined by now, create defaults */
+#ifndef PyAPI_FUNC
+# define PyAPI_FUNC(RTYPE) Py_EXPORTED_SYMBOL RTYPE
+#endif
+#ifndef PyAPI_DATA
+# define PyAPI_DATA(RTYPE) extern Py_EXPORTED_SYMBOL RTYPE
+#endif
+#ifndef PyMODINIT_FUNC
+# if defined(__cplusplus)
+# define PyMODINIT_FUNC extern "C" Py_EXPORTED_SYMBOL PyObject*
+# else /* __cplusplus */
+# define PyMODINIT_FUNC Py_EXPORTED_SYMBOL PyObject*
+# endif /* __cplusplus */
+#endif
+
+/* limits.h constants that may be missing */
+
+#ifndef INT_MAX
+#define INT_MAX 2147483647
+#endif
+
+#ifndef LONG_MAX
+#if SIZEOF_LONG == 4
+#define LONG_MAX 0X7FFFFFFFL
+#elif SIZEOF_LONG == 8
+#define LONG_MAX 0X7FFFFFFFFFFFFFFFL
+#else
+#error "could not set LONG_MAX in pyport.h"
+#endif
+#endif
+
+#ifndef LONG_MIN
+#define LONG_MIN (-LONG_MAX-1)
+#endif
+
+#ifndef LONG_BIT
+#define LONG_BIT (8 * SIZEOF_LONG)
+#endif
+
+#if LONG_BIT != 8 * SIZEOF_LONG
+/* 04-Oct-2000 LONG_BIT is apparently (mis)defined as 64 on some recent
+ * 32-bit platforms using gcc. We try to catch that here at compile-time
+ * rather than waiting for integer multiplication to trigger bogus
+ * overflows.
+ */
+#error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)."
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+/*
+ * Hide GCC attributes from compilers that don't support them.
+ */
+#if (!defined(__GNUC__) || __GNUC__ < 2 || \
+ (__GNUC__ == 2 && __GNUC_MINOR__ < 7) )
+#define Py_GCC_ATTRIBUTE(x)
+#else
+#define Py_GCC_ATTRIBUTE(x) __attribute__(x)
+#endif
+
+/*
+ * Specify alignment on compilers that support it.
+ */
+#if defined(__GNUC__) && __GNUC__ >= 3
+#define Py_ALIGNED(x) __attribute__((aligned(x)))
+#else
+#define Py_ALIGNED(x)
+#endif
+
+/* Eliminate end-of-loop code not reached warnings from SunPro C
+ * when using do{...}while(0) macros
+ */
+#ifdef __SUNPRO_C
+#pragma error_messages (off,E_END_OF_LOOP_CODE_NOT_REACHED)
+#endif
+
+#ifndef Py_LL
+#define Py_LL(x) x##LL
+#endif
+
+#ifndef Py_ULL
+#define Py_ULL(x) Py_LL(x##U)
+#endif
+
+#define Py_VA_COPY va_copy
+
+/*
+ * Convenient macros to deal with endianness of the platform. WORDS_BIGENDIAN is
+ * detected by configure and defined in pyconfig.h. The code in pyconfig.h
+ * also takes care of Apple's universal builds.
+ */
+
+#ifdef WORDS_BIGENDIAN
+# define PY_BIG_ENDIAN 1
+# define PY_LITTLE_ENDIAN 0
+#else
+# define PY_BIG_ENDIAN 0
+# define PY_LITTLE_ENDIAN 1
+#endif
+
+#ifdef __ANDROID__
+ /* The Android langinfo.h header is not used. */
+# undef HAVE_LANGINFO_H
+# undef CODESET
+#endif
+
+/* Maximum value of the Windows DWORD type */
+#define PY_DWORD_MAX 4294967295U
+
+/* This macro used to tell whether Python was built with multithreading
+ * enabled. Now multithreading is always enabled, but keep the macro
+ * for compatibility.
+ */
+#ifndef WITH_THREAD
+# define WITH_THREAD
+#endif
+
+/* Check that ALT_SOABI is consistent with Py_TRACE_REFS:
+ ./configure --with-trace-refs should must be used to define Py_TRACE_REFS */
+#if defined(ALT_SOABI) && defined(Py_TRACE_REFS)
+# error "Py_TRACE_REFS ABI is not compatible with release and debug ABI"
+#endif
+
+#if defined(__ANDROID__) || defined(__VXWORKS__)
+ // Use UTF-8 as the locale encoding, ignore the LC_CTYPE locale.
+ // See _Py_GetLocaleEncoding(), PyUnicode_DecodeLocale()
+ // and PyUnicode_EncodeLocale().
+# define _Py_FORCE_UTF8_LOCALE
+#endif
+
+#if defined(_Py_FORCE_UTF8_LOCALE) || defined(__APPLE__)
+ // Use UTF-8 as the filesystem encoding.
+ // See PyUnicode_DecodeFSDefaultAndSize(), PyUnicode_EncodeFSDefault(),
+ // Py_DecodeLocale() and Py_EncodeLocale().
+# define _Py_FORCE_UTF8_FS_ENCODING
+#endif
+
+/* Mark a function which cannot return. Example:
+ PyAPI_FUNC(void) _Py_NO_RETURN PyThread_exit_thread(void);
+
+ XLC support is intentionally omitted due to bpo-40244 */
+#ifndef _Py_NO_RETURN
+#if defined(__clang__) || \
+ (defined(__GNUC__) && \
+ ((__GNUC__ >= 3) || \
+ (__GNUC__ == 2) && (__GNUC_MINOR__ >= 5)))
+# define _Py_NO_RETURN __attribute__((__noreturn__))
+#elif defined(_MSC_VER)
+# define _Py_NO_RETURN __declspec(noreturn)
+#else
+# define _Py_NO_RETURN
+#endif
+#endif
+
+
+// Preprocessor check for a builtin preprocessor function. Always return 0
+// if __has_builtin() macro is not defined.
+//
+// __has_builtin() is available on clang and GCC 10.
+#ifdef __has_builtin
+# define _Py__has_builtin(x) __has_builtin(x)
+#else
+# define _Py__has_builtin(x) 0
+#endif
+
+
+/* A convenient way for code to know if sanitizers are enabled. */
+#if defined(__has_feature)
+# if __has_feature(memory_sanitizer)
+# if !defined(_Py_MEMORY_SANITIZER)
+# define _Py_MEMORY_SANITIZER
+# endif
+# endif
+# if __has_feature(address_sanitizer)
+# if !defined(_Py_ADDRESS_SANITIZER)
+# define _Py_ADDRESS_SANITIZER
+# endif
+# endif
+#elif defined(__GNUC__)
+# if defined(__SANITIZE_ADDRESS__)
+# define _Py_ADDRESS_SANITIZER
+# endif
+#endif
+
+#endif /* Py_PYPORT_H */
diff --git a/include/python3.11/pystate.h b/include/python3.11/pystate.h
new file mode 100644
index 0000000..e6b4de9
--- /dev/null
+++ b/include/python3.11/pystate.h
@@ -0,0 +1,132 @@
+/* Thread and interpreter state structures and their interfaces */
+
+
+#ifndef Py_PYSTATE_H
+#define Py_PYSTATE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* This limitation is for performance and simplicity. If needed it can be
+removed (with effort). */
+#define MAX_CO_EXTRA_USERS 255
+
+PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_New(void);
+PyAPI_FUNC(void) PyInterpreterState_Clear(PyInterpreterState *);
+PyAPI_FUNC(void) PyInterpreterState_Delete(PyInterpreterState *);
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03090000
+/* New in 3.9 */
+/* Get the current interpreter state.
+
+ Issue a fatal error if there no current Python thread state or no current
+ interpreter. It cannot return NULL.
+
+ The caller must hold the GIL. */
+PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Get(void);
+#endif
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03080000
+/* New in 3.8 */
+PyAPI_FUNC(PyObject *) PyInterpreterState_GetDict(PyInterpreterState *);
+#endif
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03070000
+/* New in 3.7 */
+PyAPI_FUNC(int64_t) PyInterpreterState_GetID(PyInterpreterState *);
+#endif
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+
+/* State unique per thread */
+
+/* New in 3.3 */
+PyAPI_FUNC(int) PyState_AddModule(PyObject*, PyModuleDef*);
+PyAPI_FUNC(int) PyState_RemoveModule(PyModuleDef*);
+#endif
+PyAPI_FUNC(PyObject*) PyState_FindModule(PyModuleDef*);
+
+PyAPI_FUNC(PyThreadState *) PyThreadState_New(PyInterpreterState *);
+PyAPI_FUNC(void) PyThreadState_Clear(PyThreadState *);
+PyAPI_FUNC(void) PyThreadState_Delete(PyThreadState *);
+
+/* Get the current thread state.
+
+ When the current thread state is NULL, this issues a fatal error (so that
+ the caller needn't check for NULL).
+
+ The caller must hold the GIL.
+
+ See also _PyThreadState_UncheckedGet() and _PyThreadState_GET(). */
+PyAPI_FUNC(PyThreadState *) PyThreadState_Get(void);
+
+// Alias to PyThreadState_Get()
+#define PyThreadState_GET() PyThreadState_Get()
+
+PyAPI_FUNC(PyThreadState *) PyThreadState_Swap(PyThreadState *);
+PyAPI_FUNC(PyObject *) PyThreadState_GetDict(void);
+PyAPI_FUNC(int) PyThreadState_SetAsyncExc(unsigned long, PyObject *);
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03090000
+/* New in 3.9 */
+PyAPI_FUNC(PyInterpreterState*) PyThreadState_GetInterpreter(PyThreadState *tstate);
+PyAPI_FUNC(PyFrameObject*) PyThreadState_GetFrame(PyThreadState *tstate);
+PyAPI_FUNC(uint64_t) PyThreadState_GetID(PyThreadState *tstate);
+#endif
+
+typedef
+ enum {PyGILState_LOCKED, PyGILState_UNLOCKED}
+ PyGILState_STATE;
+
+
+/* Ensure that the current thread is ready to call the Python
+ C API, regardless of the current state of Python, or of its
+ thread lock. This may be called as many times as desired
+ by a thread so long as each call is matched with a call to
+ PyGILState_Release(). In general, other thread-state APIs may
+ be used between _Ensure() and _Release() calls, so long as the
+ thread-state is restored to its previous state before the Release().
+ For example, normal use of the Py_BEGIN_ALLOW_THREADS/
+ Py_END_ALLOW_THREADS macros are acceptable.
+
+ The return value is an opaque "handle" to the thread state when
+ PyGILState_Ensure() was called, and must be passed to
+ PyGILState_Release() to ensure Python is left in the same state. Even
+ though recursive calls are allowed, these handles can *not* be shared -
+ each unique call to PyGILState_Ensure must save the handle for its
+ call to PyGILState_Release.
+
+ When the function returns, the current thread will hold the GIL.
+
+ Failure is a fatal error.
+*/
+PyAPI_FUNC(PyGILState_STATE) PyGILState_Ensure(void);
+
+/* Release any resources previously acquired. After this call, Python's
+ state will be the same as it was prior to the corresponding
+ PyGILState_Ensure() call (but generally this state will be unknown to
+ the caller, hence the use of the GILState API.)
+
+ Every call to PyGILState_Ensure must be matched by a call to
+ PyGILState_Release on the same thread.
+*/
+PyAPI_FUNC(void) PyGILState_Release(PyGILState_STATE);
+
+/* Helper/diagnostic function - get the current thread state for
+ this thread. May return NULL if no GILState API has been used
+ on the current thread. Note that the main thread always has such a
+ thread-state, even if no auto-thread-state call has been made
+ on the main thread.
+*/
+PyAPI_FUNC(PyThreadState *) PyGILState_GetThisThreadState(void);
+
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_PYSTATE_H
+# include "cpython/pystate.h"
+# undef Py_CPYTHON_PYSTATE_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_PYSTATE_H */
diff --git a/include/python3.10/pystrcmp.h b/include/python3.11/pystrcmp.h
similarity index 100%
rename from include/python3.10/pystrcmp.h
rename to include/python3.11/pystrcmp.h
diff --git a/include/python3.11/pystrtod.h b/include/python3.11/pystrtod.h
new file mode 100644
index 0000000..fa056d1
--- /dev/null
+++ b/include/python3.11/pystrtod.h
@@ -0,0 +1,46 @@
+#ifndef Py_STRTOD_H
+#define Py_STRTOD_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+PyAPI_FUNC(double) PyOS_string_to_double(const char *str,
+ char **endptr,
+ PyObject *overflow_exception);
+
+/* The caller is responsible for calling PyMem_Free to free the buffer
+ that's is returned. */
+PyAPI_FUNC(char *) PyOS_double_to_string(double val,
+ char format_code,
+ int precision,
+ int flags,
+ int *type);
+
+#ifndef Py_LIMITED_API
+PyAPI_FUNC(PyObject *) _Py_string_to_number_with_underscores(
+ const char *str, Py_ssize_t len, const char *what, PyObject *obj, void *arg,
+ PyObject *(*innerfunc)(const char *, Py_ssize_t, void *));
+
+PyAPI_FUNC(double) _Py_parse_inf_or_nan(const char *p, char **endptr);
+#endif
+
+
+/* PyOS_double_to_string's "flags" parameter can be set to 0 or more of: */
+#define Py_DTSF_SIGN 0x01 /* always add the sign */
+#define Py_DTSF_ADD_DOT_0 0x02 /* if the result is an integer add ".0" */
+#define Py_DTSF_ALT 0x04 /* "alternate" formatting. it's format_code
+ specific */
+#define Py_DTSF_NO_NEG_0 0x08 /* negative zero result is coerced to 0 */
+
+/* PyOS_double_to_string's "type", if non-NULL, will be set to one of: */
+#define Py_DTST_FINITE 0
+#define Py_DTST_INFINITE 1
+#define Py_DTST_NAN 2
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !Py_STRTOD_H */
diff --git a/include/python3.11/pythonrun.h b/include/python3.11/pythonrun.h
new file mode 100644
index 0000000..1b208b7
--- /dev/null
+++ b/include/python3.11/pythonrun.h
@@ -0,0 +1,45 @@
+
+/* Interfaces to parse and execute pieces of python code */
+
+#ifndef Py_PYTHONRUN_H
+#define Py_PYTHONRUN_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_FUNC(PyObject *) Py_CompileString(const char *, const char *, int);
+
+PyAPI_FUNC(void) PyErr_Print(void);
+PyAPI_FUNC(void) PyErr_PrintEx(int);
+PyAPI_FUNC(void) PyErr_Display(PyObject *, PyObject *, PyObject *);
+
+
+/* Stuff with no proper home (yet) */
+PyAPI_DATA(int) (*PyOS_InputHook)(void);
+
+/* Stack size, in "pointers" (so we get extra safety margins
+ on 64-bit platforms). On a 32-bit platform, this translates
+ to an 8k margin. */
+#define PYOS_STACK_MARGIN 2048
+
+#if defined(WIN32) && !defined(MS_WIN64) && !defined(_M_ARM) && defined(_MSC_VER) && _MSC_VER >= 1300
+/* Enable stack checking under Microsoft C */
+// When changing the platforms, ensure PyOS_CheckStack() docs are still correct
+#define USE_STACKCHECK
+#endif
+
+#ifdef USE_STACKCHECK
+/* Check that we aren't overflowing our stack */
+PyAPI_FUNC(int) PyOS_CheckStack(void);
+#endif
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_PYTHONRUN_H
+# include "cpython/pythonrun.h"
+# undef Py_CPYTHON_PYTHONRUN_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_PYTHONRUN_H */
diff --git a/include/python3.11/pythread.h b/include/python3.11/pythread.h
new file mode 100644
index 0000000..a483290
--- /dev/null
+++ b/include/python3.11/pythread.h
@@ -0,0 +1,133 @@
+#ifndef Py_PYTHREAD_H
+#define Py_PYTHREAD_H
+
+typedef void *PyThread_type_lock;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Return status codes for Python lock acquisition. Chosen for maximum
+ * backwards compatibility, ie failure -> 0, success -> 1. */
+typedef enum PyLockStatus {
+ PY_LOCK_FAILURE = 0,
+ PY_LOCK_ACQUIRED = 1,
+ PY_LOCK_INTR
+} PyLockStatus;
+
+PyAPI_FUNC(void) PyThread_init_thread(void);
+PyAPI_FUNC(unsigned long) PyThread_start_new_thread(void (*)(void *), void *);
+PyAPI_FUNC(void) _Py_NO_RETURN PyThread_exit_thread(void);
+PyAPI_FUNC(unsigned long) PyThread_get_thread_ident(void);
+
+#if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(_WIN32) || defined(_AIX)
+#define PY_HAVE_THREAD_NATIVE_ID
+PyAPI_FUNC(unsigned long) PyThread_get_thread_native_id(void);
+#endif
+
+PyAPI_FUNC(PyThread_type_lock) PyThread_allocate_lock(void);
+PyAPI_FUNC(void) PyThread_free_lock(PyThread_type_lock);
+PyAPI_FUNC(int) PyThread_acquire_lock(PyThread_type_lock, int);
+#define WAIT_LOCK 1
+#define NOWAIT_LOCK 0
+
+/* PY_TIMEOUT_T is the integral type used to specify timeouts when waiting
+ on a lock (see PyThread_acquire_lock_timed() below).
+ PY_TIMEOUT_MAX is the highest usable value (in microseconds) of that
+ type, and depends on the system threading API.
+
+ NOTE: this isn't the same value as `_thread.TIMEOUT_MAX`. The _thread
+ module exposes a higher-level API, with timeouts expressed in seconds
+ and floating-point numbers allowed.
+*/
+#define PY_TIMEOUT_T long long
+
+#if defined(_POSIX_THREADS)
+ /* PyThread_acquire_lock_timed() uses _PyTime_FromNanoseconds(us * 1000),
+ convert microseconds to nanoseconds. */
+# define PY_TIMEOUT_MAX (LLONG_MAX / 1000)
+#elif defined (NT_THREADS)
+ // WaitForSingleObject() accepts timeout in milliseconds in the range
+ // [0; 0xFFFFFFFE] (DWORD type). INFINITE value (0xFFFFFFFF) means no
+ // timeout. 0xFFFFFFFE milliseconds is around 49.7 days.
+# if 0xFFFFFFFELL * 1000 < LLONG_MAX
+# define PY_TIMEOUT_MAX (0xFFFFFFFELL * 1000)
+# else
+# define PY_TIMEOUT_MAX LLONG_MAX
+# endif
+#else
+# define PY_TIMEOUT_MAX LLONG_MAX
+#endif
+
+
+/* If microseconds == 0, the call is non-blocking: it returns immediately
+ even when the lock can't be acquired.
+ If microseconds > 0, the call waits up to the specified duration.
+ If microseconds < 0, the call waits until success (or abnormal failure)
+
+ microseconds must be less than PY_TIMEOUT_MAX. Behaviour otherwise is
+ undefined.
+
+ If intr_flag is true and the acquire is interrupted by a signal, then the
+ call will return PY_LOCK_INTR. The caller may reattempt to acquire the
+ lock.
+*/
+PyAPI_FUNC(PyLockStatus) PyThread_acquire_lock_timed(PyThread_type_lock,
+ PY_TIMEOUT_T microseconds,
+ int intr_flag);
+
+PyAPI_FUNC(void) PyThread_release_lock(PyThread_type_lock);
+
+PyAPI_FUNC(size_t) PyThread_get_stacksize(void);
+PyAPI_FUNC(int) PyThread_set_stacksize(size_t);
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+PyAPI_FUNC(PyObject*) PyThread_GetInfo(void);
+#endif
+
+
+/* Thread Local Storage (TLS) API
+ TLS API is DEPRECATED. Use Thread Specific Storage (TSS) API.
+
+ The existing TLS API has used int to represent TLS keys across all
+ platforms, but it is not POSIX-compliant. Therefore, the new TSS API uses
+ opaque data type to represent TSS keys to be compatible (see PEP 539).
+*/
+Py_DEPRECATED(3.7) PyAPI_FUNC(int) PyThread_create_key(void);
+Py_DEPRECATED(3.7) PyAPI_FUNC(void) PyThread_delete_key(int key);
+Py_DEPRECATED(3.7) PyAPI_FUNC(int) PyThread_set_key_value(int key,
+ void *value);
+Py_DEPRECATED(3.7) PyAPI_FUNC(void *) PyThread_get_key_value(int key);
+Py_DEPRECATED(3.7) PyAPI_FUNC(void) PyThread_delete_key_value(int key);
+
+/* Cleanup after a fork */
+Py_DEPRECATED(3.7) PyAPI_FUNC(void) PyThread_ReInitTLS(void);
+
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03070000
+/* New in 3.7 */
+/* Thread Specific Storage (TSS) API */
+
+typedef struct _Py_tss_t Py_tss_t; /* opaque */
+
+PyAPI_FUNC(Py_tss_t *) PyThread_tss_alloc(void);
+PyAPI_FUNC(void) PyThread_tss_free(Py_tss_t *key);
+
+/* The parameter key must not be NULL. */
+PyAPI_FUNC(int) PyThread_tss_is_created(Py_tss_t *key);
+PyAPI_FUNC(int) PyThread_tss_create(Py_tss_t *key);
+PyAPI_FUNC(void) PyThread_tss_delete(Py_tss_t *key);
+PyAPI_FUNC(int) PyThread_tss_set(Py_tss_t *key, void *value);
+PyAPI_FUNC(void *) PyThread_tss_get(Py_tss_t *key);
+#endif /* New in 3.7 */
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_PYTHREAD_H
+# include "cpython/pythread.h"
+# undef Py_CPYTHON_PYTHREAD_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_PYTHREAD_H */
diff --git a/include/python3.11/pytypedefs.h b/include/python3.11/pytypedefs.h
new file mode 100644
index 0000000..e78ed56
--- /dev/null
+++ b/include/python3.11/pytypedefs.h
@@ -0,0 +1,30 @@
+// Forward declarations of types of the Python C API.
+// Declare them at the same place since redefining typedef is a C11 feature.
+// Only use a forward declaration if there is an interdependency between two
+// header files.
+
+#ifndef Py_PYTYPEDEFS_H
+#define Py_PYTYPEDEFS_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct PyModuleDef PyModuleDef;
+typedef struct PyModuleDef_Slot PyModuleDef_Slot;
+typedef struct PyMethodDef PyMethodDef;
+typedef struct PyGetSetDef PyGetSetDef;
+typedef struct PyMemberDef PyMemberDef;
+
+typedef struct _object PyObject;
+typedef struct _longobject PyLongObject;
+typedef struct _typeobject PyTypeObject;
+typedef struct PyCodeObject PyCodeObject;
+typedef struct _frame PyFrameObject;
+
+typedef struct _ts PyThreadState;
+typedef struct _is PyInterpreterState;
+
+#ifdef __cplusplus
+}
+#endif
+#endif // !Py_PYTYPEDEFS_H
diff --git a/include/python3.10/rangeobject.h b/include/python3.11/rangeobject.h
similarity index 100%
rename from include/python3.10/rangeobject.h
rename to include/python3.11/rangeobject.h
diff --git a/include/python3.11/setobject.h b/include/python3.11/setobject.h
new file mode 100644
index 0000000..fdad706
--- /dev/null
+++ b/include/python3.11/setobject.h
@@ -0,0 +1,49 @@
+/* Set object interface */
+
+#ifndef Py_SETOBJECT_H
+#define Py_SETOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_DATA(PyTypeObject) PySet_Type;
+PyAPI_DATA(PyTypeObject) PyFrozenSet_Type;
+PyAPI_DATA(PyTypeObject) PySetIter_Type;
+
+PyAPI_FUNC(PyObject *) PySet_New(PyObject *);
+PyAPI_FUNC(PyObject *) PyFrozenSet_New(PyObject *);
+
+PyAPI_FUNC(int) PySet_Add(PyObject *set, PyObject *key);
+PyAPI_FUNC(int) PySet_Clear(PyObject *set);
+PyAPI_FUNC(int) PySet_Contains(PyObject *anyset, PyObject *key);
+PyAPI_FUNC(int) PySet_Discard(PyObject *set, PyObject *key);
+PyAPI_FUNC(PyObject *) PySet_Pop(PyObject *set);
+PyAPI_FUNC(Py_ssize_t) PySet_Size(PyObject *anyset);
+
+#define PyFrozenSet_CheckExact(ob) Py_IS_TYPE(ob, &PyFrozenSet_Type)
+#define PyFrozenSet_Check(ob) \
+ (Py_IS_TYPE(ob, &PyFrozenSet_Type) || \
+ PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type))
+
+#define PyAnySet_CheckExact(ob) \
+ (Py_IS_TYPE(ob, &PySet_Type) || Py_IS_TYPE(ob, &PyFrozenSet_Type))
+#define PyAnySet_Check(ob) \
+ (Py_IS_TYPE(ob, &PySet_Type) || Py_IS_TYPE(ob, &PyFrozenSet_Type) || \
+ PyType_IsSubtype(Py_TYPE(ob), &PySet_Type) || \
+ PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type))
+
+#define PySet_CheckExact(op) Py_IS_TYPE(op, &PySet_Type)
+#define PySet_Check(ob) \
+ (Py_IS_TYPE(ob, &PySet_Type) || \
+ PyType_IsSubtype(Py_TYPE(ob), &PySet_Type))
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_SETOBJECT_H
+# include "cpython/setobject.h"
+# undef Py_CPYTHON_SETOBJECT_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_SETOBJECT_H */
diff --git a/include/python3.10/sliceobject.h b/include/python3.11/sliceobject.h
similarity index 100%
rename from include/python3.10/sliceobject.h
rename to include/python3.11/sliceobject.h
diff --git a/include/python3.11/structmember.h b/include/python3.11/structmember.h
new file mode 100644
index 0000000..65a777d
--- /dev/null
+++ b/include/python3.11/structmember.h
@@ -0,0 +1,75 @@
+#ifndef Py_STRUCTMEMBER_H
+#define Py_STRUCTMEMBER_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Interface to map C struct members to Python object attributes */
+
+#include <stddef.h> /* For offsetof */
+
+/* An array of PyMemberDef structures defines the name, type and offset
+ of selected members of a C structure. These can be read by
+ PyMember_GetOne() and set by PyMember_SetOne() (except if their READONLY
+ flag is set). The array must be terminated with an entry whose name
+ pointer is NULL. */
+
+struct PyMemberDef {
+ const char *name;
+ int type;
+ Py_ssize_t offset;
+ int flags;
+ const char *doc;
+};
+
+/* Types */
+#define T_SHORT 0
+#define T_INT 1
+#define T_LONG 2
+#define T_FLOAT 3
+#define T_DOUBLE 4
+#define T_STRING 5
+#define T_OBJECT 6
+/* XXX the ordering here is weird for binary compatibility */
+#define T_CHAR 7 /* 1-character string */
+#define T_BYTE 8 /* 8-bit signed int */
+/* unsigned variants: */
+#define T_UBYTE 9
+#define T_USHORT 10
+#define T_UINT 11
+#define T_ULONG 12
+
+/* Added by Jack: strings contained in the structure */
+#define T_STRING_INPLACE 13
+
+/* Added by Lillo: bools contained in the structure (assumed char) */
+#define T_BOOL 14
+
+#define T_OBJECT_EX 16 /* Like T_OBJECT, but raises AttributeError
+ when the value is NULL, instead of
+ converting to None. */
+#define T_LONGLONG 17
+#define T_ULONGLONG 18
+
+#define T_PYSSIZET 19 /* Py_ssize_t */
+#define T_NONE 20 /* Value is always None */
+
+
+/* Flags */
+#define READONLY 1
+#define READ_RESTRICTED 2
+#define PY_WRITE_RESTRICTED 4
+#define RESTRICTED (READ_RESTRICTED | PY_WRITE_RESTRICTED)
+
+#define PY_AUDIT_READ READ_RESTRICTED
+
+/* Current API, use this */
+PyAPI_FUNC(PyObject *) PyMember_GetOne(const char *, PyMemberDef *);
+PyAPI_FUNC(int) PyMember_SetOne(char *, PyMemberDef *, PyObject *);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_STRUCTMEMBER_H */
diff --git a/include/python3.11/structseq.h b/include/python3.11/structseq.h
new file mode 100644
index 0000000..4f5c09f
--- /dev/null
+++ b/include/python3.11/structseq.h
@@ -0,0 +1,49 @@
+
+/* Named tuple object interface */
+
+#ifndef Py_STRUCTSEQ_H
+#define Py_STRUCTSEQ_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct PyStructSequence_Field {
+ const char *name;
+ const char *doc;
+} PyStructSequence_Field;
+
+typedef struct PyStructSequence_Desc {
+ const char *name;
+ const char *doc;
+ PyStructSequence_Field *fields;
+ int n_in_sequence;
+} PyStructSequence_Desc;
+
+PyAPI_DATA(const char * const) PyStructSequence_UnnamedField;
+
+#ifndef Py_LIMITED_API
+PyAPI_FUNC(void) PyStructSequence_InitType(PyTypeObject *type,
+ PyStructSequence_Desc *desc);
+PyAPI_FUNC(int) PyStructSequence_InitType2(PyTypeObject *type,
+ PyStructSequence_Desc *desc);
+#endif
+PyAPI_FUNC(PyTypeObject*) PyStructSequence_NewType(PyStructSequence_Desc *desc);
+
+PyAPI_FUNC(PyObject *) PyStructSequence_New(PyTypeObject* type);
+
+#ifndef Py_LIMITED_API
+typedef PyTupleObject PyStructSequence;
+
+/* Macro, *only* to be used to fill in brand new objects */
+#define PyStructSequence_SET_ITEM(op, i, v) PyTuple_SET_ITEM(op, i, v)
+
+#define PyStructSequence_GET_ITEM(op, i) PyTuple_GET_ITEM(op, i)
+#endif
+
+PyAPI_FUNC(void) PyStructSequence_SetItem(PyObject*, Py_ssize_t, PyObject*);
+PyAPI_FUNC(PyObject*) PyStructSequence_GetItem(PyObject*, Py_ssize_t);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_STRUCTSEQ_H */
diff --git a/include/python3.11/sysmodule.h b/include/python3.11/sysmodule.h
new file mode 100644
index 0000000..b508711
--- /dev/null
+++ b/include/python3.11/sysmodule.h
@@ -0,0 +1,41 @@
+
+/* System module interface */
+
+#ifndef Py_SYSMODULE_H
+#define Py_SYSMODULE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_FUNC(PyObject *) PySys_GetObject(const char *);
+PyAPI_FUNC(int) PySys_SetObject(const char *, PyObject *);
+
+Py_DEPRECATED(3.11) PyAPI_FUNC(void) PySys_SetArgv(int, wchar_t **);
+Py_DEPRECATED(3.11) PyAPI_FUNC(void) PySys_SetArgvEx(int, wchar_t **, int);
+Py_DEPRECATED(3.11) PyAPI_FUNC(void) PySys_SetPath(const wchar_t *);
+
+PyAPI_FUNC(void) PySys_WriteStdout(const char *format, ...)
+ Py_GCC_ATTRIBUTE((format(printf, 1, 2)));
+PyAPI_FUNC(void) PySys_WriteStderr(const char *format, ...)
+ Py_GCC_ATTRIBUTE((format(printf, 1, 2)));
+PyAPI_FUNC(void) PySys_FormatStdout(const char *format, ...);
+PyAPI_FUNC(void) PySys_FormatStderr(const char *format, ...);
+
+PyAPI_FUNC(void) PySys_ResetWarnOptions(void);
+Py_DEPRECATED(3.11) PyAPI_FUNC(void) PySys_AddWarnOption(const wchar_t *);
+Py_DEPRECATED(3.11) PyAPI_FUNC(void) PySys_AddWarnOptionUnicode(PyObject *);
+Py_DEPRECATED(3.11) PyAPI_FUNC(int) PySys_HasWarnOptions(void);
+
+Py_DEPRECATED(3.11) PyAPI_FUNC(void) PySys_AddXOption(const wchar_t *);
+PyAPI_FUNC(PyObject *) PySys_GetXOptions(void);
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_SYSMODULE_H
+# include "cpython/sysmodule.h"
+# undef Py_CPYTHON_SYSMODULE_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_SYSMODULE_H */
diff --git a/include/python3.10/token.h b/include/python3.11/token.h
similarity index 100%
rename from include/python3.10/token.h
rename to include/python3.11/token.h
diff --git a/include/python3.11/traceback.h b/include/python3.11/traceback.h
new file mode 100644
index 0000000..2dfa2ad
--- /dev/null
+++ b/include/python3.11/traceback.h
@@ -0,0 +1,26 @@
+#ifndef Py_TRACEBACK_H
+#define Py_TRACEBACK_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Traceback interface */
+
+PyAPI_FUNC(int) PyTraceBack_Here(PyFrameObject *);
+PyAPI_FUNC(int) PyTraceBack_Print(PyObject *, PyObject *);
+
+/* Reveal traceback type so we can typecheck traceback objects */
+PyAPI_DATA(PyTypeObject) PyTraceBack_Type;
+#define PyTraceBack_Check(v) Py_IS_TYPE(v, &PyTraceBack_Type)
+
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_TRACEBACK_H
+# include "cpython/traceback.h"
+# undef Py_CPYTHON_TRACEBACK_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_TRACEBACK_H */
diff --git a/include/python3.10/tracemalloc.h b/include/python3.11/tracemalloc.h
similarity index 100%
rename from include/python3.10/tracemalloc.h
rename to include/python3.11/tracemalloc.h
diff --git a/include/python3.11/tupleobject.h b/include/python3.11/tupleobject.h
new file mode 100644
index 0000000..dc68e3f
--- /dev/null
+++ b/include/python3.11/tupleobject.h
@@ -0,0 +1,46 @@
+/* Tuple object interface */
+
+#ifndef Py_TUPLEOBJECT_H
+#define Py_TUPLEOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+Another generally useful object type is a tuple of object pointers.
+For Python, this is an immutable type. C code can change the tuple items
+(but not their number), and even use tuples as general-purpose arrays of
+object references, but in general only brand new tuples should be mutated,
+not ones that might already have been exposed to Python code.
+
+*** WARNING *** PyTuple_SetItem does not increment the new item's reference
+count, but does decrement the reference count of the item it replaces,
+if not nil. It does *decrement* the reference count if it is *not*
+inserted in the tuple. Similarly, PyTuple_GetItem does not increment the
+returned item's reference count.
+*/
+
+PyAPI_DATA(PyTypeObject) PyTuple_Type;
+PyAPI_DATA(PyTypeObject) PyTupleIter_Type;
+
+#define PyTuple_Check(op) \
+ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TUPLE_SUBCLASS)
+#define PyTuple_CheckExact(op) Py_IS_TYPE(op, &PyTuple_Type)
+
+PyAPI_FUNC(PyObject *) PyTuple_New(Py_ssize_t size);
+PyAPI_FUNC(Py_ssize_t) PyTuple_Size(PyObject *);
+PyAPI_FUNC(PyObject *) PyTuple_GetItem(PyObject *, Py_ssize_t);
+PyAPI_FUNC(int) PyTuple_SetItem(PyObject *, Py_ssize_t, PyObject *);
+PyAPI_FUNC(PyObject *) PyTuple_GetSlice(PyObject *, Py_ssize_t, Py_ssize_t);
+PyAPI_FUNC(PyObject *) PyTuple_Pack(Py_ssize_t, ...);
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_TUPLEOBJECT_H
+# include "cpython/tupleobject.h"
+# undef Py_CPYTHON_TUPLEOBJECT_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_TUPLEOBJECT_H */
diff --git a/include/python3.11/typeslots.h b/include/python3.11/typeslots.h
new file mode 100644
index 0000000..506b055
--- /dev/null
+++ b/include/python3.11/typeslots.h
@@ -0,0 +1,88 @@
+/* Do not renumber the file; these numbers are part of the stable ABI. */
+#define Py_bf_getbuffer 1
+#define Py_bf_releasebuffer 2
+#define Py_mp_ass_subscript 3
+#define Py_mp_length 4
+#define Py_mp_subscript 5
+#define Py_nb_absolute 6
+#define Py_nb_add 7
+#define Py_nb_and 8
+#define Py_nb_bool 9
+#define Py_nb_divmod 10
+#define Py_nb_float 11
+#define Py_nb_floor_divide 12
+#define Py_nb_index 13
+#define Py_nb_inplace_add 14
+#define Py_nb_inplace_and 15
+#define Py_nb_inplace_floor_divide 16
+#define Py_nb_inplace_lshift 17
+#define Py_nb_inplace_multiply 18
+#define Py_nb_inplace_or 19
+#define Py_nb_inplace_power 20
+#define Py_nb_inplace_remainder 21
+#define Py_nb_inplace_rshift 22
+#define Py_nb_inplace_subtract 23
+#define Py_nb_inplace_true_divide 24
+#define Py_nb_inplace_xor 25
+#define Py_nb_int 26
+#define Py_nb_invert 27
+#define Py_nb_lshift 28
+#define Py_nb_multiply 29
+#define Py_nb_negative 30
+#define Py_nb_or 31
+#define Py_nb_positive 32
+#define Py_nb_power 33
+#define Py_nb_remainder 34
+#define Py_nb_rshift 35
+#define Py_nb_subtract 36
+#define Py_nb_true_divide 37
+#define Py_nb_xor 38
+#define Py_sq_ass_item 39
+#define Py_sq_concat 40
+#define Py_sq_contains 41
+#define Py_sq_inplace_concat 42
+#define Py_sq_inplace_repeat 43
+#define Py_sq_item 44
+#define Py_sq_length 45
+#define Py_sq_repeat 46
+#define Py_tp_alloc 47
+#define Py_tp_base 48
+#define Py_tp_bases 49
+#define Py_tp_call 50
+#define Py_tp_clear 51
+#define Py_tp_dealloc 52
+#define Py_tp_del 53
+#define Py_tp_descr_get 54
+#define Py_tp_descr_set 55
+#define Py_tp_doc 56
+#define Py_tp_getattr 57
+#define Py_tp_getattro 58
+#define Py_tp_hash 59
+#define Py_tp_init 60
+#define Py_tp_is_gc 61
+#define Py_tp_iter 62
+#define Py_tp_iternext 63
+#define Py_tp_methods 64
+#define Py_tp_new 65
+#define Py_tp_repr 66
+#define Py_tp_richcompare 67
+#define Py_tp_setattr 68
+#define Py_tp_setattro 69
+#define Py_tp_str 70
+#define Py_tp_traverse 71
+#define Py_tp_members 72
+#define Py_tp_getset 73
+#define Py_tp_free 74
+#define Py_nb_matrix_multiply 75
+#define Py_nb_inplace_matrix_multiply 76
+#define Py_am_await 77
+#define Py_am_aiter 78
+#define Py_am_anext 79
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
+/* New in 3.5 */
+#define Py_tp_finalize 80
+#endif
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000
+/* New in 3.10 */
+#define Py_am_send 81
+#endif
diff --git a/include/python3.11/unicodeobject.h b/include/python3.11/unicodeobject.h
new file mode 100644
index 0000000..1d2f546
--- /dev/null
+++ b/include/python3.11/unicodeobject.h
@@ -0,0 +1,1049 @@
+#ifndef Py_UNICODEOBJECT_H
+#define Py_UNICODEOBJECT_H
+
+#include <stdarg.h> // va_list
+
+/*
+
+Unicode implementation based on original code by Fredrik Lundh,
+modified by Marc-Andre Lemburg (mal@lemburg.com) according to the
+Unicode Integration Proposal. (See
+http://www.egenix.com/files/python/unicode-proposal.txt).
+
+Copyright (c) Corporation for National Research Initiatives.
+
+
+ Original header:
+ --------------------------------------------------------------------
+
+ * Yet another Unicode string type for Python. This type supports the
+ * 16-bit Basic Multilingual Plane (BMP) only.
+ *
+ * Written by Fredrik Lundh, January 1999.
+ *
+ * Copyright (c) 1999 by Secret Labs AB.
+ * Copyright (c) 1999 by Fredrik Lundh.
+ *
+ * fredrik@pythonware.com
+ * http://www.pythonware.com
+ *
+ * --------------------------------------------------------------------
+ * This Unicode String Type 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.
+ * -------------------------------------------------------------------- */
+
+#include <ctype.h>
+
+/* === Internal API ======================================================= */
+
+/* --- Internal Unicode Format -------------------------------------------- */
+
+/* Python 3.x requires unicode */
+#define Py_USING_UNICODE
+
+#ifndef SIZEOF_WCHAR_T
+#error Must define SIZEOF_WCHAR_T
+#endif
+
+#define Py_UNICODE_SIZE SIZEOF_WCHAR_T
+
+/* If wchar_t can be used for UCS-4 storage, set Py_UNICODE_WIDE.
+ Otherwise, Unicode strings are stored as UCS-2 (with limited support
+ for UTF-16) */
+
+#if Py_UNICODE_SIZE >= 4
+#define Py_UNICODE_WIDE
+#endif
+
+/* Set these flags if the platform has "wchar.h" and the
+ wchar_t type is a 16-bit unsigned type */
+/* #define HAVE_WCHAR_H */
+/* #define HAVE_USABLE_WCHAR_T */
+
+/* If the compiler provides a wchar_t type we try to support it
+ through the interface functions PyUnicode_FromWideChar(),
+ PyUnicode_AsWideChar() and PyUnicode_AsWideCharString(). */
+
+#ifdef HAVE_USABLE_WCHAR_T
+# ifndef HAVE_WCHAR_H
+# define HAVE_WCHAR_H
+# endif
+#endif
+
+#ifdef HAVE_WCHAR_H
+# include <wchar.h>
+#endif
+
+/* Py_UCS4 and Py_UCS2 are typedefs for the respective
+ unicode representations. */
+typedef uint32_t Py_UCS4;
+typedef uint16_t Py_UCS2;
+typedef uint8_t Py_UCS1;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+PyAPI_DATA(PyTypeObject) PyUnicode_Type;
+PyAPI_DATA(PyTypeObject) PyUnicodeIter_Type;
+
+#define PyUnicode_Check(op) \
+ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_UNICODE_SUBCLASS)
+#define PyUnicode_CheckExact(op) Py_IS_TYPE(op, &PyUnicode_Type)
+
+/* --- Constants ---------------------------------------------------------- */
+
+/* This Unicode character will be used as replacement character during
+ decoding if the errors argument is set to "replace". Note: the
+ Unicode character U+FFFD is the official REPLACEMENT CHARACTER in
+ Unicode 3.0. */
+
+#define Py_UNICODE_REPLACEMENT_CHARACTER ((Py_UCS4) 0xFFFD)
+
+/* === Public API ========================================================= */
+
+/* Similar to PyUnicode_FromUnicode(), but u points to UTF-8 encoded bytes */
+PyAPI_FUNC(PyObject*) PyUnicode_FromStringAndSize(
+ const char *u, /* UTF-8 encoded string */
+ Py_ssize_t size /* size of buffer */
+ );
+
+/* Similar to PyUnicode_FromUnicode(), but u points to null-terminated
+ UTF-8 encoded bytes. The size is determined with strlen(). */
+PyAPI_FUNC(PyObject*) PyUnicode_FromString(
+ const char *u /* UTF-8 encoded string */
+ );
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+PyAPI_FUNC(PyObject*) PyUnicode_Substring(
+ PyObject *str,
+ Py_ssize_t start,
+ Py_ssize_t end);
+#endif
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+/* Copy the string into a UCS4 buffer including the null character if copy_null
+ is set. Return NULL and raise an exception on error. Raise a SystemError if
+ the buffer is smaller than the string. Return buffer on success.
+
+ buflen is the length of the buffer in (Py_UCS4) characters. */
+PyAPI_FUNC(Py_UCS4*) PyUnicode_AsUCS4(
+ PyObject *unicode,
+ Py_UCS4* buffer,
+ Py_ssize_t buflen,
+ int copy_null);
+
+/* Copy the string into a UCS4 buffer. A new buffer is allocated using
+ * PyMem_Malloc; if this fails, NULL is returned with a memory error
+ exception set. */
+PyAPI_FUNC(Py_UCS4*) PyUnicode_AsUCS4Copy(PyObject *unicode);
+#endif
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+/* Get the length of the Unicode object. */
+
+PyAPI_FUNC(Py_ssize_t) PyUnicode_GetLength(
+ PyObject *unicode
+);
+#endif
+
+/* Get the number of Py_UNICODE units in the
+ string representation. */
+
+Py_DEPRECATED(3.3) PyAPI_FUNC(Py_ssize_t) PyUnicode_GetSize(
+ PyObject *unicode /* Unicode object */
+ );
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+/* Read a character from the string. */
+
+PyAPI_FUNC(Py_UCS4) PyUnicode_ReadChar(
+ PyObject *unicode,
+ Py_ssize_t index
+ );
+
+/* Write a character to the string. The string must have been created through
+ PyUnicode_New, must not be shared, and must not have been hashed yet.
+
+ Return 0 on success, -1 on error. */
+
+PyAPI_FUNC(int) PyUnicode_WriteChar(
+ PyObject *unicode,
+ Py_ssize_t index,
+ Py_UCS4 character
+ );
+#endif
+
+/* Resize a Unicode object. The length is the number of characters, except
+ if the kind of the string is PyUnicode_WCHAR_KIND: in this case, the length
+ is the number of Py_UNICODE characters.
+
+ *unicode is modified to point to the new (resized) object and 0
+ returned on success.
+
+ Try to resize the string in place (which is usually faster than allocating
+ a new string and copy characters), or create a new string.
+
+ Error handling is implemented as follows: an exception is set, -1
+ is returned and *unicode left untouched.
+
+ WARNING: The function doesn't check string content, the result may not be a
+ string in canonical representation. */
+
+PyAPI_FUNC(int) PyUnicode_Resize(
+ PyObject **unicode, /* Pointer to the Unicode object */
+ Py_ssize_t length /* New length */
+ );
+
+/* Decode obj to a Unicode object.
+
+ bytes, bytearray and other bytes-like objects are decoded according to the
+ given encoding and error handler. The encoding and error handler can be
+ NULL to have the interface use UTF-8 and "strict".
+
+ All other objects (including Unicode objects) raise an exception.
+
+ The API returns NULL in case of an error. The caller is responsible
+ for decref'ing the returned objects.
+
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_FromEncodedObject(
+ PyObject *obj, /* Object */
+ const char *encoding, /* encoding */
+ const char *errors /* error handling */
+ );
+
+/* Copy an instance of a Unicode subtype to a new true Unicode object if
+ necessary. If obj is already a true Unicode object (not a subtype), return
+ the reference with *incremented* refcount.
+
+ The API returns NULL in case of an error. The caller is responsible
+ for decref'ing the returned objects.
+
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_FromObject(
+ PyObject *obj /* Object */
+ );
+
+PyAPI_FUNC(PyObject *) PyUnicode_FromFormatV(
+ const char *format, /* ASCII-encoded string */
+ va_list vargs
+ );
+PyAPI_FUNC(PyObject *) PyUnicode_FromFormat(
+ const char *format, /* ASCII-encoded string */
+ ...
+ );
+
+PyAPI_FUNC(void) PyUnicode_InternInPlace(PyObject **);
+PyAPI_FUNC(PyObject *) PyUnicode_InternFromString(
+ const char *u /* UTF-8 encoded string */
+ );
+
+// PyUnicode_InternImmortal() is deprecated since Python 3.10
+// and will be removed in Python 3.12. Use PyUnicode_InternInPlace() instead.
+Py_DEPRECATED(3.10) PyAPI_FUNC(void) PyUnicode_InternImmortal(PyObject **);
+
+/* --- wchar_t support for platforms which support it --------------------- */
+
+#ifdef HAVE_WCHAR_H
+
+/* Create a Unicode Object from the wchar_t buffer w of the given
+ size.
+
+ The buffer is copied into the new object. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_FromWideChar(
+ const wchar_t *w, /* wchar_t buffer */
+ Py_ssize_t size /* size of buffer */
+ );
+
+/* Copies the Unicode Object contents into the wchar_t buffer w. At
+ most size wchar_t characters are copied.
+
+ Note that the resulting wchar_t string may or may not be
+ 0-terminated. It is the responsibility of the caller to make sure
+ that the wchar_t string is 0-terminated in case this is required by
+ the application.
+
+ Returns the number of wchar_t characters copied (excluding a
+ possibly trailing 0-termination character) or -1 in case of an
+ error. */
+
+PyAPI_FUNC(Py_ssize_t) PyUnicode_AsWideChar(
+ PyObject *unicode, /* Unicode object */
+ wchar_t *w, /* wchar_t buffer */
+ Py_ssize_t size /* size of buffer */
+ );
+
+/* Convert the Unicode object to a wide character string. The output string
+ always ends with a nul character. If size is not NULL, write the number of
+ wide characters (excluding the null character) into *size.
+
+ Returns a buffer allocated by PyMem_Malloc() (use PyMem_Free() to free it)
+ on success. On error, returns NULL, *size is undefined and raises a
+ MemoryError. */
+
+PyAPI_FUNC(wchar_t*) PyUnicode_AsWideCharString(
+ PyObject *unicode, /* Unicode object */
+ Py_ssize_t *size /* number of characters of the result */
+ );
+
+#endif
+
+/* --- Unicode ordinals --------------------------------------------------- */
+
+/* Create a Unicode Object from the given Unicode code point ordinal.
+
+ The ordinal must be in range(0x110000). A ValueError is
+ raised in case it is not.
+
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_FromOrdinal(int ordinal);
+
+/* === Builtin Codecs =====================================================
+
+ Many of these APIs take two arguments encoding and errors. These
+ parameters encoding and errors have the same semantics as the ones
+ of the builtin str() API.
+
+ Setting encoding to NULL causes the default encoding (UTF-8) to be used.
+
+ Error handling is set by errors which may also be set to NULL
+ meaning to use the default handling defined for the codec. Default
+ error handling for all builtin codecs is "strict" (ValueErrors are
+ raised).
+
+ The codecs all use a similar interface. Only deviation from the
+ generic ones are documented.
+
+*/
+
+/* --- Manage the default encoding ---------------------------------------- */
+
+/* Returns "utf-8". */
+PyAPI_FUNC(const char*) PyUnicode_GetDefaultEncoding(void);
+
+/* --- Generic Codecs ----------------------------------------------------- */
+
+/* Create a Unicode object by decoding the encoded string s of the
+ given size. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_Decode(
+ const char *s, /* encoded string */
+ Py_ssize_t size, /* size of buffer */
+ const char *encoding, /* encoding */
+ const char *errors /* error handling */
+ );
+
+/* Decode a Unicode object unicode and return the result as Python
+ object.
+
+ This API is DEPRECATED. The only supported standard encoding is rot13.
+ Use PyCodec_Decode() to decode with rot13 and non-standard codecs
+ that decode from str. */
+
+Py_DEPRECATED(3.6) PyAPI_FUNC(PyObject*) PyUnicode_AsDecodedObject(
+ PyObject *unicode, /* Unicode object */
+ const char *encoding, /* encoding */
+ const char *errors /* error handling */
+ );
+
+/* Decode a Unicode object unicode and return the result as Unicode
+ object.
+
+ This API is DEPRECATED. The only supported standard encoding is rot13.
+ Use PyCodec_Decode() to decode with rot13 and non-standard codecs
+ that decode from str to str. */
+
+Py_DEPRECATED(3.6) PyAPI_FUNC(PyObject*) PyUnicode_AsDecodedUnicode(
+ PyObject *unicode, /* Unicode object */
+ const char *encoding, /* encoding */
+ const char *errors /* error handling */
+ );
+
+/* Encodes a Unicode object and returns the result as Python
+ object.
+
+ This API is DEPRECATED. It is superseded by PyUnicode_AsEncodedString()
+ since all standard encodings (except rot13) encode str to bytes.
+ Use PyCodec_Encode() for encoding with rot13 and non-standard codecs
+ that encode form str to non-bytes. */
+
+Py_DEPRECATED(3.6) PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedObject(
+ PyObject *unicode, /* Unicode object */
+ const char *encoding, /* encoding */
+ const char *errors /* error handling */
+ );
+
+/* Encodes a Unicode object and returns the result as Python string
+ object. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedString(
+ PyObject *unicode, /* Unicode object */
+ const char *encoding, /* encoding */
+ const char *errors /* error handling */
+ );
+
+/* Encodes a Unicode object and returns the result as Unicode
+ object.
+
+ This API is DEPRECATED. The only supported standard encodings is rot13.
+ Use PyCodec_Encode() to encode with rot13 and non-standard codecs
+ that encode from str to str. */
+
+Py_DEPRECATED(3.6) PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedUnicode(
+ PyObject *unicode, /* Unicode object */
+ const char *encoding, /* encoding */
+ const char *errors /* error handling */
+ );
+
+/* Build an encoding map. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_BuildEncodingMap(
+ PyObject* string /* 256 character map */
+ );
+
+/* --- UTF-7 Codecs ------------------------------------------------------- */
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF7(
+ const char *string, /* UTF-7 encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors /* error handling */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF7Stateful(
+ const char *string, /* UTF-7 encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors, /* error handling */
+ Py_ssize_t *consumed /* bytes consumed */
+ );
+
+/* --- UTF-8 Codecs ------------------------------------------------------- */
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF8(
+ const char *string, /* UTF-8 encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors /* error handling */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF8Stateful(
+ const char *string, /* UTF-8 encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors, /* error handling */
+ Py_ssize_t *consumed /* bytes consumed */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_AsUTF8String(
+ PyObject *unicode /* Unicode object */
+ );
+
+/* Returns a pointer to the default encoding (UTF-8) of the
+ Unicode object unicode and the size of the encoded representation
+ in bytes stored in *size.
+
+ In case of an error, no *size is set.
+
+ This function caches the UTF-8 encoded string in the unicodeobject
+ and subsequent calls will return the same string. The memory is released
+ when the unicodeobject is deallocated.
+*/
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000
+PyAPI_FUNC(const char *) PyUnicode_AsUTF8AndSize(
+ PyObject *unicode,
+ Py_ssize_t *size);
+#endif
+
+/* --- UTF-32 Codecs ------------------------------------------------------ */
+
+/* Decodes length bytes from a UTF-32 encoded buffer string and returns
+ the corresponding Unicode object.
+
+ errors (if non-NULL) defines the error handling. It defaults
+ to "strict".
+
+ If byteorder is non-NULL, the decoder starts decoding using the
+ given byte order:
+
+ *byteorder == -1: little endian
+ *byteorder == 0: native order
+ *byteorder == 1: big endian
+
+ In native mode, the first four bytes of the stream are checked for a
+ BOM mark. If found, the BOM mark is analysed, the byte order
+ adjusted and the BOM skipped. In the other modes, no BOM mark
+ interpretation is done. After completion, *byteorder is set to the
+ current byte order at the end of input data.
+
+ If byteorder is NULL, the codec starts in native order mode.
+
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF32(
+ const char *string, /* UTF-32 encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors, /* error handling */
+ int *byteorder /* pointer to byteorder to use
+ 0=native;-1=LE,1=BE; updated on
+ exit */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF32Stateful(
+ const char *string, /* UTF-32 encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors, /* error handling */
+ int *byteorder, /* pointer to byteorder to use
+ 0=native;-1=LE,1=BE; updated on
+ exit */
+ Py_ssize_t *consumed /* bytes consumed */
+ );
+
+/* Returns a Python string using the UTF-32 encoding in native byte
+ order. The string always starts with a BOM mark. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_AsUTF32String(
+ PyObject *unicode /* Unicode object */
+ );
+
+/* Returns a Python string object holding the UTF-32 encoded value of
+ the Unicode data.
+
+ If byteorder is not 0, output is written according to the following
+ byte order:
+
+ byteorder == -1: little endian
+ byteorder == 0: native byte order (writes a BOM mark)
+ byteorder == 1: big endian
+
+ If byteorder is 0, the output string will always start with the
+ Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is
+ prepended.
+
+*/
+
+/* --- UTF-16 Codecs ------------------------------------------------------ */
+
+/* Decodes length bytes from a UTF-16 encoded buffer string and returns
+ the corresponding Unicode object.
+
+ errors (if non-NULL) defines the error handling. It defaults
+ to "strict".
+
+ If byteorder is non-NULL, the decoder starts decoding using the
+ given byte order:
+
+ *byteorder == -1: little endian
+ *byteorder == 0: native order
+ *byteorder == 1: big endian
+
+ In native mode, the first two bytes of the stream are checked for a
+ BOM mark. If found, the BOM mark is analysed, the byte order
+ adjusted and the BOM skipped. In the other modes, no BOM mark
+ interpretation is done. After completion, *byteorder is set to the
+ current byte order at the end of input data.
+
+ If byteorder is NULL, the codec starts in native order mode.
+
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF16(
+ const char *string, /* UTF-16 encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors, /* error handling */
+ int *byteorder /* pointer to byteorder to use
+ 0=native;-1=LE,1=BE; updated on
+ exit */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF16Stateful(
+ const char *string, /* UTF-16 encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors, /* error handling */
+ int *byteorder, /* pointer to byteorder to use
+ 0=native;-1=LE,1=BE; updated on
+ exit */
+ Py_ssize_t *consumed /* bytes consumed */
+ );
+
+/* Returns a Python string using the UTF-16 encoding in native byte
+ order. The string always starts with a BOM mark. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_AsUTF16String(
+ PyObject *unicode /* Unicode object */
+ );
+
+/* --- Unicode-Escape Codecs ---------------------------------------------- */
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeUnicodeEscape(
+ const char *string, /* Unicode-Escape encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors /* error handling */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_AsUnicodeEscapeString(
+ PyObject *unicode /* Unicode object */
+ );
+
+/* --- Raw-Unicode-Escape Codecs ------------------------------------------ */
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeRawUnicodeEscape(
+ const char *string, /* Raw-Unicode-Escape encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors /* error handling */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_AsRawUnicodeEscapeString(
+ PyObject *unicode /* Unicode object */
+ );
+
+/* --- Latin-1 Codecs -----------------------------------------------------
+
+ Note: Latin-1 corresponds to the first 256 Unicode ordinals. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeLatin1(
+ const char *string, /* Latin-1 encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors /* error handling */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_AsLatin1String(
+ PyObject *unicode /* Unicode object */
+ );
+
+/* --- ASCII Codecs -------------------------------------------------------
+
+ Only 7-bit ASCII data is excepted. All other codes generate errors.
+
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeASCII(
+ const char *string, /* ASCII encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors /* error handling */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_AsASCIIString(
+ PyObject *unicode /* Unicode object */
+ );
+
+/* --- Character Map Codecs -----------------------------------------------
+
+ This codec uses mappings to encode and decode characters.
+
+ Decoding mappings must map byte ordinals (integers in the range from 0 to
+ 255) to Unicode strings, integers (which are then interpreted as Unicode
+ ordinals) or None. Unmapped data bytes (ones which cause a LookupError)
+ as well as mapped to None, 0xFFFE or '\ufffe' are treated as "undefined
+ mapping" and cause an error.
+
+ Encoding mappings must map Unicode ordinal integers to bytes objects,
+ integers in the range from 0 to 255 or None. Unmapped character
+ ordinals (ones which cause a LookupError) as well as mapped to
+ None are treated as "undefined mapping" and cause an error.
+
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeCharmap(
+ const char *string, /* Encoded string */
+ Py_ssize_t length, /* size of string */
+ PyObject *mapping, /* decoding mapping */
+ const char *errors /* error handling */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_AsCharmapString(
+ PyObject *unicode, /* Unicode object */
+ PyObject *mapping /* encoding mapping */
+ );
+
+/* --- MBCS codecs for Windows -------------------------------------------- */
+
+#ifdef MS_WINDOWS
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeMBCS(
+ const char *string, /* MBCS encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors /* error handling */
+ );
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeMBCSStateful(
+ const char *string, /* MBCS encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors, /* error handling */
+ Py_ssize_t *consumed /* bytes consumed */
+ );
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeCodePageStateful(
+ int code_page, /* code page number */
+ const char *string, /* encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors, /* error handling */
+ Py_ssize_t *consumed /* bytes consumed */
+ );
+#endif
+
+PyAPI_FUNC(PyObject*) PyUnicode_AsMBCSString(
+ PyObject *unicode /* Unicode object */
+ );
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+PyAPI_FUNC(PyObject*) PyUnicode_EncodeCodePage(
+ int code_page, /* code page number */
+ PyObject *unicode, /* Unicode object */
+ const char *errors /* error handling */
+ );
+#endif
+
+#endif /* MS_WINDOWS */
+
+/* --- Locale encoding --------------------------------------------------- */
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+/* Decode a string from the current locale encoding. The decoder is strict if
+ *surrogateescape* is equal to zero, otherwise it uses the 'surrogateescape'
+ error handler (PEP 383) to escape undecodable bytes. If a byte sequence can
+ be decoded as a surrogate character and *surrogateescape* is not equal to
+ zero, the byte sequence is escaped using the 'surrogateescape' error handler
+ instead of being decoded. *str* must end with a null character but cannot
+ contain embedded null characters. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeLocaleAndSize(
+ const char *str,
+ Py_ssize_t len,
+ const char *errors);
+
+/* Similar to PyUnicode_DecodeLocaleAndSize(), but compute the string
+ length using strlen(). */
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeLocale(
+ const char *str,
+ const char *errors);
+
+/* Encode a Unicode object to the current locale encoding. The encoder is
+ strict is *surrogateescape* is equal to zero, otherwise the
+ "surrogateescape" error handler is used. Return a bytes object. The string
+ cannot contain embedded null characters. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_EncodeLocale(
+ PyObject *unicode,
+ const char *errors
+ );
+#endif
+
+/* --- File system encoding ---------------------------------------------- */
+
+/* ParseTuple converter: encode str objects to bytes using
+ PyUnicode_EncodeFSDefault(); bytes objects are output as-is. */
+
+PyAPI_FUNC(int) PyUnicode_FSConverter(PyObject*, void*);
+
+/* ParseTuple converter: decode bytes objects to unicode using
+ PyUnicode_DecodeFSDefaultAndSize(); str objects are output as-is. */
+
+PyAPI_FUNC(int) PyUnicode_FSDecoder(PyObject*, void*);
+
+/* Decode a null-terminated string using Py_FileSystemDefaultEncoding
+ and the "surrogateescape" error handler.
+
+ If Py_FileSystemDefaultEncoding is not set, fall back to the locale
+ encoding.
+
+ Use PyUnicode_DecodeFSDefaultAndSize() if the string length is known.
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeFSDefault(
+ const char *s /* encoded string */
+ );
+
+/* Decode a string using Py_FileSystemDefaultEncoding
+ and the "surrogateescape" error handler.
+
+ If Py_FileSystemDefaultEncoding is not set, fall back to the locale
+ encoding.
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_DecodeFSDefaultAndSize(
+ const char *s, /* encoded string */
+ Py_ssize_t size /* size */
+ );
+
+/* Encode a Unicode object to Py_FileSystemDefaultEncoding with the
+ "surrogateescape" error handler, and return bytes.
+
+ If Py_FileSystemDefaultEncoding is not set, fall back to the locale
+ encoding.
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_EncodeFSDefault(
+ PyObject *unicode
+ );
+
+/* --- Methods & Slots ----------------------------------------------------
+
+ These are capable of handling Unicode objects and strings on input
+ (we refer to them as strings in the descriptions) and return
+ Unicode objects or integers as appropriate. */
+
+/* Concat two strings giving a new Unicode string. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_Concat(
+ PyObject *left, /* Left string */
+ PyObject *right /* Right string */
+ );
+
+/* Concat two strings and put the result in *pleft
+ (sets *pleft to NULL on error) */
+
+PyAPI_FUNC(void) PyUnicode_Append(
+ PyObject **pleft, /* Pointer to left string */
+ PyObject *right /* Right string */
+ );
+
+/* Concat two strings, put the result in *pleft and drop the right object
+ (sets *pleft to NULL on error) */
+
+PyAPI_FUNC(void) PyUnicode_AppendAndDel(
+ PyObject **pleft, /* Pointer to left string */
+ PyObject *right /* Right string */
+ );
+
+/* Split a string giving a list of Unicode strings.
+
+ If sep is NULL, splitting will be done at all whitespace
+ substrings. Otherwise, splits occur at the given separator.
+
+ At most maxsplit splits will be done. If negative, no limit is set.
+
+ Separators are not included in the resulting list.
+
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_Split(
+ PyObject *s, /* String to split */
+ PyObject *sep, /* String separator */
+ Py_ssize_t maxsplit /* Maxsplit count */
+ );
+
+/* Dito, but split at line breaks.
+
+ CRLF is considered to be one line break. Line breaks are not
+ included in the resulting list. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_Splitlines(
+ PyObject *s, /* String to split */
+ int keepends /* If true, line end markers are included */
+ );
+
+/* Partition a string using a given separator. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_Partition(
+ PyObject *s, /* String to partition */
+ PyObject *sep /* String separator */
+ );
+
+/* Partition a string using a given separator, searching from the end of the
+ string. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_RPartition(
+ PyObject *s, /* String to partition */
+ PyObject *sep /* String separator */
+ );
+
+/* Split a string giving a list of Unicode strings.
+
+ If sep is NULL, splitting will be done at all whitespace
+ substrings. Otherwise, splits occur at the given separator.
+
+ At most maxsplit splits will be done. But unlike PyUnicode_Split
+ PyUnicode_RSplit splits from the end of the string. If negative,
+ no limit is set.
+
+ Separators are not included in the resulting list.
+
+*/
+
+PyAPI_FUNC(PyObject*) PyUnicode_RSplit(
+ PyObject *s, /* String to split */
+ PyObject *sep, /* String separator */
+ Py_ssize_t maxsplit /* Maxsplit count */
+ );
+
+/* Translate a string by applying a character mapping table to it and
+ return the resulting Unicode object.
+
+ The mapping table must map Unicode ordinal integers to Unicode strings,
+ Unicode ordinal integers or None (causing deletion of the character).
+
+ Mapping tables may be dictionaries or sequences. Unmapped character
+ ordinals (ones which cause a LookupError) are left untouched and
+ are copied as-is.
+
+*/
+
+PyAPI_FUNC(PyObject *) PyUnicode_Translate(
+ PyObject *str, /* String */
+ PyObject *table, /* Translate table */
+ const char *errors /* error handling */
+ );
+
+/* Join a sequence of strings using the given separator and return
+ the resulting Unicode string. */
+
+PyAPI_FUNC(PyObject*) PyUnicode_Join(
+ PyObject *separator, /* Separator string */
+ PyObject *seq /* Sequence object */
+ );
+
+/* Return 1 if substr matches str[start:end] at the given tail end, 0
+ otherwise. */
+
+PyAPI_FUNC(Py_ssize_t) PyUnicode_Tailmatch(
+ PyObject *str, /* String */
+ PyObject *substr, /* Prefix or Suffix string */
+ Py_ssize_t start, /* Start index */
+ Py_ssize_t end, /* Stop index */
+ int direction /* Tail end: -1 prefix, +1 suffix */
+ );
+
+/* Return the first position of substr in str[start:end] using the
+ given search direction or -1 if not found. -2 is returned in case
+ an error occurred and an exception is set. */
+
+PyAPI_FUNC(Py_ssize_t) PyUnicode_Find(
+ PyObject *str, /* String */
+ PyObject *substr, /* Substring to find */
+ Py_ssize_t start, /* Start index */
+ Py_ssize_t end, /* Stop index */
+ int direction /* Find direction: +1 forward, -1 backward */
+ );
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
+/* Like PyUnicode_Find, but search for single character only. */
+PyAPI_FUNC(Py_ssize_t) PyUnicode_FindChar(
+ PyObject *str,
+ Py_UCS4 ch,
+ Py_ssize_t start,
+ Py_ssize_t end,
+ int direction
+ );
+#endif
+
+/* Count the number of occurrences of substr in str[start:end]. */
+
+PyAPI_FUNC(Py_ssize_t) PyUnicode_Count(
+ PyObject *str, /* String */
+ PyObject *substr, /* Substring to count */
+ Py_ssize_t start, /* Start index */
+ Py_ssize_t end /* Stop index */
+ );
+
+/* Replace at most maxcount occurrences of substr in str with replstr
+ and return the resulting Unicode object. */
+
+PyAPI_FUNC(PyObject *) PyUnicode_Replace(
+ PyObject *str, /* String */
+ PyObject *substr, /* Substring to find */
+ PyObject *replstr, /* Substring to replace */
+ Py_ssize_t maxcount /* Max. number of replacements to apply;
+ -1 = all */
+ );
+
+/* Compare two strings and return -1, 0, 1 for less than, equal,
+ greater than resp.
+ Raise an exception and return -1 on error. */
+
+PyAPI_FUNC(int) PyUnicode_Compare(
+ PyObject *left, /* Left string */
+ PyObject *right /* Right string */
+ );
+
+/* Compare a Unicode object with C string and return -1, 0, 1 for less than,
+ equal, and greater than, respectively. It is best to pass only
+ ASCII-encoded strings, but the function interprets the input string as
+ ISO-8859-1 if it contains non-ASCII characters.
+ This function does not raise exceptions. */
+
+PyAPI_FUNC(int) PyUnicode_CompareWithASCIIString(
+ PyObject *left,
+ const char *right /* ASCII-encoded string */
+ );
+
+/* Rich compare two strings and return one of the following:
+
+ - NULL in case an exception was raised
+ - Py_True or Py_False for successful comparisons
+ - Py_NotImplemented in case the type combination is unknown
+
+ Possible values for op:
+
+ Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE
+
+*/
+
+PyAPI_FUNC(PyObject *) PyUnicode_RichCompare(
+ PyObject *left, /* Left string */
+ PyObject *right, /* Right string */
+ int op /* Operation: Py_EQ, Py_NE, Py_GT, etc. */
+ );
+
+/* Apply an argument tuple or dictionary to a format string and return
+ the resulting Unicode string. */
+
+PyAPI_FUNC(PyObject *) PyUnicode_Format(
+ PyObject *format, /* Format string */
+ PyObject *args /* Argument tuple or dictionary */
+ );
+
+/* Checks whether element is contained in container and return 1/0
+ accordingly.
+
+ element has to coerce to a one element Unicode string. -1 is
+ returned in case of an error. */
+
+PyAPI_FUNC(int) PyUnicode_Contains(
+ PyObject *container, /* Container string */
+ PyObject *element /* Element string */
+ );
+
+/* Checks whether argument is a valid identifier. */
+
+PyAPI_FUNC(int) PyUnicode_IsIdentifier(PyObject *s);
+
+/* === Characters Type APIs =============================================== */
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_UNICODEOBJECT_H
+# include "cpython/unicodeobject.h"
+# undef Py_CPYTHON_UNICODEOBJECT_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_UNICODEOBJECT_H */
diff --git a/include/python3.11/warnings.h b/include/python3.11/warnings.h
new file mode 100644
index 0000000..18ac154
--- /dev/null
+++ b/include/python3.11/warnings.h
@@ -0,0 +1,45 @@
+#ifndef Py_WARNINGS_H
+#define Py_WARNINGS_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+PyAPI_FUNC(int) PyErr_WarnEx(
+ PyObject *category,
+ const char *message, /* UTF-8 encoded string */
+ Py_ssize_t stack_level);
+
+PyAPI_FUNC(int) PyErr_WarnFormat(
+ PyObject *category,
+ Py_ssize_t stack_level,
+ const char *format, /* ASCII-encoded string */
+ ...);
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000
+/* Emit a ResourceWarning warning */
+PyAPI_FUNC(int) PyErr_ResourceWarning(
+ PyObject *source,
+ Py_ssize_t stack_level,
+ const char *format, /* ASCII-encoded string */
+ ...);
+#endif
+
+PyAPI_FUNC(int) PyErr_WarnExplicit(
+ PyObject *category,
+ const char *message, /* UTF-8 encoded string */
+ const char *filename, /* decoded from the filesystem encoding */
+ int lineno,
+ const char *module, /* UTF-8 encoded string */
+ PyObject *registry);
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_WARNINGS_H
+# include "cpython/warnings.h"
+# undef Py_CPYTHON_WARNINGS_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_WARNINGS_H */
+
diff --git a/include/python3.11/weakrefobject.h b/include/python3.11/weakrefobject.h
new file mode 100644
index 0000000..f071e9c
--- /dev/null
+++ b/include/python3.11/weakrefobject.h
@@ -0,0 +1,42 @@
+/* Weak references objects for Python. */
+
+#ifndef Py_WEAKREFOBJECT_H
+#define Py_WEAKREFOBJECT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct _PyWeakReference PyWeakReference;
+
+PyAPI_DATA(PyTypeObject) _PyWeakref_RefType;
+PyAPI_DATA(PyTypeObject) _PyWeakref_ProxyType;
+PyAPI_DATA(PyTypeObject) _PyWeakref_CallableProxyType;
+
+#define PyWeakref_CheckRef(op) PyObject_TypeCheck(op, &_PyWeakref_RefType)
+#define PyWeakref_CheckRefExact(op) \
+ Py_IS_TYPE(op, &_PyWeakref_RefType)
+#define PyWeakref_CheckProxy(op) \
+ (Py_IS_TYPE(op, &_PyWeakref_ProxyType) || \
+ Py_IS_TYPE(op, &_PyWeakref_CallableProxyType))
+
+#define PyWeakref_Check(op) \
+ (PyWeakref_CheckRef(op) || PyWeakref_CheckProxy(op))
+
+
+PyAPI_FUNC(PyObject *) PyWeakref_NewRef(PyObject *ob,
+ PyObject *callback);
+PyAPI_FUNC(PyObject *) PyWeakref_NewProxy(PyObject *ob,
+ PyObject *callback);
+PyAPI_FUNC(PyObject *) PyWeakref_GetObject(PyObject *ref);
+
+
+#ifndef Py_LIMITED_API
+# define Py_CPYTHON_WEAKREFOBJECT_H
+# include "cpython/weakrefobject.h"
+# undef Py_CPYTHON_WEAKREFOBJECT_H
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_WEAKREFOBJECT_H */
diff --git a/lib/libpython3.10.so b/lib/libpython3.10.so
deleted file mode 100644
index 1b50bdd..0000000
--- a/lib/libpython3.10.so
+++ /dev/null
Binary files differ
diff --git a/lib/libpython3.10.so.1.0 b/lib/libpython3.10.so.1.0
deleted file mode 100644
index 1b50bdd..0000000
--- a/lib/libpython3.10.so.1.0
+++ /dev/null
Binary files differ
diff --git a/lib/libpython3.11.so b/lib/libpython3.11.so
new file mode 100644
index 0000000..e524616
--- /dev/null
+++ b/lib/libpython3.11.so
Binary files differ
diff --git a/lib/libpython3.11.so.1.0 b/lib/libpython3.11.so.1.0
new file mode 100644
index 0000000..e524616
--- /dev/null
+++ b/lib/libpython3.11.so.1.0
Binary files differ
diff --git a/lib/libpython3.so b/lib/libpython3.so
index b332670..03087ca 100644
--- a/lib/libpython3.so
+++ b/lib/libpython3.so
Binary files differ
diff --git a/lib/pkgconfig/python-3.10-embed.pc b/lib/pkgconfig/python-3.10-embed.pc
deleted file mode 100644
index a146b4f..0000000
--- a/lib/pkgconfig/python-3.10-embed.pc
+++ /dev/null
@@ -1,13 +0,0 @@
-# See: man pkg-config
-prefix=/tmpfs/src/git/out/python3/install
-exec_prefix=${prefix}
-libdir=${exec_prefix}/lib
-includedir=${prefix}/include
-
-Name: Python
-Description: Embed Python into an application
-Requires:
-Version: 3.10
-Libs.private: -lcrypt -lpthread -ldl -lutil -lm
-Libs: -L${libdir} -lpython3.10
-Cflags: -I${includedir}/python3.10
diff --git a/lib/pkgconfig/python-3.10.pc b/lib/pkgconfig/python-3.10.pc
deleted file mode 100644
index ff7e124..0000000
--- a/lib/pkgconfig/python-3.10.pc
+++ /dev/null
@@ -1,13 +0,0 @@
-# See: man pkg-config
-prefix=/tmpfs/src/git/out/python3/install
-exec_prefix=${prefix}
-libdir=${exec_prefix}/lib
-includedir=${prefix}/include
-
-Name: Python
-Description: Build a C extension for Python
-Requires:
-Version: 3.10
-Libs.private: -lcrypt -lpthread -ldl -lutil -lm
-Libs:
-Cflags: -I${includedir}/python3.10
diff --git a/lib/pkgconfig/python-3.11-embed.pc b/lib/pkgconfig/python-3.11-embed.pc
new file mode 100644
index 0000000..73db451
--- /dev/null
+++ b/lib/pkgconfig/python-3.11-embed.pc
@@ -0,0 +1,13 @@
+# See: man pkg-config
+prefix=/tmpfs/src/git/out/python3/install
+exec_prefix=${prefix}
+libdir=${exec_prefix}/lib
+includedir=${prefix}/include
+
+Name: Python
+Description: Embed Python into an application
+Requires:
+Version: 3.11
+Libs.private: -lpthread -ldl -lutil
+Libs: -L${libdir} -lpython3.11
+Cflags: -I${includedir}/python3.11
diff --git a/lib/pkgconfig/python-3.11.pc b/lib/pkgconfig/python-3.11.pc
new file mode 100644
index 0000000..43651e9
--- /dev/null
+++ b/lib/pkgconfig/python-3.11.pc
@@ -0,0 +1,13 @@
+# See: man pkg-config
+prefix=/tmpfs/src/git/out/python3/install
+exec_prefix=${prefix}
+libdir=${exec_prefix}/lib
+includedir=${prefix}/include
+
+Name: Python
+Description: Build a C extension for Python
+Requires:
+Version: 3.11
+Libs.private: -lpthread -ldl -lutil
+Libs:
+Cflags: -I${includedir}/python3.11
diff --git a/lib/pkgconfig/python3-embed.pc b/lib/pkgconfig/python3-embed.pc
index a146b4f..73db451 100644
--- a/lib/pkgconfig/python3-embed.pc
+++ b/lib/pkgconfig/python3-embed.pc
@@ -7,7 +7,7 @@
Name: Python
Description: Embed Python into an application
Requires:
-Version: 3.10
-Libs.private: -lcrypt -lpthread -ldl -lutil -lm
-Libs: -L${libdir} -lpython3.10
-Cflags: -I${includedir}/python3.10
+Version: 3.11
+Libs.private: -lpthread -ldl -lutil
+Libs: -L${libdir} -lpython3.11
+Cflags: -I${includedir}/python3.11
diff --git a/lib/pkgconfig/python3.pc b/lib/pkgconfig/python3.pc
index ff7e124..43651e9 100644
--- a/lib/pkgconfig/python3.pc
+++ b/lib/pkgconfig/python3.pc
@@ -7,7 +7,7 @@
Name: Python
Description: Build a C extension for Python
Requires:
-Version: 3.10
-Libs.private: -lcrypt -lpthread -ldl -lutil -lm
+Version: 3.11
+Libs.private: -lpthread -ldl -lutil
Libs:
-Cflags: -I${includedir}/python3.10
+Cflags: -I${includedir}/python3.11
diff --git a/lib/python3.10/LICENSE.txt b/lib/python3.10/LICENSE.txt
deleted file mode 100644
index 78f250c..0000000
--- a/lib/python3.10/LICENSE.txt
+++ /dev/null
@@ -1,303 +0,0 @@
-A. HISTORY OF THE SOFTWARE
-==========================
-
-Python was created in the early 1990s by Guido van Rossum at Stichting
-Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
-as a successor of a language called ABC. Guido remains Python's
-principal author, although it includes many contributions from others.
-
-In 1995, Guido continued his work on Python at the Corporation for
-National Research Initiatives (CNRI, see http://www.cnri.reston.va.us)
-in Reston, Virginia where he released several versions of the
-software.
-
-In May 2000, Guido and the Python core development team moved to
-BeOpen.com to form the BeOpen PythonLabs team. In October of the same
-year, the PythonLabs team moved to Digital Creations, which became
-Zope Corporation. In 2001, the Python Software Foundation (PSF, see
-https://www.python.org/psf/) was formed, a non-profit organization
-created specifically to own Python-related Intellectual Property.
-Zope Corporation was a sponsoring member of the PSF.
-
-All Python releases are Open Source (see http://www.opensource.org for
-the Open Source Definition). Historically, most, but not all, Python
-releases have also been GPL-compatible; the table below summarizes
-the various releases.
-
- Release Derived Year Owner GPL-
- from compatible? (1)
-
- 0.9.0 thru 1.2 1991-1995 CWI yes
- 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
- 1.6 1.5.2 2000 CNRI no
- 2.0 1.6 2000 BeOpen.com no
- 1.6.1 1.6 2001 CNRI yes (2)
- 2.1 2.0+1.6.1 2001 PSF no
- 2.0.1 2.0+1.6.1 2001 PSF yes
- 2.1.1 2.1+2.0.1 2001 PSF yes
- 2.1.2 2.1.1 2002 PSF yes
- 2.1.3 2.1.2 2002 PSF yes
- 2.2 and above 2.1.1 2001-now PSF yes
-
-Footnotes:
-
-(1) GPL-compatible doesn't mean that we're distributing Python under
- the GPL. All Python licenses, unlike the GPL, let you distribute
- a modified version without making your changes open source. The
- GPL-compatible licenses make it possible to combine Python with
- other software that is released under the GPL; the others don't.
-
-(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
- because its license has a choice of law clause. According to
- CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
- is "not incompatible" with the GPL.
-
-Thanks to the many outside volunteers who have worked under Guido's
-direction to make these releases possible.
-
-
-B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
-===============================================================
-
-Python software and documentation are licensed under the
-Python Software Foundation License Version 2.
-
-Starting with Python 3.8.6, examples, recipes, and other code in
-the documentation are dual licensed under the PSF License Version 2
-and the Zero-Clause BSD license.
-
-Some software incorporated into Python is under different licenses.
-The licenses are listed with code falling under that license.
-
-
-PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
---------------------------------------------
-
-1. This LICENSE AGREEMENT is between the Python Software Foundation
-("PSF"), and the Individual or Organization ("Licensee") accessing and
-otherwise using this software ("Python") in source or binary form and
-its associated documentation.
-
-2. Subject to the terms and conditions of this License Agreement, PSF hereby
-grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
-analyze, test, perform and/or display publicly, prepare derivative works,
-distribute, and otherwise use Python alone or in any derivative version,
-provided, however, that PSF's License Agreement and PSF's notice of copyright,
-i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
-2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 Python Software Foundation;
-All Rights Reserved" are retained in Python alone or in any derivative version
-prepared by Licensee.
-
-3. In the event Licensee prepares a derivative work that is based on
-or incorporates Python or any part thereof, and wants to make
-the derivative work available to others as provided herein, then
-Licensee hereby agrees to include in any such work a brief summary of
-the changes made to Python.
-
-4. PSF is making Python available to Licensee on an "AS IS"
-basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
-IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
-DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
-FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
-INFRINGE ANY THIRD PARTY RIGHTS.
-
-5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
-FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
-A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
-OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-6. This License Agreement will automatically terminate upon a material
-breach of its terms and conditions.
-
-7. Nothing in this License Agreement shall be deemed to create any
-relationship of agency, partnership, or joint venture between PSF and
-Licensee. This License Agreement does not grant permission to use PSF
-trademarks or trade name in a trademark sense to endorse or promote
-products or services of Licensee, or any third party.
-
-8. By copying, installing or otherwise using Python, Licensee
-agrees to be bound by the terms and conditions of this License
-Agreement.
-
-
-BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
--------------------------------------------
-
-BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
-
-1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
-office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
-Individual or Organization ("Licensee") accessing and otherwise using
-this software in source or binary form and its associated
-documentation ("the Software").
-
-2. Subject to the terms and conditions of this BeOpen Python License
-Agreement, BeOpen hereby grants Licensee a non-exclusive,
-royalty-free, world-wide license to reproduce, analyze, test, perform
-and/or display publicly, prepare derivative works, distribute, and
-otherwise use the Software alone or in any derivative version,
-provided, however, that the BeOpen Python License is retained in the
-Software, alone or in any derivative version prepared by Licensee.
-
-3. BeOpen is making the Software available to Licensee on an "AS IS"
-basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
-IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
-DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
-FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
-INFRINGE ANY THIRD PARTY RIGHTS.
-
-4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
-SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
-AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
-DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-5. This License Agreement will automatically terminate upon a material
-breach of its terms and conditions.
-
-6. This License Agreement shall be governed by and interpreted in all
-respects by the law of the State of California, excluding conflict of
-law provisions. Nothing in this License Agreement shall be deemed to
-create any relationship of agency, partnership, or joint venture
-between BeOpen and Licensee. This License Agreement does not grant
-permission to use BeOpen trademarks or trade names in a trademark
-sense to endorse or promote products or services of Licensee, or any
-third party. As an exception, the "BeOpen Python" logos available at
-http://www.pythonlabs.com/logos.html may be used according to the
-permissions granted on that web page.
-
-7. By copying, installing or otherwise using the software, Licensee
-agrees to be bound by the terms and conditions of this License
-Agreement.
-
-
-CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
----------------------------------------
-
-1. This LICENSE AGREEMENT is between the Corporation for National
-Research Initiatives, having an office at 1895 Preston White Drive,
-Reston, VA 20191 ("CNRI"), and the Individual or Organization
-("Licensee") accessing and otherwise using Python 1.6.1 software in
-source or binary form and its associated documentation.
-
-2. Subject to the terms and conditions of this License Agreement, CNRI
-hereby grants Licensee a nonexclusive, royalty-free, world-wide
-license to reproduce, analyze, test, perform and/or display publicly,
-prepare derivative works, distribute, and otherwise use Python 1.6.1
-alone or in any derivative version, provided, however, that CNRI's
-License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
-1995-2001 Corporation for National Research Initiatives; All Rights
-Reserved" are retained in Python 1.6.1 alone or in any derivative
-version prepared by Licensee. Alternately, in lieu of CNRI's License
-Agreement, Licensee may substitute the following text (omitting the
-quotes): "Python 1.6.1 is made available subject to the terms and
-conditions in CNRI's License Agreement. This Agreement together with
-Python 1.6.1 may be located on the internet using the following
-unique, persistent identifier (known as a handle): 1895.22/1013. This
-Agreement may also be obtained from a proxy server on the internet
-using the following URL: http://hdl.handle.net/1895.22/1013".
-
-3. In the event Licensee prepares a derivative work that is based on
-or incorporates Python 1.6.1 or any part thereof, and wants to make
-the derivative work available to others as provided herein, then
-Licensee hereby agrees to include in any such work a brief summary of
-the changes made to Python 1.6.1.
-
-4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
-basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
-IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
-DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
-FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
-INFRINGE ANY THIRD PARTY RIGHTS.
-
-5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
-1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
-A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
-OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-6. This License Agreement will automatically terminate upon a material
-breach of its terms and conditions.
-
-7. This License Agreement shall be governed by the federal
-intellectual property law of the United States, including without
-limitation the federal copyright law, and, to the extent such
-U.S. federal law does not apply, by the law of the Commonwealth of
-Virginia, excluding Virginia's conflict of law provisions.
-Notwithstanding the foregoing, with regard to derivative works based
-on Python 1.6.1 that incorporate non-separable material that was
-previously distributed under the GNU General Public License (GPL), the
-law of the Commonwealth of Virginia shall govern this License
-Agreement only as to issues arising under or with respect to
-Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
-License Agreement shall be deemed to create any relationship of
-agency, partnership, or joint venture between CNRI and Licensee. This
-License Agreement does not grant permission to use CNRI trademarks or
-trade name in a trademark sense to endorse or promote products or
-services of Licensee, or any third party.
-
-8. By clicking on the "ACCEPT" button where indicated, or by copying,
-installing or otherwise using Python 1.6.1, Licensee agrees to be
-bound by the terms and conditions of this License Agreement.
-
- ACCEPT
-
-
-CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
---------------------------------------------------
-
-Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
-The Netherlands. All rights reserved.
-
-Permission to use, copy, modify, and distribute this software and its
-documentation for any purpose and without fee is hereby granted,
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in
-supporting documentation, and that the name of Stichting Mathematisch
-Centrum or CWI not be used in advertising or publicity pertaining to
-distribution of the software without specific, written prior
-permission.
-
-STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
-THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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.
-
-ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION
-----------------------------------------------------------------------
-
-Permission to use, copy, modify, and/or distribute this software for any
-purpose with or without fee is hereby granted.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-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.
-
--------------------------------------------------------------------
-
-libffi - Copyright (c) 1996-2019 Anthony Green, Red Hat, Inc and others.
-See source files for details.
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-``Software''), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/lib/python3.10/__future__.py b/lib/python3.10/__future__.py
deleted file mode 100644
index 97dc90c..0000000
--- a/lib/python3.10/__future__.py
+++ /dev/null
@@ -1,147 +0,0 @@
-"""Record of phased-in incompatible language changes.
-
-Each line is of the form:
-
- FeatureName = "_Feature(" OptionalRelease "," MandatoryRelease ","
- CompilerFlag ")"
-
-where, normally, OptionalRelease < MandatoryRelease, and both are 5-tuples
-of the same form as sys.version_info:
-
- (PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int
- PY_MINOR_VERSION, # the 1; an int
- PY_MICRO_VERSION, # the 0; an int
- PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" or "final"; string
- PY_RELEASE_SERIAL # the 3; an int
- )
-
-OptionalRelease records the first release in which
-
- from __future__ import FeatureName
-
-was accepted.
-
-In the case of MandatoryReleases that have not yet occurred,
-MandatoryRelease predicts the release in which the feature will become part
-of the language.
-
-Else MandatoryRelease records when the feature became part of the language;
-in releases at or after that, modules no longer need
-
- from __future__ import FeatureName
-
-to use the feature in question, but may continue to use such imports.
-
-MandatoryRelease may also be None, meaning that a planned feature got
-dropped.
-
-Instances of class _Feature have two corresponding methods,
-.getOptionalRelease() and .getMandatoryRelease().
-
-CompilerFlag is the (bitfield) flag that should be passed in the fourth
-argument to the builtin function compile() to enable the feature in
-dynamically compiled code. This flag is stored in the .compiler_flag
-attribute on _Future instances. These values must match the appropriate
-#defines of CO_xxx flags in Include/cpython/compile.h.
-
-No feature line is ever to be deleted from this file.
-"""
-
-all_feature_names = [
- "nested_scopes",
- "generators",
- "division",
- "absolute_import",
- "with_statement",
- "print_function",
- "unicode_literals",
- "barry_as_FLUFL",
- "generator_stop",
- "annotations",
-]
-
-__all__ = ["all_feature_names"] + all_feature_names
-
-# The CO_xxx symbols are defined here under the same names defined in
-# code.h and used by compile.h, so that an editor search will find them here.
-# However, they're not exported in __all__, because they don't really belong to
-# this module.
-CO_NESTED = 0x0010 # nested_scopes
-CO_GENERATOR_ALLOWED = 0 # generators (obsolete, was 0x1000)
-CO_FUTURE_DIVISION = 0x20000 # division
-CO_FUTURE_ABSOLUTE_IMPORT = 0x40000 # perform absolute imports by default
-CO_FUTURE_WITH_STATEMENT = 0x80000 # with statement
-CO_FUTURE_PRINT_FUNCTION = 0x100000 # print function
-CO_FUTURE_UNICODE_LITERALS = 0x200000 # unicode string literals
-CO_FUTURE_BARRY_AS_BDFL = 0x400000
-CO_FUTURE_GENERATOR_STOP = 0x800000 # StopIteration becomes RuntimeError in generators
-CO_FUTURE_ANNOTATIONS = 0x1000000 # annotations become strings at runtime
-
-
-class _Feature:
-
- def __init__(self, optionalRelease, mandatoryRelease, compiler_flag):
- self.optional = optionalRelease
- self.mandatory = mandatoryRelease
- self.compiler_flag = compiler_flag
-
- def getOptionalRelease(self):
- """Return first release in which this feature was recognized.
-
- This is a 5-tuple, of the same form as sys.version_info.
- """
- return self.optional
-
- def getMandatoryRelease(self):
- """Return release in which this feature will become mandatory.
-
- This is a 5-tuple, of the same form as sys.version_info, or, if
- the feature was dropped, is None.
- """
- return self.mandatory
-
- def __repr__(self):
- return "_Feature" + repr((self.optional,
- self.mandatory,
- self.compiler_flag))
-
-
-nested_scopes = _Feature((2, 1, 0, "beta", 1),
- (2, 2, 0, "alpha", 0),
- CO_NESTED)
-
-generators = _Feature((2, 2, 0, "alpha", 1),
- (2, 3, 0, "final", 0),
- CO_GENERATOR_ALLOWED)
-
-division = _Feature((2, 2, 0, "alpha", 2),
- (3, 0, 0, "alpha", 0),
- CO_FUTURE_DIVISION)
-
-absolute_import = _Feature((2, 5, 0, "alpha", 1),
- (3, 0, 0, "alpha", 0),
- CO_FUTURE_ABSOLUTE_IMPORT)
-
-with_statement = _Feature((2, 5, 0, "alpha", 1),
- (2, 6, 0, "alpha", 0),
- CO_FUTURE_WITH_STATEMENT)
-
-print_function = _Feature((2, 6, 0, "alpha", 2),
- (3, 0, 0, "alpha", 0),
- CO_FUTURE_PRINT_FUNCTION)
-
-unicode_literals = _Feature((2, 6, 0, "alpha", 2),
- (3, 0, 0, "alpha", 0),
- CO_FUTURE_UNICODE_LITERALS)
-
-barry_as_FLUFL = _Feature((3, 1, 0, "alpha", 2),
- (4, 0, 0, "alpha", 0),
- CO_FUTURE_BARRY_AS_BDFL)
-
-generator_stop = _Feature((3, 5, 0, "beta", 1),
- (3, 7, 0, "alpha", 0),
- CO_FUTURE_GENERATOR_STOP)
-
-annotations = _Feature((3, 7, 0, "beta", 1),
- (3, 11, 0, "alpha", 0),
- CO_FUTURE_ANNOTATIONS)
diff --git a/lib/python3.10/__phello__.foo.py b/lib/python3.10/__phello__.foo.py
deleted file mode 100644
index 8e8623e..0000000
--- a/lib/python3.10/__phello__.foo.py
+++ /dev/null
@@ -1 +0,0 @@
-# This file exists as a helper for the test.test_frozen module.
diff --git a/lib/python3.10/_aix_support.py b/lib/python3.10/_aix_support.py
deleted file mode 100644
index 4550493..0000000
--- a/lib/python3.10/_aix_support.py
+++ /dev/null
@@ -1,89 +0,0 @@
-"""Shared AIX support functions."""
-
-import sys
-import sysconfig
-
-try:
- import subprocess
-except ImportError: # pragma: no cover
- # _aix_support is used in distutils by setup.py to build C extensions,
- # before subprocess dependencies like _posixsubprocess are available.
- import _bootsubprocess as subprocess
-
-
-def _aix_tag(vrtl, bd):
- # type: (List[int], int) -> str
- # Infer the ABI bitwidth from maxsize (assuming 64 bit as the default)
- _sz = 32 if sys.maxsize == (2**31-1) else 64
- # vrtl[version, release, technology_level]
- return "aix-{:1x}{:1d}{:02d}-{:04d}-{}".format(vrtl[0], vrtl[1], vrtl[2], bd, _sz)
-
-
-# extract version, release and technology level from a VRMF string
-def _aix_vrtl(vrmf):
- # type: (str) -> List[int]
- v, r, tl = vrmf.split(".")[:3]
- return [int(v[-1]), int(r), int(tl)]
-
-
-def _aix_bosmp64():
- # type: () -> Tuple[str, int]
- """
- Return a Tuple[str, int] e.g., ['7.1.4.34', 1806]
- The fileset bos.mp64 is the AIX kernel. It's VRMF and builddate
- reflect the current ABI levels of the runtime environment.
- """
- # We expect all AIX systems to have lslpp installed in this location
- out = subprocess.check_output(["/usr/bin/lslpp", "-Lqc", "bos.mp64"])
- out = out.decode("utf-8")
- out = out.strip().split(":") # type: ignore
- # Use str() and int() to help mypy see types
- return (str(out[2]), int(out[-1]))
-
-
-def aix_platform():
- # type: () -> str
- """
- AIX filesets are identified by four decimal values: V.R.M.F.
- V (version) and R (release) can be retreived using ``uname``
- Since 2007, starting with AIX 5.3 TL7, the M value has been
- included with the fileset bos.mp64 and represents the Technology
- Level (TL) of AIX. The F (Fix) value also increases, but is not
- relevant for comparing releases and binary compatibility.
- For binary compatibility the so-called builddate is needed.
- Again, the builddate of an AIX release is associated with bos.mp64.
- AIX ABI compatibility is described as guaranteed at: https://www.ibm.com/\
- support/knowledgecenter/en/ssw_aix_72/install/binary_compatability.html
-
- For pep425 purposes the AIX platform tag becomes:
- "aix-{:1x}{:1d}{:02d}-{:04d}-{}".format(v, r, tl, builddate, bitsize)
- e.g., "aix-6107-1415-32" for AIX 6.1 TL7 bd 1415, 32-bit
- and, "aix-6107-1415-64" for AIX 6.1 TL7 bd 1415, 64-bit
- """
- vrmf, bd = _aix_bosmp64()
- return _aix_tag(_aix_vrtl(vrmf), bd)
-
-
-# extract vrtl from the BUILD_GNU_TYPE as an int
-def _aix_bgt():
- # type: () -> List[int]
- gnu_type = sysconfig.get_config_var("BUILD_GNU_TYPE")
- if not gnu_type:
- raise ValueError("BUILD_GNU_TYPE is not defined")
- return _aix_vrtl(vrmf=gnu_type)
-
-
-def aix_buildtag():
- # type: () -> str
- """
- Return the platform_tag of the system Python was built on.
- """
- # AIX_BUILDDATE is defined by configure with:
- # lslpp -Lcq bos.mp64 | awk -F: '{ print $NF }'
- build_date = sysconfig.get_config_var("AIX_BUILDDATE")
- try:
- build_date = int(build_date)
- except (ValueError, TypeError):
- raise ValueError(f"AIX_BUILDDATE is not defined or invalid: "
- f"{build_date!r}")
- return _aix_tag(_aix_bgt(), build_date)
diff --git a/lib/python3.10/_collections_abc.py b/lib/python3.10/_collections_abc.py
deleted file mode 100644
index 40417dc..0000000
--- a/lib/python3.10/_collections_abc.py
+++ /dev/null
@@ -1,1166 +0,0 @@
-# Copyright 2007 Google, Inc. All Rights Reserved.
-# Licensed to PSF under a Contributor Agreement.
-
-"""Abstract Base Classes (ABCs) for collections, according to PEP 3119.
-
-Unit tests are in test_collections.
-"""
-
-from abc import ABCMeta, abstractmethod
-import sys
-
-GenericAlias = type(list[int])
-EllipsisType = type(...)
-def _f(): pass
-FunctionType = type(_f)
-del _f
-
-__all__ = ["Awaitable", "Coroutine",
- "AsyncIterable", "AsyncIterator", "AsyncGenerator",
- "Hashable", "Iterable", "Iterator", "Generator", "Reversible",
- "Sized", "Container", "Callable", "Collection",
- "Set", "MutableSet",
- "Mapping", "MutableMapping",
- "MappingView", "KeysView", "ItemsView", "ValuesView",
- "Sequence", "MutableSequence",
- "ByteString",
- ]
-
-# This module has been renamed from collections.abc to _collections_abc to
-# speed up interpreter startup. Some of the types such as MutableMapping are
-# required early but collections module imports a lot of other modules.
-# See issue #19218
-__name__ = "collections.abc"
-
-# Private list of types that we want to register with the various ABCs
-# so that they will pass tests like:
-# it = iter(somebytearray)
-# assert isinstance(it, Iterable)
-# Note: in other implementations, these types might not be distinct
-# and they may have their own implementation specific types that
-# are not included on this list.
-bytes_iterator = type(iter(b''))
-bytearray_iterator = type(iter(bytearray()))
-#callable_iterator = ???
-dict_keyiterator = type(iter({}.keys()))
-dict_valueiterator = type(iter({}.values()))
-dict_itemiterator = type(iter({}.items()))
-list_iterator = type(iter([]))
-list_reverseiterator = type(iter(reversed([])))
-range_iterator = type(iter(range(0)))
-longrange_iterator = type(iter(range(1 << 1000)))
-set_iterator = type(iter(set()))
-str_iterator = type(iter(""))
-tuple_iterator = type(iter(()))
-zip_iterator = type(iter(zip()))
-## views ##
-dict_keys = type({}.keys())
-dict_values = type({}.values())
-dict_items = type({}.items())
-## misc ##
-mappingproxy = type(type.__dict__)
-generator = type((lambda: (yield))())
-## coroutine ##
-async def _coro(): pass
-_coro = _coro()
-coroutine = type(_coro)
-_coro.close() # Prevent ResourceWarning
-del _coro
-## asynchronous generator ##
-async def _ag(): yield
-_ag = _ag()
-async_generator = type(_ag)
-del _ag
-
-
-### ONE-TRICK PONIES ###
-
-def _check_methods(C, *methods):
- mro = C.__mro__
- for method in methods:
- for B in mro:
- if method in B.__dict__:
- if B.__dict__[method] is None:
- return NotImplemented
- break
- else:
- return NotImplemented
- return True
-
-class Hashable(metaclass=ABCMeta):
-
- __slots__ = ()
-
- @abstractmethod
- def __hash__(self):
- return 0
-
- @classmethod
- def __subclasshook__(cls, C):
- if cls is Hashable:
- return _check_methods(C, "__hash__")
- return NotImplemented
-
-
-class Awaitable(metaclass=ABCMeta):
-
- __slots__ = ()
-
- @abstractmethod
- def __await__(self):
- yield
-
- @classmethod
- def __subclasshook__(cls, C):
- if cls is Awaitable:
- return _check_methods(C, "__await__")
- return NotImplemented
-
- __class_getitem__ = classmethod(GenericAlias)
-
-
-class Coroutine(Awaitable):
-
- __slots__ = ()
-
- @abstractmethod
- def send(self, value):
- """Send a value into the coroutine.
- Return next yielded value or raise StopIteration.
- """
- raise StopIteration
-
- @abstractmethod
- def throw(self, typ, val=None, tb=None):
- """Raise an exception in the coroutine.
- Return next yielded value or raise StopIteration.
- """
- if val is None:
- if tb is None:
- raise typ
- val = typ()
- if tb is not None:
- val = val.with_traceback(tb)
- raise val
-
- def close(self):
- """Raise GeneratorExit inside coroutine.
- """
- try:
- self.throw(GeneratorExit)
- except (GeneratorExit, StopIteration):
- pass
- else:
- raise RuntimeError("coroutine ignored GeneratorExit")
-
- @classmethod
- def __subclasshook__(cls, C):
- if cls is Coroutine:
- return _check_methods(C, '__await__', 'send', 'throw', 'close')
- return NotImplemented
-
-
-Coroutine.register(coroutine)
-
-
-class AsyncIterable(metaclass=ABCMeta):
-
- __slots__ = ()
-
- @abstractmethod
- def __aiter__(self):
- return AsyncIterator()
-
- @classmethod
- def __subclasshook__(cls, C):
- if cls is AsyncIterable:
- return _check_methods(C, "__aiter__")
- return NotImplemented
-
- __class_getitem__ = classmethod(GenericAlias)
-
-
-class AsyncIterator(AsyncIterable):
-
- __slots__ = ()
-
- @abstractmethod
- async def __anext__(self):
- """Return the next item or raise StopAsyncIteration when exhausted."""
- raise StopAsyncIteration
-
- def __aiter__(self):
- return self
-
- @classmethod
- def __subclasshook__(cls, C):
- if cls is AsyncIterator:
- return _check_methods(C, "__anext__", "__aiter__")
- return NotImplemented
-
-
-class AsyncGenerator(AsyncIterator):
-
- __slots__ = ()
-
- async def __anext__(self):
- """Return the next item from the asynchronous generator.
- When exhausted, raise StopAsyncIteration.
- """
- return await self.asend(None)
-
- @abstractmethod
- async def asend(self, value):
- """Send a value into the asynchronous generator.
- Return next yielded value or raise StopAsyncIteration.
- """
- raise StopAsyncIteration
-
- @abstractmethod
- async def athrow(self, typ, val=None, tb=None):
- """Raise an exception in the asynchronous generator.
- Return next yielded value or raise StopAsyncIteration.
- """
- if val is None:
- if tb is None:
- raise typ
- val = typ()
- if tb is not None:
- val = val.with_traceback(tb)
- raise val
-
- async def aclose(self):
- """Raise GeneratorExit inside coroutine.
- """
- try:
- await self.athrow(GeneratorExit)
- except (GeneratorExit, StopAsyncIteration):
- pass
- else:
- raise RuntimeError("asynchronous generator ignored GeneratorExit")
-
- @classmethod
- def __subclasshook__(cls, C):
- if cls is AsyncGenerator:
- return _check_methods(C, '__aiter__', '__anext__',
- 'asend', 'athrow', 'aclose')
- return NotImplemented
-
-
-AsyncGenerator.register(async_generator)
-
-
-class Iterable(metaclass=ABCMeta):
-
- __slots__ = ()
-
- @abstractmethod
- def __iter__(self):
- while False:
- yield None
-
- @classmethod
- def __subclasshook__(cls, C):
- if cls is Iterable:
- return _check_methods(C, "__iter__")
- return NotImplemented
-
- __class_getitem__ = classmethod(GenericAlias)
-
-
-class Iterator(Iterable):
-
- __slots__ = ()
-
- @abstractmethod
- def __next__(self):
- 'Return the next item from the iterator. When exhausted, raise StopIteration'
- raise StopIteration
-
- def __iter__(self):
- return self
-
- @classmethod
- def __subclasshook__(cls, C):
- if cls is Iterator:
- return _check_methods(C, '__iter__', '__next__')
- return NotImplemented
-
-
-Iterator.register(bytes_iterator)
-Iterator.register(bytearray_iterator)
-#Iterator.register(callable_iterator)
-Iterator.register(dict_keyiterator)
-Iterator.register(dict_valueiterator)
-Iterator.register(dict_itemiterator)
-Iterator.register(list_iterator)
-Iterator.register(list_reverseiterator)
-Iterator.register(range_iterator)
-Iterator.register(longrange_iterator)
-Iterator.register(set_iterator)
-Iterator.register(str_iterator)
-Iterator.register(tuple_iterator)
-Iterator.register(zip_iterator)
-
-
-class Reversible(Iterable):
-
- __slots__ = ()
-
- @abstractmethod
- def __reversed__(self):
- while False:
- yield None
-
- @classmethod
- def __subclasshook__(cls, C):
- if cls is Reversible:
- return _check_methods(C, "__reversed__", "__iter__")
- return NotImplemented
-
-
-class Generator(Iterator):
-
- __slots__ = ()
-
- def __next__(self):
- """Return the next item from the generator.
- When exhausted, raise StopIteration.
- """
- return self.send(None)
-
- @abstractmethod
- def send(self, value):
- """Send a value into the generator.
- Return next yielded value or raise StopIteration.
- """
- raise StopIteration
-
- @abstractmethod
- def throw(self, typ, val=None, tb=None):
- """Raise an exception in the generator.
- Return next yielded value or raise StopIteration.
- """
- if val is None:
- if tb is None:
- raise typ
- val = typ()
- if tb is not None:
- val = val.with_traceback(tb)
- raise val
-
- def close(self):
- """Raise GeneratorExit inside generator.
- """
- try:
- self.throw(GeneratorExit)
- except (GeneratorExit, StopIteration):
- pass
- else:
- raise RuntimeError("generator ignored GeneratorExit")
-
- @classmethod
- def __subclasshook__(cls, C):
- if cls is Generator:
- return _check_methods(C, '__iter__', '__next__',
- 'send', 'throw', 'close')
- return NotImplemented
-
-
-Generator.register(generator)
-
-
-class Sized(metaclass=ABCMeta):
-
- __slots__ = ()
-
- @abstractmethod
- def __len__(self):
- return 0
-
- @classmethod
- def __subclasshook__(cls, C):
- if cls is Sized:
- return _check_methods(C, "__len__")
- return NotImplemented
-
-
-class Container(metaclass=ABCMeta):
-
- __slots__ = ()
-
- @abstractmethod
- def __contains__(self, x):
- return False
-
- @classmethod
- def __subclasshook__(cls, C):
- if cls is Container:
- return _check_methods(C, "__contains__")
- return NotImplemented
-
- __class_getitem__ = classmethod(GenericAlias)
-
-
-class Collection(Sized, Iterable, Container):
-
- __slots__ = ()
-
- @classmethod
- def __subclasshook__(cls, C):
- if cls is Collection:
- return _check_methods(C, "__len__", "__iter__", "__contains__")
- return NotImplemented
-
-
-class _CallableGenericAlias(GenericAlias):
- """ Represent `Callable[argtypes, resulttype]`.
-
- This sets ``__args__`` to a tuple containing the flattened ``argtypes``
- followed by ``resulttype``.
-
- Example: ``Callable[[int, str], float]`` sets ``__args__`` to
- ``(int, str, float)``.
- """
-
- __slots__ = ()
-
- def __new__(cls, origin, args):
- if not (isinstance(args, tuple) and len(args) == 2):
- raise TypeError(
- "Callable must be used as Callable[[arg, ...], result].")
- t_args, t_result = args
- if isinstance(t_args, list):
- args = (*t_args, t_result)
- elif not _is_param_expr(t_args):
- raise TypeError(f"Expected a list of types, an ellipsis, "
- f"ParamSpec, or Concatenate. Got {t_args}")
- return super().__new__(cls, origin, args)
-
- @property
- def __parameters__(self):
- params = []
- for arg in self.__args__:
- # Looks like a genericalias
- if hasattr(arg, "__parameters__") and isinstance(arg.__parameters__, tuple):
- params.extend(arg.__parameters__)
- else:
- if _is_typevarlike(arg):
- params.append(arg)
- return tuple(dict.fromkeys(params))
-
- def __repr__(self):
- if len(self.__args__) == 2 and _is_param_expr(self.__args__[0]):
- return super().__repr__()
- return (f'collections.abc.Callable'
- f'[[{", ".join([_type_repr(a) for a in self.__args__[:-1]])}], '
- f'{_type_repr(self.__args__[-1])}]')
-
- def __reduce__(self):
- args = self.__args__
- if not (len(args) == 2 and _is_param_expr(args[0])):
- args = list(args[:-1]), args[-1]
- return _CallableGenericAlias, (Callable, args)
-
- def __getitem__(self, item):
- # Called during TypeVar substitution, returns the custom subclass
- # rather than the default types.GenericAlias object. Most of the
- # code is copied from typing's _GenericAlias and the builtin
- # types.GenericAlias.
-
- # A special case in PEP 612 where if X = Callable[P, int],
- # then X[int, str] == X[[int, str]].
- param_len = len(self.__parameters__)
- if param_len == 0:
- raise TypeError(f'{self} is not a generic class')
- if not isinstance(item, tuple):
- item = (item,)
- if (param_len == 1 and _is_param_expr(self.__parameters__[0])
- and item and not _is_param_expr(item[0])):
- item = (list(item),)
- item_len = len(item)
- if item_len != param_len:
- raise TypeError(f'Too {"many" if item_len > param_len else "few"}'
- f' arguments for {self};'
- f' actual {item_len}, expected {param_len}')
- subst = dict(zip(self.__parameters__, item))
- new_args = []
- for arg in self.__args__:
- if _is_typevarlike(arg):
- if _is_param_expr(arg):
- arg = subst[arg]
- if not _is_param_expr(arg):
- raise TypeError(f"Expected a list of types, an ellipsis, "
- f"ParamSpec, or Concatenate. Got {arg}")
- else:
- arg = subst[arg]
- # Looks like a GenericAlias
- elif hasattr(arg, '__parameters__') and isinstance(arg.__parameters__, tuple):
- subparams = arg.__parameters__
- if subparams:
- subargs = tuple(subst[x] for x in subparams)
- arg = arg[subargs]
- if isinstance(arg, tuple):
- new_args.extend(arg)
- else:
- new_args.append(arg)
-
- # args[0] occurs due to things like Z[[int, str, bool]] from PEP 612
- if not isinstance(new_args[0], list):
- t_result = new_args[-1]
- t_args = new_args[:-1]
- new_args = (t_args, t_result)
- return _CallableGenericAlias(Callable, tuple(new_args))
-
-
-def _is_typevarlike(arg):
- obj = type(arg)
- # looks like a TypeVar/ParamSpec
- return (obj.__module__ == 'typing'
- and obj.__name__ in {'ParamSpec', 'TypeVar'})
-
-def _is_param_expr(obj):
- """Checks if obj matches either a list of types, ``...``, ``ParamSpec`` or
- ``_ConcatenateGenericAlias`` from typing.py
- """
- if obj is Ellipsis:
- return True
- if isinstance(obj, list):
- return True
- obj = type(obj)
- names = ('ParamSpec', '_ConcatenateGenericAlias')
- return obj.__module__ == 'typing' and any(obj.__name__ == name for name in names)
-
-def _type_repr(obj):
- """Return the repr() of an object, special-casing types (internal helper).
-
- Copied from :mod:`typing` since collections.abc
- shouldn't depend on that module.
- """
- if isinstance(obj, GenericAlias):
- return repr(obj)
- if isinstance(obj, type):
- if obj.__module__ == 'builtins':
- return obj.__qualname__
- return f'{obj.__module__}.{obj.__qualname__}'
- if obj is Ellipsis:
- return '...'
- if isinstance(obj, FunctionType):
- return obj.__name__
- return repr(obj)
-
-
-class Callable(metaclass=ABCMeta):
-
- __slots__ = ()
-
- @abstractmethod
- def __call__(self, *args, **kwds):
- return False
-
- @classmethod
- def __subclasshook__(cls, C):
- if cls is Callable:
- return _check_methods(C, "__call__")
- return NotImplemented
-
- __class_getitem__ = classmethod(_CallableGenericAlias)
-
-
-### SETS ###
-
-
-class Set(Collection):
- """A set is a finite, iterable container.
-
- This class provides concrete generic implementations of all
- methods except for __contains__, __iter__ and __len__.
-
- To override the comparisons (presumably for speed, as the
- semantics are fixed), redefine __le__ and __ge__,
- then the other operations will automatically follow suit.
- """
-
- __slots__ = ()
-
- def __le__(self, other):
- if not isinstance(other, Set):
- return NotImplemented
- if len(self) > len(other):
- return False
- for elem in self:
- if elem not in other:
- return False
- return True
-
- def __lt__(self, other):
- if not isinstance(other, Set):
- return NotImplemented
- return len(self) < len(other) and self.__le__(other)
-
- def __gt__(self, other):
- if not isinstance(other, Set):
- return NotImplemented
- return len(self) > len(other) and self.__ge__(other)
-
- def __ge__(self, other):
- if not isinstance(other, Set):
- return NotImplemented
- if len(self) < len(other):
- return False
- for elem in other:
- if elem not in self:
- return False
- return True
-
- def __eq__(self, other):
- if not isinstance(other, Set):
- return NotImplemented
- return len(self) == len(other) and self.__le__(other)
-
- @classmethod
- def _from_iterable(cls, it):
- '''Construct an instance of the class from any iterable input.
-
- Must override this method if the class constructor signature
- does not accept an iterable for an input.
- '''
- return cls(it)
-
- def __and__(self, other):
- if not isinstance(other, Iterable):
- return NotImplemented
- return self._from_iterable(value for value in other if value in self)
-
- __rand__ = __and__
-
- def isdisjoint(self, other):
- 'Return True if two sets have a null intersection.'
- for value in other:
- if value in self:
- return False
- return True
-
- def __or__(self, other):
- if not isinstance(other, Iterable):
- return NotImplemented
- chain = (e for s in (self, other) for e in s)
- return self._from_iterable(chain)
-
- __ror__ = __or__
-
- def __sub__(self, other):
- if not isinstance(other, Set):
- if not isinstance(other, Iterable):
- return NotImplemented
- other = self._from_iterable(other)
- return self._from_iterable(value for value in self
- if value not in other)
-
- def __rsub__(self, other):
- if not isinstance(other, Set):
- if not isinstance(other, Iterable):
- return NotImplemented
- other = self._from_iterable(other)
- return self._from_iterable(value for value in other
- if value not in self)
-
- def __xor__(self, other):
- if not isinstance(other, Set):
- if not isinstance(other, Iterable):
- return NotImplemented
- other = self._from_iterable(other)
- return (self - other) | (other - self)
-
- __rxor__ = __xor__
-
- def _hash(self):
- """Compute the hash value of a set.
-
- Note that we don't define __hash__: not all sets are hashable.
- But if you define a hashable set type, its __hash__ should
- call this function.
-
- This must be compatible __eq__.
-
- All sets ought to compare equal if they contain the same
- elements, regardless of how they are implemented, and
- regardless of the order of the elements; so there's not much
- freedom for __eq__ or __hash__. We match the algorithm used
- by the built-in frozenset type.
- """
- MAX = sys.maxsize
- MASK = 2 * MAX + 1
- n = len(self)
- h = 1927868237 * (n + 1)
- h &= MASK
- for x in self:
- hx = hash(x)
- h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167
- h &= MASK
- h ^= (h >> 11) ^ (h >> 25)
- h = h * 69069 + 907133923
- h &= MASK
- if h > MAX:
- h -= MASK + 1
- if h == -1:
- h = 590923713
- return h
-
-
-Set.register(frozenset)
-
-
-class MutableSet(Set):
- """A mutable set is a finite, iterable container.
-
- This class provides concrete generic implementations of all
- methods except for __contains__, __iter__, __len__,
- add(), and discard().
-
- To override the comparisons (presumably for speed, as the
- semantics are fixed), all you have to do is redefine __le__ and
- then the other operations will automatically follow suit.
- """
-
- __slots__ = ()
-
- @abstractmethod
- def add(self, value):
- """Add an element."""
- raise NotImplementedError
-
- @abstractmethod
- def discard(self, value):
- """Remove an element. Do not raise an exception if absent."""
- raise NotImplementedError
-
- def remove(self, value):
- """Remove an element. If not a member, raise a KeyError."""
- if value not in self:
- raise KeyError(value)
- self.discard(value)
-
- def pop(self):
- """Return the popped value. Raise KeyError if empty."""
- it = iter(self)
- try:
- value = next(it)
- except StopIteration:
- raise KeyError from None
- self.discard(value)
- return value
-
- def clear(self):
- """This is slow (creates N new iterators!) but effective."""
- try:
- while True:
- self.pop()
- except KeyError:
- pass
-
- def __ior__(self, it):
- for value in it:
- self.add(value)
- return self
-
- def __iand__(self, it):
- for value in (self - it):
- self.discard(value)
- return self
-
- def __ixor__(self, it):
- if it is self:
- self.clear()
- else:
- if not isinstance(it, Set):
- it = self._from_iterable(it)
- for value in it:
- if value in self:
- self.discard(value)
- else:
- self.add(value)
- return self
-
- def __isub__(self, it):
- if it is self:
- self.clear()
- else:
- for value in it:
- self.discard(value)
- return self
-
-
-MutableSet.register(set)
-
-
-### MAPPINGS ###
-
-class Mapping(Collection):
- """A Mapping is a generic container for associating key/value
- pairs.
-
- This class provides concrete generic implementations of all
- methods except for __getitem__, __iter__, and __len__.
- """
-
- __slots__ = ()
-
- # Tell ABCMeta.__new__ that this class should have TPFLAGS_MAPPING set.
- __abc_tpflags__ = 1 << 6 # Py_TPFLAGS_MAPPING
-
- @abstractmethod
- def __getitem__(self, key):
- raise KeyError
-
- def get(self, key, default=None):
- 'D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.'
- try:
- return self[key]
- except KeyError:
- return default
-
- def __contains__(self, key):
- try:
- self[key]
- except KeyError:
- return False
- else:
- return True
-
- def keys(self):
- "D.keys() -> a set-like object providing a view on D's keys"
- return KeysView(self)
-
- def items(self):
- "D.items() -> a set-like object providing a view on D's items"
- return ItemsView(self)
-
- def values(self):
- "D.values() -> an object providing a view on D's values"
- return ValuesView(self)
-
- def __eq__(self, other):
- if not isinstance(other, Mapping):
- return NotImplemented
- return dict(self.items()) == dict(other.items())
-
- __reversed__ = None
-
-Mapping.register(mappingproxy)
-
-
-class MappingView(Sized):
-
- __slots__ = '_mapping',
-
- def __init__(self, mapping):
- self._mapping = mapping
-
- def __len__(self):
- return len(self._mapping)
-
- def __repr__(self):
- return '{0.__class__.__name__}({0._mapping!r})'.format(self)
-
- __class_getitem__ = classmethod(GenericAlias)
-
-
-class KeysView(MappingView, Set):
-
- __slots__ = ()
-
- @classmethod
- def _from_iterable(cls, it):
- return set(it)
-
- def __contains__(self, key):
- return key in self._mapping
-
- def __iter__(self):
- yield from self._mapping
-
-
-KeysView.register(dict_keys)
-
-
-class ItemsView(MappingView, Set):
-
- __slots__ = ()
-
- @classmethod
- def _from_iterable(cls, it):
- return set(it)
-
- def __contains__(self, item):
- key, value = item
- try:
- v = self._mapping[key]
- except KeyError:
- return False
- else:
- return v is value or v == value
-
- def __iter__(self):
- for key in self._mapping:
- yield (key, self._mapping[key])
-
-
-ItemsView.register(dict_items)
-
-
-class ValuesView(MappingView, Collection):
-
- __slots__ = ()
-
- def __contains__(self, value):
- for key in self._mapping:
- v = self._mapping[key]
- if v is value or v == value:
- return True
- return False
-
- def __iter__(self):
- for key in self._mapping:
- yield self._mapping[key]
-
-
-ValuesView.register(dict_values)
-
-
-class MutableMapping(Mapping):
- """A MutableMapping is a generic container for associating
- key/value pairs.
-
- This class provides concrete generic implementations of all
- methods except for __getitem__, __setitem__, __delitem__,
- __iter__, and __len__.
- """
-
- __slots__ = ()
-
- @abstractmethod
- def __setitem__(self, key, value):
- raise KeyError
-
- @abstractmethod
- def __delitem__(self, key):
- raise KeyError
-
- __marker = object()
-
- def pop(self, key, default=__marker):
- '''D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
- If key is not found, d is returned if given, otherwise KeyError is raised.
- '''
- try:
- value = self[key]
- except KeyError:
- if default is self.__marker:
- raise
- return default
- else:
- del self[key]
- return value
-
- def popitem(self):
- '''D.popitem() -> (k, v), remove and return some (key, value) pair
- as a 2-tuple; but raise KeyError if D is empty.
- '''
- try:
- key = next(iter(self))
- except StopIteration:
- raise KeyError from None
- value = self[key]
- del self[key]
- return key, value
-
- def clear(self):
- 'D.clear() -> None. Remove all items from D.'
- try:
- while True:
- self.popitem()
- except KeyError:
- pass
-
- def update(self, other=(), /, **kwds):
- ''' D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
- If E present and has a .keys() method, does: for k in E: D[k] = E[k]
- If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
- In either case, this is followed by: for k, v in F.items(): D[k] = v
- '''
- if isinstance(other, Mapping):
- for key in other:
- self[key] = other[key]
- elif hasattr(other, "keys"):
- for key in other.keys():
- self[key] = other[key]
- else:
- for key, value in other:
- self[key] = value
- for key, value in kwds.items():
- self[key] = value
-
- def setdefault(self, key, default=None):
- 'D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D'
- try:
- return self[key]
- except KeyError:
- self[key] = default
- return default
-
-
-MutableMapping.register(dict)
-
-
-### SEQUENCES ###
-
-class Sequence(Reversible, Collection):
- """All the operations on a read-only sequence.
-
- Concrete subclasses must override __new__ or __init__,
- __getitem__, and __len__.
- """
-
- __slots__ = ()
-
- # Tell ABCMeta.__new__ that this class should have TPFLAGS_SEQUENCE set.
- __abc_tpflags__ = 1 << 5 # Py_TPFLAGS_SEQUENCE
-
- @abstractmethod
- def __getitem__(self, index):
- raise IndexError
-
- def __iter__(self):
- i = 0
- try:
- while True:
- v = self[i]
- yield v
- i += 1
- except IndexError:
- return
-
- def __contains__(self, value):
- for v in self:
- if v is value or v == value:
- return True
- return False
-
- def __reversed__(self):
- for i in reversed(range(len(self))):
- yield self[i]
-
- def index(self, value, start=0, stop=None):
- '''S.index(value, [start, [stop]]) -> integer -- return first index of value.
- Raises ValueError if the value is not present.
-
- Supporting start and stop arguments is optional, but
- recommended.
- '''
- if start is not None and start < 0:
- start = max(len(self) + start, 0)
- if stop is not None and stop < 0:
- stop += len(self)
-
- i = start
- while stop is None or i < stop:
- try:
- v = self[i]
- if v is value or v == value:
- return i
- except IndexError:
- break
- i += 1
- raise ValueError
-
- def count(self, value):
- 'S.count(value) -> integer -- return number of occurrences of value'
- return sum(1 for v in self if v is value or v == value)
-
-Sequence.register(tuple)
-Sequence.register(str)
-Sequence.register(range)
-Sequence.register(memoryview)
-
-
-class ByteString(Sequence):
- """This unifies bytes and bytearray.
-
- XXX Should add all their methods.
- """
-
- __slots__ = ()
-
-ByteString.register(bytes)
-ByteString.register(bytearray)
-
-
-class MutableSequence(Sequence):
- """All the operations on a read-write sequence.
-
- Concrete subclasses must provide __new__ or __init__,
- __getitem__, __setitem__, __delitem__, __len__, and insert().
- """
-
- __slots__ = ()
-
- @abstractmethod
- def __setitem__(self, index, value):
- raise IndexError
-
- @abstractmethod
- def __delitem__(self, index):
- raise IndexError
-
- @abstractmethod
- def insert(self, index, value):
- 'S.insert(index, value) -- insert value before index'
- raise IndexError
-
- def append(self, value):
- 'S.append(value) -- append value to the end of the sequence'
- self.insert(len(self), value)
-
- def clear(self):
- 'S.clear() -> None -- remove all items from S'
- try:
- while True:
- self.pop()
- except IndexError:
- pass
-
- def reverse(self):
- 'S.reverse() -- reverse *IN PLACE*'
- n = len(self)
- for i in range(n//2):
- self[i], self[n-i-1] = self[n-i-1], self[i]
-
- def extend(self, values):
- 'S.extend(iterable) -- extend sequence by appending elements from the iterable'
- if values is self:
- values = list(values)
- for v in values:
- self.append(v)
-
- def pop(self, index=-1):
- '''S.pop([index]) -> item -- remove and return item at index (default last).
- Raise IndexError if list is empty or index is out of range.
- '''
- v = self[index]
- del self[index]
- return v
-
- def remove(self, value):
- '''S.remove(value) -- remove first occurrence of value.
- Raise ValueError if the value is not present.
- '''
- del self[self.index(value)]
-
- def __iadd__(self, values):
- self.extend(values)
- return self
-
-
-MutableSequence.register(list)
-MutableSequence.register(bytearray) # Multiply inheriting, see ByteString
diff --git a/lib/python3.10/_compat_pickle.py b/lib/python3.10/_compat_pickle.py
deleted file mode 100644
index f68496a..0000000
--- a/lib/python3.10/_compat_pickle.py
+++ /dev/null
@@ -1,251 +0,0 @@
-# This module is used to map the old Python 2 names to the new names used in
-# Python 3 for the pickle module. This needed to make pickle streams
-# generated with Python 2 loadable by Python 3.
-
-# This is a copy of lib2to3.fixes.fix_imports.MAPPING. We cannot import
-# lib2to3 and use the mapping defined there, because lib2to3 uses pickle.
-# Thus, this could cause the module to be imported recursively.
-IMPORT_MAPPING = {
- '__builtin__' : 'builtins',
- 'copy_reg': 'copyreg',
- 'Queue': 'queue',
- 'SocketServer': 'socketserver',
- 'ConfigParser': 'configparser',
- 'repr': 'reprlib',
- 'tkFileDialog': 'tkinter.filedialog',
- 'tkSimpleDialog': 'tkinter.simpledialog',
- 'tkColorChooser': 'tkinter.colorchooser',
- 'tkCommonDialog': 'tkinter.commondialog',
- 'Dialog': 'tkinter.dialog',
- 'Tkdnd': 'tkinter.dnd',
- 'tkFont': 'tkinter.font',
- 'tkMessageBox': 'tkinter.messagebox',
- 'ScrolledText': 'tkinter.scrolledtext',
- 'Tkconstants': 'tkinter.constants',
- 'Tix': 'tkinter.tix',
- 'ttk': 'tkinter.ttk',
- 'Tkinter': 'tkinter',
- 'markupbase': '_markupbase',
- '_winreg': 'winreg',
- 'thread': '_thread',
- 'dummy_thread': '_dummy_thread',
- 'dbhash': 'dbm.bsd',
- 'dumbdbm': 'dbm.dumb',
- 'dbm': 'dbm.ndbm',
- 'gdbm': 'dbm.gnu',
- 'xmlrpclib': 'xmlrpc.client',
- 'SimpleXMLRPCServer': 'xmlrpc.server',
- 'httplib': 'http.client',
- 'htmlentitydefs' : 'html.entities',
- 'HTMLParser' : 'html.parser',
- 'Cookie': 'http.cookies',
- 'cookielib': 'http.cookiejar',
- 'BaseHTTPServer': 'http.server',
- 'test.test_support': 'test.support',
- 'commands': 'subprocess',
- 'urlparse' : 'urllib.parse',
- 'robotparser' : 'urllib.robotparser',
- 'urllib2': 'urllib.request',
- 'anydbm': 'dbm',
- '_abcoll' : 'collections.abc',
-}
-
-
-# This contains rename rules that are easy to handle. We ignore the more
-# complex stuff (e.g. mapping the names in the urllib and types modules).
-# These rules should be run before import names are fixed.
-NAME_MAPPING = {
- ('__builtin__', 'xrange'): ('builtins', 'range'),
- ('__builtin__', 'reduce'): ('functools', 'reduce'),
- ('__builtin__', 'intern'): ('sys', 'intern'),
- ('__builtin__', 'unichr'): ('builtins', 'chr'),
- ('__builtin__', 'unicode'): ('builtins', 'str'),
- ('__builtin__', 'long'): ('builtins', 'int'),
- ('itertools', 'izip'): ('builtins', 'zip'),
- ('itertools', 'imap'): ('builtins', 'map'),
- ('itertools', 'ifilter'): ('builtins', 'filter'),
- ('itertools', 'ifilterfalse'): ('itertools', 'filterfalse'),
- ('itertools', 'izip_longest'): ('itertools', 'zip_longest'),
- ('UserDict', 'IterableUserDict'): ('collections', 'UserDict'),
- ('UserList', 'UserList'): ('collections', 'UserList'),
- ('UserString', 'UserString'): ('collections', 'UserString'),
- ('whichdb', 'whichdb'): ('dbm', 'whichdb'),
- ('_socket', 'fromfd'): ('socket', 'fromfd'),
- ('_multiprocessing', 'Connection'): ('multiprocessing.connection', 'Connection'),
- ('multiprocessing.process', 'Process'): ('multiprocessing.context', 'Process'),
- ('multiprocessing.forking', 'Popen'): ('multiprocessing.popen_fork', 'Popen'),
- ('urllib', 'ContentTooShortError'): ('urllib.error', 'ContentTooShortError'),
- ('urllib', 'getproxies'): ('urllib.request', 'getproxies'),
- ('urllib', 'pathname2url'): ('urllib.request', 'pathname2url'),
- ('urllib', 'quote_plus'): ('urllib.parse', 'quote_plus'),
- ('urllib', 'quote'): ('urllib.parse', 'quote'),
- ('urllib', 'unquote_plus'): ('urllib.parse', 'unquote_plus'),
- ('urllib', 'unquote'): ('urllib.parse', 'unquote'),
- ('urllib', 'url2pathname'): ('urllib.request', 'url2pathname'),
- ('urllib', 'urlcleanup'): ('urllib.request', 'urlcleanup'),
- ('urllib', 'urlencode'): ('urllib.parse', 'urlencode'),
- ('urllib', 'urlopen'): ('urllib.request', 'urlopen'),
- ('urllib', 'urlretrieve'): ('urllib.request', 'urlretrieve'),
- ('urllib2', 'HTTPError'): ('urllib.error', 'HTTPError'),
- ('urllib2', 'URLError'): ('urllib.error', 'URLError'),
-}
-
-PYTHON2_EXCEPTIONS = (
- "ArithmeticError",
- "AssertionError",
- "AttributeError",
- "BaseException",
- "BufferError",
- "BytesWarning",
- "DeprecationWarning",
- "EOFError",
- "EnvironmentError",
- "Exception",
- "FloatingPointError",
- "FutureWarning",
- "GeneratorExit",
- "IOError",
- "ImportError",
- "ImportWarning",
- "IndentationError",
- "IndexError",
- "KeyError",
- "KeyboardInterrupt",
- "LookupError",
- "MemoryError",
- "NameError",
- "NotImplementedError",
- "OSError",
- "OverflowError",
- "PendingDeprecationWarning",
- "ReferenceError",
- "RuntimeError",
- "RuntimeWarning",
- # StandardError is gone in Python 3, so we map it to Exception
- "StopIteration",
- "SyntaxError",
- "SyntaxWarning",
- "SystemError",
- "SystemExit",
- "TabError",
- "TypeError",
- "UnboundLocalError",
- "UnicodeDecodeError",
- "UnicodeEncodeError",
- "UnicodeError",
- "UnicodeTranslateError",
- "UnicodeWarning",
- "UserWarning",
- "ValueError",
- "Warning",
- "ZeroDivisionError",
-)
-
-try:
- WindowsError
-except NameError:
- pass
-else:
- PYTHON2_EXCEPTIONS += ("WindowsError",)
-
-for excname in PYTHON2_EXCEPTIONS:
- NAME_MAPPING[("exceptions", excname)] = ("builtins", excname)
-
-MULTIPROCESSING_EXCEPTIONS = (
- 'AuthenticationError',
- 'BufferTooShort',
- 'ProcessError',
- 'TimeoutError',
-)
-
-for excname in MULTIPROCESSING_EXCEPTIONS:
- NAME_MAPPING[("multiprocessing", excname)] = ("multiprocessing.context", excname)
-
-# Same, but for 3.x to 2.x
-REVERSE_IMPORT_MAPPING = dict((v, k) for (k, v) in IMPORT_MAPPING.items())
-assert len(REVERSE_IMPORT_MAPPING) == len(IMPORT_MAPPING)
-REVERSE_NAME_MAPPING = dict((v, k) for (k, v) in NAME_MAPPING.items())
-assert len(REVERSE_NAME_MAPPING) == len(NAME_MAPPING)
-
-# Non-mutual mappings.
-
-IMPORT_MAPPING.update({
- 'cPickle': 'pickle',
- '_elementtree': 'xml.etree.ElementTree',
- 'FileDialog': 'tkinter.filedialog',
- 'SimpleDialog': 'tkinter.simpledialog',
- 'DocXMLRPCServer': 'xmlrpc.server',
- 'SimpleHTTPServer': 'http.server',
- 'CGIHTTPServer': 'http.server',
- # For compatibility with broken pickles saved in old Python 3 versions
- 'UserDict': 'collections',
- 'UserList': 'collections',
- 'UserString': 'collections',
- 'whichdb': 'dbm',
- 'StringIO': 'io',
- 'cStringIO': 'io',
-})
-
-REVERSE_IMPORT_MAPPING.update({
- '_bz2': 'bz2',
- '_dbm': 'dbm',
- '_functools': 'functools',
- '_gdbm': 'gdbm',
- '_pickle': 'pickle',
-})
-
-NAME_MAPPING.update({
- ('__builtin__', 'basestring'): ('builtins', 'str'),
- ('exceptions', 'StandardError'): ('builtins', 'Exception'),
- ('UserDict', 'UserDict'): ('collections', 'UserDict'),
- ('socket', '_socketobject'): ('socket', 'SocketType'),
-})
-
-REVERSE_NAME_MAPPING.update({
- ('_functools', 'reduce'): ('__builtin__', 'reduce'),
- ('tkinter.filedialog', 'FileDialog'): ('FileDialog', 'FileDialog'),
- ('tkinter.filedialog', 'LoadFileDialog'): ('FileDialog', 'LoadFileDialog'),
- ('tkinter.filedialog', 'SaveFileDialog'): ('FileDialog', 'SaveFileDialog'),
- ('tkinter.simpledialog', 'SimpleDialog'): ('SimpleDialog', 'SimpleDialog'),
- ('xmlrpc.server', 'ServerHTMLDoc'): ('DocXMLRPCServer', 'ServerHTMLDoc'),
- ('xmlrpc.server', 'XMLRPCDocGenerator'):
- ('DocXMLRPCServer', 'XMLRPCDocGenerator'),
- ('xmlrpc.server', 'DocXMLRPCRequestHandler'):
- ('DocXMLRPCServer', 'DocXMLRPCRequestHandler'),
- ('xmlrpc.server', 'DocXMLRPCServer'):
- ('DocXMLRPCServer', 'DocXMLRPCServer'),
- ('xmlrpc.server', 'DocCGIXMLRPCRequestHandler'):
- ('DocXMLRPCServer', 'DocCGIXMLRPCRequestHandler'),
- ('http.server', 'SimpleHTTPRequestHandler'):
- ('SimpleHTTPServer', 'SimpleHTTPRequestHandler'),
- ('http.server', 'CGIHTTPRequestHandler'):
- ('CGIHTTPServer', 'CGIHTTPRequestHandler'),
- ('_socket', 'socket'): ('socket', '_socketobject'),
-})
-
-PYTHON3_OSERROR_EXCEPTIONS = (
- 'BrokenPipeError',
- 'ChildProcessError',
- 'ConnectionAbortedError',
- 'ConnectionError',
- 'ConnectionRefusedError',
- 'ConnectionResetError',
- 'FileExistsError',
- 'FileNotFoundError',
- 'InterruptedError',
- 'IsADirectoryError',
- 'NotADirectoryError',
- 'PermissionError',
- 'ProcessLookupError',
- 'TimeoutError',
-)
-
-for excname in PYTHON3_OSERROR_EXCEPTIONS:
- REVERSE_NAME_MAPPING[('builtins', excname)] = ('exceptions', 'OSError')
-
-PYTHON3_IMPORTERROR_EXCEPTIONS = (
- 'ModuleNotFoundError',
-)
-
-for excname in PYTHON3_IMPORTERROR_EXCEPTIONS:
- REVERSE_NAME_MAPPING[('builtins', excname)] = ('exceptions', 'ImportError')
diff --git a/lib/python3.10/_pydecimal.py b/lib/python3.10/_pydecimal.py
deleted file mode 100644
index 3d6cece..0000000
--- a/lib/python3.10/_pydecimal.py
+++ /dev/null
@@ -1,6410 +0,0 @@
-# Copyright (c) 2004 Python Software Foundation.
-# All rights reserved.
-
-# Written by Eric Price <eprice at tjhsst.edu>
-# and Facundo Batista <facundo at taniquetil.com.ar>
-# and Raymond Hettinger <python at rcn.com>
-# and Aahz <aahz at pobox.com>
-# and Tim Peters
-
-# This module should be kept in sync with the latest updates of the
-# IBM specification as it evolves. Those updates will be treated
-# as bug fixes (deviation from the spec is a compatibility, usability
-# bug) and will be backported. At this point the spec is stabilizing
-# and the updates are becoming fewer, smaller, and less significant.
-
-"""
-This is an implementation of decimal floating point arithmetic based on
-the General Decimal Arithmetic Specification:
-
- http://speleotrove.com/decimal/decarith.html
-
-and IEEE standard 854-1987:
-
- http://en.wikipedia.org/wiki/IEEE_854-1987
-
-Decimal floating point has finite precision with arbitrarily large bounds.
-
-The purpose of this module is to support arithmetic using familiar
-"schoolhouse" rules and to avoid some of the tricky representation
-issues associated with binary floating point. The package is especially
-useful for financial applications or for contexts where users have
-expectations that are at odds with binary floating point (for instance,
-in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
-of 0.0; Decimal('1.00') % Decimal('0.1') returns the expected
-Decimal('0.00')).
-
-Here are some examples of using the decimal module:
-
->>> from decimal import *
->>> setcontext(ExtendedContext)
->>> Decimal(0)
-Decimal('0')
->>> Decimal('1')
-Decimal('1')
->>> Decimal('-.0123')
-Decimal('-0.0123')
->>> Decimal(123456)
-Decimal('123456')
->>> Decimal('123.45e12345678')
-Decimal('1.2345E+12345680')
->>> Decimal('1.33') + Decimal('1.27')
-Decimal('2.60')
->>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
-Decimal('-2.20')
->>> dig = Decimal(1)
->>> print(dig / Decimal(3))
-0.333333333
->>> getcontext().prec = 18
->>> print(dig / Decimal(3))
-0.333333333333333333
->>> print(dig.sqrt())
-1
->>> print(Decimal(3).sqrt())
-1.73205080756887729
->>> print(Decimal(3) ** 123)
-4.85192780976896427E+58
->>> inf = Decimal(1) / Decimal(0)
->>> print(inf)
-Infinity
->>> neginf = Decimal(-1) / Decimal(0)
->>> print(neginf)
--Infinity
->>> print(neginf + inf)
-NaN
->>> print(neginf * inf)
--Infinity
->>> print(dig / 0)
-Infinity
->>> getcontext().traps[DivisionByZero] = 1
->>> print(dig / 0)
-Traceback (most recent call last):
- ...
- ...
- ...
-decimal.DivisionByZero: x / 0
->>> c = Context()
->>> c.traps[InvalidOperation] = 0
->>> print(c.flags[InvalidOperation])
-0
->>> c.divide(Decimal(0), Decimal(0))
-Decimal('NaN')
->>> c.traps[InvalidOperation] = 1
->>> print(c.flags[InvalidOperation])
-1
->>> c.flags[InvalidOperation] = 0
->>> print(c.flags[InvalidOperation])
-0
->>> print(c.divide(Decimal(0), Decimal(0)))
-Traceback (most recent call last):
- ...
- ...
- ...
-decimal.InvalidOperation: 0 / 0
->>> print(c.flags[InvalidOperation])
-1
->>> c.flags[InvalidOperation] = 0
->>> c.traps[InvalidOperation] = 0
->>> print(c.divide(Decimal(0), Decimal(0)))
-NaN
->>> print(c.flags[InvalidOperation])
-1
->>>
-"""
-
-__all__ = [
- # Two major classes
- 'Decimal', 'Context',
-
- # Named tuple representation
- 'DecimalTuple',
-
- # Contexts
- 'DefaultContext', 'BasicContext', 'ExtendedContext',
-
- # Exceptions
- 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
- 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
- 'FloatOperation',
-
- # Exceptional conditions that trigger InvalidOperation
- 'DivisionImpossible', 'InvalidContext', 'ConversionSyntax', 'DivisionUndefined',
-
- # Constants for use in setting up contexts
- 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
- 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
-
- # Functions for manipulating contexts
- 'setcontext', 'getcontext', 'localcontext',
-
- # Limits for the C version for compatibility
- 'MAX_PREC', 'MAX_EMAX', 'MIN_EMIN', 'MIN_ETINY',
-
- # C version: compile time choice that enables the thread local context (deprecated, now always true)
- 'HAVE_THREADS',
-
- # C version: compile time choice that enables the coroutine local context
- 'HAVE_CONTEXTVAR'
-]
-
-__xname__ = __name__ # sys.modules lookup (--without-threads)
-__name__ = 'decimal' # For pickling
-__version__ = '1.70' # Highest version of the spec this complies with
- # See http://speleotrove.com/decimal/
-__libmpdec_version__ = "2.4.2" # compatible libmpdec version
-
-import math as _math
-import numbers as _numbers
-import sys
-
-try:
- from collections import namedtuple as _namedtuple
- DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
-except ImportError:
- DecimalTuple = lambda *args: args
-
-# Rounding
-ROUND_DOWN = 'ROUND_DOWN'
-ROUND_HALF_UP = 'ROUND_HALF_UP'
-ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
-ROUND_CEILING = 'ROUND_CEILING'
-ROUND_FLOOR = 'ROUND_FLOOR'
-ROUND_UP = 'ROUND_UP'
-ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
-ROUND_05UP = 'ROUND_05UP'
-
-# Compatibility with the C version
-HAVE_THREADS = True
-HAVE_CONTEXTVAR = True
-if sys.maxsize == 2**63-1:
- MAX_PREC = 999999999999999999
- MAX_EMAX = 999999999999999999
- MIN_EMIN = -999999999999999999
-else:
- MAX_PREC = 425000000
- MAX_EMAX = 425000000
- MIN_EMIN = -425000000
-
-MIN_ETINY = MIN_EMIN - (MAX_PREC-1)
-
-# Errors
-
-class DecimalException(ArithmeticError):
- """Base exception class.
-
- Used exceptions derive from this.
- If an exception derives from another exception besides this (such as
- Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
- called if the others are present. This isn't actually used for
- anything, though.
-
- handle -- Called when context._raise_error is called and the
- trap_enabler is not set. First argument is self, second is the
- context. More arguments can be given, those being after
- the explanation in _raise_error (For example,
- context._raise_error(NewError, '(-x)!', self._sign) would
- call NewError().handle(context, self._sign).)
-
- To define a new exception, it should be sufficient to have it derive
- from DecimalException.
- """
- def handle(self, context, *args):
- pass
-
-
-class Clamped(DecimalException):
- """Exponent of a 0 changed to fit bounds.
-
- This occurs and signals clamped if the exponent of a result has been
- altered in order to fit the constraints of a specific concrete
- representation. This may occur when the exponent of a zero result would
- be outside the bounds of a representation, or when a large normal
- number would have an encoded exponent that cannot be represented. In
- this latter case, the exponent is reduced to fit and the corresponding
- number of zero digits are appended to the coefficient ("fold-down").
- """
-
-class InvalidOperation(DecimalException):
- """An invalid operation was performed.
-
- Various bad things cause this:
-
- Something creates a signaling NaN
- -INF + INF
- 0 * (+-)INF
- (+-)INF / (+-)INF
- x % 0
- (+-)INF % x
- x._rescale( non-integer )
- sqrt(-x) , x > 0
- 0 ** 0
- x ** (non-integer)
- x ** (+-)INF
- An operand is invalid
-
- The result of the operation after these is a quiet positive NaN,
- except when the cause is a signaling NaN, in which case the result is
- also a quiet NaN, but with the original sign, and an optional
- diagnostic information.
- """
- def handle(self, context, *args):
- if args:
- ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
- return ans._fix_nan(context)
- return _NaN
-
-class ConversionSyntax(InvalidOperation):
- """Trying to convert badly formed string.
-
- This occurs and signals invalid-operation if a string is being
- converted to a number and it does not conform to the numeric string
- syntax. The result is [0,qNaN].
- """
- def handle(self, context, *args):
- return _NaN
-
-class DivisionByZero(DecimalException, ZeroDivisionError):
- """Division by 0.
-
- This occurs and signals division-by-zero if division of a finite number
- by zero was attempted (during a divide-integer or divide operation, or a
- power operation with negative right-hand operand), and the dividend was
- not zero.
-
- The result of the operation is [sign,inf], where sign is the exclusive
- or of the signs of the operands for divide, or is 1 for an odd power of
- -0, for power.
- """
-
- def handle(self, context, sign, *args):
- return _SignedInfinity[sign]
-
-class DivisionImpossible(InvalidOperation):
- """Cannot perform the division adequately.
-
- This occurs and signals invalid-operation if the integer result of a
- divide-integer or remainder operation had too many digits (would be
- longer than precision). The result is [0,qNaN].
- """
-
- def handle(self, context, *args):
- return _NaN
-
-class DivisionUndefined(InvalidOperation, ZeroDivisionError):
- """Undefined result of division.
-
- This occurs and signals invalid-operation if division by zero was
- attempted (during a divide-integer, divide, or remainder operation), and
- the dividend is also zero. The result is [0,qNaN].
- """
-
- def handle(self, context, *args):
- return _NaN
-
-class Inexact(DecimalException):
- """Had to round, losing information.
-
- This occurs and signals inexact whenever the result of an operation is
- not exact (that is, it needed to be rounded and any discarded digits
- were non-zero), or if an overflow or underflow condition occurs. The
- result in all cases is unchanged.
-
- The inexact signal may be tested (or trapped) to determine if a given
- operation (or sequence of operations) was inexact.
- """
-
-class InvalidContext(InvalidOperation):
- """Invalid context. Unknown rounding, for example.
-
- This occurs and signals invalid-operation if an invalid context was
- detected during an operation. This can occur if contexts are not checked
- on creation and either the precision exceeds the capability of the
- underlying concrete representation or an unknown or unsupported rounding
- was specified. These aspects of the context need only be checked when
- the values are required to be used. The result is [0,qNaN].
- """
-
- def handle(self, context, *args):
- return _NaN
-
-class Rounded(DecimalException):
- """Number got rounded (not necessarily changed during rounding).
-
- This occurs and signals rounded whenever the result of an operation is
- rounded (that is, some zero or non-zero digits were discarded from the
- coefficient), or if an overflow or underflow condition occurs. The
- result in all cases is unchanged.
-
- The rounded signal may be tested (or trapped) to determine if a given
- operation (or sequence of operations) caused a loss of precision.
- """
-
-class Subnormal(DecimalException):
- """Exponent < Emin before rounding.
-
- This occurs and signals subnormal whenever the result of a conversion or
- operation is subnormal (that is, its adjusted exponent is less than
- Emin, before any rounding). The result in all cases is unchanged.
-
- The subnormal signal may be tested (or trapped) to determine if a given
- or operation (or sequence of operations) yielded a subnormal result.
- """
-
-class Overflow(Inexact, Rounded):
- """Numerical overflow.
-
- This occurs and signals overflow if the adjusted exponent of a result
- (from a conversion or from an operation that is not an attempt to divide
- by zero), after rounding, would be greater than the largest value that
- can be handled by the implementation (the value Emax).
-
- The result depends on the rounding mode:
-
- For round-half-up and round-half-even (and for round-half-down and
- round-up, if implemented), the result of the operation is [sign,inf],
- where sign is the sign of the intermediate result. For round-down, the
- result is the largest finite number that can be represented in the
- current precision, with the sign of the intermediate result. For
- round-ceiling, the result is the same as for round-down if the sign of
- the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
- the result is the same as for round-down if the sign of the intermediate
- result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
- will also be raised.
- """
-
- def handle(self, context, sign, *args):
- if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
- ROUND_HALF_DOWN, ROUND_UP):
- return _SignedInfinity[sign]
- if sign == 0:
- if context.rounding == ROUND_CEILING:
- return _SignedInfinity[sign]
- return _dec_from_triple(sign, '9'*context.prec,
- context.Emax-context.prec+1)
- if sign == 1:
- if context.rounding == ROUND_FLOOR:
- return _SignedInfinity[sign]
- return _dec_from_triple(sign, '9'*context.prec,
- context.Emax-context.prec+1)
-
-
-class Underflow(Inexact, Rounded, Subnormal):
- """Numerical underflow with result rounded to 0.
-
- This occurs and signals underflow if a result is inexact and the
- adjusted exponent of the result would be smaller (more negative) than
- the smallest value that can be handled by the implementation (the value
- Emin). That is, the result is both inexact and subnormal.
-
- The result after an underflow will be a subnormal number rounded, if
- necessary, so that its exponent is not less than Etiny. This may result
- in 0 with the sign of the intermediate result and an exponent of Etiny.
-
- In all cases, Inexact, Rounded, and Subnormal will also be raised.
- """
-
-class FloatOperation(DecimalException, TypeError):
- """Enable stricter semantics for mixing floats and Decimals.
-
- If the signal is not trapped (default), mixing floats and Decimals is
- permitted in the Decimal() constructor, context.create_decimal() and
- all comparison operators. Both conversion and comparisons are exact.
- Any occurrence of a mixed operation is silently recorded by setting
- FloatOperation in the context flags. Explicit conversions with
- Decimal.from_float() or context.create_decimal_from_float() do not
- set the flag.
-
- Otherwise (the signal is trapped), only equality comparisons and explicit
- conversions are silent. All other mixed operations raise FloatOperation.
- """
-
-# List of public traps and flags
-_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
- Underflow, InvalidOperation, Subnormal, FloatOperation]
-
-# Map conditions (per the spec) to signals
-_condition_map = {ConversionSyntax:InvalidOperation,
- DivisionImpossible:InvalidOperation,
- DivisionUndefined:InvalidOperation,
- InvalidContext:InvalidOperation}
-
-# Valid rounding modes
-_rounding_modes = (ROUND_DOWN, ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_CEILING,
- ROUND_FLOOR, ROUND_UP, ROUND_HALF_DOWN, ROUND_05UP)
-
-##### Context Functions ##################################################
-
-# The getcontext() and setcontext() function manage access to a thread-local
-# current context.
-
-import contextvars
-
-_current_context_var = contextvars.ContextVar('decimal_context')
-
-def getcontext():
- """Returns this thread's context.
-
- If this thread does not yet have a context, returns
- a new context and sets this thread's context.
- New contexts are copies of DefaultContext.
- """
- try:
- return _current_context_var.get()
- except LookupError:
- context = Context()
- _current_context_var.set(context)
- return context
-
-def setcontext(context):
- """Set this thread's context to context."""
- if context in (DefaultContext, BasicContext, ExtendedContext):
- context = context.copy()
- context.clear_flags()
- _current_context_var.set(context)
-
-del contextvars # Don't contaminate the namespace
-
-def localcontext(ctx=None):
- """Return a context manager for a copy of the supplied context
-
- Uses a copy of the current context if no context is specified
- The returned context manager creates a local decimal context
- in a with statement:
- def sin(x):
- with localcontext() as ctx:
- ctx.prec += 2
- # Rest of sin calculation algorithm
- # uses a precision 2 greater than normal
- return +s # Convert result to normal precision
-
- def sin(x):
- with localcontext(ExtendedContext):
- # Rest of sin calculation algorithm
- # uses the Extended Context from the
- # General Decimal Arithmetic Specification
- return +s # Convert result to normal context
-
- >>> setcontext(DefaultContext)
- >>> print(getcontext().prec)
- 28
- >>> with localcontext():
- ... ctx = getcontext()
- ... ctx.prec += 2
- ... print(ctx.prec)
- ...
- 30
- >>> with localcontext(ExtendedContext):
- ... print(getcontext().prec)
- ...
- 9
- >>> print(getcontext().prec)
- 28
- """
- if ctx is None: ctx = getcontext()
- return _ContextManager(ctx)
-
-
-##### Decimal class #######################################################
-
-# Do not subclass Decimal from numbers.Real and do not register it as such
-# (because Decimals are not interoperable with floats). See the notes in
-# numbers.py for more detail.
-
-class Decimal(object):
- """Floating point class for decimal arithmetic."""
-
- __slots__ = ('_exp','_int','_sign', '_is_special')
- # Generally, the value of the Decimal instance is given by
- # (-1)**_sign * _int * 10**_exp
- # Special values are signified by _is_special == True
-
- # We're immutable, so use __new__ not __init__
- def __new__(cls, value="0", context=None):
- """Create a decimal point instance.
-
- >>> Decimal('3.14') # string input
- Decimal('3.14')
- >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
- Decimal('3.14')
- >>> Decimal(314) # int
- Decimal('314')
- >>> Decimal(Decimal(314)) # another decimal instance
- Decimal('314')
- >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
- Decimal('3.14')
- """
-
- # Note that the coefficient, self._int, is actually stored as
- # a string rather than as a tuple of digits. This speeds up
- # the "digits to integer" and "integer to digits" conversions
- # that are used in almost every arithmetic operation on
- # Decimals. This is an internal detail: the as_tuple function
- # and the Decimal constructor still deal with tuples of
- # digits.
-
- self = object.__new__(cls)
-
- # From a string
- # REs insist on real strings, so we can too.
- if isinstance(value, str):
- m = _parser(value.strip().replace("_", ""))
- if m is None:
- if context is None:
- context = getcontext()
- return context._raise_error(ConversionSyntax,
- "Invalid literal for Decimal: %r" % value)
-
- if m.group('sign') == "-":
- self._sign = 1
- else:
- self._sign = 0
- intpart = m.group('int')
- if intpart is not None:
- # finite number
- fracpart = m.group('frac') or ''
- exp = int(m.group('exp') or '0')
- self._int = str(int(intpart+fracpart))
- self._exp = exp - len(fracpart)
- self._is_special = False
- else:
- diag = m.group('diag')
- if diag is not None:
- # NaN
- self._int = str(int(diag or '0')).lstrip('0')
- if m.group('signal'):
- self._exp = 'N'
- else:
- self._exp = 'n'
- else:
- # infinity
- self._int = '0'
- self._exp = 'F'
- self._is_special = True
- return self
-
- # From an integer
- if isinstance(value, int):
- if value >= 0:
- self._sign = 0
- else:
- self._sign = 1
- self._exp = 0
- self._int = str(abs(value))
- self._is_special = False
- return self
-
- # From another decimal
- if isinstance(value, Decimal):
- self._exp = value._exp
- self._sign = value._sign
- self._int = value._int
- self._is_special = value._is_special
- return self
-
- # From an internal working value
- if isinstance(value, _WorkRep):
- self._sign = value.sign
- self._int = str(value.int)
- self._exp = int(value.exp)
- self._is_special = False
- return self
-
- # tuple/list conversion (possibly from as_tuple())
- if isinstance(value, (list,tuple)):
- if len(value) != 3:
- raise ValueError('Invalid tuple size in creation of Decimal '
- 'from list or tuple. The list or tuple '
- 'should have exactly three elements.')
- # process sign. The isinstance test rejects floats
- if not (isinstance(value[0], int) and value[0] in (0,1)):
- raise ValueError("Invalid sign. The first value in the tuple "
- "should be an integer; either 0 for a "
- "positive number or 1 for a negative number.")
- self._sign = value[0]
- if value[2] == 'F':
- # infinity: value[1] is ignored
- self._int = '0'
- self._exp = value[2]
- self._is_special = True
- else:
- # process and validate the digits in value[1]
- digits = []
- for digit in value[1]:
- if isinstance(digit, int) and 0 <= digit <= 9:
- # skip leading zeros
- if digits or digit != 0:
- digits.append(digit)
- else:
- raise ValueError("The second value in the tuple must "
- "be composed of integers in the range "
- "0 through 9.")
- if value[2] in ('n', 'N'):
- # NaN: digits form the diagnostic
- self._int = ''.join(map(str, digits))
- self._exp = value[2]
- self._is_special = True
- elif isinstance(value[2], int):
- # finite number: digits give the coefficient
- self._int = ''.join(map(str, digits or [0]))
- self._exp = value[2]
- self._is_special = False
- else:
- raise ValueError("The third value in the tuple must "
- "be an integer, or one of the "
- "strings 'F', 'n', 'N'.")
- return self
-
- if isinstance(value, float):
- if context is None:
- context = getcontext()
- context._raise_error(FloatOperation,
- "strict semantics for mixing floats and Decimals are "
- "enabled")
- value = Decimal.from_float(value)
- self._exp = value._exp
- self._sign = value._sign
- self._int = value._int
- self._is_special = value._is_special
- return self
-
- raise TypeError("Cannot convert %r to Decimal" % value)
-
- @classmethod
- def from_float(cls, f):
- """Converts a float to a decimal number, exactly.
-
- Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
- Since 0.1 is not exactly representable in binary floating point, the
- value is stored as the nearest representable value which is
- 0x1.999999999999ap-4. The exact equivalent of the value in decimal
- is 0.1000000000000000055511151231257827021181583404541015625.
-
- >>> Decimal.from_float(0.1)
- Decimal('0.1000000000000000055511151231257827021181583404541015625')
- >>> Decimal.from_float(float('nan'))
- Decimal('NaN')
- >>> Decimal.from_float(float('inf'))
- Decimal('Infinity')
- >>> Decimal.from_float(-float('inf'))
- Decimal('-Infinity')
- >>> Decimal.from_float(-0.0)
- Decimal('-0')
-
- """
- if isinstance(f, int): # handle integer inputs
- sign = 0 if f >= 0 else 1
- k = 0
- coeff = str(abs(f))
- elif isinstance(f, float):
- if _math.isinf(f) or _math.isnan(f):
- return cls(repr(f))
- if _math.copysign(1.0, f) == 1.0:
- sign = 0
- else:
- sign = 1
- n, d = abs(f).as_integer_ratio()
- k = d.bit_length() - 1
- coeff = str(n*5**k)
- else:
- raise TypeError("argument must be int or float.")
-
- result = _dec_from_triple(sign, coeff, -k)
- if cls is Decimal:
- return result
- else:
- return cls(result)
-
- def _isnan(self):
- """Returns whether the number is not actually one.
-
- 0 if a number
- 1 if NaN
- 2 if sNaN
- """
- if self._is_special:
- exp = self._exp
- if exp == 'n':
- return 1
- elif exp == 'N':
- return 2
- return 0
-
- def _isinfinity(self):
- """Returns whether the number is infinite
-
- 0 if finite or not a number
- 1 if +INF
- -1 if -INF
- """
- if self._exp == 'F':
- if self._sign:
- return -1
- return 1
- return 0
-
- def _check_nans(self, other=None, context=None):
- """Returns whether the number is not actually one.
-
- if self, other are sNaN, signal
- if self, other are NaN return nan
- return 0
-
- Done before operations.
- """
-
- self_is_nan = self._isnan()
- if other is None:
- other_is_nan = False
- else:
- other_is_nan = other._isnan()
-
- if self_is_nan or other_is_nan:
- if context is None:
- context = getcontext()
-
- if self_is_nan == 2:
- return context._raise_error(InvalidOperation, 'sNaN',
- self)
- if other_is_nan == 2:
- return context._raise_error(InvalidOperation, 'sNaN',
- other)
- if self_is_nan:
- return self._fix_nan(context)
-
- return other._fix_nan(context)
- return 0
-
- def _compare_check_nans(self, other, context):
- """Version of _check_nans used for the signaling comparisons
- compare_signal, __le__, __lt__, __ge__, __gt__.
-
- Signal InvalidOperation if either self or other is a (quiet
- or signaling) NaN. Signaling NaNs take precedence over quiet
- NaNs.
-
- Return 0 if neither operand is a NaN.
-
- """
- if context is None:
- context = getcontext()
-
- if self._is_special or other._is_special:
- if self.is_snan():
- return context._raise_error(InvalidOperation,
- 'comparison involving sNaN',
- self)
- elif other.is_snan():
- return context._raise_error(InvalidOperation,
- 'comparison involving sNaN',
- other)
- elif self.is_qnan():
- return context._raise_error(InvalidOperation,
- 'comparison involving NaN',
- self)
- elif other.is_qnan():
- return context._raise_error(InvalidOperation,
- 'comparison involving NaN',
- other)
- return 0
-
- def __bool__(self):
- """Return True if self is nonzero; otherwise return False.
-
- NaNs and infinities are considered nonzero.
- """
- return self._is_special or self._int != '0'
-
- def _cmp(self, other):
- """Compare the two non-NaN decimal instances self and other.
-
- Returns -1 if self < other, 0 if self == other and 1
- if self > other. This routine is for internal use only."""
-
- if self._is_special or other._is_special:
- self_inf = self._isinfinity()
- other_inf = other._isinfinity()
- if self_inf == other_inf:
- return 0
- elif self_inf < other_inf:
- return -1
- else:
- return 1
-
- # check for zeros; Decimal('0') == Decimal('-0')
- if not self:
- if not other:
- return 0
- else:
- return -((-1)**other._sign)
- if not other:
- return (-1)**self._sign
-
- # If different signs, neg one is less
- if other._sign < self._sign:
- return -1
- if self._sign < other._sign:
- return 1
-
- self_adjusted = self.adjusted()
- other_adjusted = other.adjusted()
- if self_adjusted == other_adjusted:
- self_padded = self._int + '0'*(self._exp - other._exp)
- other_padded = other._int + '0'*(other._exp - self._exp)
- if self_padded == other_padded:
- return 0
- elif self_padded < other_padded:
- return -(-1)**self._sign
- else:
- return (-1)**self._sign
- elif self_adjusted > other_adjusted:
- return (-1)**self._sign
- else: # self_adjusted < other_adjusted
- return -((-1)**self._sign)
-
- # Note: The Decimal standard doesn't cover rich comparisons for
- # Decimals. In particular, the specification is silent on the
- # subject of what should happen for a comparison involving a NaN.
- # We take the following approach:
- #
- # == comparisons involving a quiet NaN always return False
- # != comparisons involving a quiet NaN always return True
- # == or != comparisons involving a signaling NaN signal
- # InvalidOperation, and return False or True as above if the
- # InvalidOperation is not trapped.
- # <, >, <= and >= comparisons involving a (quiet or signaling)
- # NaN signal InvalidOperation, and return False if the
- # InvalidOperation is not trapped.
- #
- # This behavior is designed to conform as closely as possible to
- # that specified by IEEE 754.
-
- def __eq__(self, other, context=None):
- self, other = _convert_for_comparison(self, other, equality_op=True)
- if other is NotImplemented:
- return other
- if self._check_nans(other, context):
- return False
- return self._cmp(other) == 0
-
- def __lt__(self, other, context=None):
- self, other = _convert_for_comparison(self, other)
- if other is NotImplemented:
- return other
- ans = self._compare_check_nans(other, context)
- if ans:
- return False
- return self._cmp(other) < 0
-
- def __le__(self, other, context=None):
- self, other = _convert_for_comparison(self, other)
- if other is NotImplemented:
- return other
- ans = self._compare_check_nans(other, context)
- if ans:
- return False
- return self._cmp(other) <= 0
-
- def __gt__(self, other, context=None):
- self, other = _convert_for_comparison(self, other)
- if other is NotImplemented:
- return other
- ans = self._compare_check_nans(other, context)
- if ans:
- return False
- return self._cmp(other) > 0
-
- def __ge__(self, other, context=None):
- self, other = _convert_for_comparison(self, other)
- if other is NotImplemented:
- return other
- ans = self._compare_check_nans(other, context)
- if ans:
- return False
- return self._cmp(other) >= 0
-
- def compare(self, other, context=None):
- """Compare self to other. Return a decimal value:
-
- a or b is a NaN ==> Decimal('NaN')
- a < b ==> Decimal('-1')
- a == b ==> Decimal('0')
- a > b ==> Decimal('1')
- """
- other = _convert_other(other, raiseit=True)
-
- # Compare(NaN, NaN) = NaN
- if (self._is_special or other and other._is_special):
- ans = self._check_nans(other, context)
- if ans:
- return ans
-
- return Decimal(self._cmp(other))
-
- def __hash__(self):
- """x.__hash__() <==> hash(x)"""
-
- # In order to make sure that the hash of a Decimal instance
- # agrees with the hash of a numerically equal integer, float
- # or Fraction, we follow the rules for numeric hashes outlined
- # in the documentation. (See library docs, 'Built-in Types').
- if self._is_special:
- if self.is_snan():
- raise TypeError('Cannot hash a signaling NaN value.')
- elif self.is_nan():
- return object.__hash__(self)
- else:
- if self._sign:
- return -_PyHASH_INF
- else:
- return _PyHASH_INF
-
- if self._exp >= 0:
- exp_hash = pow(10, self._exp, _PyHASH_MODULUS)
- else:
- exp_hash = pow(_PyHASH_10INV, -self._exp, _PyHASH_MODULUS)
- hash_ = int(self._int) * exp_hash % _PyHASH_MODULUS
- ans = hash_ if self >= 0 else -hash_
- return -2 if ans == -1 else ans
-
- def as_tuple(self):
- """Represents the number as a triple tuple.
-
- To show the internals exactly as they are.
- """
- return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
-
- def as_integer_ratio(self):
- """Express a finite Decimal instance in the form n / d.
-
- Returns a pair (n, d) of integers. When called on an infinity
- or NaN, raises OverflowError or ValueError respectively.
-
- >>> Decimal('3.14').as_integer_ratio()
- (157, 50)
- >>> Decimal('-123e5').as_integer_ratio()
- (-12300000, 1)
- >>> Decimal('0.00').as_integer_ratio()
- (0, 1)
-
- """
- if self._is_special:
- if self.is_nan():
- raise ValueError("cannot convert NaN to integer ratio")
- else:
- raise OverflowError("cannot convert Infinity to integer ratio")
-
- if not self:
- return 0, 1
-
- # Find n, d in lowest terms such that abs(self) == n / d;
- # we'll deal with the sign later.
- n = int(self._int)
- if self._exp >= 0:
- # self is an integer.
- n, d = n * 10**self._exp, 1
- else:
- # Find d2, d5 such that abs(self) = n / (2**d2 * 5**d5).
- d5 = -self._exp
- while d5 > 0 and n % 5 == 0:
- n //= 5
- d5 -= 1
-
- # (n & -n).bit_length() - 1 counts trailing zeros in binary
- # representation of n (provided n is nonzero).
- d2 = -self._exp
- shift2 = min((n & -n).bit_length() - 1, d2)
- if shift2:
- n >>= shift2
- d2 -= shift2
-
- d = 5**d5 << d2
-
- if self._sign:
- n = -n
- return n, d
-
- def __repr__(self):
- """Represents the number as an instance of Decimal."""
- # Invariant: eval(repr(d)) == d
- return "Decimal('%s')" % str(self)
-
- def __str__(self, eng=False, context=None):
- """Return string representation of the number in scientific notation.
-
- Captures all of the information in the underlying representation.
- """
-
- sign = ['', '-'][self._sign]
- if self._is_special:
- if self._exp == 'F':
- return sign + 'Infinity'
- elif self._exp == 'n':
- return sign + 'NaN' + self._int
- else: # self._exp == 'N'
- return sign + 'sNaN' + self._int
-
- # number of digits of self._int to left of decimal point
- leftdigits = self._exp + len(self._int)
-
- # dotplace is number of digits of self._int to the left of the
- # decimal point in the mantissa of the output string (that is,
- # after adjusting the exponent)
- if self._exp <= 0 and leftdigits > -6:
- # no exponent required
- dotplace = leftdigits
- elif not eng:
- # usual scientific notation: 1 digit on left of the point
- dotplace = 1
- elif self._int == '0':
- # engineering notation, zero
- dotplace = (leftdigits + 1) % 3 - 1
- else:
- # engineering notation, nonzero
- dotplace = (leftdigits - 1) % 3 + 1
-
- if dotplace <= 0:
- intpart = '0'
- fracpart = '.' + '0'*(-dotplace) + self._int
- elif dotplace >= len(self._int):
- intpart = self._int+'0'*(dotplace-len(self._int))
- fracpart = ''
- else:
- intpart = self._int[:dotplace]
- fracpart = '.' + self._int[dotplace:]
- if leftdigits == dotplace:
- exp = ''
- else:
- if context is None:
- context = getcontext()
- exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
-
- return sign + intpart + fracpart + exp
-
- def to_eng_string(self, context=None):
- """Convert to a string, using engineering notation if an exponent is needed.
-
- Engineering notation has an exponent which is a multiple of 3. This
- can leave up to 3 digits to the left of the decimal place and may
- require the addition of either one or two trailing zeros.
- """
- return self.__str__(eng=True, context=context)
-
- def __neg__(self, context=None):
- """Returns a copy with the sign switched.
-
- Rounds, if it has reason.
- """
- if self._is_special:
- ans = self._check_nans(context=context)
- if ans:
- return ans
-
- if context is None:
- context = getcontext()
-
- if not self and context.rounding != ROUND_FLOOR:
- # -Decimal('0') is Decimal('0'), not Decimal('-0'), except
- # in ROUND_FLOOR rounding mode.
- ans = self.copy_abs()
- else:
- ans = self.copy_negate()
-
- return ans._fix(context)
-
- def __pos__(self, context=None):
- """Returns a copy, unless it is a sNaN.
-
- Rounds the number (if more than precision digits)
- """
- if self._is_special:
- ans = self._check_nans(context=context)
- if ans:
- return ans
-
- if context is None:
- context = getcontext()
-
- if not self and context.rounding != ROUND_FLOOR:
- # + (-0) = 0, except in ROUND_FLOOR rounding mode.
- ans = self.copy_abs()
- else:
- ans = Decimal(self)
-
- return ans._fix(context)
-
- def __abs__(self, round=True, context=None):
- """Returns the absolute value of self.
-
- If the keyword argument 'round' is false, do not round. The
- expression self.__abs__(round=False) is equivalent to
- self.copy_abs().
- """
- if not round:
- return self.copy_abs()
-
- if self._is_special:
- ans = self._check_nans(context=context)
- if ans:
- return ans
-
- if self._sign:
- ans = self.__neg__(context=context)
- else:
- ans = self.__pos__(context=context)
-
- return ans
-
- def __add__(self, other, context=None):
- """Returns self + other.
-
- -INF + INF (or the reverse) cause InvalidOperation errors.
- """
- other = _convert_other(other)
- if other is NotImplemented:
- return other
-
- if context is None:
- context = getcontext()
-
- if self._is_special or other._is_special:
- ans = self._check_nans(other, context)
- if ans:
- return ans
-
- if self._isinfinity():
- # If both INF, same sign => same as both, opposite => error.
- if self._sign != other._sign and other._isinfinity():
- return context._raise_error(InvalidOperation, '-INF + INF')
- return Decimal(self)
- if other._isinfinity():
- return Decimal(other) # Can't both be infinity here
-
- exp = min(self._exp, other._exp)
- negativezero = 0
- if context.rounding == ROUND_FLOOR and self._sign != other._sign:
- # If the answer is 0, the sign should be negative, in this case.
- negativezero = 1
-
- if not self and not other:
- sign = min(self._sign, other._sign)
- if negativezero:
- sign = 1
- ans = _dec_from_triple(sign, '0', exp)
- ans = ans._fix(context)
- return ans
- if not self:
- exp = max(exp, other._exp - context.prec-1)
- ans = other._rescale(exp, context.rounding)
- ans = ans._fix(context)
- return ans
- if not other:
- exp = max(exp, self._exp - context.prec-1)
- ans = self._rescale(exp, context.rounding)
- ans = ans._fix(context)
- return ans
-
- op1 = _WorkRep(self)
- op2 = _WorkRep(other)
- op1, op2 = _normalize(op1, op2, context.prec)
-
- result = _WorkRep()
- if op1.sign != op2.sign:
- # Equal and opposite
- if op1.int == op2.int:
- ans = _dec_from_triple(negativezero, '0', exp)
- ans = ans._fix(context)
- return ans
- if op1.int < op2.int:
- op1, op2 = op2, op1
- # OK, now abs(op1) > abs(op2)
- if op1.sign == 1:
- result.sign = 1
- op1.sign, op2.sign = op2.sign, op1.sign
- else:
- result.sign = 0
- # So we know the sign, and op1 > 0.
- elif op1.sign == 1:
- result.sign = 1
- op1.sign, op2.sign = (0, 0)
- else:
- result.sign = 0
- # Now, op1 > abs(op2) > 0
-
- if op2.sign == 0:
- result.int = op1.int + op2.int
- else:
- result.int = op1.int - op2.int
-
- result.exp = op1.exp
- ans = Decimal(result)
- ans = ans._fix(context)
- return ans
-
- __radd__ = __add__
-
- def __sub__(self, other, context=None):
- """Return self - other"""
- other = _convert_other(other)
- if other is NotImplemented:
- return other
-
- if self._is_special or other._is_special:
- ans = self._check_nans(other, context=context)
- if ans:
- return ans
-
- # self - other is computed as self + other.copy_negate()
- return self.__add__(other.copy_negate(), context=context)
-
- def __rsub__(self, other, context=None):
- """Return other - self"""
- other = _convert_other(other)
- if other is NotImplemented:
- return other
-
- return other.__sub__(self, context=context)
-
- def __mul__(self, other, context=None):
- """Return self * other.
-
- (+-) INF * 0 (or its reverse) raise InvalidOperation.
- """
- other = _convert_other(other)
- if other is NotImplemented:
- return other
-
- if context is None:
- context = getcontext()
-
- resultsign = self._sign ^ other._sign
-
- if self._is_special or other._is_special:
- ans = self._check_nans(other, context)
- if ans:
- return ans
-
- if self._isinfinity():
- if not other:
- return context._raise_error(InvalidOperation, '(+-)INF * 0')
- return _SignedInfinity[resultsign]
-
- if other._isinfinity():
- if not self:
- return context._raise_error(InvalidOperation, '0 * (+-)INF')
- return _SignedInfinity[resultsign]
-
- resultexp = self._exp + other._exp
-
- # Special case for multiplying by zero
- if not self or not other:
- ans = _dec_from_triple(resultsign, '0', resultexp)
- # Fixing in case the exponent is out of bounds
- ans = ans._fix(context)
- return ans
-
- # Special case for multiplying by power of 10
- if self._int == '1':
- ans = _dec_from_triple(resultsign, other._int, resultexp)
- ans = ans._fix(context)
- return ans
- if other._int == '1':
- ans = _dec_from_triple(resultsign, self._int, resultexp)
- ans = ans._fix(context)
- return ans
-
- op1 = _WorkRep(self)
- op2 = _WorkRep(other)
-
- ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
- ans = ans._fix(context)
-
- return ans
- __rmul__ = __mul__
-
- def __truediv__(self, other, context=None):
- """Return self / other."""
- other = _convert_other(other)
- if other is NotImplemented:
- return NotImplemented
-
- if context is None:
- context = getcontext()
-
- sign = self._sign ^ other._sign
-
- if self._is_special or other._is_special:
- ans = self._check_nans(other, context)
- if ans:
- return ans
-
- if self._isinfinity() and other._isinfinity():
- return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
-
- if self._isinfinity():
- return _SignedInfinity[sign]
-
- if other._isinfinity():
- context._raise_error(Clamped, 'Division by infinity')
- return _dec_from_triple(sign, '0', context.Etiny())
-
- # Special cases for zeroes
- if not other:
- if not self:
- return context._raise_error(DivisionUndefined, '0 / 0')
- return context._raise_error(DivisionByZero, 'x / 0', sign)
-
- if not self:
- exp = self._exp - other._exp
- coeff = 0
- else:
- # OK, so neither = 0, INF or NaN
- shift = len(other._int) - len(self._int) + context.prec + 1
- exp = self._exp - other._exp - shift
- op1 = _WorkRep(self)
- op2 = _WorkRep(other)
- if shift >= 0:
- coeff, remainder = divmod(op1.int * 10**shift, op2.int)
- else:
- coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
- if remainder:
- # result is not exact; adjust to ensure correct rounding
- if coeff % 5 == 0:
- coeff += 1
- else:
- # result is exact; get as close to ideal exponent as possible
- ideal_exp = self._exp - other._exp
- while exp < ideal_exp and coeff % 10 == 0:
- coeff //= 10
- exp += 1
-
- ans = _dec_from_triple(sign, str(coeff), exp)
- return ans._fix(context)
-
- def _divide(self, other, context):
- """Return (self // other, self % other), to context.prec precision.
-
- Assumes that neither self nor other is a NaN, that self is not
- infinite and that other is nonzero.
- """
- sign = self._sign ^ other._sign
- if other._isinfinity():
- ideal_exp = self._exp
- else:
- ideal_exp = min(self._exp, other._exp)
-
- expdiff = self.adjusted() - other.adjusted()
- if not self or other._isinfinity() or expdiff <= -2:
- return (_dec_from_triple(sign, '0', 0),
- self._rescale(ideal_exp, context.rounding))
- if expdiff <= context.prec:
- op1 = _WorkRep(self)
- op2 = _WorkRep(other)
- if op1.exp >= op2.exp:
- op1.int *= 10**(op1.exp - op2.exp)
- else:
- op2.int *= 10**(op2.exp - op1.exp)
- q, r = divmod(op1.int, op2.int)
- if q < 10**context.prec:
- return (_dec_from_triple(sign, str(q), 0),
- _dec_from_triple(self._sign, str(r), ideal_exp))
-
- # Here the quotient is too large to be representable
- ans = context._raise_error(DivisionImpossible,
- 'quotient too large in //, % or divmod')
- return ans, ans
-
- def __rtruediv__(self, other, context=None):
- """Swaps self/other and returns __truediv__."""
- other = _convert_other(other)
- if other is NotImplemented:
- return other
- return other.__truediv__(self, context=context)
-
- def __divmod__(self, other, context=None):
- """
- Return (self // other, self % other)
- """
- other = _convert_other(other)
- if other is NotImplemented:
- return other
-
- if context is None:
- context = getcontext()
-
- ans = self._check_nans(other, context)
- if ans:
- return (ans, ans)
-
- sign = self._sign ^ other._sign
- if self._isinfinity():
- if other._isinfinity():
- ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
- return ans, ans
- else:
- return (_SignedInfinity[sign],
- context._raise_error(InvalidOperation, 'INF % x'))
-
- if not other:
- if not self:
- ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
- return ans, ans
- else:
- return (context._raise_error(DivisionByZero, 'x // 0', sign),
- context._raise_error(InvalidOperation, 'x % 0'))
-
- quotient, remainder = self._divide(other, context)
- remainder = remainder._fix(context)
- return quotient, remainder
-
- def __rdivmod__(self, other, context=None):
- """Swaps self/other and returns __divmod__."""
- other = _convert_other(other)
- if other is NotImplemented:
- return other
- return other.__divmod__(self, context=context)
-
- def __mod__(self, other, context=None):
- """
- self % other
- """
- other = _convert_other(other)
- if other is NotImplemented:
- return other
-
- if context is None:
- context = getcontext()
-
- ans = self._check_nans(other, context)
- if ans:
- return ans
-
- if self._isinfinity():
- return context._raise_error(InvalidOperation, 'INF % x')
- elif not other:
- if self:
- return context._raise_error(InvalidOperation, 'x % 0')
- else:
- return context._raise_error(DivisionUndefined, '0 % 0')
-
- remainder = self._divide(other, context)[1]
- remainder = remainder._fix(context)
- return remainder
-
- def __rmod__(self, other, context=None):
- """Swaps self/other and returns __mod__."""
- other = _convert_other(other)
- if other is NotImplemented:
- return other
- return other.__mod__(self, context=context)
-
- def remainder_near(self, other, context=None):
- """
- Remainder nearest to 0- abs(remainder-near) <= other/2
- """
- if context is None:
- context = getcontext()
-
- other = _convert_other(other, raiseit=True)
-
- ans = self._check_nans(other, context)
- if ans:
- return ans
-
- # self == +/-infinity -> InvalidOperation
- if self._isinfinity():
- return context._raise_error(InvalidOperation,
- 'remainder_near(infinity, x)')
-
- # other == 0 -> either InvalidOperation or DivisionUndefined
- if not other:
- if self:
- return context._raise_error(InvalidOperation,
- 'remainder_near(x, 0)')
- else:
- return context._raise_error(DivisionUndefined,
- 'remainder_near(0, 0)')
-
- # other = +/-infinity -> remainder = self
- if other._isinfinity():
- ans = Decimal(self)
- return ans._fix(context)
-
- # self = 0 -> remainder = self, with ideal exponent
- ideal_exponent = min(self._exp, other._exp)
- if not self:
- ans = _dec_from_triple(self._sign, '0', ideal_exponent)
- return ans._fix(context)
-
- # catch most cases of large or small quotient
- expdiff = self.adjusted() - other.adjusted()
- if expdiff >= context.prec + 1:
- # expdiff >= prec+1 => abs(self/other) > 10**prec
- return context._raise_error(DivisionImpossible)
- if expdiff <= -2:
- # expdiff <= -2 => abs(self/other) < 0.1
- ans = self._rescale(ideal_exponent, context.rounding)
- return ans._fix(context)
-
- # adjust both arguments to have the same exponent, then divide
- op1 = _WorkRep(self)
- op2 = _WorkRep(other)
- if op1.exp >= op2.exp:
- op1.int *= 10**(op1.exp - op2.exp)
- else:
- op2.int *= 10**(op2.exp - op1.exp)
- q, r = divmod(op1.int, op2.int)
- # remainder is r*10**ideal_exponent; other is +/-op2.int *
- # 10**ideal_exponent. Apply correction to ensure that
- # abs(remainder) <= abs(other)/2
- if 2*r + (q&1) > op2.int:
- r -= op2.int
- q += 1
-
- if q >= 10**context.prec:
- return context._raise_error(DivisionImpossible)
-
- # result has same sign as self unless r is negative
- sign = self._sign
- if r < 0:
- sign = 1-sign
- r = -r
-
- ans = _dec_from_triple(sign, str(r), ideal_exponent)
- return ans._fix(context)
-
- def __floordiv__(self, other, context=None):
- """self // other"""
- other = _convert_other(other)
- if other is NotImplemented:
- return other
-
- if context is None:
- context = getcontext()
-
- ans = self._check_nans(other, context)
- if ans:
- return ans
-
- if self._isinfinity():
- if other._isinfinity():
- return context._raise_error(InvalidOperation, 'INF // INF')
- else:
- return _SignedInfinity[self._sign ^ other._sign]
-
- if not other:
- if self:
- return context._raise_error(DivisionByZero, 'x // 0',
- self._sign ^ other._sign)
- else:
- return context._raise_error(DivisionUndefined, '0 // 0')
-
- return self._divide(other, context)[0]
-
- def __rfloordiv__(self, other, context=None):
- """Swaps self/other and returns __floordiv__."""
- other = _convert_other(other)
- if other is NotImplemented:
- return other
- return other.__floordiv__(self, context=context)
-
- def __float__(self):
- """Float representation."""
- if self._isnan():
- if self.is_snan():
- raise ValueError("Cannot convert signaling NaN to float")
- s = "-nan" if self._sign else "nan"
- else:
- s = str(self)
- return float(s)
-
- def __int__(self):
- """Converts self to an int, truncating if necessary."""
- if self._is_special:
- if self._isnan():
- raise ValueError("Cannot convert NaN to integer")
- elif self._isinfinity():
- raise OverflowError("Cannot convert infinity to integer")
- s = (-1)**self._sign
- if self._exp >= 0:
- return s*int(self._int)*10**self._exp
- else:
- return s*int(self._int[:self._exp] or '0')
-
- __trunc__ = __int__
-
- @property
- def real(self):
- return self
-
- @property
- def imag(self):
- return Decimal(0)
-
- def conjugate(self):
- return self
-
- def __complex__(self):
- return complex(float(self))
-
- def _fix_nan(self, context):
- """Decapitate the payload of a NaN to fit the context"""
- payload = self._int
-
- # maximum length of payload is precision if clamp=0,
- # precision-1 if clamp=1.
- max_payload_len = context.prec - context.clamp
- if len(payload) > max_payload_len:
- payload = payload[len(payload)-max_payload_len:].lstrip('0')
- return _dec_from_triple(self._sign, payload, self._exp, True)
- return Decimal(self)
-
- def _fix(self, context):
- """Round if it is necessary to keep self within prec precision.
-
- Rounds and fixes the exponent. Does not raise on a sNaN.
-
- Arguments:
- self - Decimal instance
- context - context used.
- """
-
- if self._is_special:
- if self._isnan():
- # decapitate payload if necessary
- return self._fix_nan(context)
- else:
- # self is +/-Infinity; return unaltered
- return Decimal(self)
-
- # if self is zero then exponent should be between Etiny and
- # Emax if clamp==0, and between Etiny and Etop if clamp==1.
- Etiny = context.Etiny()
- Etop = context.Etop()
- if not self:
- exp_max = [context.Emax, Etop][context.clamp]
- new_exp = min(max(self._exp, Etiny), exp_max)
- if new_exp != self._exp:
- context._raise_error(Clamped)
- return _dec_from_triple(self._sign, '0', new_exp)
- else:
- return Decimal(self)
-
- # exp_min is the smallest allowable exponent of the result,
- # equal to max(self.adjusted()-context.prec+1, Etiny)
- exp_min = len(self._int) + self._exp - context.prec
- if exp_min > Etop:
- # overflow: exp_min > Etop iff self.adjusted() > Emax
- ans = context._raise_error(Overflow, 'above Emax', self._sign)
- context._raise_error(Inexact)
- context._raise_error(Rounded)
- return ans
-
- self_is_subnormal = exp_min < Etiny
- if self_is_subnormal:
- exp_min = Etiny
-
- # round if self has too many digits
- if self._exp < exp_min:
- digits = len(self._int) + self._exp - exp_min
- if digits < 0:
- self = _dec_from_triple(self._sign, '1', exp_min-1)
- digits = 0
- rounding_method = self._pick_rounding_function[context.rounding]
- changed = rounding_method(self, digits)
- coeff = self._int[:digits] or '0'
- if changed > 0:
- coeff = str(int(coeff)+1)
- if len(coeff) > context.prec:
- coeff = coeff[:-1]
- exp_min += 1
-
- # check whether the rounding pushed the exponent out of range
- if exp_min > Etop:
- ans = context._raise_error(Overflow, 'above Emax', self._sign)
- else:
- ans = _dec_from_triple(self._sign, coeff, exp_min)
-
- # raise the appropriate signals, taking care to respect
- # the precedence described in the specification
- if changed and self_is_subnormal:
- context._raise_error(Underflow)
- if self_is_subnormal:
- context._raise_error(Subnormal)
- if changed:
- context._raise_error(Inexact)
- context._raise_error(Rounded)
- if not ans:
- # raise Clamped on underflow to 0
- context._raise_error(Clamped)
- return ans
-
- if self_is_subnormal:
- context._raise_error(Subnormal)
-
- # fold down if clamp == 1 and self has too few digits
- if context.clamp == 1 and self._exp > Etop:
- context._raise_error(Clamped)
- self_padded = self._int + '0'*(self._exp - Etop)
- return _dec_from_triple(self._sign, self_padded, Etop)
-
- # here self was representable to begin with; return unchanged
- return Decimal(self)
-
- # for each of the rounding functions below:
- # self is a finite, nonzero Decimal
- # prec is an integer satisfying 0 <= prec < len(self._int)
- #
- # each function returns either -1, 0, or 1, as follows:
- # 1 indicates that self should be rounded up (away from zero)
- # 0 indicates that self should be truncated, and that all the
- # digits to be truncated are zeros (so the value is unchanged)
- # -1 indicates that there are nonzero digits to be truncated
-
- def _round_down(self, prec):
- """Also known as round-towards-0, truncate."""
- if _all_zeros(self._int, prec):
- return 0
- else:
- return -1
-
- def _round_up(self, prec):
- """Rounds away from 0."""
- return -self._round_down(prec)
-
- def _round_half_up(self, prec):
- """Rounds 5 up (away from 0)"""
- if self._int[prec] in '56789':
- return 1
- elif _all_zeros(self._int, prec):
- return 0
- else:
- return -1
-
- def _round_half_down(self, prec):
- """Round 5 down"""
- if _exact_half(self._int, prec):
- return -1
- else:
- return self._round_half_up(prec)
-
- def _round_half_even(self, prec):
- """Round 5 to even, rest to nearest."""
- if _exact_half(self._int, prec) and \
- (prec == 0 or self._int[prec-1] in '02468'):
- return -1
- else:
- return self._round_half_up(prec)
-
- def _round_ceiling(self, prec):
- """Rounds up (not away from 0 if negative.)"""
- if self._sign:
- return self._round_down(prec)
- else:
- return -self._round_down(prec)
-
- def _round_floor(self, prec):
- """Rounds down (not towards 0 if negative)"""
- if not self._sign:
- return self._round_down(prec)
- else:
- return -self._round_down(prec)
-
- def _round_05up(self, prec):
- """Round down unless digit prec-1 is 0 or 5."""
- if prec and self._int[prec-1] not in '05':
- return self._round_down(prec)
- else:
- return -self._round_down(prec)
-
- _pick_rounding_function = dict(
- ROUND_DOWN = _round_down,
- ROUND_UP = _round_up,
- ROUND_HALF_UP = _round_half_up,
- ROUND_HALF_DOWN = _round_half_down,
- ROUND_HALF_EVEN = _round_half_even,
- ROUND_CEILING = _round_ceiling,
- ROUND_FLOOR = _round_floor,
- ROUND_05UP = _round_05up,
- )
-
- def __round__(self, n=None):
- """Round self to the nearest integer, or to a given precision.
-
- If only one argument is supplied, round a finite Decimal
- instance self to the nearest integer. If self is infinite or
- a NaN then a Python exception is raised. If self is finite
- and lies exactly halfway between two integers then it is
- rounded to the integer with even last digit.
-
- >>> round(Decimal('123.456'))
- 123
- >>> round(Decimal('-456.789'))
- -457
- >>> round(Decimal('-3.0'))
- -3
- >>> round(Decimal('2.5'))
- 2
- >>> round(Decimal('3.5'))
- 4
- >>> round(Decimal('Inf'))
- Traceback (most recent call last):
- ...
- OverflowError: cannot round an infinity
- >>> round(Decimal('NaN'))
- Traceback (most recent call last):
- ...
- ValueError: cannot round a NaN
-
- If a second argument n is supplied, self is rounded to n
- decimal places using the rounding mode for the current
- context.
-
- For an integer n, round(self, -n) is exactly equivalent to
- self.quantize(Decimal('1En')).
-
- >>> round(Decimal('123.456'), 0)
- Decimal('123')
- >>> round(Decimal('123.456'), 2)
- Decimal('123.46')
- >>> round(Decimal('123.456'), -2)
- Decimal('1E+2')
- >>> round(Decimal('-Infinity'), 37)
- Decimal('NaN')
- >>> round(Decimal('sNaN123'), 0)
- Decimal('NaN123')
-
- """
- if n is not None:
- # two-argument form: use the equivalent quantize call
- if not isinstance(n, int):
- raise TypeError('Second argument to round should be integral')
- exp = _dec_from_triple(0, '1', -n)
- return self.quantize(exp)
-
- # one-argument form
- if self._is_special:
- if self.is_nan():
- raise ValueError("cannot round a NaN")
- else:
- raise OverflowError("cannot round an infinity")
- return int(self._rescale(0, ROUND_HALF_EVEN))
-
- def __floor__(self):
- """Return the floor of self, as an integer.
-
- For a finite Decimal instance self, return the greatest
- integer n such that n <= self. If self is infinite or a NaN
- then a Python exception is raised.
-
- """
- if self._is_special:
- if self.is_nan():
- raise ValueError("cannot round a NaN")
- else:
- raise OverflowError("cannot round an infinity")
- return int(self._rescale(0, ROUND_FLOOR))
-
- def __ceil__(self):
- """Return the ceiling of self, as an integer.
-
- For a finite Decimal instance self, return the least integer n
- such that n >= self. If self is infinite or a NaN then a
- Python exception is raised.
-
- """
- if self._is_special:
- if self.is_nan():
- raise ValueError("cannot round a NaN")
- else:
- raise OverflowError("cannot round an infinity")
- return int(self._rescale(0, ROUND_CEILING))
-
- def fma(self, other, third, context=None):
- """Fused multiply-add.
-
- Returns self*other+third with no rounding of the intermediate
- product self*other.
-
- self and other are multiplied together, with no rounding of
- the result. The third operand is then added to the result,
- and a single final rounding is performed.
- """
-
- other = _convert_other(other, raiseit=True)
- third = _convert_other(third, raiseit=True)
-
- # compute product; raise InvalidOperation if either operand is
- # a signaling NaN or if the product is zero times infinity.
- if self._is_special or other._is_special:
- if context is None:
- context = getcontext()
- if self._exp == 'N':
- return context._raise_error(InvalidOperation, 'sNaN', self)
- if other._exp == 'N':
- return context._raise_error(InvalidOperation, 'sNaN', other)
- if self._exp == 'n':
- product = self
- elif other._exp == 'n':
- product = other
- elif self._exp == 'F':
- if not other:
- return context._raise_error(InvalidOperation,
- 'INF * 0 in fma')
- product = _SignedInfinity[self._sign ^ other._sign]
- elif other._exp == 'F':
- if not self:
- return context._raise_error(InvalidOperation,
- '0 * INF in fma')
- product = _SignedInfinity[self._sign ^ other._sign]
- else:
- product = _dec_from_triple(self._sign ^ other._sign,
- str(int(self._int) * int(other._int)),
- self._exp + other._exp)
-
- return product.__add__(third, context)
-
- def _power_modulo(self, other, modulo, context=None):
- """Three argument version of __pow__"""
-
- other = _convert_other(other)
- if other is NotImplemented:
- return other
- modulo = _convert_other(modulo)
- if modulo is NotImplemented:
- return modulo
-
- if context is None:
- context = getcontext()
-
- # deal with NaNs: if there are any sNaNs then first one wins,
- # (i.e. behaviour for NaNs is identical to that of fma)
- self_is_nan = self._isnan()
- other_is_nan = other._isnan()
- modulo_is_nan = modulo._isnan()
- if self_is_nan or other_is_nan or modulo_is_nan:
- if self_is_nan == 2:
- return context._raise_error(InvalidOperation, 'sNaN',
- self)
- if other_is_nan == 2:
- return context._raise_error(InvalidOperation, 'sNaN',
- other)
- if modulo_is_nan == 2:
- return context._raise_error(InvalidOperation, 'sNaN',
- modulo)
- if self_is_nan:
- return self._fix_nan(context)
- if other_is_nan:
- return other._fix_nan(context)
- return modulo._fix_nan(context)
-
- # check inputs: we apply same restrictions as Python's pow()
- if not (self._isinteger() and
- other._isinteger() and
- modulo._isinteger()):
- return context._raise_error(InvalidOperation,
- 'pow() 3rd argument not allowed '
- 'unless all arguments are integers')
- if other < 0:
- return context._raise_error(InvalidOperation,
- 'pow() 2nd argument cannot be '
- 'negative when 3rd argument specified')
- if not modulo:
- return context._raise_error(InvalidOperation,
- 'pow() 3rd argument cannot be 0')
-
- # additional restriction for decimal: the modulus must be less
- # than 10**prec in absolute value
- if modulo.adjusted() >= context.prec:
- return context._raise_error(InvalidOperation,
- 'insufficient precision: pow() 3rd '
- 'argument must not have more than '
- 'precision digits')
-
- # define 0**0 == NaN, for consistency with two-argument pow
- # (even though it hurts!)
- if not other and not self:
- return context._raise_error(InvalidOperation,
- 'at least one of pow() 1st argument '
- 'and 2nd argument must be nonzero; '
- '0**0 is not defined')
-
- # compute sign of result
- if other._iseven():
- sign = 0
- else:
- sign = self._sign
-
- # convert modulo to a Python integer, and self and other to
- # Decimal integers (i.e. force their exponents to be >= 0)
- modulo = abs(int(modulo))
- base = _WorkRep(self.to_integral_value())
- exponent = _WorkRep(other.to_integral_value())
-
- # compute result using integer pow()
- base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
- for i in range(exponent.exp):
- base = pow(base, 10, modulo)
- base = pow(base, exponent.int, modulo)
-
- return _dec_from_triple(sign, str(base), 0)
-
- def _power_exact(self, other, p):
- """Attempt to compute self**other exactly.
-
- Given Decimals self and other and an integer p, attempt to
- compute an exact result for the power self**other, with p
- digits of precision. Return None if self**other is not
- exactly representable in p digits.
-
- Assumes that elimination of special cases has already been
- performed: self and other must both be nonspecial; self must
- be positive and not numerically equal to 1; other must be
- nonzero. For efficiency, other._exp should not be too large,
- so that 10**abs(other._exp) is a feasible calculation."""
-
- # In the comments below, we write x for the value of self and y for the
- # value of other. Write x = xc*10**xe and abs(y) = yc*10**ye, with xc
- # and yc positive integers not divisible by 10.
-
- # The main purpose of this method is to identify the *failure*
- # of x**y to be exactly representable with as little effort as
- # possible. So we look for cheap and easy tests that
- # eliminate the possibility of x**y being exact. Only if all
- # these tests are passed do we go on to actually compute x**y.
-
- # Here's the main idea. Express y as a rational number m/n, with m and
- # n relatively prime and n>0. Then for x**y to be exactly
- # representable (at *any* precision), xc must be the nth power of a
- # positive integer and xe must be divisible by n. If y is negative
- # then additionally xc must be a power of either 2 or 5, hence a power
- # of 2**n or 5**n.
- #
- # There's a limit to how small |y| can be: if y=m/n as above
- # then:
- #
- # (1) if xc != 1 then for the result to be representable we
- # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
- # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
- # 2**(1/|y|), hence xc**|y| < 2 and the result is not
- # representable.
- #
- # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
- # |y| < 1/|xe| then the result is not representable.
- #
- # Note that since x is not equal to 1, at least one of (1) and
- # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
- # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
- #
- # There's also a limit to how large y can be, at least if it's
- # positive: the normalized result will have coefficient xc**y,
- # so if it's representable then xc**y < 10**p, and y <
- # p/log10(xc). Hence if y*log10(xc) >= p then the result is
- # not exactly representable.
-
- # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
- # so |y| < 1/xe and the result is not representable.
- # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
- # < 1/nbits(xc).
-
- x = _WorkRep(self)
- xc, xe = x.int, x.exp
- while xc % 10 == 0:
- xc //= 10
- xe += 1
-
- y = _WorkRep(other)
- yc, ye = y.int, y.exp
- while yc % 10 == 0:
- yc //= 10
- ye += 1
-
- # case where xc == 1: result is 10**(xe*y), with xe*y
- # required to be an integer
- if xc == 1:
- xe *= yc
- # result is now 10**(xe * 10**ye); xe * 10**ye must be integral
- while xe % 10 == 0:
- xe //= 10
- ye += 1
- if ye < 0:
- return None
- exponent = xe * 10**ye
- if y.sign == 1:
- exponent = -exponent
- # if other is a nonnegative integer, use ideal exponent
- if other._isinteger() and other._sign == 0:
- ideal_exponent = self._exp*int(other)
- zeros = min(exponent-ideal_exponent, p-1)
- else:
- zeros = 0
- return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
-
- # case where y is negative: xc must be either a power
- # of 2 or a power of 5.
- if y.sign == 1:
- last_digit = xc % 10
- if last_digit in (2,4,6,8):
- # quick test for power of 2
- if xc & -xc != xc:
- return None
- # now xc is a power of 2; e is its exponent
- e = _nbits(xc)-1
-
- # We now have:
- #
- # x = 2**e * 10**xe, e > 0, and y < 0.
- #
- # The exact result is:
- #
- # x**y = 5**(-e*y) * 10**(e*y + xe*y)
- #
- # provided that both e*y and xe*y are integers. Note that if
- # 5**(-e*y) >= 10**p, then the result can't be expressed
- # exactly with p digits of precision.
- #
- # Using the above, we can guard against large values of ye.
- # 93/65 is an upper bound for log(10)/log(5), so if
- #
- # ye >= len(str(93*p//65))
- #
- # then
- #
- # -e*y >= -y >= 10**ye > 93*p/65 > p*log(10)/log(5),
- #
- # so 5**(-e*y) >= 10**p, and the coefficient of the result
- # can't be expressed in p digits.
-
- # emax >= largest e such that 5**e < 10**p.
- emax = p*93//65
- if ye >= len(str(emax)):
- return None
-
- # Find -e*y and -xe*y; both must be integers
- e = _decimal_lshift_exact(e * yc, ye)
- xe = _decimal_lshift_exact(xe * yc, ye)
- if e is None or xe is None:
- return None
-
- if e > emax:
- return None
- xc = 5**e
-
- elif last_digit == 5:
- # e >= log_5(xc) if xc is a power of 5; we have
- # equality all the way up to xc=5**2658
- e = _nbits(xc)*28//65
- xc, remainder = divmod(5**e, xc)
- if remainder:
- return None
- while xc % 5 == 0:
- xc //= 5
- e -= 1
-
- # Guard against large values of ye, using the same logic as in
- # the 'xc is a power of 2' branch. 10/3 is an upper bound for
- # log(10)/log(2).
- emax = p*10//3
- if ye >= len(str(emax)):
- return None
-
- e = _decimal_lshift_exact(e * yc, ye)
- xe = _decimal_lshift_exact(xe * yc, ye)
- if e is None or xe is None:
- return None
-
- if e > emax:
- return None
- xc = 2**e
- else:
- return None
-
- if xc >= 10**p:
- return None
- xe = -e-xe
- return _dec_from_triple(0, str(xc), xe)
-
- # now y is positive; find m and n such that y = m/n
- if ye >= 0:
- m, n = yc*10**ye, 1
- else:
- if xe != 0 and len(str(abs(yc*xe))) <= -ye:
- return None
- xc_bits = _nbits(xc)
- if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
- return None
- m, n = yc, 10**(-ye)
- while m % 2 == n % 2 == 0:
- m //= 2
- n //= 2
- while m % 5 == n % 5 == 0:
- m //= 5
- n //= 5
-
- # compute nth root of xc*10**xe
- if n > 1:
- # if 1 < xc < 2**n then xc isn't an nth power
- if xc != 1 and xc_bits <= n:
- return None
-
- xe, rem = divmod(xe, n)
- if rem != 0:
- return None
-
- # compute nth root of xc using Newton's method
- a = 1 << -(-_nbits(xc)//n) # initial estimate
- while True:
- q, r = divmod(xc, a**(n-1))
- if a <= q:
- break
- else:
- a = (a*(n-1) + q)//n
- if not (a == q and r == 0):
- return None
- xc = a
-
- # now xc*10**xe is the nth root of the original xc*10**xe
- # compute mth power of xc*10**xe
-
- # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
- # 10**p and the result is not representable.
- if xc > 1 and m > p*100//_log10_lb(xc):
- return None
- xc = xc**m
- xe *= m
- if xc > 10**p:
- return None
-
- # by this point the result *is* exactly representable
- # adjust the exponent to get as close as possible to the ideal
- # exponent, if necessary
- str_xc = str(xc)
- if other._isinteger() and other._sign == 0:
- ideal_exponent = self._exp*int(other)
- zeros = min(xe-ideal_exponent, p-len(str_xc))
- else:
- zeros = 0
- return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
-
- def __pow__(self, other, modulo=None, context=None):
- """Return self ** other [ % modulo].
-
- With two arguments, compute self**other.
-
- With three arguments, compute (self**other) % modulo. For the
- three argument form, the following restrictions on the
- arguments hold:
-
- - all three arguments must be integral
- - other must be nonnegative
- - either self or other (or both) must be nonzero
- - modulo must be nonzero and must have at most p digits,
- where p is the context precision.
-
- If any of these restrictions is violated the InvalidOperation
- flag is raised.
-
- The result of pow(self, other, modulo) is identical to the
- result that would be obtained by computing (self**other) %
- modulo with unbounded precision, but is computed more
- efficiently. It is always exact.
- """
-
- if modulo is not None:
- return self._power_modulo(other, modulo, context)
-
- other = _convert_other(other)
- if other is NotImplemented:
- return other
-
- if context is None:
- context = getcontext()
-
- # either argument is a NaN => result is NaN
- ans = self._check_nans(other, context)
- if ans:
- return ans
-
- # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
- if not other:
- if not self:
- return context._raise_error(InvalidOperation, '0 ** 0')
- else:
- return _One
-
- # result has sign 1 iff self._sign is 1 and other is an odd integer
- result_sign = 0
- if self._sign == 1:
- if other._isinteger():
- if not other._iseven():
- result_sign = 1
- else:
- # -ve**noninteger = NaN
- # (-0)**noninteger = 0**noninteger
- if self:
- return context._raise_error(InvalidOperation,
- 'x ** y with x negative and y not an integer')
- # negate self, without doing any unwanted rounding
- self = self.copy_negate()
-
- # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
- if not self:
- if other._sign == 0:
- return _dec_from_triple(result_sign, '0', 0)
- else:
- return _SignedInfinity[result_sign]
-
- # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
- if self._isinfinity():
- if other._sign == 0:
- return _SignedInfinity[result_sign]
- else:
- return _dec_from_triple(result_sign, '0', 0)
-
- # 1**other = 1, but the choice of exponent and the flags
- # depend on the exponent of self, and on whether other is a
- # positive integer, a negative integer, or neither
- if self == _One:
- if other._isinteger():
- # exp = max(self._exp*max(int(other), 0),
- # 1-context.prec) but evaluating int(other) directly
- # is dangerous until we know other is small (other
- # could be 1e999999999)
- if other._sign == 1:
- multiplier = 0
- elif other > context.prec:
- multiplier = context.prec
- else:
- multiplier = int(other)
-
- exp = self._exp * multiplier
- if exp < 1-context.prec:
- exp = 1-context.prec
- context._raise_error(Rounded)
- else:
- context._raise_error(Inexact)
- context._raise_error(Rounded)
- exp = 1-context.prec
-
- return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
-
- # compute adjusted exponent of self
- self_adj = self.adjusted()
-
- # self ** infinity is infinity if self > 1, 0 if self < 1
- # self ** -infinity is infinity if self < 1, 0 if self > 1
- if other._isinfinity():
- if (other._sign == 0) == (self_adj < 0):
- return _dec_from_triple(result_sign, '0', 0)
- else:
- return _SignedInfinity[result_sign]
-
- # from here on, the result always goes through the call
- # to _fix at the end of this function.
- ans = None
- exact = False
-
- # crude test to catch cases of extreme overflow/underflow. If
- # log10(self)*other >= 10**bound and bound >= len(str(Emax))
- # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
- # self**other >= 10**(Emax+1), so overflow occurs. The test
- # for underflow is similar.
- bound = self._log10_exp_bound() + other.adjusted()
- if (self_adj >= 0) == (other._sign == 0):
- # self > 1 and other +ve, or self < 1 and other -ve
- # possibility of overflow
- if bound >= len(str(context.Emax)):
- ans = _dec_from_triple(result_sign, '1', context.Emax+1)
- else:
- # self > 1 and other -ve, or self < 1 and other +ve
- # possibility of underflow to 0
- Etiny = context.Etiny()
- if bound >= len(str(-Etiny)):
- ans = _dec_from_triple(result_sign, '1', Etiny-1)
-
- # try for an exact result with precision +1
- if ans is None:
- ans = self._power_exact(other, context.prec + 1)
- if ans is not None:
- if result_sign == 1:
- ans = _dec_from_triple(1, ans._int, ans._exp)
- exact = True
-
- # usual case: inexact result, x**y computed directly as exp(y*log(x))
- if ans is None:
- p = context.prec
- x = _WorkRep(self)
- xc, xe = x.int, x.exp
- y = _WorkRep(other)
- yc, ye = y.int, y.exp
- if y.sign == 1:
- yc = -yc
-
- # compute correctly rounded result: start with precision +3,
- # then increase precision until result is unambiguously roundable
- extra = 3
- while True:
- coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
- if coeff % (5*10**(len(str(coeff))-p-1)):
- break
- extra += 3
-
- ans = _dec_from_triple(result_sign, str(coeff), exp)
-
- # unlike exp, ln and log10, the power function respects the
- # rounding mode; no need to switch to ROUND_HALF_EVEN here
-
- # There's a difficulty here when 'other' is not an integer and
- # the result is exact. In this case, the specification
- # requires that the Inexact flag be raised (in spite of
- # exactness), but since the result is exact _fix won't do this
- # for us. (Correspondingly, the Underflow signal should also
- # be raised for subnormal results.) We can't directly raise
- # these signals either before or after calling _fix, since
- # that would violate the precedence for signals. So we wrap
- # the ._fix call in a temporary context, and reraise
- # afterwards.
- if exact and not other._isinteger():
- # pad with zeros up to length context.prec+1 if necessary; this
- # ensures that the Rounded signal will be raised.
- if len(ans._int) <= context.prec:
- expdiff = context.prec + 1 - len(ans._int)
- ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
- ans._exp-expdiff)
-
- # create a copy of the current context, with cleared flags/traps
- newcontext = context.copy()
- newcontext.clear_flags()
- for exception in _signals:
- newcontext.traps[exception] = 0
-
- # round in the new context
- ans = ans._fix(newcontext)
-
- # raise Inexact, and if necessary, Underflow
- newcontext._raise_error(Inexact)
- if newcontext.flags[Subnormal]:
- newcontext._raise_error(Underflow)
-
- # propagate signals to the original context; _fix could
- # have raised any of Overflow, Underflow, Subnormal,
- # Inexact, Rounded, Clamped. Overflow needs the correct
- # arguments. Note that the order of the exceptions is
- # important here.
- if newcontext.flags[Overflow]:
- context._raise_error(Overflow, 'above Emax', ans._sign)
- for exception in Underflow, Subnormal, Inexact, Rounded, Clamped:
- if newcontext.flags[exception]:
- context._raise_error(exception)
-
- else:
- ans = ans._fix(context)
-
- return ans
-
- def __rpow__(self, other, context=None):
- """Swaps self/other and returns __pow__."""
- other = _convert_other(other)
- if other is NotImplemented:
- return other
- return other.__pow__(self, context=context)
-
- def normalize(self, context=None):
- """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
-
- if context is None:
- context = getcontext()
-
- if self._is_special:
- ans = self._check_nans(context=context)
- if ans:
- return ans
-
- dup = self._fix(context)
- if dup._isinfinity():
- return dup
-
- if not dup:
- return _dec_from_triple(dup._sign, '0', 0)
- exp_max = [context.Emax, context.Etop()][context.clamp]
- end = len(dup._int)
- exp = dup._exp
- while dup._int[end-1] == '0' and exp < exp_max:
- exp += 1
- end -= 1
- return _dec_from_triple(dup._sign, dup._int[:end], exp)
-
- def quantize(self, exp, rounding=None, context=None):
- """Quantize self so its exponent is the same as that of exp.
-
- Similar to self._rescale(exp._exp) but with error checking.
- """
- exp = _convert_other(exp, raiseit=True)
-
- if context is None:
- context = getcontext()
- if rounding is None:
- rounding = context.rounding
-
- if self._is_special or exp._is_special:
- ans = self._check_nans(exp, context)
- if ans:
- return ans
-
- if exp._isinfinity() or self._isinfinity():
- if exp._isinfinity() and self._isinfinity():
- return Decimal(self) # if both are inf, it is OK
- return context._raise_error(InvalidOperation,
- 'quantize with one INF')
-
- # exp._exp should be between Etiny and Emax
- if not (context.Etiny() <= exp._exp <= context.Emax):
- return context._raise_error(InvalidOperation,
- 'target exponent out of bounds in quantize')
-
- if not self:
- ans = _dec_from_triple(self._sign, '0', exp._exp)
- return ans._fix(context)
-
- self_adjusted = self.adjusted()
- if self_adjusted > context.Emax:
- return context._raise_error(InvalidOperation,
- 'exponent of quantize result too large for current context')
- if self_adjusted - exp._exp + 1 > context.prec:
- return context._raise_error(InvalidOperation,
- 'quantize result has too many digits for current context')
-
- ans = self._rescale(exp._exp, rounding)
- if ans.adjusted() > context.Emax:
- return context._raise_error(InvalidOperation,
- 'exponent of quantize result too large for current context')
- if len(ans._int) > context.prec:
- return context._raise_error(InvalidOperation,
- 'quantize result has too many digits for current context')
-
- # raise appropriate flags
- if ans and ans.adjusted() < context.Emin:
- context._raise_error(Subnormal)
- if ans._exp > self._exp:
- if ans != self:
- context._raise_error(Inexact)
- context._raise_error(Rounded)
-
- # call to fix takes care of any necessary folddown, and
- # signals Clamped if necessary
- ans = ans._fix(context)
- return ans
-
- def same_quantum(self, other, context=None):
- """Return True if self and other have the same exponent; otherwise
- return False.
-
- If either operand is a special value, the following rules are used:
- * return True if both operands are infinities
- * return True if both operands are NaNs
- * otherwise, return False.
- """
- other = _convert_other(other, raiseit=True)
- if self._is_special or other._is_special:
- return (self.is_nan() and other.is_nan() or
- self.is_infinite() and other.is_infinite())
- return self._exp == other._exp
-
- def _rescale(self, exp, rounding):
- """Rescale self so that the exponent is exp, either by padding with zeros
- or by truncating digits, using the given rounding mode.
-
- Specials are returned without change. This operation is
- quiet: it raises no flags, and uses no information from the
- context.
-
- exp = exp to scale to (an integer)
- rounding = rounding mode
- """
- if self._is_special:
- return Decimal(self)
- if not self:
- return _dec_from_triple(self._sign, '0', exp)
-
- if self._exp >= exp:
- # pad answer with zeros if necessary
- return _dec_from_triple(self._sign,
- self._int + '0'*(self._exp - exp), exp)
-
- # too many digits; round and lose data. If self.adjusted() <
- # exp-1, replace self by 10**(exp-1) before rounding
- digits = len(self._int) + self._exp - exp
- if digits < 0:
- self = _dec_from_triple(self._sign, '1', exp-1)
- digits = 0
- this_function = self._pick_rounding_function[rounding]
- changed = this_function(self, digits)
- coeff = self._int[:digits] or '0'
- if changed == 1:
- coeff = str(int(coeff)+1)
- return _dec_from_triple(self._sign, coeff, exp)
-
- def _round(self, places, rounding):
- """Round a nonzero, nonspecial Decimal to a fixed number of
- significant figures, using the given rounding mode.
-
- Infinities, NaNs and zeros are returned unaltered.
-
- This operation is quiet: it raises no flags, and uses no
- information from the context.
-
- """
- if places <= 0:
- raise ValueError("argument should be at least 1 in _round")
- if self._is_special or not self:
- return Decimal(self)
- ans = self._rescale(self.adjusted()+1-places, rounding)
- # it can happen that the rescale alters the adjusted exponent;
- # for example when rounding 99.97 to 3 significant figures.
- # When this happens we end up with an extra 0 at the end of
- # the number; a second rescale fixes this.
- if ans.adjusted() != self.adjusted():
- ans = ans._rescale(ans.adjusted()+1-places, rounding)
- return ans
-
- def to_integral_exact(self, rounding=None, context=None):
- """Rounds to a nearby integer.
-
- If no rounding mode is specified, take the rounding mode from
- the context. This method raises the Rounded and Inexact flags
- when appropriate.
-
- See also: to_integral_value, which does exactly the same as
- this method except that it doesn't raise Inexact or Rounded.
- """
- if self._is_special:
- ans = self._check_nans(context=context)
- if ans:
- return ans
- return Decimal(self)
- if self._exp >= 0:
- return Decimal(self)
- if not self:
- return _dec_from_triple(self._sign, '0', 0)
- if context is None:
- context = getcontext()
- if rounding is None:
- rounding = context.rounding
- ans = self._rescale(0, rounding)
- if ans != self:
- context._raise_error(Inexact)
- context._raise_error(Rounded)
- return ans
-
- def to_integral_value(self, rounding=None, context=None):
- """Rounds to the nearest integer, without raising inexact, rounded."""
- if context is None:
- context = getcontext()
- if rounding is None:
- rounding = context.rounding
- if self._is_special:
- ans = self._check_nans(context=context)
- if ans:
- return ans
- return Decimal(self)
- if self._exp >= 0:
- return Decimal(self)
- else:
- return self._rescale(0, rounding)
-
- # the method name changed, but we provide also the old one, for compatibility
- to_integral = to_integral_value
-
- def sqrt(self, context=None):
- """Return the square root of self."""
- if context is None:
- context = getcontext()
-
- if self._is_special:
- ans = self._check_nans(context=context)
- if ans:
- return ans
-
- if self._isinfinity() and self._sign == 0:
- return Decimal(self)
-
- if not self:
- # exponent = self._exp // 2. sqrt(-0) = -0
- ans = _dec_from_triple(self._sign, '0', self._exp // 2)
- return ans._fix(context)
-
- if self._sign == 1:
- return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
-
- # At this point self represents a positive number. Let p be
- # the desired precision and express self in the form c*100**e
- # with c a positive real number and e an integer, c and e
- # being chosen so that 100**(p-1) <= c < 100**p. Then the
- # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
- # <= sqrt(c) < 10**p, so the closest representable Decimal at
- # precision p is n*10**e where n = round_half_even(sqrt(c)),
- # the closest integer to sqrt(c) with the even integer chosen
- # in the case of a tie.
- #
- # To ensure correct rounding in all cases, we use the
- # following trick: we compute the square root to an extra
- # place (precision p+1 instead of precision p), rounding down.
- # Then, if the result is inexact and its last digit is 0 or 5,
- # we increase the last digit to 1 or 6 respectively; if it's
- # exact we leave the last digit alone. Now the final round to
- # p places (or fewer in the case of underflow) will round
- # correctly and raise the appropriate flags.
-
- # use an extra digit of precision
- prec = context.prec+1
-
- # write argument in the form c*100**e where e = self._exp//2
- # is the 'ideal' exponent, to be used if the square root is
- # exactly representable. l is the number of 'digits' of c in
- # base 100, so that 100**(l-1) <= c < 100**l.
- op = _WorkRep(self)
- e = op.exp >> 1
- if op.exp & 1:
- c = op.int * 10
- l = (len(self._int) >> 1) + 1
- else:
- c = op.int
- l = len(self._int)+1 >> 1
-
- # rescale so that c has exactly prec base 100 'digits'
- shift = prec-l
- if shift >= 0:
- c *= 100**shift
- exact = True
- else:
- c, remainder = divmod(c, 100**-shift)
- exact = not remainder
- e -= shift
-
- # find n = floor(sqrt(c)) using Newton's method
- n = 10**prec
- while True:
- q = c//n
- if n <= q:
- break
- else:
- n = n + q >> 1
- exact = exact and n*n == c
-
- if exact:
- # result is exact; rescale to use ideal exponent e
- if shift >= 0:
- # assert n % 10**shift == 0
- n //= 10**shift
- else:
- n *= 10**-shift
- e += shift
- else:
- # result is not exact; fix last digit as described above
- if n % 5 == 0:
- n += 1
-
- ans = _dec_from_triple(0, str(n), e)
-
- # round, and fit to current context
- context = context._shallow_copy()
- rounding = context._set_rounding(ROUND_HALF_EVEN)
- ans = ans._fix(context)
- context.rounding = rounding
-
- return ans
-
- def max(self, other, context=None):
- """Returns the larger value.
-
- Like max(self, other) except if one is not a number, returns
- NaN (and signals if one is sNaN). Also rounds.
- """
- other = _convert_other(other, raiseit=True)
-
- if context is None:
- context = getcontext()
-
- if self._is_special or other._is_special:
- # If one operand is a quiet NaN and the other is number, then the
- # number is always returned
- sn = self._isnan()
- on = other._isnan()
- if sn or on:
- if on == 1 and sn == 0:
- return self._fix(context)
- if sn == 1 and on == 0:
- return other._fix(context)
- return self._check_nans(other, context)
-
- c = self._cmp(other)
- if c == 0:
- # If both operands are finite and equal in numerical value
- # then an ordering is applied:
- #
- # If the signs differ then max returns the operand with the
- # positive sign and min returns the operand with the negative sign
- #
- # If the signs are the same then the exponent is used to select
- # the result. This is exactly the ordering used in compare_total.
- c = self.compare_total(other)
-
- if c == -1:
- ans = other
- else:
- ans = self
-
- return ans._fix(context)
-
- def min(self, other, context=None):
- """Returns the smaller value.
-
- Like min(self, other) except if one is not a number, returns
- NaN (and signals if one is sNaN). Also rounds.
- """
- other = _convert_other(other, raiseit=True)
-
- if context is None:
- context = getcontext()
-
- if self._is_special or other._is_special:
- # If one operand is a quiet NaN and the other is number, then the
- # number is always returned
- sn = self._isnan()
- on = other._isnan()
- if sn or on:
- if on == 1 and sn == 0:
- return self._fix(context)
- if sn == 1 and on == 0:
- return other._fix(context)
- return self._check_nans(other, context)
-
- c = self._cmp(other)
- if c == 0:
- c = self.compare_total(other)
-
- if c == -1:
- ans = self
- else:
- ans = other
-
- return ans._fix(context)
-
- def _isinteger(self):
- """Returns whether self is an integer"""
- if self._is_special:
- return False
- if self._exp >= 0:
- return True
- rest = self._int[self._exp:]
- return rest == '0'*len(rest)
-
- def _iseven(self):
- """Returns True if self is even. Assumes self is an integer."""
- if not self or self._exp > 0:
- return True
- return self._int[-1+self._exp] in '02468'
-
- def adjusted(self):
- """Return the adjusted exponent of self"""
- try:
- return self._exp + len(self._int) - 1
- # If NaN or Infinity, self._exp is string
- except TypeError:
- return 0
-
- def canonical(self):
- """Returns the same Decimal object.
-
- As we do not have different encodings for the same number, the
- received object already is in its canonical form.
- """
- return self
-
- def compare_signal(self, other, context=None):
- """Compares self to the other operand numerically.
-
- It's pretty much like compare(), but all NaNs signal, with signaling
- NaNs taking precedence over quiet NaNs.
- """
- other = _convert_other(other, raiseit = True)
- ans = self._compare_check_nans(other, context)
- if ans:
- return ans
- return self.compare(other, context=context)
-
- def compare_total(self, other, context=None):
- """Compares self to other using the abstract representations.
-
- This is not like the standard compare, which use their numerical
- value. Note that a total ordering is defined for all possible abstract
- representations.
- """
- other = _convert_other(other, raiseit=True)
-
- # if one is negative and the other is positive, it's easy
- if self._sign and not other._sign:
- return _NegativeOne
- if not self._sign and other._sign:
- return _One
- sign = self._sign
-
- # let's handle both NaN types
- self_nan = self._isnan()
- other_nan = other._isnan()
- if self_nan or other_nan:
- if self_nan == other_nan:
- # compare payloads as though they're integers
- self_key = len(self._int), self._int
- other_key = len(other._int), other._int
- if self_key < other_key:
- if sign:
- return _One
- else:
- return _NegativeOne
- if self_key > other_key:
- if sign:
- return _NegativeOne
- else:
- return _One
- return _Zero
-
- if sign:
- if self_nan == 1:
- return _NegativeOne
- if other_nan == 1:
- return _One
- if self_nan == 2:
- return _NegativeOne
- if other_nan == 2:
- return _One
- else:
- if self_nan == 1:
- return _One
- if other_nan == 1:
- return _NegativeOne
- if self_nan == 2:
- return _One
- if other_nan == 2:
- return _NegativeOne
-
- if self < other:
- return _NegativeOne
- if self > other:
- return _One
-
- if self._exp < other._exp:
- if sign:
- return _One
- else:
- return _NegativeOne
- if self._exp > other._exp:
- if sign:
- return _NegativeOne
- else:
- return _One
- return _Zero
-
-
- def compare_total_mag(self, other, context=None):
- """Compares self to other using abstract repr., ignoring sign.
-
- Like compare_total, but with operand's sign ignored and assumed to be 0.
- """
- other = _convert_other(other, raiseit=True)
-
- s = self.copy_abs()
- o = other.copy_abs()
- return s.compare_total(o)
-
- def copy_abs(self):
- """Returns a copy with the sign set to 0. """
- return _dec_from_triple(0, self._int, self._exp, self._is_special)
-
- def copy_negate(self):
- """Returns a copy with the sign inverted."""
- if self._sign:
- return _dec_from_triple(0, self._int, self._exp, self._is_special)
- else:
- return _dec_from_triple(1, self._int, self._exp, self._is_special)
-
- def copy_sign(self, other, context=None):
- """Returns self with the sign of other."""
- other = _convert_other(other, raiseit=True)
- return _dec_from_triple(other._sign, self._int,
- self._exp, self._is_special)
-
- def exp(self, context=None):
- """Returns e ** self."""
-
- if context is None:
- context = getcontext()
-
- # exp(NaN) = NaN
- ans = self._check_nans(context=context)
- if ans:
- return ans
-
- # exp(-Infinity) = 0
- if self._isinfinity() == -1:
- return _Zero
-
- # exp(0) = 1
- if not self:
- return _One
-
- # exp(Infinity) = Infinity
- if self._isinfinity() == 1:
- return Decimal(self)
-
- # the result is now guaranteed to be inexact (the true
- # mathematical result is transcendental). There's no need to
- # raise Rounded and Inexact here---they'll always be raised as
- # a result of the call to _fix.
- p = context.prec
- adj = self.adjusted()
-
- # we only need to do any computation for quite a small range
- # of adjusted exponents---for example, -29 <= adj <= 10 for
- # the default context. For smaller exponent the result is
- # indistinguishable from 1 at the given precision, while for
- # larger exponent the result either overflows or underflows.
- if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
- # overflow
- ans = _dec_from_triple(0, '1', context.Emax+1)
- elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
- # underflow to 0
- ans = _dec_from_triple(0, '1', context.Etiny()-1)
- elif self._sign == 0 and adj < -p:
- # p+1 digits; final round will raise correct flags
- ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
- elif self._sign == 1 and adj < -p-1:
- # p+1 digits; final round will raise correct flags
- ans = _dec_from_triple(0, '9'*(p+1), -p-1)
- # general case
- else:
- op = _WorkRep(self)
- c, e = op.int, op.exp
- if op.sign == 1:
- c = -c
-
- # compute correctly rounded result: increase precision by
- # 3 digits at a time until we get an unambiguously
- # roundable result
- extra = 3
- while True:
- coeff, exp = _dexp(c, e, p+extra)
- if coeff % (5*10**(len(str(coeff))-p-1)):
- break
- extra += 3
-
- ans = _dec_from_triple(0, str(coeff), exp)
-
- # at this stage, ans should round correctly with *any*
- # rounding mode, not just with ROUND_HALF_EVEN
- context = context._shallow_copy()
- rounding = context._set_rounding(ROUND_HALF_EVEN)
- ans = ans._fix(context)
- context.rounding = rounding
-
- return ans
-
- def is_canonical(self):
- """Return True if self is canonical; otherwise return False.
-
- Currently, the encoding of a Decimal instance is always
- canonical, so this method returns True for any Decimal.
- """
- return True
-
- def is_finite(self):
- """Return True if self is finite; otherwise return False.
-
- A Decimal instance is considered finite if it is neither
- infinite nor a NaN.
- """
- return not self._is_special
-
- def is_infinite(self):
- """Return True if self is infinite; otherwise return False."""
- return self._exp == 'F'
-
- def is_nan(self):
- """Return True if self is a qNaN or sNaN; otherwise return False."""
- return self._exp in ('n', 'N')
-
- def is_normal(self, context=None):
- """Return True if self is a normal number; otherwise return False."""
- if self._is_special or not self:
- return False
- if context is None:
- context = getcontext()
- return context.Emin <= self.adjusted()
-
- def is_qnan(self):
- """Return True if self is a quiet NaN; otherwise return False."""
- return self._exp == 'n'
-
- def is_signed(self):
- """Return True if self is negative; otherwise return False."""
- return self._sign == 1
-
- def is_snan(self):
- """Return True if self is a signaling NaN; otherwise return False."""
- return self._exp == 'N'
-
- def is_subnormal(self, context=None):
- """Return True if self is subnormal; otherwise return False."""
- if self._is_special or not self:
- return False
- if context is None:
- context = getcontext()
- return self.adjusted() < context.Emin
-
- def is_zero(self):
- """Return True if self is a zero; otherwise return False."""
- return not self._is_special and self._int == '0'
-
- def _ln_exp_bound(self):
- """Compute a lower bound for the adjusted exponent of self.ln().
- In other words, compute r such that self.ln() >= 10**r. Assumes
- that self is finite and positive and that self != 1.
- """
-
- # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
- adj = self._exp + len(self._int) - 1
- if adj >= 1:
- # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
- return len(str(adj*23//10)) - 1
- if adj <= -2:
- # argument <= 0.1
- return len(str((-1-adj)*23//10)) - 1
- op = _WorkRep(self)
- c, e = op.int, op.exp
- if adj == 0:
- # 1 < self < 10
- num = str(c-10**-e)
- den = str(c)
- return len(num) - len(den) - (num < den)
- # adj == -1, 0.1 <= self < 1
- return e + len(str(10**-e - c)) - 1
-
-
- def ln(self, context=None):
- """Returns the natural (base e) logarithm of self."""
-
- if context is None:
- context = getcontext()
-
- # ln(NaN) = NaN
- ans = self._check_nans(context=context)
- if ans:
- return ans
-
- # ln(0.0) == -Infinity
- if not self:
- return _NegativeInfinity
-
- # ln(Infinity) = Infinity
- if self._isinfinity() == 1:
- return _Infinity
-
- # ln(1.0) == 0.0
- if self == _One:
- return _Zero
-
- # ln(negative) raises InvalidOperation
- if self._sign == 1:
- return context._raise_error(InvalidOperation,
- 'ln of a negative value')
-
- # result is irrational, so necessarily inexact
- op = _WorkRep(self)
- c, e = op.int, op.exp
- p = context.prec
-
- # correctly rounded result: repeatedly increase precision by 3
- # until we get an unambiguously roundable result
- places = p - self._ln_exp_bound() + 2 # at least p+3 places
- while True:
- coeff = _dlog(c, e, places)
- # assert len(str(abs(coeff)))-p >= 1
- if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
- break
- places += 3
- ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
-
- context = context._shallow_copy()
- rounding = context._set_rounding(ROUND_HALF_EVEN)
- ans = ans._fix(context)
- context.rounding = rounding
- return ans
-
- def _log10_exp_bound(self):
- """Compute a lower bound for the adjusted exponent of self.log10().
- In other words, find r such that self.log10() >= 10**r.
- Assumes that self is finite and positive and that self != 1.
- """
-
- # For x >= 10 or x < 0.1 we only need a bound on the integer
- # part of log10(self), and this comes directly from the
- # exponent of x. For 0.1 <= x <= 10 we use the inequalities
- # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
- # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
-
- adj = self._exp + len(self._int) - 1
- if adj >= 1:
- # self >= 10
- return len(str(adj))-1
- if adj <= -2:
- # self < 0.1
- return len(str(-1-adj))-1
- op = _WorkRep(self)
- c, e = op.int, op.exp
- if adj == 0:
- # 1 < self < 10
- num = str(c-10**-e)
- den = str(231*c)
- return len(num) - len(den) - (num < den) + 2
- # adj == -1, 0.1 <= self < 1
- num = str(10**-e-c)
- return len(num) + e - (num < "231") - 1
-
- def log10(self, context=None):
- """Returns the base 10 logarithm of self."""
-
- if context is None:
- context = getcontext()
-
- # log10(NaN) = NaN
- ans = self._check_nans(context=context)
- if ans:
- return ans
-
- # log10(0.0) == -Infinity
- if not self:
- return _NegativeInfinity
-
- # log10(Infinity) = Infinity
- if self._isinfinity() == 1:
- return _Infinity
-
- # log10(negative or -Infinity) raises InvalidOperation
- if self._sign == 1:
- return context._raise_error(InvalidOperation,
- 'log10 of a negative value')
-
- # log10(10**n) = n
- if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
- # answer may need rounding
- ans = Decimal(self._exp + len(self._int) - 1)
- else:
- # result is irrational, so necessarily inexact
- op = _WorkRep(self)
- c, e = op.int, op.exp
- p = context.prec
-
- # correctly rounded result: repeatedly increase precision
- # until result is unambiguously roundable
- places = p-self._log10_exp_bound()+2
- while True:
- coeff = _dlog10(c, e, places)
- # assert len(str(abs(coeff)))-p >= 1
- if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
- break
- places += 3
- ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
-
- context = context._shallow_copy()
- rounding = context._set_rounding(ROUND_HALF_EVEN)
- ans = ans._fix(context)
- context.rounding = rounding
- return ans
-
- def logb(self, context=None):
- """ Returns the exponent of the magnitude of self's MSD.
-
- The result is the integer which is the exponent of the magnitude
- of the most significant digit of self (as though it were truncated
- to a single digit while maintaining the value of that digit and
- without limiting the resulting exponent).
- """
- # logb(NaN) = NaN
- ans = self._check_nans(context=context)
- if ans:
- return ans
-
- if context is None:
- context = getcontext()
-
- # logb(+/-Inf) = +Inf
- if self._isinfinity():
- return _Infinity
-
- # logb(0) = -Inf, DivisionByZero
- if not self:
- return context._raise_error(DivisionByZero, 'logb(0)', 1)
-
- # otherwise, simply return the adjusted exponent of self, as a
- # Decimal. Note that no attempt is made to fit the result
- # into the current context.
- ans = Decimal(self.adjusted())
- return ans._fix(context)
-
- def _islogical(self):
- """Return True if self is a logical operand.
-
- For being logical, it must be a finite number with a sign of 0,
- an exponent of 0, and a coefficient whose digits must all be
- either 0 or 1.
- """
- if self._sign != 0 or self._exp != 0:
- return False
- for dig in self._int:
- if dig not in '01':
- return False
- return True
-
- def _fill_logical(self, context, opa, opb):
- dif = context.prec - len(opa)
- if dif > 0:
- opa = '0'*dif + opa
- elif dif < 0:
- opa = opa[-context.prec:]
- dif = context.prec - len(opb)
- if dif > 0:
- opb = '0'*dif + opb
- elif dif < 0:
- opb = opb[-context.prec:]
- return opa, opb
-
- def logical_and(self, other, context=None):
- """Applies an 'and' operation between self and other's digits."""
- if context is None:
- context = getcontext()
-
- other = _convert_other(other, raiseit=True)
-
- if not self._islogical() or not other._islogical():
- return context._raise_error(InvalidOperation)
-
- # fill to context.prec
- (opa, opb) = self._fill_logical(context, self._int, other._int)
-
- # make the operation, and clean starting zeroes
- result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
- return _dec_from_triple(0, result.lstrip('0') or '0', 0)
-
- def logical_invert(self, context=None):
- """Invert all its digits."""
- if context is None:
- context = getcontext()
- return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
- context)
-
- def logical_or(self, other, context=None):
- """Applies an 'or' operation between self and other's digits."""
- if context is None:
- context = getcontext()
-
- other = _convert_other(other, raiseit=True)
-
- if not self._islogical() or not other._islogical():
- return context._raise_error(InvalidOperation)
-
- # fill to context.prec
- (opa, opb) = self._fill_logical(context, self._int, other._int)
-
- # make the operation, and clean starting zeroes
- result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
- return _dec_from_triple(0, result.lstrip('0') or '0', 0)
-
- def logical_xor(self, other, context=None):
- """Applies an 'xor' operation between self and other's digits."""
- if context is None:
- context = getcontext()
-
- other = _convert_other(other, raiseit=True)
-
- if not self._islogical() or not other._islogical():
- return context._raise_error(InvalidOperation)
-
- # fill to context.prec
- (opa, opb) = self._fill_logical(context, self._int, other._int)
-
- # make the operation, and clean starting zeroes
- result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
- return _dec_from_triple(0, result.lstrip('0') or '0', 0)
-
- def max_mag(self, other, context=None):
- """Compares the values numerically with their sign ignored."""
- other = _convert_other(other, raiseit=True)
-
- if context is None:
- context = getcontext()
-
- if self._is_special or other._is_special:
- # If one operand is a quiet NaN and the other is number, then the
- # number is always returned
- sn = self._isnan()
- on = other._isnan()
- if sn or on:
- if on == 1 and sn == 0:
- return self._fix(context)
- if sn == 1 and on == 0:
- return other._fix(context)
- return self._check_nans(other, context)
-
- c = self.copy_abs()._cmp(other.copy_abs())
- if c == 0:
- c = self.compare_total(other)
-
- if c == -1:
- ans = other
- else:
- ans = self
-
- return ans._fix(context)
-
- def min_mag(self, other, context=None):
- """Compares the values numerically with their sign ignored."""
- other = _convert_other(other, raiseit=True)
-
- if context is None:
- context = getcontext()
-
- if self._is_special or other._is_special:
- # If one operand is a quiet NaN and the other is number, then the
- # number is always returned
- sn = self._isnan()
- on = other._isnan()
- if sn or on:
- if on == 1 and sn == 0:
- return self._fix(context)
- if sn == 1 and on == 0:
- return other._fix(context)
- return self._check_nans(other, context)
-
- c = self.copy_abs()._cmp(other.copy_abs())
- if c == 0:
- c = self.compare_total(other)
-
- if c == -1:
- ans = self
- else:
- ans = other
-
- return ans._fix(context)
-
- def next_minus(self, context=None):
- """Returns the largest representable number smaller than itself."""
- if context is None:
- context = getcontext()
-
- ans = self._check_nans(context=context)
- if ans:
- return ans
-
- if self._isinfinity() == -1:
- return _NegativeInfinity
- if self._isinfinity() == 1:
- return _dec_from_triple(0, '9'*context.prec, context.Etop())
-
- context = context.copy()
- context._set_rounding(ROUND_FLOOR)
- context._ignore_all_flags()
- new_self = self._fix(context)
- if new_self != self:
- return new_self
- return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
- context)
-
- def next_plus(self, context=None):
- """Returns the smallest representable number larger than itself."""
- if context is None:
- context = getcontext()
-
- ans = self._check_nans(context=context)
- if ans:
- return ans
-
- if self._isinfinity() == 1:
- return _Infinity
- if self._isinfinity() == -1:
- return _dec_from_triple(1, '9'*context.prec, context.Etop())
-
- context = context.copy()
- context._set_rounding(ROUND_CEILING)
- context._ignore_all_flags()
- new_self = self._fix(context)
- if new_self != self:
- return new_self
- return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
- context)
-
- def next_toward(self, other, context=None):
- """Returns the number closest to self, in the direction towards other.
-
- The result is the closest representable number to self
- (excluding self) that is in the direction towards other,
- unless both have the same value. If the two operands are
- numerically equal, then the result is a copy of self with the
- sign set to be the same as the sign of other.
- """
- other = _convert_other(other, raiseit=True)
-
- if context is None:
- context = getcontext()
-
- ans = self._check_nans(other, context)
- if ans:
- return ans
-
- comparison = self._cmp(other)
- if comparison == 0:
- return self.copy_sign(other)
-
- if comparison == -1:
- ans = self.next_plus(context)
- else: # comparison == 1
- ans = self.next_minus(context)
-
- # decide which flags to raise using value of ans
- if ans._isinfinity():
- context._raise_error(Overflow,
- 'Infinite result from next_toward',
- ans._sign)
- context._raise_error(Inexact)
- context._raise_error(Rounded)
- elif ans.adjusted() < context.Emin:
- context._raise_error(Underflow)
- context._raise_error(Subnormal)
- context._raise_error(Inexact)
- context._raise_error(Rounded)
- # if precision == 1 then we don't raise Clamped for a
- # result 0E-Etiny.
- if not ans:
- context._raise_error(Clamped)
-
- return ans
-
- def number_class(self, context=None):
- """Returns an indication of the class of self.
-
- The class is one of the following strings:
- sNaN
- NaN
- -Infinity
- -Normal
- -Subnormal
- -Zero
- +Zero
- +Subnormal
- +Normal
- +Infinity
- """
- if self.is_snan():
- return "sNaN"
- if self.is_qnan():
- return "NaN"
- inf = self._isinfinity()
- if inf == 1:
- return "+Infinity"
- if inf == -1:
- return "-Infinity"
- if self.is_zero():
- if self._sign:
- return "-Zero"
- else:
- return "+Zero"
- if context is None:
- context = getcontext()
- if self.is_subnormal(context=context):
- if self._sign:
- return "-Subnormal"
- else:
- return "+Subnormal"
- # just a normal, regular, boring number, :)
- if self._sign:
- return "-Normal"
- else:
- return "+Normal"
-
- def radix(self):
- """Just returns 10, as this is Decimal, :)"""
- return Decimal(10)
-
- def rotate(self, other, context=None):
- """Returns a rotated copy of self, value-of-other times."""
- if context is None:
- context = getcontext()
-
- other = _convert_other(other, raiseit=True)
-
- ans = self._check_nans(other, context)
- if ans:
- return ans
-
- if other._exp != 0:
- return context._raise_error(InvalidOperation)
- if not (-context.prec <= int(other) <= context.prec):
- return context._raise_error(InvalidOperation)
-
- if self._isinfinity():
- return Decimal(self)
-
- # get values, pad if necessary
- torot = int(other)
- rotdig = self._int
- topad = context.prec - len(rotdig)
- if topad > 0:
- rotdig = '0'*topad + rotdig
- elif topad < 0:
- rotdig = rotdig[-topad:]
-
- # let's rotate!
- rotated = rotdig[torot:] + rotdig[:torot]
- return _dec_from_triple(self._sign,
- rotated.lstrip('0') or '0', self._exp)
-
- def scaleb(self, other, context=None):
- """Returns self operand after adding the second value to its exp."""
- if context is None:
- context = getcontext()
-
- other = _convert_other(other, raiseit=True)
-
- ans = self._check_nans(other, context)
- if ans:
- return ans
-
- if other._exp != 0:
- return context._raise_error(InvalidOperation)
- liminf = -2 * (context.Emax + context.prec)
- limsup = 2 * (context.Emax + context.prec)
- if not (liminf <= int(other) <= limsup):
- return context._raise_error(InvalidOperation)
-
- if self._isinfinity():
- return Decimal(self)
-
- d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
- d = d._fix(context)
- return d
-
- def shift(self, other, context=None):
- """Returns a shifted copy of self, value-of-other times."""
- if context is None:
- context = getcontext()
-
- other = _convert_other(other, raiseit=True)
-
- ans = self._check_nans(other, context)
- if ans:
- return ans
-
- if other._exp != 0:
- return context._raise_error(InvalidOperation)
- if not (-context.prec <= int(other) <= context.prec):
- return context._raise_error(InvalidOperation)
-
- if self._isinfinity():
- return Decimal(self)
-
- # get values, pad if necessary
- torot = int(other)
- rotdig = self._int
- topad = context.prec - len(rotdig)
- if topad > 0:
- rotdig = '0'*topad + rotdig
- elif topad < 0:
- rotdig = rotdig[-topad:]
-
- # let's shift!
- if torot < 0:
- shifted = rotdig[:torot]
- else:
- shifted = rotdig + '0'*torot
- shifted = shifted[-context.prec:]
-
- return _dec_from_triple(self._sign,
- shifted.lstrip('0') or '0', self._exp)
-
- # Support for pickling, copy, and deepcopy
- def __reduce__(self):
- return (self.__class__, (str(self),))
-
- def __copy__(self):
- if type(self) is Decimal:
- return self # I'm immutable; therefore I am my own clone
- return self.__class__(str(self))
-
- def __deepcopy__(self, memo):
- if type(self) is Decimal:
- return self # My components are also immutable
- return self.__class__(str(self))
-
- # PEP 3101 support. the _localeconv keyword argument should be
- # considered private: it's provided for ease of testing only.
- def __format__(self, specifier, context=None, _localeconv=None):
- """Format a Decimal instance according to the given specifier.
-
- The specifier should be a standard format specifier, with the
- form described in PEP 3101. Formatting types 'e', 'E', 'f',
- 'F', 'g', 'G', 'n' and '%' are supported. If the formatting
- type is omitted it defaults to 'g' or 'G', depending on the
- value of context.capitals.
- """
-
- # Note: PEP 3101 says that if the type is not present then
- # there should be at least one digit after the decimal point.
- # We take the liberty of ignoring this requirement for
- # Decimal---it's presumably there to make sure that
- # format(float, '') behaves similarly to str(float).
- if context is None:
- context = getcontext()
-
- spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
-
- # special values don't care about the type or precision
- if self._is_special:
- sign = _format_sign(self._sign, spec)
- body = str(self.copy_abs())
- if spec['type'] == '%':
- body += '%'
- return _format_align(sign, body, spec)
-
- # a type of None defaults to 'g' or 'G', depending on context
- if spec['type'] is None:
- spec['type'] = ['g', 'G'][context.capitals]
-
- # if type is '%', adjust exponent of self accordingly
- if spec['type'] == '%':
- self = _dec_from_triple(self._sign, self._int, self._exp+2)
-
- # round if necessary, taking rounding mode from the context
- rounding = context.rounding
- precision = spec['precision']
- if precision is not None:
- if spec['type'] in 'eE':
- self = self._round(precision+1, rounding)
- elif spec['type'] in 'fF%':
- self = self._rescale(-precision, rounding)
- elif spec['type'] in 'gG' and len(self._int) > precision:
- self = self._round(precision, rounding)
- # special case: zeros with a positive exponent can't be
- # represented in fixed point; rescale them to 0e0.
- if not self and self._exp > 0 and spec['type'] in 'fF%':
- self = self._rescale(0, rounding)
-
- # figure out placement of the decimal point
- leftdigits = self._exp + len(self._int)
- if spec['type'] in 'eE':
- if not self and precision is not None:
- dotplace = 1 - precision
- else:
- dotplace = 1
- elif spec['type'] in 'fF%':
- dotplace = leftdigits
- elif spec['type'] in 'gG':
- if self._exp <= 0 and leftdigits > -6:
- dotplace = leftdigits
- else:
- dotplace = 1
-
- # find digits before and after decimal point, and get exponent
- if dotplace < 0:
- intpart = '0'
- fracpart = '0'*(-dotplace) + self._int
- elif dotplace > len(self._int):
- intpart = self._int + '0'*(dotplace-len(self._int))
- fracpart = ''
- else:
- intpart = self._int[:dotplace] or '0'
- fracpart = self._int[dotplace:]
- exp = leftdigits-dotplace
-
- # done with the decimal-specific stuff; hand over the rest
- # of the formatting to the _format_number function
- return _format_number(self._sign, intpart, fracpart, exp, spec)
-
-def _dec_from_triple(sign, coefficient, exponent, special=False):
- """Create a decimal instance directly, without any validation,
- normalization (e.g. removal of leading zeros) or argument
- conversion.
-
- This function is for *internal use only*.
- """
-
- self = object.__new__(Decimal)
- self._sign = sign
- self._int = coefficient
- self._exp = exponent
- self._is_special = special
-
- return self
-
-# Register Decimal as a kind of Number (an abstract base class).
-# However, do not register it as Real (because Decimals are not
-# interoperable with floats).
-_numbers.Number.register(Decimal)
-
-
-##### Context class #######################################################
-
-class _ContextManager(object):
- """Context manager class to support localcontext().
-
- Sets a copy of the supplied context in __enter__() and restores
- the previous decimal context in __exit__()
- """
- def __init__(self, new_context):
- self.new_context = new_context.copy()
- def __enter__(self):
- self.saved_context = getcontext()
- setcontext(self.new_context)
- return self.new_context
- def __exit__(self, t, v, tb):
- setcontext(self.saved_context)
-
-class Context(object):
- """Contains the context for a Decimal instance.
-
- Contains:
- prec - precision (for use in rounding, division, square roots..)
- rounding - rounding type (how you round)
- traps - If traps[exception] = 1, then the exception is
- raised when it is caused. Otherwise, a value is
- substituted in.
- flags - When an exception is caused, flags[exception] is set.
- (Whether or not the trap_enabler is set)
- Should be reset by user of Decimal instance.
- Emin - Minimum exponent
- Emax - Maximum exponent
- capitals - If 1, 1*10^1 is printed as 1E+1.
- If 0, printed as 1e1
- clamp - If 1, change exponents if too high (Default 0)
- """
-
- def __init__(self, prec=None, rounding=None, Emin=None, Emax=None,
- capitals=None, clamp=None, flags=None, traps=None,
- _ignored_flags=None):
- # Set defaults; for everything except flags and _ignored_flags,
- # inherit from DefaultContext.
- try:
- dc = DefaultContext
- except NameError:
- pass
-
- self.prec = prec if prec is not None else dc.prec
- self.rounding = rounding if rounding is not None else dc.rounding
- self.Emin = Emin if Emin is not None else dc.Emin
- self.Emax = Emax if Emax is not None else dc.Emax
- self.capitals = capitals if capitals is not None else dc.capitals
- self.clamp = clamp if clamp is not None else dc.clamp
-
- if _ignored_flags is None:
- self._ignored_flags = []
- else:
- self._ignored_flags = _ignored_flags
-
- if traps is None:
- self.traps = dc.traps.copy()
- elif not isinstance(traps, dict):
- self.traps = dict((s, int(s in traps)) for s in _signals + traps)
- else:
- self.traps = traps
-
- if flags is None:
- self.flags = dict.fromkeys(_signals, 0)
- elif not isinstance(flags, dict):
- self.flags = dict((s, int(s in flags)) for s in _signals + flags)
- else:
- self.flags = flags
-
- def _set_integer_check(self, name, value, vmin, vmax):
- if not isinstance(value, int):
- raise TypeError("%s must be an integer" % name)
- if vmin == '-inf':
- if value > vmax:
- raise ValueError("%s must be in [%s, %d]. got: %s" % (name, vmin, vmax, value))
- elif vmax == 'inf':
- if value < vmin:
- raise ValueError("%s must be in [%d, %s]. got: %s" % (name, vmin, vmax, value))
- else:
- if value < vmin or value > vmax:
- raise ValueError("%s must be in [%d, %d]. got %s" % (name, vmin, vmax, value))
- return object.__setattr__(self, name, value)
-
- def _set_signal_dict(self, name, d):
- if not isinstance(d, dict):
- raise TypeError("%s must be a signal dict" % d)
- for key in d:
- if not key in _signals:
- raise KeyError("%s is not a valid signal dict" % d)
- for key in _signals:
- if not key in d:
- raise KeyError("%s is not a valid signal dict" % d)
- return object.__setattr__(self, name, d)
-
- def __setattr__(self, name, value):
- if name == 'prec':
- return self._set_integer_check(name, value, 1, 'inf')
- elif name == 'Emin':
- return self._set_integer_check(name, value, '-inf', 0)
- elif name == 'Emax':
- return self._set_integer_check(name, value, 0, 'inf')
- elif name == 'capitals':
- return self._set_integer_check(name, value, 0, 1)
- elif name == 'clamp':
- return self._set_integer_check(name, value, 0, 1)
- elif name == 'rounding':
- if not value in _rounding_modes:
- # raise TypeError even for strings to have consistency
- # among various implementations.
- raise TypeError("%s: invalid rounding mode" % value)
- return object.__setattr__(self, name, value)
- elif name == 'flags' or name == 'traps':
- return self._set_signal_dict(name, value)
- elif name == '_ignored_flags':
- return object.__setattr__(self, name, value)
- else:
- raise AttributeError(
- "'decimal.Context' object has no attribute '%s'" % name)
-
- def __delattr__(self, name):
- raise AttributeError("%s cannot be deleted" % name)
-
- # Support for pickling, copy, and deepcopy
- def __reduce__(self):
- flags = [sig for sig, v in self.flags.items() if v]
- traps = [sig for sig, v in self.traps.items() if v]
- return (self.__class__,
- (self.prec, self.rounding, self.Emin, self.Emax,
- self.capitals, self.clamp, flags, traps))
-
- def __repr__(self):
- """Show the current context."""
- s = []
- s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
- 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d, '
- 'clamp=%(clamp)d'
- % vars(self))
- names = [f.__name__ for f, v in self.flags.items() if v]
- s.append('flags=[' + ', '.join(names) + ']')
- names = [t.__name__ for t, v in self.traps.items() if v]
- s.append('traps=[' + ', '.join(names) + ']')
- return ', '.join(s) + ')'
-
- def clear_flags(self):
- """Reset all flags to zero"""
- for flag in self.flags:
- self.flags[flag] = 0
-
- def clear_traps(self):
- """Reset all traps to zero"""
- for flag in self.traps:
- self.traps[flag] = 0
-
- def _shallow_copy(self):
- """Returns a shallow copy from self."""
- nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
- self.capitals, self.clamp, self.flags, self.traps,
- self._ignored_flags)
- return nc
-
- def copy(self):
- """Returns a deep copy from self."""
- nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
- self.capitals, self.clamp,
- self.flags.copy(), self.traps.copy(),
- self._ignored_flags)
- return nc
- __copy__ = copy
-
- def _raise_error(self, condition, explanation = None, *args):
- """Handles an error
-
- If the flag is in _ignored_flags, returns the default response.
- Otherwise, it sets the flag, then, if the corresponding
- trap_enabler is set, it reraises the exception. Otherwise, it returns
- the default value after setting the flag.
- """
- error = _condition_map.get(condition, condition)
- if error in self._ignored_flags:
- # Don't touch the flag
- return error().handle(self, *args)
-
- self.flags[error] = 1
- if not self.traps[error]:
- # The errors define how to handle themselves.
- return condition().handle(self, *args)
-
- # Errors should only be risked on copies of the context
- # self._ignored_flags = []
- raise error(explanation)
-
- def _ignore_all_flags(self):
- """Ignore all flags, if they are raised"""
- return self._ignore_flags(*_signals)
-
- def _ignore_flags(self, *flags):
- """Ignore the flags, if they are raised"""
- # Do not mutate-- This way, copies of a context leave the original
- # alone.
- self._ignored_flags = (self._ignored_flags + list(flags))
- return list(flags)
-
- def _regard_flags(self, *flags):
- """Stop ignoring the flags, if they are raised"""
- if flags and isinstance(flags[0], (tuple,list)):
- flags = flags[0]
- for flag in flags:
- self._ignored_flags.remove(flag)
-
- # We inherit object.__hash__, so we must deny this explicitly
- __hash__ = None
-
- def Etiny(self):
- """Returns Etiny (= Emin - prec + 1)"""
- return int(self.Emin - self.prec + 1)
-
- def Etop(self):
- """Returns maximum exponent (= Emax - prec + 1)"""
- return int(self.Emax - self.prec + 1)
-
- def _set_rounding(self, type):
- """Sets the rounding type.
-
- Sets the rounding type, and returns the current (previous)
- rounding type. Often used like:
-
- context = context.copy()
- # so you don't change the calling context
- # if an error occurs in the middle.
- rounding = context._set_rounding(ROUND_UP)
- val = self.__sub__(other, context=context)
- context._set_rounding(rounding)
-
- This will make it round up for that operation.
- """
- rounding = self.rounding
- self.rounding = type
- return rounding
-
- def create_decimal(self, num='0'):
- """Creates a new Decimal instance but using self as context.
-
- This method implements the to-number operation of the
- IBM Decimal specification."""
-
- if isinstance(num, str) and (num != num.strip() or '_' in num):
- return self._raise_error(ConversionSyntax,
- "trailing or leading whitespace and "
- "underscores are not permitted.")
-
- d = Decimal(num, context=self)
- if d._isnan() and len(d._int) > self.prec - self.clamp:
- return self._raise_error(ConversionSyntax,
- "diagnostic info too long in NaN")
- return d._fix(self)
-
- def create_decimal_from_float(self, f):
- """Creates a new Decimal instance from a float but rounding using self
- as the context.
-
- >>> context = Context(prec=5, rounding=ROUND_DOWN)
- >>> context.create_decimal_from_float(3.1415926535897932)
- Decimal('3.1415')
- >>> context = Context(prec=5, traps=[Inexact])
- >>> context.create_decimal_from_float(3.1415926535897932)
- Traceback (most recent call last):
- ...
- decimal.Inexact: None
-
- """
- d = Decimal.from_float(f) # An exact conversion
- return d._fix(self) # Apply the context rounding
-
- # Methods
- def abs(self, a):
- """Returns the absolute value of the operand.
-
- If the operand is negative, the result is the same as using the minus
- operation on the operand. Otherwise, the result is the same as using
- the plus operation on the operand.
-
- >>> ExtendedContext.abs(Decimal('2.1'))
- Decimal('2.1')
- >>> ExtendedContext.abs(Decimal('-100'))
- Decimal('100')
- >>> ExtendedContext.abs(Decimal('101.5'))
- Decimal('101.5')
- >>> ExtendedContext.abs(Decimal('-101.5'))
- Decimal('101.5')
- >>> ExtendedContext.abs(-1)
- Decimal('1')
- """
- a = _convert_other(a, raiseit=True)
- return a.__abs__(context=self)
-
- def add(self, a, b):
- """Return the sum of the two operands.
-
- >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
- Decimal('19.00')
- >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
- Decimal('1.02E+4')
- >>> ExtendedContext.add(1, Decimal(2))
- Decimal('3')
- >>> ExtendedContext.add(Decimal(8), 5)
- Decimal('13')
- >>> ExtendedContext.add(5, 5)
- Decimal('10')
- """
- a = _convert_other(a, raiseit=True)
- r = a.__add__(b, context=self)
- if r is NotImplemented:
- raise TypeError("Unable to convert %s to Decimal" % b)
- else:
- return r
-
- def _apply(self, a):
- return str(a._fix(self))
-
- def canonical(self, a):
- """Returns the same Decimal object.
-
- As we do not have different encodings for the same number, the
- received object already is in its canonical form.
-
- >>> ExtendedContext.canonical(Decimal('2.50'))
- Decimal('2.50')
- """
- if not isinstance(a, Decimal):
- raise TypeError("canonical requires a Decimal as an argument.")
- return a.canonical()
-
- def compare(self, a, b):
- """Compares values numerically.
-
- If the signs of the operands differ, a value representing each operand
- ('-1' if the operand is less than zero, '0' if the operand is zero or
- negative zero, or '1' if the operand is greater than zero) is used in
- place of that operand for the comparison instead of the actual
- operand.
-
- The comparison is then effected by subtracting the second operand from
- the first and then returning a value according to the result of the
- subtraction: '-1' if the result is less than zero, '0' if the result is
- zero or negative zero, or '1' if the result is greater than zero.
-
- >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
- Decimal('-1')
- >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
- Decimal('0')
- >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
- Decimal('0')
- >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
- Decimal('1')
- >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
- Decimal('1')
- >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
- Decimal('-1')
- >>> ExtendedContext.compare(1, 2)
- Decimal('-1')
- >>> ExtendedContext.compare(Decimal(1), 2)
- Decimal('-1')
- >>> ExtendedContext.compare(1, Decimal(2))
- Decimal('-1')
- """
- a = _convert_other(a, raiseit=True)
- return a.compare(b, context=self)
-
- def compare_signal(self, a, b):
- """Compares the values of the two operands numerically.
-
- It's pretty much like compare(), but all NaNs signal, with signaling
- NaNs taking precedence over quiet NaNs.
-
- >>> c = ExtendedContext
- >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
- Decimal('-1')
- >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
- Decimal('0')
- >>> c.flags[InvalidOperation] = 0
- >>> print(c.flags[InvalidOperation])
- 0
- >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
- Decimal('NaN')
- >>> print(c.flags[InvalidOperation])
- 1
- >>> c.flags[InvalidOperation] = 0
- >>> print(c.flags[InvalidOperation])
- 0
- >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
- Decimal('NaN')
- >>> print(c.flags[InvalidOperation])
- 1
- >>> c.compare_signal(-1, 2)
- Decimal('-1')
- >>> c.compare_signal(Decimal(-1), 2)
- Decimal('-1')
- >>> c.compare_signal(-1, Decimal(2))
- Decimal('-1')
- """
- a = _convert_other(a, raiseit=True)
- return a.compare_signal(b, context=self)
-
- def compare_total(self, a, b):
- """Compares two operands using their abstract representation.
-
- This is not like the standard compare, which use their numerical
- value. Note that a total ordering is defined for all possible abstract
- representations.
-
- >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
- Decimal('-1')
- >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
- Decimal('-1')
- >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
- Decimal('-1')
- >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
- Decimal('0')
- >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
- Decimal('1')
- >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
- Decimal('-1')
- >>> ExtendedContext.compare_total(1, 2)
- Decimal('-1')
- >>> ExtendedContext.compare_total(Decimal(1), 2)
- Decimal('-1')
- >>> ExtendedContext.compare_total(1, Decimal(2))
- Decimal('-1')
- """
- a = _convert_other(a, raiseit=True)
- return a.compare_total(b)
-
- def compare_total_mag(self, a, b):
- """Compares two operands using their abstract representation ignoring sign.
-
- Like compare_total, but with operand's sign ignored and assumed to be 0.
- """
- a = _convert_other(a, raiseit=True)
- return a.compare_total_mag(b)
-
- def copy_abs(self, a):
- """Returns a copy of the operand with the sign set to 0.
-
- >>> ExtendedContext.copy_abs(Decimal('2.1'))
- Decimal('2.1')
- >>> ExtendedContext.copy_abs(Decimal('-100'))
- Decimal('100')
- >>> ExtendedContext.copy_abs(-1)
- Decimal('1')
- """
- a = _convert_other(a, raiseit=True)
- return a.copy_abs()
-
- def copy_decimal(self, a):
- """Returns a copy of the decimal object.
-
- >>> ExtendedContext.copy_decimal(Decimal('2.1'))
- Decimal('2.1')
- >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
- Decimal('-1.00')
- >>> ExtendedContext.copy_decimal(1)
- Decimal('1')
- """
- a = _convert_other(a, raiseit=True)
- return Decimal(a)
-
- def copy_negate(self, a):
- """Returns a copy of the operand with the sign inverted.
-
- >>> ExtendedContext.copy_negate(Decimal('101.5'))
- Decimal('-101.5')
- >>> ExtendedContext.copy_negate(Decimal('-101.5'))
- Decimal('101.5')
- >>> ExtendedContext.copy_negate(1)
- Decimal('-1')
- """
- a = _convert_other(a, raiseit=True)
- return a.copy_negate()
-
- def copy_sign(self, a, b):
- """Copies the second operand's sign to the first one.
-
- In detail, it returns a copy of the first operand with the sign
- equal to the sign of the second operand.
-
- >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
- Decimal('1.50')
- >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
- Decimal('1.50')
- >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
- Decimal('-1.50')
- >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
- Decimal('-1.50')
- >>> ExtendedContext.copy_sign(1, -2)
- Decimal('-1')
- >>> ExtendedContext.copy_sign(Decimal(1), -2)
- Decimal('-1')
- >>> ExtendedContext.copy_sign(1, Decimal(-2))
- Decimal('-1')
- """
- a = _convert_other(a, raiseit=True)
- return a.copy_sign(b)
-
- def divide(self, a, b):
- """Decimal division in a specified context.
-
- >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
- Decimal('0.333333333')
- >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
- Decimal('0.666666667')
- >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
- Decimal('2.5')
- >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
- Decimal('0.1')
- >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
- Decimal('1')
- >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
- Decimal('4.00')
- >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
- Decimal('1.20')
- >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
- Decimal('10')
- >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
- Decimal('1000')
- >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
- Decimal('1.20E+6')
- >>> ExtendedContext.divide(5, 5)
- Decimal('1')
- >>> ExtendedContext.divide(Decimal(5), 5)
- Decimal('1')
- >>> ExtendedContext.divide(5, Decimal(5))
- Decimal('1')
- """
- a = _convert_other(a, raiseit=True)
- r = a.__truediv__(b, context=self)
- if r is NotImplemented:
- raise TypeError("Unable to convert %s to Decimal" % b)
- else:
- return r
-
- def divide_int(self, a, b):
- """Divides two numbers and returns the integer part of the result.
-
- >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
- Decimal('0')
- >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
- Decimal('3')
- >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
- Decimal('3')
- >>> ExtendedContext.divide_int(10, 3)
- Decimal('3')
- >>> ExtendedContext.divide_int(Decimal(10), 3)
- Decimal('3')
- >>> ExtendedContext.divide_int(10, Decimal(3))
- Decimal('3')
- """
- a = _convert_other(a, raiseit=True)
- r = a.__floordiv__(b, context=self)
- if r is NotImplemented:
- raise TypeError("Unable to convert %s to Decimal" % b)
- else:
- return r
-
- def divmod(self, a, b):
- """Return (a // b, a % b).
-
- >>> ExtendedContext.divmod(Decimal(8), Decimal(3))
- (Decimal('2'), Decimal('2'))
- >>> ExtendedContext.divmod(Decimal(8), Decimal(4))
- (Decimal('2'), Decimal('0'))
- >>> ExtendedContext.divmod(8, 4)
- (Decimal('2'), Decimal('0'))
- >>> ExtendedContext.divmod(Decimal(8), 4)
- (Decimal('2'), Decimal('0'))
- >>> ExtendedContext.divmod(8, Decimal(4))
- (Decimal('2'), Decimal('0'))
- """
- a = _convert_other(a, raiseit=True)
- r = a.__divmod__(b, context=self)
- if r is NotImplemented:
- raise TypeError("Unable to convert %s to Decimal" % b)
- else:
- return r
-
- def exp(self, a):
- """Returns e ** a.
-
- >>> c = ExtendedContext.copy()
- >>> c.Emin = -999
- >>> c.Emax = 999
- >>> c.exp(Decimal('-Infinity'))
- Decimal('0')
- >>> c.exp(Decimal('-1'))
- Decimal('0.367879441')
- >>> c.exp(Decimal('0'))
- Decimal('1')
- >>> c.exp(Decimal('1'))
- Decimal('2.71828183')
- >>> c.exp(Decimal('0.693147181'))
- Decimal('2.00000000')
- >>> c.exp(Decimal('+Infinity'))
- Decimal('Infinity')
- >>> c.exp(10)
- Decimal('22026.4658')
- """
- a =_convert_other(a, raiseit=True)
- return a.exp(context=self)
-
- def fma(self, a, b, c):
- """Returns a multiplied by b, plus c.
-
- The first two operands are multiplied together, using multiply,
- the third operand is then added to the result of that
- multiplication, using add, all with only one final rounding.
-
- >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
- Decimal('22')
- >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
- Decimal('-8')
- >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
- Decimal('1.38435736E+12')
- >>> ExtendedContext.fma(1, 3, 4)
- Decimal('7')
- >>> ExtendedContext.fma(1, Decimal(3), 4)
- Decimal('7')
- >>> ExtendedContext.fma(1, 3, Decimal(4))
- Decimal('7')
- """
- a = _convert_other(a, raiseit=True)
- return a.fma(b, c, context=self)
-
- def is_canonical(self, a):
- """Return True if the operand is canonical; otherwise return False.
-
- Currently, the encoding of a Decimal instance is always
- canonical, so this method returns True for any Decimal.
-
- >>> ExtendedContext.is_canonical(Decimal('2.50'))
- True
- """
- if not isinstance(a, Decimal):
- raise TypeError("is_canonical requires a Decimal as an argument.")
- return a.is_canonical()
-
- def is_finite(self, a):
- """Return True if the operand is finite; otherwise return False.
-
- A Decimal instance is considered finite if it is neither
- infinite nor a NaN.
-
- >>> ExtendedContext.is_finite(Decimal('2.50'))
- True
- >>> ExtendedContext.is_finite(Decimal('-0.3'))
- True
- >>> ExtendedContext.is_finite(Decimal('0'))
- True
- >>> ExtendedContext.is_finite(Decimal('Inf'))
- False
- >>> ExtendedContext.is_finite(Decimal('NaN'))
- False
- >>> ExtendedContext.is_finite(1)
- True
- """
- a = _convert_other(a, raiseit=True)
- return a.is_finite()
-
- def is_infinite(self, a):
- """Return True if the operand is infinite; otherwise return False.
-
- >>> ExtendedContext.is_infinite(Decimal('2.50'))
- False
- >>> ExtendedContext.is_infinite(Decimal('-Inf'))
- True
- >>> ExtendedContext.is_infinite(Decimal('NaN'))
- False
- >>> ExtendedContext.is_infinite(1)
- False
- """
- a = _convert_other(a, raiseit=True)
- return a.is_infinite()
-
- def is_nan(self, a):
- """Return True if the operand is a qNaN or sNaN;
- otherwise return False.
-
- >>> ExtendedContext.is_nan(Decimal('2.50'))
- False
- >>> ExtendedContext.is_nan(Decimal('NaN'))
- True
- >>> ExtendedContext.is_nan(Decimal('-sNaN'))
- True
- >>> ExtendedContext.is_nan(1)
- False
- """
- a = _convert_other(a, raiseit=True)
- return a.is_nan()
-
- def is_normal(self, a):
- """Return True if the operand is a normal number;
- otherwise return False.
-
- >>> c = ExtendedContext.copy()
- >>> c.Emin = -999
- >>> c.Emax = 999
- >>> c.is_normal(Decimal('2.50'))
- True
- >>> c.is_normal(Decimal('0.1E-999'))
- False
- >>> c.is_normal(Decimal('0.00'))
- False
- >>> c.is_normal(Decimal('-Inf'))
- False
- >>> c.is_normal(Decimal('NaN'))
- False
- >>> c.is_normal(1)
- True
- """
- a = _convert_other(a, raiseit=True)
- return a.is_normal(context=self)
-
- def is_qnan(self, a):
- """Return True if the operand is a quiet NaN; otherwise return False.
-
- >>> ExtendedContext.is_qnan(Decimal('2.50'))
- False
- >>> ExtendedContext.is_qnan(Decimal('NaN'))
- True
- >>> ExtendedContext.is_qnan(Decimal('sNaN'))
- False
- >>> ExtendedContext.is_qnan(1)
- False
- """
- a = _convert_other(a, raiseit=True)
- return a.is_qnan()
-
- def is_signed(self, a):
- """Return True if the operand is negative; otherwise return False.
-
- >>> ExtendedContext.is_signed(Decimal('2.50'))
- False
- >>> ExtendedContext.is_signed(Decimal('-12'))
- True
- >>> ExtendedContext.is_signed(Decimal('-0'))
- True
- >>> ExtendedContext.is_signed(8)
- False
- >>> ExtendedContext.is_signed(-8)
- True
- """
- a = _convert_other(a, raiseit=True)
- return a.is_signed()
-
- def is_snan(self, a):
- """Return True if the operand is a signaling NaN;
- otherwise return False.
-
- >>> ExtendedContext.is_snan(Decimal('2.50'))
- False
- >>> ExtendedContext.is_snan(Decimal('NaN'))
- False
- >>> ExtendedContext.is_snan(Decimal('sNaN'))
- True
- >>> ExtendedContext.is_snan(1)
- False
- """
- a = _convert_other(a, raiseit=True)
- return a.is_snan()
-
- def is_subnormal(self, a):
- """Return True if the operand is subnormal; otherwise return False.
-
- >>> c = ExtendedContext.copy()
- >>> c.Emin = -999
- >>> c.Emax = 999
- >>> c.is_subnormal(Decimal('2.50'))
- False
- >>> c.is_subnormal(Decimal('0.1E-999'))
- True
- >>> c.is_subnormal(Decimal('0.00'))
- False
- >>> c.is_subnormal(Decimal('-Inf'))
- False
- >>> c.is_subnormal(Decimal('NaN'))
- False
- >>> c.is_subnormal(1)
- False
- """
- a = _convert_other(a, raiseit=True)
- return a.is_subnormal(context=self)
-
- def is_zero(self, a):
- """Return True if the operand is a zero; otherwise return False.
-
- >>> ExtendedContext.is_zero(Decimal('0'))
- True
- >>> ExtendedContext.is_zero(Decimal('2.50'))
- False
- >>> ExtendedContext.is_zero(Decimal('-0E+2'))
- True
- >>> ExtendedContext.is_zero(1)
- False
- >>> ExtendedContext.is_zero(0)
- True
- """
- a = _convert_other(a, raiseit=True)
- return a.is_zero()
-
- def ln(self, a):
- """Returns the natural (base e) logarithm of the operand.
-
- >>> c = ExtendedContext.copy()
- >>> c.Emin = -999
- >>> c.Emax = 999
- >>> c.ln(Decimal('0'))
- Decimal('-Infinity')
- >>> c.ln(Decimal('1.000'))
- Decimal('0')
- >>> c.ln(Decimal('2.71828183'))
- Decimal('1.00000000')
- >>> c.ln(Decimal('10'))
- Decimal('2.30258509')
- >>> c.ln(Decimal('+Infinity'))
- Decimal('Infinity')
- >>> c.ln(1)
- Decimal('0')
- """
- a = _convert_other(a, raiseit=True)
- return a.ln(context=self)
-
- def log10(self, a):
- """Returns the base 10 logarithm of the operand.
-
- >>> c = ExtendedContext.copy()
- >>> c.Emin = -999
- >>> c.Emax = 999
- >>> c.log10(Decimal('0'))
- Decimal('-Infinity')
- >>> c.log10(Decimal('0.001'))
- Decimal('-3')
- >>> c.log10(Decimal('1.000'))
- Decimal('0')
- >>> c.log10(Decimal('2'))
- Decimal('0.301029996')
- >>> c.log10(Decimal('10'))
- Decimal('1')
- >>> c.log10(Decimal('70'))
- Decimal('1.84509804')
- >>> c.log10(Decimal('+Infinity'))
- Decimal('Infinity')
- >>> c.log10(0)
- Decimal('-Infinity')
- >>> c.log10(1)
- Decimal('0')
- """
- a = _convert_other(a, raiseit=True)
- return a.log10(context=self)
-
- def logb(self, a):
- """ Returns the exponent of the magnitude of the operand's MSD.
-
- The result is the integer which is the exponent of the magnitude
- of the most significant digit of the operand (as though the
- operand were truncated to a single digit while maintaining the
- value of that digit and without limiting the resulting exponent).
-
- >>> ExtendedContext.logb(Decimal('250'))
- Decimal('2')
- >>> ExtendedContext.logb(Decimal('2.50'))
- Decimal('0')
- >>> ExtendedContext.logb(Decimal('0.03'))
- Decimal('-2')
- >>> ExtendedContext.logb(Decimal('0'))
- Decimal('-Infinity')
- >>> ExtendedContext.logb(1)
- Decimal('0')
- >>> ExtendedContext.logb(10)
- Decimal('1')
- >>> ExtendedContext.logb(100)
- Decimal('2')
- """
- a = _convert_other(a, raiseit=True)
- return a.logb(context=self)
-
- def logical_and(self, a, b):
- """Applies the logical operation 'and' between each operand's digits.
-
- The operands must be both logical numbers.
-
- >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
- Decimal('0')
- >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
- Decimal('0')
- >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
- Decimal('0')
- >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
- Decimal('1')
- >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
- Decimal('1000')
- >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
- Decimal('10')
- >>> ExtendedContext.logical_and(110, 1101)
- Decimal('100')
- >>> ExtendedContext.logical_and(Decimal(110), 1101)
- Decimal('100')
- >>> ExtendedContext.logical_and(110, Decimal(1101))
- Decimal('100')
- """
- a = _convert_other(a, raiseit=True)
- return a.logical_and(b, context=self)
-
- def logical_invert(self, a):
- """Invert all the digits in the operand.
-
- The operand must be a logical number.
-
- >>> ExtendedContext.logical_invert(Decimal('0'))
- Decimal('111111111')
- >>> ExtendedContext.logical_invert(Decimal('1'))
- Decimal('111111110')
- >>> ExtendedContext.logical_invert(Decimal('111111111'))
- Decimal('0')
- >>> ExtendedContext.logical_invert(Decimal('101010101'))
- Decimal('10101010')
- >>> ExtendedContext.logical_invert(1101)
- Decimal('111110010')
- """
- a = _convert_other(a, raiseit=True)
- return a.logical_invert(context=self)
-
- def logical_or(self, a, b):
- """Applies the logical operation 'or' between each operand's digits.
-
- The operands must be both logical numbers.
-
- >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
- Decimal('0')
- >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
- Decimal('1')
- >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
- Decimal('1')
- >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
- Decimal('1')
- >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
- Decimal('1110')
- >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
- Decimal('1110')
- >>> ExtendedContext.logical_or(110, 1101)
- Decimal('1111')
- >>> ExtendedContext.logical_or(Decimal(110), 1101)
- Decimal('1111')
- >>> ExtendedContext.logical_or(110, Decimal(1101))
- Decimal('1111')
- """
- a = _convert_other(a, raiseit=True)
- return a.logical_or(b, context=self)
-
- def logical_xor(self, a, b):
- """Applies the logical operation 'xor' between each operand's digits.
-
- The operands must be both logical numbers.
-
- >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
- Decimal('0')
- >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
- Decimal('1')
- >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
- Decimal('1')
- >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
- Decimal('0')
- >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
- Decimal('110')
- >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
- Decimal('1101')
- >>> ExtendedContext.logical_xor(110, 1101)
- Decimal('1011')
- >>> ExtendedContext.logical_xor(Decimal(110), 1101)
- Decimal('1011')
- >>> ExtendedContext.logical_xor(110, Decimal(1101))
- Decimal('1011')
- """
- a = _convert_other(a, raiseit=True)
- return a.logical_xor(b, context=self)
-
- def max(self, a, b):
- """max compares two values numerically and returns the maximum.
-
- If either operand is a NaN then the general rules apply.
- Otherwise, the operands are compared as though by the compare
- operation. If they are numerically equal then the left-hand operand
- is chosen as the result. Otherwise the maximum (closer to positive
- infinity) of the two operands is chosen as the result.
-
- >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
- Decimal('3')
- >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
- Decimal('3')
- >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
- Decimal('1')
- >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
- Decimal('7')
- >>> ExtendedContext.max(1, 2)
- Decimal('2')
- >>> ExtendedContext.max(Decimal(1), 2)
- Decimal('2')
- >>> ExtendedContext.max(1, Decimal(2))
- Decimal('2')
- """
- a = _convert_other(a, raiseit=True)
- return a.max(b, context=self)
-
- def max_mag(self, a, b):
- """Compares the values numerically with their sign ignored.
-
- >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN'))
- Decimal('7')
- >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10'))
- Decimal('-10')
- >>> ExtendedContext.max_mag(1, -2)
- Decimal('-2')
- >>> ExtendedContext.max_mag(Decimal(1), -2)
- Decimal('-2')
- >>> ExtendedContext.max_mag(1, Decimal(-2))
- Decimal('-2')
- """
- a = _convert_other(a, raiseit=True)
- return a.max_mag(b, context=self)
-
- def min(self, a, b):
- """min compares two values numerically and returns the minimum.
-
- If either operand is a NaN then the general rules apply.
- Otherwise, the operands are compared as though by the compare
- operation. If they are numerically equal then the left-hand operand
- is chosen as the result. Otherwise the minimum (closer to negative
- infinity) of the two operands is chosen as the result.
-
- >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
- Decimal('2')
- >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
- Decimal('-10')
- >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
- Decimal('1.0')
- >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
- Decimal('7')
- >>> ExtendedContext.min(1, 2)
- Decimal('1')
- >>> ExtendedContext.min(Decimal(1), 2)
- Decimal('1')
- >>> ExtendedContext.min(1, Decimal(29))
- Decimal('1')
- """
- a = _convert_other(a, raiseit=True)
- return a.min(b, context=self)
-
- def min_mag(self, a, b):
- """Compares the values numerically with their sign ignored.
-
- >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2'))
- Decimal('-2')
- >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN'))
- Decimal('-3')
- >>> ExtendedContext.min_mag(1, -2)
- Decimal('1')
- >>> ExtendedContext.min_mag(Decimal(1), -2)
- Decimal('1')
- >>> ExtendedContext.min_mag(1, Decimal(-2))
- Decimal('1')
- """
- a = _convert_other(a, raiseit=True)
- return a.min_mag(b, context=self)
-
- def minus(self, a):
- """Minus corresponds to unary prefix minus in Python.
-
- The operation is evaluated using the same rules as subtract; the
- operation minus(a) is calculated as subtract('0', a) where the '0'
- has the same exponent as the operand.
-
- >>> ExtendedContext.minus(Decimal('1.3'))
- Decimal('-1.3')
- >>> ExtendedContext.minus(Decimal('-1.3'))
- Decimal('1.3')
- >>> ExtendedContext.minus(1)
- Decimal('-1')
- """
- a = _convert_other(a, raiseit=True)
- return a.__neg__(context=self)
-
- def multiply(self, a, b):
- """multiply multiplies two operands.
-
- If either operand is a special value then the general rules apply.
- Otherwise, the operands are multiplied together
- ('long multiplication'), resulting in a number which may be as long as
- the sum of the lengths of the two operands.
-
- >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
- Decimal('3.60')
- >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
- Decimal('21')
- >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
- Decimal('0.72')
- >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
- Decimal('-0.0')
- >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
- Decimal('4.28135971E+11')
- >>> ExtendedContext.multiply(7, 7)
- Decimal('49')
- >>> ExtendedContext.multiply(Decimal(7), 7)
- Decimal('49')
- >>> ExtendedContext.multiply(7, Decimal(7))
- Decimal('49')
- """
- a = _convert_other(a, raiseit=True)
- r = a.__mul__(b, context=self)
- if r is NotImplemented:
- raise TypeError("Unable to convert %s to Decimal" % b)
- else:
- return r
-
- def next_minus(self, a):
- """Returns the largest representable number smaller than a.
-
- >>> c = ExtendedContext.copy()
- >>> c.Emin = -999
- >>> c.Emax = 999
- >>> ExtendedContext.next_minus(Decimal('1'))
- Decimal('0.999999999')
- >>> c.next_minus(Decimal('1E-1007'))
- Decimal('0E-1007')
- >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
- Decimal('-1.00000004')
- >>> c.next_minus(Decimal('Infinity'))
- Decimal('9.99999999E+999')
- >>> c.next_minus(1)
- Decimal('0.999999999')
- """
- a = _convert_other(a, raiseit=True)
- return a.next_minus(context=self)
-
- def next_plus(self, a):
- """Returns the smallest representable number larger than a.
-
- >>> c = ExtendedContext.copy()
- >>> c.Emin = -999
- >>> c.Emax = 999
- >>> ExtendedContext.next_plus(Decimal('1'))
- Decimal('1.00000001')
- >>> c.next_plus(Decimal('-1E-1007'))
- Decimal('-0E-1007')
- >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
- Decimal('-1.00000002')
- >>> c.next_plus(Decimal('-Infinity'))
- Decimal('-9.99999999E+999')
- >>> c.next_plus(1)
- Decimal('1.00000001')
- """
- a = _convert_other(a, raiseit=True)
- return a.next_plus(context=self)
-
- def next_toward(self, a, b):
- """Returns the number closest to a, in direction towards b.
-
- The result is the closest representable number from the first
- operand (but not the first operand) that is in the direction
- towards the second operand, unless the operands have the same
- value.
-
- >>> c = ExtendedContext.copy()
- >>> c.Emin = -999
- >>> c.Emax = 999
- >>> c.next_toward(Decimal('1'), Decimal('2'))
- Decimal('1.00000001')
- >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
- Decimal('-0E-1007')
- >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
- Decimal('-1.00000002')
- >>> c.next_toward(Decimal('1'), Decimal('0'))
- Decimal('0.999999999')
- >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
- Decimal('0E-1007')
- >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
- Decimal('-1.00000004')
- >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
- Decimal('-0.00')
- >>> c.next_toward(0, 1)
- Decimal('1E-1007')
- >>> c.next_toward(Decimal(0), 1)
- Decimal('1E-1007')
- >>> c.next_toward(0, Decimal(1))
- Decimal('1E-1007')
- """
- a = _convert_other(a, raiseit=True)
- return a.next_toward(b, context=self)
-
- def normalize(self, a):
- """normalize reduces an operand to its simplest form.
-
- Essentially a plus operation with all trailing zeros removed from the
- result.
-
- >>> ExtendedContext.normalize(Decimal('2.1'))
- Decimal('2.1')
- >>> ExtendedContext.normalize(Decimal('-2.0'))
- Decimal('-2')
- >>> ExtendedContext.normalize(Decimal('1.200'))
- Decimal('1.2')
- >>> ExtendedContext.normalize(Decimal('-120'))
- Decimal('-1.2E+2')
- >>> ExtendedContext.normalize(Decimal('120.00'))
- Decimal('1.2E+2')
- >>> ExtendedContext.normalize(Decimal('0.00'))
- Decimal('0')
- >>> ExtendedContext.normalize(6)
- Decimal('6')
- """
- a = _convert_other(a, raiseit=True)
- return a.normalize(context=self)
-
- def number_class(self, a):
- """Returns an indication of the class of the operand.
-
- The class is one of the following strings:
- -sNaN
- -NaN
- -Infinity
- -Normal
- -Subnormal
- -Zero
- +Zero
- +Subnormal
- +Normal
- +Infinity
-
- >>> c = ExtendedContext.copy()
- >>> c.Emin = -999
- >>> c.Emax = 999
- >>> c.number_class(Decimal('Infinity'))
- '+Infinity'
- >>> c.number_class(Decimal('1E-10'))
- '+Normal'
- >>> c.number_class(Decimal('2.50'))
- '+Normal'
- >>> c.number_class(Decimal('0.1E-999'))
- '+Subnormal'
- >>> c.number_class(Decimal('0'))
- '+Zero'
- >>> c.number_class(Decimal('-0'))
- '-Zero'
- >>> c.number_class(Decimal('-0.1E-999'))
- '-Subnormal'
- >>> c.number_class(Decimal('-1E-10'))
- '-Normal'
- >>> c.number_class(Decimal('-2.50'))
- '-Normal'
- >>> c.number_class(Decimal('-Infinity'))
- '-Infinity'
- >>> c.number_class(Decimal('NaN'))
- 'NaN'
- >>> c.number_class(Decimal('-NaN'))
- 'NaN'
- >>> c.number_class(Decimal('sNaN'))
- 'sNaN'
- >>> c.number_class(123)
- '+Normal'
- """
- a = _convert_other(a, raiseit=True)
- return a.number_class(context=self)
-
- def plus(self, a):
- """Plus corresponds to unary prefix plus in Python.
-
- The operation is evaluated using the same rules as add; the
- operation plus(a) is calculated as add('0', a) where the '0'
- has the same exponent as the operand.
-
- >>> ExtendedContext.plus(Decimal('1.3'))
- Decimal('1.3')
- >>> ExtendedContext.plus(Decimal('-1.3'))
- Decimal('-1.3')
- >>> ExtendedContext.plus(-1)
- Decimal('-1')
- """
- a = _convert_other(a, raiseit=True)
- return a.__pos__(context=self)
-
- def power(self, a, b, modulo=None):
- """Raises a to the power of b, to modulo if given.
-
- With two arguments, compute a**b. If a is negative then b
- must be integral. The result will be inexact unless b is
- integral and the result is finite and can be expressed exactly
- in 'precision' digits.
-
- With three arguments, compute (a**b) % modulo. For the
- three argument form, the following restrictions on the
- arguments hold:
-
- - all three arguments must be integral
- - b must be nonnegative
- - at least one of a or b must be nonzero
- - modulo must be nonzero and have at most 'precision' digits
-
- The result of pow(a, b, modulo) is identical to the result
- that would be obtained by computing (a**b) % modulo with
- unbounded precision, but is computed more efficiently. It is
- always exact.
-
- >>> c = ExtendedContext.copy()
- >>> c.Emin = -999
- >>> c.Emax = 999
- >>> c.power(Decimal('2'), Decimal('3'))
- Decimal('8')
- >>> c.power(Decimal('-2'), Decimal('3'))
- Decimal('-8')
- >>> c.power(Decimal('2'), Decimal('-3'))
- Decimal('0.125')
- >>> c.power(Decimal('1.7'), Decimal('8'))
- Decimal('69.7575744')
- >>> c.power(Decimal('10'), Decimal('0.301029996'))
- Decimal('2.00000000')
- >>> c.power(Decimal('Infinity'), Decimal('-1'))
- Decimal('0')
- >>> c.power(Decimal('Infinity'), Decimal('0'))
- Decimal('1')
- >>> c.power(Decimal('Infinity'), Decimal('1'))
- Decimal('Infinity')
- >>> c.power(Decimal('-Infinity'), Decimal('-1'))
- Decimal('-0')
- >>> c.power(Decimal('-Infinity'), Decimal('0'))
- Decimal('1')
- >>> c.power(Decimal('-Infinity'), Decimal('1'))
- Decimal('-Infinity')
- >>> c.power(Decimal('-Infinity'), Decimal('2'))
- Decimal('Infinity')
- >>> c.power(Decimal('0'), Decimal('0'))
- Decimal('NaN')
-
- >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
- Decimal('11')
- >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
- Decimal('-11')
- >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
- Decimal('1')
- >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
- Decimal('11')
- >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
- Decimal('11729830')
- >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
- Decimal('-0')
- >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
- Decimal('1')
- >>> ExtendedContext.power(7, 7)
- Decimal('823543')
- >>> ExtendedContext.power(Decimal(7), 7)
- Decimal('823543')
- >>> ExtendedContext.power(7, Decimal(7), 2)
- Decimal('1')
- """
- a = _convert_other(a, raiseit=True)
- r = a.__pow__(b, modulo, context=self)
- if r is NotImplemented:
- raise TypeError("Unable to convert %s to Decimal" % b)
- else:
- return r
-
- def quantize(self, a, b):
- """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
-
- The coefficient of the result is derived from that of the left-hand
- operand. It may be rounded using the current rounding setting (if the
- exponent is being increased), multiplied by a positive power of ten (if
- the exponent is being decreased), or is unchanged (if the exponent is
- already equal to that of the right-hand operand).
-
- Unlike other operations, if the length of the coefficient after the
- quantize operation would be greater than precision then an Invalid
- operation condition is raised. This guarantees that, unless there is
- an error condition, the exponent of the result of a quantize is always
- equal to that of the right-hand operand.
-
- Also unlike other operations, quantize will never raise Underflow, even
- if the result is subnormal and inexact.
-
- >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
- Decimal('2.170')
- >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
- Decimal('2.17')
- >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
- Decimal('2.2')
- >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
- Decimal('2')
- >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
- Decimal('0E+1')
- >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
- Decimal('-Infinity')
- >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
- Decimal('NaN')
- >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
- Decimal('-0')
- >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
- Decimal('-0E+5')
- >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
- Decimal('NaN')
- >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
- Decimal('NaN')
- >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
- Decimal('217.0')
- >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
- Decimal('217')
- >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
- Decimal('2.2E+2')
- >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
- Decimal('2E+2')
- >>> ExtendedContext.quantize(1, 2)
- Decimal('1')
- >>> ExtendedContext.quantize(Decimal(1), 2)
- Decimal('1')
- >>> ExtendedContext.quantize(1, Decimal(2))
- Decimal('1')
- """
- a = _convert_other(a, raiseit=True)
- return a.quantize(b, context=self)
-
- def radix(self):
- """Just returns 10, as this is Decimal, :)
-
- >>> ExtendedContext.radix()
- Decimal('10')
- """
- return Decimal(10)
-
- def remainder(self, a, b):
- """Returns the remainder from integer division.
-
- The result is the residue of the dividend after the operation of
- calculating integer division as described for divide-integer, rounded
- to precision digits if necessary. The sign of the result, if
- non-zero, is the same as that of the original dividend.
-
- This operation will fail under the same conditions as integer division
- (that is, if integer division on the same two operands would fail, the
- remainder cannot be calculated).
-
- >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
- Decimal('2.1')
- >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
- Decimal('1')
- >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
- Decimal('-1')
- >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
- Decimal('0.2')
- >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
- Decimal('0.1')
- >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
- Decimal('1.0')
- >>> ExtendedContext.remainder(22, 6)
- Decimal('4')
- >>> ExtendedContext.remainder(Decimal(22), 6)
- Decimal('4')
- >>> ExtendedContext.remainder(22, Decimal(6))
- Decimal('4')
- """
- a = _convert_other(a, raiseit=True)
- r = a.__mod__(b, context=self)
- if r is NotImplemented:
- raise TypeError("Unable to convert %s to Decimal" % b)
- else:
- return r
-
- def remainder_near(self, a, b):
- """Returns to be "a - b * n", where n is the integer nearest the exact
- value of "x / b" (if two integers are equally near then the even one
- is chosen). If the result is equal to 0 then its sign will be the
- sign of a.
-
- This operation will fail under the same conditions as integer division
- (that is, if integer division on the same two operands would fail, the
- remainder cannot be calculated).
-
- >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
- Decimal('-0.9')
- >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
- Decimal('-2')
- >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
- Decimal('1')
- >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
- Decimal('-1')
- >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
- Decimal('0.2')
- >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
- Decimal('0.1')
- >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
- Decimal('-0.3')
- >>> ExtendedContext.remainder_near(3, 11)
- Decimal('3')
- >>> ExtendedContext.remainder_near(Decimal(3), 11)
- Decimal('3')
- >>> ExtendedContext.remainder_near(3, Decimal(11))
- Decimal('3')
- """
- a = _convert_other(a, raiseit=True)
- return a.remainder_near(b, context=self)
-
- def rotate(self, a, b):
- """Returns a rotated copy of a, b times.
-
- The coefficient of the result is a rotated copy of the digits in
- the coefficient of the first operand. The number of places of
- rotation is taken from the absolute value of the second operand,
- with the rotation being to the left if the second operand is
- positive or to the right otherwise.
-
- >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
- Decimal('400000003')
- >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
- Decimal('12')
- >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
- Decimal('891234567')
- >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
- Decimal('123456789')
- >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
- Decimal('345678912')
- >>> ExtendedContext.rotate(1333333, 1)
- Decimal('13333330')
- >>> ExtendedContext.rotate(Decimal(1333333), 1)
- Decimal('13333330')
- >>> ExtendedContext.rotate(1333333, Decimal(1))
- Decimal('13333330')
- """
- a = _convert_other(a, raiseit=True)
- return a.rotate(b, context=self)
-
- def same_quantum(self, a, b):
- """Returns True if the two operands have the same exponent.
-
- The result is never affected by either the sign or the coefficient of
- either operand.
-
- >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
- False
- >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
- True
- >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
- False
- >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
- True
- >>> ExtendedContext.same_quantum(10000, -1)
- True
- >>> ExtendedContext.same_quantum(Decimal(10000), -1)
- True
- >>> ExtendedContext.same_quantum(10000, Decimal(-1))
- True
- """
- a = _convert_other(a, raiseit=True)
- return a.same_quantum(b)
-
- def scaleb (self, a, b):
- """Returns the first operand after adding the second value its exp.
-
- >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
- Decimal('0.0750')
- >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
- Decimal('7.50')
- >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
- Decimal('7.50E+3')
- >>> ExtendedContext.scaleb(1, 4)
- Decimal('1E+4')
- >>> ExtendedContext.scaleb(Decimal(1), 4)
- Decimal('1E+4')
- >>> ExtendedContext.scaleb(1, Decimal(4))
- Decimal('1E+4')
- """
- a = _convert_other(a, raiseit=True)
- return a.scaleb(b, context=self)
-
- def shift(self, a, b):
- """Returns a shifted copy of a, b times.
-
- The coefficient of the result is a shifted copy of the digits
- in the coefficient of the first operand. The number of places
- to shift is taken from the absolute value of the second operand,
- with the shift being to the left if the second operand is
- positive or to the right otherwise. Digits shifted into the
- coefficient are zeros.
-
- >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
- Decimal('400000000')
- >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
- Decimal('0')
- >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
- Decimal('1234567')
- >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
- Decimal('123456789')
- >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
- Decimal('345678900')
- >>> ExtendedContext.shift(88888888, 2)
- Decimal('888888800')
- >>> ExtendedContext.shift(Decimal(88888888), 2)
- Decimal('888888800')
- >>> ExtendedContext.shift(88888888, Decimal(2))
- Decimal('888888800')
- """
- a = _convert_other(a, raiseit=True)
- return a.shift(b, context=self)
-
- def sqrt(self, a):
- """Square root of a non-negative number to context precision.
-
- If the result must be inexact, it is rounded using the round-half-even
- algorithm.
-
- >>> ExtendedContext.sqrt(Decimal('0'))
- Decimal('0')
- >>> ExtendedContext.sqrt(Decimal('-0'))
- Decimal('-0')
- >>> ExtendedContext.sqrt(Decimal('0.39'))
- Decimal('0.624499800')
- >>> ExtendedContext.sqrt(Decimal('100'))
- Decimal('10')
- >>> ExtendedContext.sqrt(Decimal('1'))
- Decimal('1')
- >>> ExtendedContext.sqrt(Decimal('1.0'))
- Decimal('1.0')
- >>> ExtendedContext.sqrt(Decimal('1.00'))
- Decimal('1.0')
- >>> ExtendedContext.sqrt(Decimal('7'))
- Decimal('2.64575131')
- >>> ExtendedContext.sqrt(Decimal('10'))
- Decimal('3.16227766')
- >>> ExtendedContext.sqrt(2)
- Decimal('1.41421356')
- >>> ExtendedContext.prec
- 9
- """
- a = _convert_other(a, raiseit=True)
- return a.sqrt(context=self)
-
- def subtract(self, a, b):
- """Return the difference between the two operands.
-
- >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
- Decimal('0.23')
- >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
- Decimal('0.00')
- >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
- Decimal('-0.77')
- >>> ExtendedContext.subtract(8, 5)
- Decimal('3')
- >>> ExtendedContext.subtract(Decimal(8), 5)
- Decimal('3')
- >>> ExtendedContext.subtract(8, Decimal(5))
- Decimal('3')
- """
- a = _convert_other(a, raiseit=True)
- r = a.__sub__(b, context=self)
- if r is NotImplemented:
- raise TypeError("Unable to convert %s to Decimal" % b)
- else:
- return r
-
- def to_eng_string(self, a):
- """Convert to a string, using engineering notation if an exponent is needed.
-
- Engineering notation has an exponent which is a multiple of 3. This
- can leave up to 3 digits to the left of the decimal place and may
- require the addition of either one or two trailing zeros.
-
- The operation is not affected by the context.
-
- >>> ExtendedContext.to_eng_string(Decimal('123E+1'))
- '1.23E+3'
- >>> ExtendedContext.to_eng_string(Decimal('123E+3'))
- '123E+3'
- >>> ExtendedContext.to_eng_string(Decimal('123E-10'))
- '12.3E-9'
- >>> ExtendedContext.to_eng_string(Decimal('-123E-12'))
- '-123E-12'
- >>> ExtendedContext.to_eng_string(Decimal('7E-7'))
- '700E-9'
- >>> ExtendedContext.to_eng_string(Decimal('7E+1'))
- '70'
- >>> ExtendedContext.to_eng_string(Decimal('0E+1'))
- '0.00E+3'
-
- """
- a = _convert_other(a, raiseit=True)
- return a.to_eng_string(context=self)
-
- def to_sci_string(self, a):
- """Converts a number to a string, using scientific notation.
-
- The operation is not affected by the context.
- """
- a = _convert_other(a, raiseit=True)
- return a.__str__(context=self)
-
- def to_integral_exact(self, a):
- """Rounds to an integer.
-
- When the operand has a negative exponent, the result is the same
- as using the quantize() operation using the given operand as the
- left-hand-operand, 1E+0 as the right-hand-operand, and the precision
- of the operand as the precision setting; Inexact and Rounded flags
- are allowed in this operation. The rounding mode is taken from the
- context.
-
- >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
- Decimal('2')
- >>> ExtendedContext.to_integral_exact(Decimal('100'))
- Decimal('100')
- >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
- Decimal('100')
- >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
- Decimal('102')
- >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
- Decimal('-102')
- >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
- Decimal('1.0E+6')
- >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
- Decimal('7.89E+77')
- >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
- Decimal('-Infinity')
- """
- a = _convert_other(a, raiseit=True)
- return a.to_integral_exact(context=self)
-
- def to_integral_value(self, a):
- """Rounds to an integer.
-
- When the operand has a negative exponent, the result is the same
- as using the quantize() operation using the given operand as the
- left-hand-operand, 1E+0 as the right-hand-operand, and the precision
- of the operand as the precision setting, except that no flags will
- be set. The rounding mode is taken from the context.
-
- >>> ExtendedContext.to_integral_value(Decimal('2.1'))
- Decimal('2')
- >>> ExtendedContext.to_integral_value(Decimal('100'))
- Decimal('100')
- >>> ExtendedContext.to_integral_value(Decimal('100.0'))
- Decimal('100')
- >>> ExtendedContext.to_integral_value(Decimal('101.5'))
- Decimal('102')
- >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
- Decimal('-102')
- >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
- Decimal('1.0E+6')
- >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
- Decimal('7.89E+77')
- >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
- Decimal('-Infinity')
- """
- a = _convert_other(a, raiseit=True)
- return a.to_integral_value(context=self)
-
- # the method name changed, but we provide also the old one, for compatibility
- to_integral = to_integral_value
-
-class _WorkRep(object):
- __slots__ = ('sign','int','exp')
- # sign: 0 or 1
- # int: int
- # exp: None, int, or string
-
- def __init__(self, value=None):
- if value is None:
- self.sign = None
- self.int = 0
- self.exp = None
- elif isinstance(value, Decimal):
- self.sign = value._sign
- self.int = int(value._int)
- self.exp = value._exp
- else:
- # assert isinstance(value, tuple)
- self.sign = value[0]
- self.int = value[1]
- self.exp = value[2]
-
- def __repr__(self):
- return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
-
-
-
-def _normalize(op1, op2, prec = 0):
- """Normalizes op1, op2 to have the same exp and length of coefficient.
-
- Done during addition.
- """
- if op1.exp < op2.exp:
- tmp = op2
- other = op1
- else:
- tmp = op1
- other = op2
-
- # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
- # Then adding 10**exp to tmp has the same effect (after rounding)
- # as adding any positive quantity smaller than 10**exp; similarly
- # for subtraction. So if other is smaller than 10**exp we replace
- # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
- tmp_len = len(str(tmp.int))
- other_len = len(str(other.int))
- exp = tmp.exp + min(-1, tmp_len - prec - 2)
- if other_len + other.exp - 1 < exp:
- other.int = 1
- other.exp = exp
-
- tmp.int *= 10 ** (tmp.exp - other.exp)
- tmp.exp = other.exp
- return op1, op2
-
-##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
-
-_nbits = int.bit_length
-
-def _decimal_lshift_exact(n, e):
- """ Given integers n and e, return n * 10**e if it's an integer, else None.
-
- The computation is designed to avoid computing large powers of 10
- unnecessarily.
-
- >>> _decimal_lshift_exact(3, 4)
- 30000
- >>> _decimal_lshift_exact(300, -999999999) # returns None
-
- """
- if n == 0:
- return 0
- elif e >= 0:
- return n * 10**e
- else:
- # val_n = largest power of 10 dividing n.
- str_n = str(abs(n))
- val_n = len(str_n) - len(str_n.rstrip('0'))
- return None if val_n < -e else n // 10**-e
-
-def _sqrt_nearest(n, a):
- """Closest integer to the square root of the positive integer n. a is
- an initial approximation to the square root. Any positive integer
- will do for a, but the closer a is to the square root of n the
- faster convergence will be.
-
- """
- if n <= 0 or a <= 0:
- raise ValueError("Both arguments to _sqrt_nearest should be positive.")
-
- b=0
- while a != b:
- b, a = a, a--n//a>>1
- return a
-
-def _rshift_nearest(x, shift):
- """Given an integer x and a nonnegative integer shift, return closest
- integer to x / 2**shift; use round-to-even in case of a tie.
-
- """
- b, q = 1 << shift, x >> shift
- return q + (2*(x & (b-1)) + (q&1) > b)
-
-def _div_nearest(a, b):
- """Closest integer to a/b, a and b positive integers; rounds to even
- in the case of a tie.
-
- """
- q, r = divmod(a, b)
- return q + (2*r + (q&1) > b)
-
-def _ilog(x, M, L = 8):
- """Integer approximation to M*log(x/M), with absolute error boundable
- in terms only of x/M.
-
- Given positive integers x and M, return an integer approximation to
- M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
- between the approximation and the exact result is at most 22. For
- L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
- both cases these are upper bounds on the error; it will usually be
- much smaller."""
-
- # The basic algorithm is the following: let log1p be the function
- # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
- # the reduction
- #
- # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
- #
- # repeatedly until the argument to log1p is small (< 2**-L in
- # absolute value). For small y we can use the Taylor series
- # expansion
- #
- # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
- #
- # truncating at T such that y**T is small enough. The whole
- # computation is carried out in a form of fixed-point arithmetic,
- # with a real number z being represented by an integer
- # approximation to z*M. To avoid loss of precision, the y below
- # is actually an integer approximation to 2**R*y*M, where R is the
- # number of reductions performed so far.
-
- y = x-M
- # argument reduction; R = number of reductions performed
- R = 0
- while (R <= L and abs(y) << L-R >= M or
- R > L and abs(y) >> R-L >= M):
- y = _div_nearest((M*y) << 1,
- M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
- R += 1
-
- # Taylor series with T terms
- T = -int(-10*len(str(M))//(3*L))
- yshift = _rshift_nearest(y, R)
- w = _div_nearest(M, T)
- for k in range(T-1, 0, -1):
- w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
-
- return _div_nearest(w*y, M)
-
-def _dlog10(c, e, p):
- """Given integers c, e and p with c > 0, p >= 0, compute an integer
- approximation to 10**p * log10(c*10**e), with an absolute error of
- at most 1. Assumes that c*10**e is not exactly 1."""
-
- # increase precision by 2; compensate for this by dividing
- # final result by 100
- p += 2
-
- # write c*10**e as d*10**f with either:
- # f >= 0 and 1 <= d <= 10, or
- # f <= 0 and 0.1 <= d <= 1.
- # Thus for c*10**e close to 1, f = 0
- l = len(str(c))
- f = e+l - (e+l >= 1)
-
- if p > 0:
- M = 10**p
- k = e+p-f
- if k >= 0:
- c *= 10**k
- else:
- c = _div_nearest(c, 10**-k)
-
- log_d = _ilog(c, M) # error < 5 + 22 = 27
- log_10 = _log10_digits(p) # error < 1
- log_d = _div_nearest(log_d*M, log_10)
- log_tenpower = f*M # exact
- else:
- log_d = 0 # error < 2.31
- log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
-
- return _div_nearest(log_tenpower+log_d, 100)
-
-def _dlog(c, e, p):
- """Given integers c, e and p with c > 0, compute an integer
- approximation to 10**p * log(c*10**e), with an absolute error of
- at most 1. Assumes that c*10**e is not exactly 1."""
-
- # Increase precision by 2. The precision increase is compensated
- # for at the end with a division by 100.
- p += 2
-
- # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
- # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
- # as 10**p * log(d) + 10**p*f * log(10).
- l = len(str(c))
- f = e+l - (e+l >= 1)
-
- # compute approximation to 10**p*log(d), with error < 27
- if p > 0:
- k = e+p-f
- if k >= 0:
- c *= 10**k
- else:
- c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
-
- # _ilog magnifies existing error in c by a factor of at most 10
- log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
- else:
- # p <= 0: just approximate the whole thing by 0; error < 2.31
- log_d = 0
-
- # compute approximation to f*10**p*log(10), with error < 11.
- if f:
- extra = len(str(abs(f)))-1
- if p + extra >= 0:
- # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
- # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
- f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
- else:
- f_log_ten = 0
- else:
- f_log_ten = 0
-
- # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
- return _div_nearest(f_log_ten + log_d, 100)
-
-class _Log10Memoize(object):
- """Class to compute, store, and allow retrieval of, digits of the
- constant log(10) = 2.302585.... This constant is needed by
- Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
- def __init__(self):
- self.digits = "23025850929940456840179914546843642076011014886"
-
- def getdigits(self, p):
- """Given an integer p >= 0, return floor(10**p)*log(10).
-
- For example, self.getdigits(3) returns 2302.
- """
- # digits are stored as a string, for quick conversion to
- # integer in the case that we've already computed enough
- # digits; the stored digits should always be correct
- # (truncated, not rounded to nearest).
- if p < 0:
- raise ValueError("p should be nonnegative")
-
- if p >= len(self.digits):
- # compute p+3, p+6, p+9, ... digits; continue until at
- # least one of the extra digits is nonzero
- extra = 3
- while True:
- # compute p+extra digits, correct to within 1ulp
- M = 10**(p+extra+2)
- digits = str(_div_nearest(_ilog(10*M, M), 100))
- if digits[-extra:] != '0'*extra:
- break
- extra += 3
- # keep all reliable digits so far; remove trailing zeros
- # and next nonzero digit
- self.digits = digits.rstrip('0')[:-1]
- return int(self.digits[:p+1])
-
-_log10_digits = _Log10Memoize().getdigits
-
-def _iexp(x, M, L=8):
- """Given integers x and M, M > 0, such that x/M is small in absolute
- value, compute an integer approximation to M*exp(x/M). For 0 <=
- x/M <= 2.4, the absolute error in the result is bounded by 60 (and
- is usually much smaller)."""
-
- # Algorithm: to compute exp(z) for a real number z, first divide z
- # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
- # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
- # series
- #
- # expm1(x) = x + x**2/2! + x**3/3! + ...
- #
- # Now use the identity
- #
- # expm1(2x) = expm1(x)*(expm1(x)+2)
- #
- # R times to compute the sequence expm1(z/2**R),
- # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
-
- # Find R such that x/2**R/M <= 2**-L
- R = _nbits((x<<L)//M)
-
- # Taylor series. (2**L)**T > M
- T = -int(-10*len(str(M))//(3*L))
- y = _div_nearest(x, T)
- Mshift = M<<R
- for i in range(T-1, 0, -1):
- y = _div_nearest(x*(Mshift + y), Mshift * i)
-
- # Expansion
- for k in range(R-1, -1, -1):
- Mshift = M<<(k+2)
- y = _div_nearest(y*(y+Mshift), Mshift)
-
- return M+y
-
-def _dexp(c, e, p):
- """Compute an approximation to exp(c*10**e), with p decimal places of
- precision.
-
- Returns integers d, f such that:
-
- 10**(p-1) <= d <= 10**p, and
- (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
-
- In other words, d*10**f is an approximation to exp(c*10**e) with p
- digits of precision, and with an error in d of at most 1. This is
- almost, but not quite, the same as the error being < 1ulp: when d
- = 10**(p-1) the error could be up to 10 ulp."""
-
- # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
- p += 2
-
- # compute log(10) with extra precision = adjusted exponent of c*10**e
- extra = max(0, e + len(str(c)) - 1)
- q = p + extra
-
- # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
- # rounding down
- shift = e+q
- if shift >= 0:
- cshift = c*10**shift
- else:
- cshift = c//10**-shift
- quot, rem = divmod(cshift, _log10_digits(q))
-
- # reduce remainder back to original precision
- rem = _div_nearest(rem, 10**extra)
-
- # error in result of _iexp < 120; error after division < 0.62
- return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
-
-def _dpower(xc, xe, yc, ye, p):
- """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
- y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
-
- 10**(p-1) <= c <= 10**p, and
- (c-1)*10**e < x**y < (c+1)*10**e
-
- in other words, c*10**e is an approximation to x**y with p digits
- of precision, and with an error in c of at most 1. (This is
- almost, but not quite, the same as the error being < 1ulp: when c
- == 10**(p-1) we can only guarantee error < 10ulp.)
-
- We assume that: x is positive and not equal to 1, and y is nonzero.
- """
-
- # Find b such that 10**(b-1) <= |y| <= 10**b
- b = len(str(abs(yc))) + ye
-
- # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
- lxc = _dlog(xc, xe, p+b+1)
-
- # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
- shift = ye-b
- if shift >= 0:
- pc = lxc*yc*10**shift
- else:
- pc = _div_nearest(lxc*yc, 10**-shift)
-
- if pc == 0:
- # we prefer a result that isn't exactly 1; this makes it
- # easier to compute a correctly rounded result in __pow__
- if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
- coeff, exp = 10**(p-1)+1, 1-p
- else:
- coeff, exp = 10**p-1, -p
- else:
- coeff, exp = _dexp(pc, -(p+1), p+1)
- coeff = _div_nearest(coeff, 10)
- exp += 1
-
- return coeff, exp
-
-def _log10_lb(c, correction = {
- '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
- '6': 23, '7': 16, '8': 10, '9': 5}):
- """Compute a lower bound for 100*log10(c) for a positive integer c."""
- if c <= 0:
- raise ValueError("The argument to _log10_lb should be nonnegative.")
- str_c = str(c)
- return 100*len(str_c) - correction[str_c[0]]
-
-##### Helper Functions ####################################################
-
-def _convert_other(other, raiseit=False, allow_float=False):
- """Convert other to Decimal.
-
- Verifies that it's ok to use in an implicit construction.
- If allow_float is true, allow conversion from float; this
- is used in the comparison methods (__eq__ and friends).
-
- """
- if isinstance(other, Decimal):
- return other
- if isinstance(other, int):
- return Decimal(other)
- if allow_float and isinstance(other, float):
- return Decimal.from_float(other)
-
- if raiseit:
- raise TypeError("Unable to convert %s to Decimal" % other)
- return NotImplemented
-
-def _convert_for_comparison(self, other, equality_op=False):
- """Given a Decimal instance self and a Python object other, return
- a pair (s, o) of Decimal instances such that "s op o" is
- equivalent to "self op other" for any of the 6 comparison
- operators "op".
-
- """
- if isinstance(other, Decimal):
- return self, other
-
- # Comparison with a Rational instance (also includes integers):
- # self op n/d <=> self*d op n (for n and d integers, d positive).
- # A NaN or infinity can be left unchanged without affecting the
- # comparison result.
- if isinstance(other, _numbers.Rational):
- if not self._is_special:
- self = _dec_from_triple(self._sign,
- str(int(self._int) * other.denominator),
- self._exp)
- return self, Decimal(other.numerator)
-
- # Comparisons with float and complex types. == and != comparisons
- # with complex numbers should succeed, returning either True or False
- # as appropriate. Other comparisons return NotImplemented.
- if equality_op and isinstance(other, _numbers.Complex) and other.imag == 0:
- other = other.real
- if isinstance(other, float):
- context = getcontext()
- if equality_op:
- context.flags[FloatOperation] = 1
- else:
- context._raise_error(FloatOperation,
- "strict semantics for mixing floats and Decimals are enabled")
- return self, Decimal.from_float(other)
- return NotImplemented, NotImplemented
-
-
-##### Setup Specific Contexts ############################################
-
-# The default context prototype used by Context()
-# Is mutable, so that new contexts can have different default values
-
-DefaultContext = Context(
- prec=28, rounding=ROUND_HALF_EVEN,
- traps=[DivisionByZero, Overflow, InvalidOperation],
- flags=[],
- Emax=999999,
- Emin=-999999,
- capitals=1,
- clamp=0
-)
-
-# Pre-made alternate contexts offered by the specification
-# Don't change these; the user should be able to select these
-# contexts and be able to reproduce results from other implementations
-# of the spec.
-
-BasicContext = Context(
- prec=9, rounding=ROUND_HALF_UP,
- traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
- flags=[],
-)
-
-ExtendedContext = Context(
- prec=9, rounding=ROUND_HALF_EVEN,
- traps=[],
- flags=[],
-)
-
-
-##### crud for parsing strings #############################################
-#
-# Regular expression used for parsing numeric strings. Additional
-# comments:
-#
-# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
-# whitespace. But note that the specification disallows whitespace in
-# a numeric string.
-#
-# 2. For finite numbers (not infinities and NaNs) the body of the
-# number between the optional sign and the optional exponent must have
-# at least one decimal digit, possibly after the decimal point. The
-# lookahead expression '(?=\d|\.\d)' checks this.
-
-import re
-_parser = re.compile(r""" # A numeric string consists of:
-# \s*
- (?P<sign>[-+])? # an optional sign, followed by either...
- (
- (?=\d|\.\d) # ...a number (with at least one digit)
- (?P<int>\d*) # having a (possibly empty) integer part
- (\.(?P<frac>\d*))? # followed by an optional fractional part
- (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
- |
- Inf(inity)? # ...an infinity, or...
- |
- (?P<signal>s)? # ...an (optionally signaling)
- NaN # NaN
- (?P<diag>\d*) # with (possibly empty) diagnostic info.
- )
-# \s*
- \Z
-""", re.VERBOSE | re.IGNORECASE).match
-
-_all_zeros = re.compile('0*$').match
-_exact_half = re.compile('50*$').match
-
-##### PEP3101 support functions ##############################################
-# The functions in this section have little to do with the Decimal
-# class, and could potentially be reused or adapted for other pure
-# Python numeric classes that want to implement __format__
-#
-# A format specifier for Decimal looks like:
-#
-# [[fill]align][sign][#][0][minimumwidth][,][.precision][type]
-
-_parse_format_specifier_regex = re.compile(r"""\A
-(?:
- (?P<fill>.)?
- (?P<align>[<>=^])
-)?
-(?P<sign>[-+ ])?
-(?P<alt>\#)?
-(?P<zeropad>0)?
-(?P<minimumwidth>(?!0)\d+)?
-(?P<thousands_sep>,)?
-(?:\.(?P<precision>0|(?!0)\d+))?
-(?P<type>[eEfFgGn%])?
-\Z
-""", re.VERBOSE|re.DOTALL)
-
-del re
-
-# The locale module is only needed for the 'n' format specifier. The
-# rest of the PEP 3101 code functions quite happily without it, so we
-# don't care too much if locale isn't present.
-try:
- import locale as _locale
-except ImportError:
- pass
-
-def _parse_format_specifier(format_spec, _localeconv=None):
- """Parse and validate a format specifier.
-
- Turns a standard numeric format specifier into a dict, with the
- following entries:
-
- fill: fill character to pad field to minimum width
- align: alignment type, either '<', '>', '=' or '^'
- sign: either '+', '-' or ' '
- minimumwidth: nonnegative integer giving minimum width
- zeropad: boolean, indicating whether to pad with zeros
- thousands_sep: string to use as thousands separator, or ''
- grouping: grouping for thousands separators, in format
- used by localeconv
- decimal_point: string to use for decimal point
- precision: nonnegative integer giving precision, or None
- type: one of the characters 'eEfFgG%', or None
-
- """
- m = _parse_format_specifier_regex.match(format_spec)
- if m is None:
- raise ValueError("Invalid format specifier: " + format_spec)
-
- # get the dictionary
- format_dict = m.groupdict()
-
- # zeropad; defaults for fill and alignment. If zero padding
- # is requested, the fill and align fields should be absent.
- fill = format_dict['fill']
- align = format_dict['align']
- format_dict['zeropad'] = (format_dict['zeropad'] is not None)
- if format_dict['zeropad']:
- if fill is not None:
- raise ValueError("Fill character conflicts with '0'"
- " in format specifier: " + format_spec)
- if align is not None:
- raise ValueError("Alignment conflicts with '0' in "
- "format specifier: " + format_spec)
- format_dict['fill'] = fill or ' '
- # PEP 3101 originally specified that the default alignment should
- # be left; it was later agreed that right-aligned makes more sense
- # for numeric types. See http://bugs.python.org/issue6857.
- format_dict['align'] = align or '>'
-
- # default sign handling: '-' for negative, '' for positive
- if format_dict['sign'] is None:
- format_dict['sign'] = '-'
-
- # minimumwidth defaults to 0; precision remains None if not given
- format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
- if format_dict['precision'] is not None:
- format_dict['precision'] = int(format_dict['precision'])
-
- # if format type is 'g' or 'G' then a precision of 0 makes little
- # sense; convert it to 1. Same if format type is unspecified.
- if format_dict['precision'] == 0:
- if format_dict['type'] is None or format_dict['type'] in 'gGn':
- format_dict['precision'] = 1
-
- # determine thousands separator, grouping, and decimal separator, and
- # add appropriate entries to format_dict
- if format_dict['type'] == 'n':
- # apart from separators, 'n' behaves just like 'g'
- format_dict['type'] = 'g'
- if _localeconv is None:
- _localeconv = _locale.localeconv()
- if format_dict['thousands_sep'] is not None:
- raise ValueError("Explicit thousands separator conflicts with "
- "'n' type in format specifier: " + format_spec)
- format_dict['thousands_sep'] = _localeconv['thousands_sep']
- format_dict['grouping'] = _localeconv['grouping']
- format_dict['decimal_point'] = _localeconv['decimal_point']
- else:
- if format_dict['thousands_sep'] is None:
- format_dict['thousands_sep'] = ''
- format_dict['grouping'] = [3, 0]
- format_dict['decimal_point'] = '.'
-
- return format_dict
-
-def _format_align(sign, body, spec):
- """Given an unpadded, non-aligned numeric string 'body' and sign
- string 'sign', add padding and alignment conforming to the given
- format specifier dictionary 'spec' (as produced by
- parse_format_specifier).
-
- """
- # how much extra space do we have to play with?
- minimumwidth = spec['minimumwidth']
- fill = spec['fill']
- padding = fill*(minimumwidth - len(sign) - len(body))
-
- align = spec['align']
- if align == '<':
- result = sign + body + padding
- elif align == '>':
- result = padding + sign + body
- elif align == '=':
- result = sign + padding + body
- elif align == '^':
- half = len(padding)//2
- result = padding[:half] + sign + body + padding[half:]
- else:
- raise ValueError('Unrecognised alignment field')
-
- return result
-
-def _group_lengths(grouping):
- """Convert a localeconv-style grouping into a (possibly infinite)
- iterable of integers representing group lengths.
-
- """
- # The result from localeconv()['grouping'], and the input to this
- # function, should be a list of integers in one of the
- # following three forms:
- #
- # (1) an empty list, or
- # (2) nonempty list of positive integers + [0]
- # (3) list of positive integers + [locale.CHAR_MAX], or
-
- from itertools import chain, repeat
- if not grouping:
- return []
- elif grouping[-1] == 0 and len(grouping) >= 2:
- return chain(grouping[:-1], repeat(grouping[-2]))
- elif grouping[-1] == _locale.CHAR_MAX:
- return grouping[:-1]
- else:
- raise ValueError('unrecognised format for grouping')
-
-def _insert_thousands_sep(digits, spec, min_width=1):
- """Insert thousands separators into a digit string.
-
- spec is a dictionary whose keys should include 'thousands_sep' and
- 'grouping'; typically it's the result of parsing the format
- specifier using _parse_format_specifier.
-
- The min_width keyword argument gives the minimum length of the
- result, which will be padded on the left with zeros if necessary.
-
- If necessary, the zero padding adds an extra '0' on the left to
- avoid a leading thousands separator. For example, inserting
- commas every three digits in '123456', with min_width=8, gives
- '0,123,456', even though that has length 9.
-
- """
-
- sep = spec['thousands_sep']
- grouping = spec['grouping']
-
- groups = []
- for l in _group_lengths(grouping):
- if l <= 0:
- raise ValueError("group length should be positive")
- # max(..., 1) forces at least 1 digit to the left of a separator
- l = min(max(len(digits), min_width, 1), l)
- groups.append('0'*(l - len(digits)) + digits[-l:])
- digits = digits[:-l]
- min_width -= l
- if not digits and min_width <= 0:
- break
- min_width -= len(sep)
- else:
- l = max(len(digits), min_width, 1)
- groups.append('0'*(l - len(digits)) + digits[-l:])
- return sep.join(reversed(groups))
-
-def _format_sign(is_negative, spec):
- """Determine sign character."""
-
- if is_negative:
- return '-'
- elif spec['sign'] in ' +':
- return spec['sign']
- else:
- return ''
-
-def _format_number(is_negative, intpart, fracpart, exp, spec):
- """Format a number, given the following data:
-
- is_negative: true if the number is negative, else false
- intpart: string of digits that must appear before the decimal point
- fracpart: string of digits that must come after the point
- exp: exponent, as an integer
- spec: dictionary resulting from parsing the format specifier
-
- This function uses the information in spec to:
- insert separators (decimal separator and thousands separators)
- format the sign
- format the exponent
- add trailing '%' for the '%' type
- zero-pad if necessary
- fill and align if necessary
- """
-
- sign = _format_sign(is_negative, spec)
-
- if fracpart or spec['alt']:
- fracpart = spec['decimal_point'] + fracpart
-
- if exp != 0 or spec['type'] in 'eE':
- echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
- fracpart += "{0}{1:+}".format(echar, exp)
- if spec['type'] == '%':
- fracpart += '%'
-
- if spec['zeropad']:
- min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
- else:
- min_width = 0
- intpart = _insert_thousands_sep(intpart, spec, min_width)
-
- return _format_align(sign, intpart+fracpart, spec)
-
-
-##### Useful Constants (internal use only) ################################
-
-# Reusable defaults
-_Infinity = Decimal('Inf')
-_NegativeInfinity = Decimal('-Inf')
-_NaN = Decimal('NaN')
-_Zero = Decimal(0)
-_One = Decimal(1)
-_NegativeOne = Decimal(-1)
-
-# _SignedInfinity[sign] is infinity w/ that sign
-_SignedInfinity = (_Infinity, _NegativeInfinity)
-
-# Constants related to the hash implementation; hash(x) is based
-# on the reduction of x modulo _PyHASH_MODULUS
-_PyHASH_MODULUS = sys.hash_info.modulus
-# hash values to use for positive and negative infinities, and nans
-_PyHASH_INF = sys.hash_info.inf
-_PyHASH_NAN = sys.hash_info.nan
-
-# _PyHASH_10INV is the inverse of 10 modulo the prime _PyHASH_MODULUS
-_PyHASH_10INV = pow(10, _PyHASH_MODULUS - 2, _PyHASH_MODULUS)
-del sys
diff --git a/lib/python3.10/_pyio.py b/lib/python3.10/_pyio.py
deleted file mode 100644
index fb867fb..0000000
--- a/lib/python3.10/_pyio.py
+++ /dev/null
@@ -1,2718 +0,0 @@
-"""
-Python implementation of the io module.
-"""
-
-import os
-import abc
-import codecs
-import errno
-import stat
-import sys
-# Import _thread instead of threading to reduce startup cost
-from _thread import allocate_lock as Lock
-if sys.platform in {'win32', 'cygwin'}:
- from msvcrt import setmode as _setmode
-else:
- _setmode = None
-
-import io
-from io import (__all__, SEEK_SET, SEEK_CUR, SEEK_END)
-
-valid_seek_flags = {0, 1, 2} # Hardwired values
-if hasattr(os, 'SEEK_HOLE') :
- valid_seek_flags.add(os.SEEK_HOLE)
- valid_seek_flags.add(os.SEEK_DATA)
-
-# open() uses st_blksize whenever we can
-DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
-
-# NOTE: Base classes defined here are registered with the "official" ABCs
-# defined in io.py. We don't use real inheritance though, because we don't want
-# to inherit the C implementations.
-
-# Rebind for compatibility
-BlockingIOError = BlockingIOError
-
-# Does io.IOBase finalizer log the exception if the close() method fails?
-# The exception is ignored silently by default in release build.
-_IOBASE_EMITS_UNRAISABLE = (hasattr(sys, "gettotalrefcount") or sys.flags.dev_mode)
-# Does open() check its 'errors' argument?
-_CHECK_ERRORS = _IOBASE_EMITS_UNRAISABLE
-
-
-def text_encoding(encoding, stacklevel=2):
- """
- A helper function to choose the text encoding.
-
- When encoding is not None, just return it.
- Otherwise, return the default text encoding (i.e. "locale").
-
- This function emits an EncodingWarning if *encoding* is None and
- sys.flags.warn_default_encoding is true.
-
- This can be used in APIs with an encoding=None parameter
- that pass it to TextIOWrapper or open.
- However, please consider using encoding="utf-8" for new APIs.
- """
- if encoding is None:
- encoding = "locale"
- if sys.flags.warn_default_encoding:
- import warnings
- warnings.warn("'encoding' argument not specified.",
- EncodingWarning, stacklevel + 1)
- return encoding
-
-
-# Wrapper for builtins.open
-#
-# Trick so that open() won't become a bound method when stored
-# as a class variable (as dbm.dumb does).
-#
-# See init_set_builtins_open() in Python/pylifecycle.c.
-@staticmethod
-def open(file, mode="r", buffering=-1, encoding=None, errors=None,
- newline=None, closefd=True, opener=None):
-
- r"""Open file and return a stream. Raise OSError upon failure.
-
- file is either a text or byte string giving the name (and the path
- if the file isn't in the current working directory) of the file to
- be opened or an integer file descriptor of the file to be
- wrapped. (If a file descriptor is given, it is closed when the
- returned I/O object is closed, unless closefd is set to False.)
-
- mode is an optional string that specifies the mode in which the file is
- opened. It defaults to 'r' which means open for reading in text mode. Other
- common values are 'w' for writing (truncating the file if it already
- exists), 'x' for exclusive creation of a new file, and 'a' for appending
- (which on some Unix systems, means that all writes append to the end of the
- file regardless of the current seek position). In text mode, if encoding is
- not specified the encoding used is platform dependent. (For reading and
- writing raw bytes use binary mode and leave encoding unspecified.) The
- available modes are:
-
- ========= ===============================================================
- Character Meaning
- --------- ---------------------------------------------------------------
- 'r' open for reading (default)
- 'w' open for writing, truncating the file first
- 'x' create a new file and open it for writing
- 'a' open for writing, appending to the end of the file if it exists
- 'b' binary mode
- 't' text mode (default)
- '+' open a disk file for updating (reading and writing)
- 'U' universal newline mode (deprecated)
- ========= ===============================================================
-
- The default mode is 'rt' (open for reading text). For binary random
- access, the mode 'w+b' opens and truncates the file to 0 bytes, while
- 'r+b' opens the file without truncation. The 'x' mode implies 'w' and
- raises an `FileExistsError` if the file already exists.
-
- Python distinguishes between files opened in binary and text modes,
- even when the underlying operating system doesn't. Files opened in
- binary mode (appending 'b' to the mode argument) return contents as
- bytes objects without any decoding. In text mode (the default, or when
- 't' is appended to the mode argument), the contents of the file are
- returned as strings, the bytes having been first decoded using a
- platform-dependent encoding or using the specified encoding if given.
-
- 'U' mode is deprecated and will raise an exception in future versions
- of Python. It has no effect in Python 3. Use newline to control
- universal newlines mode.
-
- buffering is an optional integer used to set the buffering policy.
- Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
- line buffering (only usable in text mode), and an integer > 1 to indicate
- the size of a fixed-size chunk buffer. When no buffering argument is
- given, the default buffering policy works as follows:
-
- * Binary files are buffered in fixed-size chunks; the size of the buffer
- is chosen using a heuristic trying to determine the underlying device's
- "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
- On many systems, the buffer will typically be 4096 or 8192 bytes long.
-
- * "Interactive" text files (files for which isatty() returns True)
- use line buffering. Other text files use the policy described above
- for binary files.
-
- encoding is the str name of the encoding used to decode or encode the
- file. This should only be used in text mode. The default encoding is
- platform dependent, but any encoding supported by Python can be
- passed. See the codecs module for the list of supported encodings.
-
- errors is an optional string that specifies how encoding errors are to
- be handled---this argument should not be used in binary mode. Pass
- 'strict' to raise a ValueError exception if there is an encoding error
- (the default of None has the same effect), or pass 'ignore' to ignore
- errors. (Note that ignoring encoding errors can lead to data loss.)
- See the documentation for codecs.register for a list of the permitted
- encoding error strings.
-
- newline is a string controlling how universal newlines works (it only
- applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works
- as follows:
-
- * On input, if newline is None, universal newlines mode is
- enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
- these are translated into '\n' before being returned to the
- caller. If it is '', universal newline mode is enabled, but line
- endings are returned to the caller untranslated. If it has any of
- the other legal values, input lines are only terminated by the given
- string, and the line ending is returned to the caller untranslated.
-
- * On output, if newline is None, any '\n' characters written are
- translated to the system default line separator, os.linesep. If
- newline is '', no translation takes place. If newline is any of the
- other legal values, any '\n' characters written are translated to
- the given string.
-
- closedfd is a bool. If closefd is False, the underlying file descriptor will
- be kept open when the file is closed. This does not work when a file name is
- given and must be True in that case.
-
- The newly created file is non-inheritable.
-
- A custom opener can be used by passing a callable as *opener*. The
- underlying file descriptor for the file object is then obtained by calling
- *opener* with (*file*, *flags*). *opener* must return an open file
- descriptor (passing os.open as *opener* results in functionality similar to
- passing None).
-
- open() returns a file object whose type depends on the mode, and
- through which the standard file operations such as reading and writing
- are performed. When open() is used to open a file in a text mode ('w',
- 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
- a file in a binary mode, the returned class varies: in read binary
- mode, it returns a BufferedReader; in write binary and append binary
- modes, it returns a BufferedWriter, and in read/write mode, it returns
- a BufferedRandom.
-
- It is also possible to use a string or bytearray as a file for both
- reading and writing. For strings StringIO can be used like a file
- opened in a text mode, and for bytes a BytesIO can be used like a file
- opened in a binary mode.
- """
- if not isinstance(file, int):
- file = os.fspath(file)
- if not isinstance(file, (str, bytes, int)):
- raise TypeError("invalid file: %r" % file)
- if not isinstance(mode, str):
- raise TypeError("invalid mode: %r" % mode)
- if not isinstance(buffering, int):
- raise TypeError("invalid buffering: %r" % buffering)
- if encoding is not None and not isinstance(encoding, str):
- raise TypeError("invalid encoding: %r" % encoding)
- if errors is not None and not isinstance(errors, str):
- raise TypeError("invalid errors: %r" % errors)
- modes = set(mode)
- if modes - set("axrwb+tU") or len(mode) > len(modes):
- raise ValueError("invalid mode: %r" % mode)
- creating = "x" in modes
- reading = "r" in modes
- writing = "w" in modes
- appending = "a" in modes
- updating = "+" in modes
- text = "t" in modes
- binary = "b" in modes
- if "U" in modes:
- if creating or writing or appending or updating:
- raise ValueError("mode U cannot be combined with 'x', 'w', 'a', or '+'")
- import warnings
- warnings.warn("'U' mode is deprecated",
- DeprecationWarning, 2)
- reading = True
- if text and binary:
- raise ValueError("can't have text and binary mode at once")
- if creating + reading + writing + appending > 1:
- raise ValueError("can't have read/write/append mode at once")
- if not (creating or reading or writing or appending):
- raise ValueError("must have exactly one of read/write/append mode")
- if binary and encoding is not None:
- raise ValueError("binary mode doesn't take an encoding argument")
- if binary and errors is not None:
- raise ValueError("binary mode doesn't take an errors argument")
- if binary and newline is not None:
- raise ValueError("binary mode doesn't take a newline argument")
- if binary and buffering == 1:
- import warnings
- warnings.warn("line buffering (buffering=1) isn't supported in binary "
- "mode, the default buffer size will be used",
- RuntimeWarning, 2)
- raw = FileIO(file,
- (creating and "x" or "") +
- (reading and "r" or "") +
- (writing and "w" or "") +
- (appending and "a" or "") +
- (updating and "+" or ""),
- closefd, opener=opener)
- result = raw
- try:
- line_buffering = False
- if buffering == 1 or buffering < 0 and raw.isatty():
- buffering = -1
- line_buffering = True
- if buffering < 0:
- buffering = DEFAULT_BUFFER_SIZE
- try:
- bs = os.fstat(raw.fileno()).st_blksize
- except (OSError, AttributeError):
- pass
- else:
- if bs > 1:
- buffering = bs
- if buffering < 0:
- raise ValueError("invalid buffering size")
- if buffering == 0:
- if binary:
- return result
- raise ValueError("can't have unbuffered text I/O")
- if updating:
- buffer = BufferedRandom(raw, buffering)
- elif creating or writing or appending:
- buffer = BufferedWriter(raw, buffering)
- elif reading:
- buffer = BufferedReader(raw, buffering)
- else:
- raise ValueError("unknown mode: %r" % mode)
- result = buffer
- if binary:
- return result
- encoding = text_encoding(encoding)
- text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
- result = text
- text.mode = mode
- return result
- except:
- result.close()
- raise
-
-# Define a default pure-Python implementation for open_code()
-# that does not allow hooks. Warn on first use. Defined for tests.
-def _open_code_with_warning(path):
- """Opens the provided file with mode ``'rb'``. This function
- should be used when the intent is to treat the contents as
- executable code.
-
- ``path`` should be an absolute path.
-
- When supported by the runtime, this function can be hooked
- in order to allow embedders more control over code files.
- This functionality is not supported on the current runtime.
- """
- import warnings
- warnings.warn("_pyio.open_code() may not be using hooks",
- RuntimeWarning, 2)
- return open(path, "rb")
-
-try:
- open_code = io.open_code
-except AttributeError:
- open_code = _open_code_with_warning
-
-
-def __getattr__(name):
- if name == "OpenWrapper":
- # bpo-43680: Until Python 3.9, _pyio.open was not a static method and
- # builtins.open was set to OpenWrapper to not become a bound method
- # when set to a class variable. _io.open is a built-in function whereas
- # _pyio.open is a Python function. In Python 3.10, _pyio.open() is now
- # a static method, and builtins.open() is now io.open().
- import warnings
- warnings.warn('OpenWrapper is deprecated, use open instead',
- DeprecationWarning, stacklevel=2)
- global OpenWrapper
- OpenWrapper = open
- return OpenWrapper
- raise AttributeError(name)
-
-
-# In normal operation, both `UnsupportedOperation`s should be bound to the
-# same object.
-try:
- UnsupportedOperation = io.UnsupportedOperation
-except AttributeError:
- class UnsupportedOperation(OSError, ValueError):
- pass
-
-
-class IOBase(metaclass=abc.ABCMeta):
-
- """The abstract base class for all I/O classes.
-
- This class provides dummy implementations for many methods that
- derived classes can override selectively; the default implementations
- represent a file that cannot be read, written or seeked.
-
- Even though IOBase does not declare read or write because
- their signatures will vary, implementations and clients should
- consider those methods part of the interface. Also, implementations
- may raise UnsupportedOperation when operations they do not support are
- called.
-
- The basic type used for binary data read from or written to a file is
- bytes. Other bytes-like objects are accepted as method arguments too.
- Text I/O classes work with str data.
-
- Note that calling any method (even inquiries) on a closed stream is
- undefined. Implementations may raise OSError in this case.
-
- IOBase (and its subclasses) support the iterator protocol, meaning
- that an IOBase object can be iterated over yielding the lines in a
- stream.
-
- IOBase also supports the :keyword:`with` statement. In this example,
- fp is closed after the suite of the with statement is complete:
-
- with open('spam.txt', 'r') as fp:
- fp.write('Spam and eggs!')
- """
-
- ### Internal ###
-
- def _unsupported(self, name):
- """Internal: raise an OSError exception for unsupported operations."""
- raise UnsupportedOperation("%s.%s() not supported" %
- (self.__class__.__name__, name))
-
- ### Positioning ###
-
- def seek(self, pos, whence=0):
- """Change stream position.
-
- Change the stream position to byte offset pos. Argument pos is
- interpreted relative to the position indicated by whence. Values
- for whence are ints:
-
- * 0 -- start of stream (the default); offset should be zero or positive
- * 1 -- current stream position; offset may be negative
- * 2 -- end of stream; offset is usually negative
- Some operating systems / file systems could provide additional values.
-
- Return an int indicating the new absolute position.
- """
- self._unsupported("seek")
-
- def tell(self):
- """Return an int indicating the current stream position."""
- return self.seek(0, 1)
-
- def truncate(self, pos=None):
- """Truncate file to size bytes.
-
- Size defaults to the current IO position as reported by tell(). Return
- the new size.
- """
- self._unsupported("truncate")
-
- ### Flush and close ###
-
- def flush(self):
- """Flush write buffers, if applicable.
-
- This is not implemented for read-only and non-blocking streams.
- """
- self._checkClosed()
- # XXX Should this return the number of bytes written???
-
- __closed = False
-
- def close(self):
- """Flush and close the IO object.
-
- This method has no effect if the file is already closed.
- """
- if not self.__closed:
- try:
- self.flush()
- finally:
- self.__closed = True
-
- def __del__(self):
- """Destructor. Calls close()."""
- try:
- closed = self.closed
- except AttributeError:
- # If getting closed fails, then the object is probably
- # in an unusable state, so ignore.
- return
-
- if closed:
- return
-
- if _IOBASE_EMITS_UNRAISABLE:
- self.close()
- else:
- # The try/except block is in case this is called at program
- # exit time, when it's possible that globals have already been
- # deleted, and then the close() call might fail. Since
- # there's nothing we can do about such failures and they annoy
- # the end users, we suppress the traceback.
- try:
- self.close()
- except:
- pass
-
- ### Inquiries ###
-
- def seekable(self):
- """Return a bool indicating whether object supports random access.
-
- If False, seek(), tell() and truncate() will raise OSError.
- This method may need to do a test seek().
- """
- return False
-
- def _checkSeekable(self, msg=None):
- """Internal: raise UnsupportedOperation if file is not seekable
- """
- if not self.seekable():
- raise UnsupportedOperation("File or stream is not seekable."
- if msg is None else msg)
-
- def readable(self):
- """Return a bool indicating whether object was opened for reading.
-
- If False, read() will raise OSError.
- """
- return False
-
- def _checkReadable(self, msg=None):
- """Internal: raise UnsupportedOperation if file is not readable
- """
- if not self.readable():
- raise UnsupportedOperation("File or stream is not readable."
- if msg is None else msg)
-
- def writable(self):
- """Return a bool indicating whether object was opened for writing.
-
- If False, write() and truncate() will raise OSError.
- """
- return False
-
- def _checkWritable(self, msg=None):
- """Internal: raise UnsupportedOperation if file is not writable
- """
- if not self.writable():
- raise UnsupportedOperation("File or stream is not writable."
- if msg is None else msg)
-
- @property
- def closed(self):
- """closed: bool. True iff the file has been closed.
-
- For backwards compatibility, this is a property, not a predicate.
- """
- return self.__closed
-
- def _checkClosed(self, msg=None):
- """Internal: raise a ValueError if file is closed
- """
- if self.closed:
- raise ValueError("I/O operation on closed file."
- if msg is None else msg)
-
- ### Context manager ###
-
- def __enter__(self): # That's a forward reference
- """Context management protocol. Returns self (an instance of IOBase)."""
- self._checkClosed()
- return self
-
- def __exit__(self, *args):
- """Context management protocol. Calls close()"""
- self.close()
-
- ### Lower-level APIs ###
-
- # XXX Should these be present even if unimplemented?
-
- def fileno(self):
- """Returns underlying file descriptor (an int) if one exists.
-
- An OSError is raised if the IO object does not use a file descriptor.
- """
- self._unsupported("fileno")
-
- def isatty(self):
- """Return a bool indicating whether this is an 'interactive' stream.
-
- Return False if it can't be determined.
- """
- self._checkClosed()
- return False
-
- ### Readline[s] and writelines ###
-
- def readline(self, size=-1):
- r"""Read and return a line of bytes from the stream.
-
- If size is specified, at most size bytes will be read.
- Size should be an int.
-
- The line terminator is always b'\n' for binary files; for text
- files, the newlines argument to open can be used to select the line
- terminator(s) recognized.
- """
- # For backwards compatibility, a (slowish) readline().
- if hasattr(self, "peek"):
- def nreadahead():
- readahead = self.peek(1)
- if not readahead:
- return 1
- n = (readahead.find(b"\n") + 1) or len(readahead)
- if size >= 0:
- n = min(n, size)
- return n
- else:
- def nreadahead():
- return 1
- if size is None:
- size = -1
- else:
- try:
- size_index = size.__index__
- except AttributeError:
- raise TypeError(f"{size!r} is not an integer")
- else:
- size = size_index()
- res = bytearray()
- while size < 0 or len(res) < size:
- b = self.read(nreadahead())
- if not b:
- break
- res += b
- if res.endswith(b"\n"):
- break
- return bytes(res)
-
- def __iter__(self):
- self._checkClosed()
- return self
-
- def __next__(self):
- line = self.readline()
- if not line:
- raise StopIteration
- return line
-
- def readlines(self, hint=None):
- """Return a list of lines from the stream.
-
- hint can be specified to control the number of lines read: no more
- lines will be read if the total size (in bytes/characters) of all
- lines so far exceeds hint.
- """
- if hint is None or hint <= 0:
- return list(self)
- n = 0
- lines = []
- for line in self:
- lines.append(line)
- n += len(line)
- if n >= hint:
- break
- return lines
-
- def writelines(self, lines):
- """Write a list of lines to the stream.
-
- Line separators are not added, so it is usual for each of the lines
- provided to have a line separator at the end.
- """
- self._checkClosed()
- for line in lines:
- self.write(line)
-
-io.IOBase.register(IOBase)
-
-
-class RawIOBase(IOBase):
-
- """Base class for raw binary I/O."""
-
- # The read() method is implemented by calling readinto(); derived
- # classes that want to support read() only need to implement
- # readinto() as a primitive operation. In general, readinto() can be
- # more efficient than read().
-
- # (It would be tempting to also provide an implementation of
- # readinto() in terms of read(), in case the latter is a more suitable
- # primitive operation, but that would lead to nasty recursion in case
- # a subclass doesn't implement either.)
-
- def read(self, size=-1):
- """Read and return up to size bytes, where size is an int.
-
- Returns an empty bytes object on EOF, or None if the object is
- set not to block and has no data to read.
- """
- if size is None:
- size = -1
- if size < 0:
- return self.readall()
- b = bytearray(size.__index__())
- n = self.readinto(b)
- if n is None:
- return None
- del b[n:]
- return bytes(b)
-
- def readall(self):
- """Read until EOF, using multiple read() call."""
- res = bytearray()
- while True:
- data = self.read(DEFAULT_BUFFER_SIZE)
- if not data:
- break
- res += data
- if res:
- return bytes(res)
- else:
- # b'' or None
- return data
-
- def readinto(self, b):
- """Read bytes into a pre-allocated bytes-like object b.
-
- Returns an int representing the number of bytes read (0 for EOF), or
- None if the object is set not to block and has no data to read.
- """
- self._unsupported("readinto")
-
- def write(self, b):
- """Write the given buffer to the IO stream.
-
- Returns the number of bytes written, which may be less than the
- length of b in bytes.
- """
- self._unsupported("write")
-
-io.RawIOBase.register(RawIOBase)
-from _io import FileIO
-RawIOBase.register(FileIO)
-
-
-class BufferedIOBase(IOBase):
-
- """Base class for buffered IO objects.
-
- The main difference with RawIOBase is that the read() method
- supports omitting the size argument, and does not have a default
- implementation that defers to readinto().
-
- In addition, read(), readinto() and write() may raise
- BlockingIOError if the underlying raw stream is in non-blocking
- mode and not ready; unlike their raw counterparts, they will never
- return None.
-
- A typical implementation should not inherit from a RawIOBase
- implementation, but wrap one.
- """
-
- def read(self, size=-1):
- """Read and return up to size bytes, where size is an int.
-
- If the argument is omitted, None, or negative, reads and
- returns all data until EOF.
-
- If the argument is positive, and the underlying raw stream is
- not 'interactive', multiple raw reads may be issued to satisfy
- the byte count (unless EOF is reached first). But for
- interactive raw streams (XXX and for pipes?), at most one raw
- read will be issued, and a short result does not imply that
- EOF is imminent.
-
- Returns an empty bytes array on EOF.
-
- Raises BlockingIOError if the underlying raw stream has no
- data at the moment.
- """
- self._unsupported("read")
-
- def read1(self, size=-1):
- """Read up to size bytes with at most one read() system call,
- where size is an int.
- """
- self._unsupported("read1")
-
- def readinto(self, b):
- """Read bytes into a pre-allocated bytes-like object b.
-
- Like read(), this may issue multiple reads to the underlying raw
- stream, unless the latter is 'interactive'.
-
- Returns an int representing the number of bytes read (0 for EOF).
-
- Raises BlockingIOError if the underlying raw stream has no
- data at the moment.
- """
-
- return self._readinto(b, read1=False)
-
- def readinto1(self, b):
- """Read bytes into buffer *b*, using at most one system call
-
- Returns an int representing the number of bytes read (0 for EOF).
-
- Raises BlockingIOError if the underlying raw stream has no
- data at the moment.
- """
-
- return self._readinto(b, read1=True)
-
- def _readinto(self, b, read1):
- if not isinstance(b, memoryview):
- b = memoryview(b)
- b = b.cast('B')
-
- if read1:
- data = self.read1(len(b))
- else:
- data = self.read(len(b))
- n = len(data)
-
- b[:n] = data
-
- return n
-
- def write(self, b):
- """Write the given bytes buffer to the IO stream.
-
- Return the number of bytes written, which is always the length of b
- in bytes.
-
- Raises BlockingIOError if the buffer is full and the
- underlying raw stream cannot accept more data at the moment.
- """
- self._unsupported("write")
-
- def detach(self):
- """
- Separate the underlying raw stream from the buffer and return it.
-
- After the raw stream has been detached, the buffer is in an unusable
- state.
- """
- self._unsupported("detach")
-
-io.BufferedIOBase.register(BufferedIOBase)
-
-
-class _BufferedIOMixin(BufferedIOBase):
-
- """A mixin implementation of BufferedIOBase with an underlying raw stream.
-
- This passes most requests on to the underlying raw stream. It
- does *not* provide implementations of read(), readinto() or
- write().
- """
-
- def __init__(self, raw):
- self._raw = raw
-
- ### Positioning ###
-
- def seek(self, pos, whence=0):
- new_position = self.raw.seek(pos, whence)
- if new_position < 0:
- raise OSError("seek() returned an invalid position")
- return new_position
-
- def tell(self):
- pos = self.raw.tell()
- if pos < 0:
- raise OSError("tell() returned an invalid position")
- return pos
-
- def truncate(self, pos=None):
- self._checkClosed()
- self._checkWritable()
-
- # Flush the stream. We're mixing buffered I/O with lower-level I/O,
- # and a flush may be necessary to synch both views of the current
- # file state.
- self.flush()
-
- if pos is None:
- pos = self.tell()
- # XXX: Should seek() be used, instead of passing the position
- # XXX directly to truncate?
- return self.raw.truncate(pos)
-
- ### Flush and close ###
-
- def flush(self):
- if self.closed:
- raise ValueError("flush on closed file")
- self.raw.flush()
-
- def close(self):
- if self.raw is not None and not self.closed:
- try:
- # may raise BlockingIOError or BrokenPipeError etc
- self.flush()
- finally:
- self.raw.close()
-
- def detach(self):
- if self.raw is None:
- raise ValueError("raw stream already detached")
- self.flush()
- raw = self._raw
- self._raw = None
- return raw
-
- ### Inquiries ###
-
- def seekable(self):
- return self.raw.seekable()
-
- @property
- def raw(self):
- return self._raw
-
- @property
- def closed(self):
- return self.raw.closed
-
- @property
- def name(self):
- return self.raw.name
-
- @property
- def mode(self):
- return self.raw.mode
-
- def __getstate__(self):
- raise TypeError(f"cannot pickle {self.__class__.__name__!r} object")
-
- def __repr__(self):
- modname = self.__class__.__module__
- clsname = self.__class__.__qualname__
- try:
- name = self.name
- except AttributeError:
- return "<{}.{}>".format(modname, clsname)
- else:
- return "<{}.{} name={!r}>".format(modname, clsname, name)
-
- ### Lower-level APIs ###
-
- def fileno(self):
- return self.raw.fileno()
-
- def isatty(self):
- return self.raw.isatty()
-
-
-class BytesIO(BufferedIOBase):
-
- """Buffered I/O implementation using an in-memory bytes buffer."""
-
- # Initialize _buffer as soon as possible since it's used by __del__()
- # which calls close()
- _buffer = None
-
- def __init__(self, initial_bytes=None):
- buf = bytearray()
- if initial_bytes is not None:
- buf += initial_bytes
- self._buffer = buf
- self._pos = 0
-
- def __getstate__(self):
- if self.closed:
- raise ValueError("__getstate__ on closed file")
- return self.__dict__.copy()
-
- def getvalue(self):
- """Return the bytes value (contents) of the buffer
- """
- if self.closed:
- raise ValueError("getvalue on closed file")
- return bytes(self._buffer)
-
- def getbuffer(self):
- """Return a readable and writable view of the buffer.
- """
- if self.closed:
- raise ValueError("getbuffer on closed file")
- return memoryview(self._buffer)
-
- def close(self):
- if self._buffer is not None:
- self._buffer.clear()
- super().close()
-
- def read(self, size=-1):
- if self.closed:
- raise ValueError("read from closed file")
- if size is None:
- size = -1
- else:
- try:
- size_index = size.__index__
- except AttributeError:
- raise TypeError(f"{size!r} is not an integer")
- else:
- size = size_index()
- if size < 0:
- size = len(self._buffer)
- if len(self._buffer) <= self._pos:
- return b""
- newpos = min(len(self._buffer), self._pos + size)
- b = self._buffer[self._pos : newpos]
- self._pos = newpos
- return bytes(b)
-
- def read1(self, size=-1):
- """This is the same as read.
- """
- return self.read(size)
-
- def write(self, b):
- if self.closed:
- raise ValueError("write to closed file")
- if isinstance(b, str):
- raise TypeError("can't write str to binary stream")
- with memoryview(b) as view:
- n = view.nbytes # Size of any bytes-like object
- if n == 0:
- return 0
- pos = self._pos
- if pos > len(self._buffer):
- # Inserts null bytes between the current end of the file
- # and the new write position.
- padding = b'\x00' * (pos - len(self._buffer))
- self._buffer += padding
- self._buffer[pos:pos + n] = b
- self._pos += n
- return n
-
- def seek(self, pos, whence=0):
- if self.closed:
- raise ValueError("seek on closed file")
- try:
- pos_index = pos.__index__
- except AttributeError:
- raise TypeError(f"{pos!r} is not an integer")
- else:
- pos = pos_index()
- if whence == 0:
- if pos < 0:
- raise ValueError("negative seek position %r" % (pos,))
- self._pos = pos
- elif whence == 1:
- self._pos = max(0, self._pos + pos)
- elif whence == 2:
- self._pos = max(0, len(self._buffer) + pos)
- else:
- raise ValueError("unsupported whence value")
- return self._pos
-
- def tell(self):
- if self.closed:
- raise ValueError("tell on closed file")
- return self._pos
-
- def truncate(self, pos=None):
- if self.closed:
- raise ValueError("truncate on closed file")
- if pos is None:
- pos = self._pos
- else:
- try:
- pos_index = pos.__index__
- except AttributeError:
- raise TypeError(f"{pos!r} is not an integer")
- else:
- pos = pos_index()
- if pos < 0:
- raise ValueError("negative truncate position %r" % (pos,))
- del self._buffer[pos:]
- return pos
-
- def readable(self):
- if self.closed:
- raise ValueError("I/O operation on closed file.")
- return True
-
- def writable(self):
- if self.closed:
- raise ValueError("I/O operation on closed file.")
- return True
-
- def seekable(self):
- if self.closed:
- raise ValueError("I/O operation on closed file.")
- return True
-
-
-class BufferedReader(_BufferedIOMixin):
-
- """BufferedReader(raw[, buffer_size])
-
- A buffer for a readable, sequential BaseRawIO object.
-
- The constructor creates a BufferedReader for the given readable raw
- stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
- is used.
- """
-
- def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
- """Create a new buffered reader using the given readable raw IO object.
- """
- if not raw.readable():
- raise OSError('"raw" argument must be readable.')
-
- _BufferedIOMixin.__init__(self, raw)
- if buffer_size <= 0:
- raise ValueError("invalid buffer size")
- self.buffer_size = buffer_size
- self._reset_read_buf()
- self._read_lock = Lock()
-
- def readable(self):
- return self.raw.readable()
-
- def _reset_read_buf(self):
- self._read_buf = b""
- self._read_pos = 0
-
- def read(self, size=None):
- """Read size bytes.
-
- Returns exactly size bytes of data unless the underlying raw IO
- stream reaches EOF or if the call would block in non-blocking
- mode. If size is negative, read until EOF or until read() would
- block.
- """
- if size is not None and size < -1:
- raise ValueError("invalid number of bytes to read")
- with self._read_lock:
- return self._read_unlocked(size)
-
- def _read_unlocked(self, n=None):
- nodata_val = b""
- empty_values = (b"", None)
- buf = self._read_buf
- pos = self._read_pos
-
- # Special case for when the number of bytes to read is unspecified.
- if n is None or n == -1:
- self._reset_read_buf()
- if hasattr(self.raw, 'readall'):
- chunk = self.raw.readall()
- if chunk is None:
- return buf[pos:] or None
- else:
- return buf[pos:] + chunk
- chunks = [buf[pos:]] # Strip the consumed bytes.
- current_size = 0
- while True:
- # Read until EOF or until read() would block.
- chunk = self.raw.read()
- if chunk in empty_values:
- nodata_val = chunk
- break
- current_size += len(chunk)
- chunks.append(chunk)
- return b"".join(chunks) or nodata_val
-
- # The number of bytes to read is specified, return at most n bytes.
- avail = len(buf) - pos # Length of the available buffered data.
- if n <= avail:
- # Fast path: the data to read is fully buffered.
- self._read_pos += n
- return buf[pos:pos+n]
- # Slow path: read from the stream until enough bytes are read,
- # or until an EOF occurs or until read() would block.
- chunks = [buf[pos:]]
- wanted = max(self.buffer_size, n)
- while avail < n:
- chunk = self.raw.read(wanted)
- if chunk in empty_values:
- nodata_val = chunk
- break
- avail += len(chunk)
- chunks.append(chunk)
- # n is more than avail only when an EOF occurred or when
- # read() would have blocked.
- n = min(n, avail)
- out = b"".join(chunks)
- self._read_buf = out[n:] # Save the extra data in the buffer.
- self._read_pos = 0
- return out[:n] if out else nodata_val
-
- def peek(self, size=0):
- """Returns buffered bytes without advancing the position.
-
- The argument indicates a desired minimal number of bytes; we
- do at most one raw read to satisfy it. We never return more
- than self.buffer_size.
- """
- with self._read_lock:
- return self._peek_unlocked(size)
-
- def _peek_unlocked(self, n=0):
- want = min(n, self.buffer_size)
- have = len(self._read_buf) - self._read_pos
- if have < want or have <= 0:
- to_read = self.buffer_size - have
- current = self.raw.read(to_read)
- if current:
- self._read_buf = self._read_buf[self._read_pos:] + current
- self._read_pos = 0
- return self._read_buf[self._read_pos:]
-
- def read1(self, size=-1):
- """Reads up to size bytes, with at most one read() system call."""
- # Returns up to size bytes. If at least one byte is buffered, we
- # only return buffered bytes. Otherwise, we do one raw read.
- if size < 0:
- size = self.buffer_size
- if size == 0:
- return b""
- with self._read_lock:
- self._peek_unlocked(1)
- return self._read_unlocked(
- min(size, len(self._read_buf) - self._read_pos))
-
- # Implementing readinto() and readinto1() is not strictly necessary (we
- # could rely on the base class that provides an implementation in terms of
- # read() and read1()). We do it anyway to keep the _pyio implementation
- # similar to the io implementation (which implements the methods for
- # performance reasons).
- def _readinto(self, buf, read1):
- """Read data into *buf* with at most one system call."""
-
- # Need to create a memoryview object of type 'b', otherwise
- # we may not be able to assign bytes to it, and slicing it
- # would create a new object.
- if not isinstance(buf, memoryview):
- buf = memoryview(buf)
- if buf.nbytes == 0:
- return 0
- buf = buf.cast('B')
-
- written = 0
- with self._read_lock:
- while written < len(buf):
-
- # First try to read from internal buffer
- avail = min(len(self._read_buf) - self._read_pos, len(buf))
- if avail:
- buf[written:written+avail] = \
- self._read_buf[self._read_pos:self._read_pos+avail]
- self._read_pos += avail
- written += avail
- if written == len(buf):
- break
-
- # If remaining space in callers buffer is larger than
- # internal buffer, read directly into callers buffer
- if len(buf) - written > self.buffer_size:
- n = self.raw.readinto(buf[written:])
- if not n:
- break # eof
- written += n
-
- # Otherwise refill internal buffer - unless we're
- # in read1 mode and already got some data
- elif not (read1 and written):
- if not self._peek_unlocked(1):
- break # eof
-
- # In readinto1 mode, return as soon as we have some data
- if read1 and written:
- break
-
- return written
-
- def tell(self):
- return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos
-
- def seek(self, pos, whence=0):
- if whence not in valid_seek_flags:
- raise ValueError("invalid whence value")
- with self._read_lock:
- if whence == 1:
- pos -= len(self._read_buf) - self._read_pos
- pos = _BufferedIOMixin.seek(self, pos, whence)
- self._reset_read_buf()
- return pos
-
-class BufferedWriter(_BufferedIOMixin):
-
- """A buffer for a writeable sequential RawIO object.
-
- The constructor creates a BufferedWriter for the given writeable raw
- stream. If the buffer_size is not given, it defaults to
- DEFAULT_BUFFER_SIZE.
- """
-
- def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
- if not raw.writable():
- raise OSError('"raw" argument must be writable.')
-
- _BufferedIOMixin.__init__(self, raw)
- if buffer_size <= 0:
- raise ValueError("invalid buffer size")
- self.buffer_size = buffer_size
- self._write_buf = bytearray()
- self._write_lock = Lock()
-
- def writable(self):
- return self.raw.writable()
-
- def write(self, b):
- if isinstance(b, str):
- raise TypeError("can't write str to binary stream")
- with self._write_lock:
- if self.closed:
- raise ValueError("write to closed file")
- # XXX we can implement some more tricks to try and avoid
- # partial writes
- if len(self._write_buf) > self.buffer_size:
- # We're full, so let's pre-flush the buffer. (This may
- # raise BlockingIOError with characters_written == 0.)
- self._flush_unlocked()
- before = len(self._write_buf)
- self._write_buf.extend(b)
- written = len(self._write_buf) - before
- if len(self._write_buf) > self.buffer_size:
- try:
- self._flush_unlocked()
- except BlockingIOError as e:
- if len(self._write_buf) > self.buffer_size:
- # We've hit the buffer_size. We have to accept a partial
- # write and cut back our buffer.
- overage = len(self._write_buf) - self.buffer_size
- written -= overage
- self._write_buf = self._write_buf[:self.buffer_size]
- raise BlockingIOError(e.errno, e.strerror, written)
- return written
-
- def truncate(self, pos=None):
- with self._write_lock:
- self._flush_unlocked()
- if pos is None:
- pos = self.raw.tell()
- return self.raw.truncate(pos)
-
- def flush(self):
- with self._write_lock:
- self._flush_unlocked()
-
- def _flush_unlocked(self):
- if self.closed:
- raise ValueError("flush on closed file")
- while self._write_buf:
- try:
- n = self.raw.write(self._write_buf)
- except BlockingIOError:
- raise RuntimeError("self.raw should implement RawIOBase: it "
- "should not raise BlockingIOError")
- if n is None:
- raise BlockingIOError(
- errno.EAGAIN,
- "write could not complete without blocking", 0)
- if n > len(self._write_buf) or n < 0:
- raise OSError("write() returned incorrect number of bytes")
- del self._write_buf[:n]
-
- def tell(self):
- return _BufferedIOMixin.tell(self) + len(self._write_buf)
-
- def seek(self, pos, whence=0):
- if whence not in valid_seek_flags:
- raise ValueError("invalid whence value")
- with self._write_lock:
- self._flush_unlocked()
- return _BufferedIOMixin.seek(self, pos, whence)
-
- def close(self):
- with self._write_lock:
- if self.raw is None or self.closed:
- return
- # We have to release the lock and call self.flush() (which will
- # probably just re-take the lock) in case flush has been overridden in
- # a subclass or the user set self.flush to something. This is the same
- # behavior as the C implementation.
- try:
- # may raise BlockingIOError or BrokenPipeError etc
- self.flush()
- finally:
- with self._write_lock:
- self.raw.close()
-
-
-class BufferedRWPair(BufferedIOBase):
-
- """A buffered reader and writer object together.
-
- A buffered reader object and buffered writer object put together to
- form a sequential IO object that can read and write. This is typically
- used with a socket or two-way pipe.
-
- reader and writer are RawIOBase objects that are readable and
- writeable respectively. If the buffer_size is omitted it defaults to
- DEFAULT_BUFFER_SIZE.
- """
-
- # XXX The usefulness of this (compared to having two separate IO
- # objects) is questionable.
-
- def __init__(self, reader, writer, buffer_size=DEFAULT_BUFFER_SIZE):
- """Constructor.
-
- The arguments are two RawIO instances.
- """
- if not reader.readable():
- raise OSError('"reader" argument must be readable.')
-
- if not writer.writable():
- raise OSError('"writer" argument must be writable.')
-
- self.reader = BufferedReader(reader, buffer_size)
- self.writer = BufferedWriter(writer, buffer_size)
-
- def read(self, size=-1):
- if size is None:
- size = -1
- return self.reader.read(size)
-
- def readinto(self, b):
- return self.reader.readinto(b)
-
- def write(self, b):
- return self.writer.write(b)
-
- def peek(self, size=0):
- return self.reader.peek(size)
-
- def read1(self, size=-1):
- return self.reader.read1(size)
-
- def readinto1(self, b):
- return self.reader.readinto1(b)
-
- def readable(self):
- return self.reader.readable()
-
- def writable(self):
- return self.writer.writable()
-
- def flush(self):
- return self.writer.flush()
-
- def close(self):
- try:
- self.writer.close()
- finally:
- self.reader.close()
-
- def isatty(self):
- return self.reader.isatty() or self.writer.isatty()
-
- @property
- def closed(self):
- return self.writer.closed
-
-
-class BufferedRandom(BufferedWriter, BufferedReader):
-
- """A buffered interface to random access streams.
-
- The constructor creates a reader and writer for a seekable stream,
- raw, given in the first argument. If the buffer_size is omitted it
- defaults to DEFAULT_BUFFER_SIZE.
- """
-
- def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
- raw._checkSeekable()
- BufferedReader.__init__(self, raw, buffer_size)
- BufferedWriter.__init__(self, raw, buffer_size)
-
- def seek(self, pos, whence=0):
- if whence not in valid_seek_flags:
- raise ValueError("invalid whence value")
- self.flush()
- if self._read_buf:
- # Undo read ahead.
- with self._read_lock:
- self.raw.seek(self._read_pos - len(self._read_buf), 1)
- # First do the raw seek, then empty the read buffer, so that
- # if the raw seek fails, we don't lose buffered data forever.
- pos = self.raw.seek(pos, whence)
- with self._read_lock:
- self._reset_read_buf()
- if pos < 0:
- raise OSError("seek() returned invalid position")
- return pos
-
- def tell(self):
- if self._write_buf:
- return BufferedWriter.tell(self)
- else:
- return BufferedReader.tell(self)
-
- def truncate(self, pos=None):
- if pos is None:
- pos = self.tell()
- # Use seek to flush the read buffer.
- return BufferedWriter.truncate(self, pos)
-
- def read(self, size=None):
- if size is None:
- size = -1
- self.flush()
- return BufferedReader.read(self, size)
-
- def readinto(self, b):
- self.flush()
- return BufferedReader.readinto(self, b)
-
- def peek(self, size=0):
- self.flush()
- return BufferedReader.peek(self, size)
-
- def read1(self, size=-1):
- self.flush()
- return BufferedReader.read1(self, size)
-
- def readinto1(self, b):
- self.flush()
- return BufferedReader.readinto1(self, b)
-
- def write(self, b):
- if self._read_buf:
- # Undo readahead
- with self._read_lock:
- self.raw.seek(self._read_pos - len(self._read_buf), 1)
- self._reset_read_buf()
- return BufferedWriter.write(self, b)
-
-
-class FileIO(RawIOBase):
- _fd = -1
- _created = False
- _readable = False
- _writable = False
- _appending = False
- _seekable = None
- _closefd = True
-
- def __init__(self, file, mode='r', closefd=True, opener=None):
- """Open a file. The mode can be 'r' (default), 'w', 'x' or 'a' for reading,
- writing, exclusive creation or appending. The file will be created if it
- doesn't exist when opened for writing or appending; it will be truncated
- when opened for writing. A FileExistsError will be raised if it already
- exists when opened for creating. Opening a file for creating implies
- writing so this mode behaves in a similar way to 'w'. Add a '+' to the mode
- to allow simultaneous reading and writing. A custom opener can be used by
- passing a callable as *opener*. The underlying file descriptor for the file
- object is then obtained by calling opener with (*name*, *flags*).
- *opener* must return an open file descriptor (passing os.open as *opener*
- results in functionality similar to passing None).
- """
- if self._fd >= 0:
- # Have to close the existing file first.
- try:
- if self._closefd:
- os.close(self._fd)
- finally:
- self._fd = -1
-
- if isinstance(file, float):
- raise TypeError('integer argument expected, got float')
- if isinstance(file, int):
- fd = file
- if fd < 0:
- raise ValueError('negative file descriptor')
- else:
- fd = -1
-
- if not isinstance(mode, str):
- raise TypeError('invalid mode: %s' % (mode,))
- if not set(mode) <= set('xrwab+'):
- raise ValueError('invalid mode: %s' % (mode,))
- if sum(c in 'rwax' for c in mode) != 1 or mode.count('+') > 1:
- raise ValueError('Must have exactly one of create/read/write/append '
- 'mode and at most one plus')
-
- if 'x' in mode:
- self._created = True
- self._writable = True
- flags = os.O_EXCL | os.O_CREAT
- elif 'r' in mode:
- self._readable = True
- flags = 0
- elif 'w' in mode:
- self._writable = True
- flags = os.O_CREAT | os.O_TRUNC
- elif 'a' in mode:
- self._writable = True
- self._appending = True
- flags = os.O_APPEND | os.O_CREAT
-
- if '+' in mode:
- self._readable = True
- self._writable = True
-
- if self._readable and self._writable:
- flags |= os.O_RDWR
- elif self._readable:
- flags |= os.O_RDONLY
- else:
- flags |= os.O_WRONLY
-
- flags |= getattr(os, 'O_BINARY', 0)
-
- noinherit_flag = (getattr(os, 'O_NOINHERIT', 0) or
- getattr(os, 'O_CLOEXEC', 0))
- flags |= noinherit_flag
-
- owned_fd = None
- try:
- if fd < 0:
- if not closefd:
- raise ValueError('Cannot use closefd=False with file name')
- if opener is None:
- fd = os.open(file, flags, 0o666)
- else:
- fd = opener(file, flags)
- if not isinstance(fd, int):
- raise TypeError('expected integer from opener')
- if fd < 0:
- raise OSError('Negative file descriptor')
- owned_fd = fd
- if not noinherit_flag:
- os.set_inheritable(fd, False)
-
- self._closefd = closefd
- fdfstat = os.fstat(fd)
- try:
- if stat.S_ISDIR(fdfstat.st_mode):
- raise IsADirectoryError(errno.EISDIR,
- os.strerror(errno.EISDIR), file)
- except AttributeError:
- # Ignore the AttributeError if stat.S_ISDIR or errno.EISDIR
- # don't exist.
- pass
- self._blksize = getattr(fdfstat, 'st_blksize', 0)
- if self._blksize <= 1:
- self._blksize = DEFAULT_BUFFER_SIZE
-
- if _setmode:
- # don't translate newlines (\r\n <=> \n)
- _setmode(fd, os.O_BINARY)
-
- self.name = file
- if self._appending:
- # For consistent behaviour, we explicitly seek to the
- # end of file (otherwise, it might be done only on the
- # first write()).
- try:
- os.lseek(fd, 0, SEEK_END)
- except OSError as e:
- if e.errno != errno.ESPIPE:
- raise
- except:
- if owned_fd is not None:
- os.close(owned_fd)
- raise
- self._fd = fd
-
- def __del__(self):
- if self._fd >= 0 and self._closefd and not self.closed:
- import warnings
- warnings.warn('unclosed file %r' % (self,), ResourceWarning,
- stacklevel=2, source=self)
- self.close()
-
- def __getstate__(self):
- raise TypeError(f"cannot pickle {self.__class__.__name__!r} object")
-
- def __repr__(self):
- class_name = '%s.%s' % (self.__class__.__module__,
- self.__class__.__qualname__)
- if self.closed:
- return '<%s [closed]>' % class_name
- try:
- name = self.name
- except AttributeError:
- return ('<%s fd=%d mode=%r closefd=%r>' %
- (class_name, self._fd, self.mode, self._closefd))
- else:
- return ('<%s name=%r mode=%r closefd=%r>' %
- (class_name, name, self.mode, self._closefd))
-
- def _checkReadable(self):
- if not self._readable:
- raise UnsupportedOperation('File not open for reading')
-
- def _checkWritable(self, msg=None):
- if not self._writable:
- raise UnsupportedOperation('File not open for writing')
-
- def read(self, size=None):
- """Read at most size bytes, returned as bytes.
-
- Only makes one system call, so less data may be returned than requested
- In non-blocking mode, returns None if no data is available.
- Return an empty bytes object at EOF.
- """
- self._checkClosed()
- self._checkReadable()
- if size is None or size < 0:
- return self.readall()
- try:
- return os.read(self._fd, size)
- except BlockingIOError:
- return None
-
- def readall(self):
- """Read all data from the file, returned as bytes.
-
- In non-blocking mode, returns as much as is immediately available,
- or None if no data is available. Return an empty bytes object at EOF.
- """
- self._checkClosed()
- self._checkReadable()
- bufsize = DEFAULT_BUFFER_SIZE
- try:
- pos = os.lseek(self._fd, 0, SEEK_CUR)
- end = os.fstat(self._fd).st_size
- if end >= pos:
- bufsize = end - pos + 1
- except OSError:
- pass
-
- result = bytearray()
- while True:
- if len(result) >= bufsize:
- bufsize = len(result)
- bufsize += max(bufsize, DEFAULT_BUFFER_SIZE)
- n = bufsize - len(result)
- try:
- chunk = os.read(self._fd, n)
- except BlockingIOError:
- if result:
- break
- return None
- if not chunk: # reached the end of the file
- break
- result += chunk
-
- return bytes(result)
-
- def readinto(self, b):
- """Same as RawIOBase.readinto()."""
- m = memoryview(b).cast('B')
- data = self.read(len(m))
- n = len(data)
- m[:n] = data
- return n
-
- def write(self, b):
- """Write bytes b to file, return number written.
-
- Only makes one system call, so not all of the data may be written.
- The number of bytes actually written is returned. In non-blocking mode,
- returns None if the write would block.
- """
- self._checkClosed()
- self._checkWritable()
- try:
- return os.write(self._fd, b)
- except BlockingIOError:
- return None
-
- def seek(self, pos, whence=SEEK_SET):
- """Move to new file position.
-
- Argument offset is a byte count. Optional argument whence defaults to
- SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
- are SEEK_CUR or 1 (move relative to current position, positive or negative),
- and SEEK_END or 2 (move relative to end of file, usually negative, although
- many platforms allow seeking beyond the end of a file).
-
- Note that not all file objects are seekable.
- """
- if isinstance(pos, float):
- raise TypeError('an integer is required')
- self._checkClosed()
- return os.lseek(self._fd, pos, whence)
-
- def tell(self):
- """tell() -> int. Current file position.
-
- Can raise OSError for non seekable files."""
- self._checkClosed()
- return os.lseek(self._fd, 0, SEEK_CUR)
-
- def truncate(self, size=None):
- """Truncate the file to at most size bytes.
-
- Size defaults to the current file position, as returned by tell().
- The current file position is changed to the value of size.
- """
- self._checkClosed()
- self._checkWritable()
- if size is None:
- size = self.tell()
- os.ftruncate(self._fd, size)
- return size
-
- def close(self):
- """Close the file.
-
- A closed file cannot be used for further I/O operations. close() may be
- called more than once without error.
- """
- if not self.closed:
- try:
- if self._closefd:
- os.close(self._fd)
- finally:
- super().close()
-
- def seekable(self):
- """True if file supports random-access."""
- self._checkClosed()
- if self._seekable is None:
- try:
- self.tell()
- except OSError:
- self._seekable = False
- else:
- self._seekable = True
- return self._seekable
-
- def readable(self):
- """True if file was opened in a read mode."""
- self._checkClosed()
- return self._readable
-
- def writable(self):
- """True if file was opened in a write mode."""
- self._checkClosed()
- return self._writable
-
- def fileno(self):
- """Return the underlying file descriptor (an integer)."""
- self._checkClosed()
- return self._fd
-
- def isatty(self):
- """True if the file is connected to a TTY device."""
- self._checkClosed()
- return os.isatty(self._fd)
-
- @property
- def closefd(self):
- """True if the file descriptor will be closed by close()."""
- return self._closefd
-
- @property
- def mode(self):
- """String giving the file mode"""
- if self._created:
- if self._readable:
- return 'xb+'
- else:
- return 'xb'
- elif self._appending:
- if self._readable:
- return 'ab+'
- else:
- return 'ab'
- elif self._readable:
- if self._writable:
- return 'rb+'
- else:
- return 'rb'
- else:
- return 'wb'
-
-
-class TextIOBase(IOBase):
-
- """Base class for text I/O.
-
- This class provides a character and line based interface to stream
- I/O.
- """
-
- def read(self, size=-1):
- """Read at most size characters from stream, where size is an int.
-
- Read from underlying buffer until we have size characters or we hit EOF.
- If size is negative or omitted, read until EOF.
-
- Returns a string.
- """
- self._unsupported("read")
-
- def write(self, s):
- """Write string s to stream and returning an int."""
- self._unsupported("write")
-
- def truncate(self, pos=None):
- """Truncate size to pos, where pos is an int."""
- self._unsupported("truncate")
-
- def readline(self):
- """Read until newline or EOF.
-
- Returns an empty string if EOF is hit immediately.
- """
- self._unsupported("readline")
-
- def detach(self):
- """
- Separate the underlying buffer from the TextIOBase and return it.
-
- After the underlying buffer has been detached, the TextIO is in an
- unusable state.
- """
- self._unsupported("detach")
-
- @property
- def encoding(self):
- """Subclasses should override."""
- return None
-
- @property
- def newlines(self):
- """Line endings translated so far.
-
- Only line endings translated during reading are considered.
-
- Subclasses should override.
- """
- return None
-
- @property
- def errors(self):
- """Error setting of the decoder or encoder.
-
- Subclasses should override."""
- return None
-
-io.TextIOBase.register(TextIOBase)
-
-
-class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
- r"""Codec used when reading a file in universal newlines mode. It wraps
- another incremental decoder, translating \r\n and \r into \n. It also
- records the types of newlines encountered. When used with
- translate=False, it ensures that the newline sequence is returned in
- one piece.
- """
- def __init__(self, decoder, translate, errors='strict'):
- codecs.IncrementalDecoder.__init__(self, errors=errors)
- self.translate = translate
- self.decoder = decoder
- self.seennl = 0
- self.pendingcr = False
-
- def decode(self, input, final=False):
- # decode input (with the eventual \r from a previous pass)
- if self.decoder is None:
- output = input
- else:
- output = self.decoder.decode(input, final=final)
- if self.pendingcr and (output or final):
- output = "\r" + output
- self.pendingcr = False
-
- # retain last \r even when not translating data:
- # then readline() is sure to get \r\n in one pass
- if output.endswith("\r") and not final:
- output = output[:-1]
- self.pendingcr = True
-
- # Record which newlines are read
- crlf = output.count('\r\n')
- cr = output.count('\r') - crlf
- lf = output.count('\n') - crlf
- self.seennl |= (lf and self._LF) | (cr and self._CR) \
- | (crlf and self._CRLF)
-
- if self.translate:
- if crlf:
- output = output.replace("\r\n", "\n")
- if cr:
- output = output.replace("\r", "\n")
-
- return output
-
- def getstate(self):
- if self.decoder is None:
- buf = b""
- flag = 0
- else:
- buf, flag = self.decoder.getstate()
- flag <<= 1
- if self.pendingcr:
- flag |= 1
- return buf, flag
-
- def setstate(self, state):
- buf, flag = state
- self.pendingcr = bool(flag & 1)
- if self.decoder is not None:
- self.decoder.setstate((buf, flag >> 1))
-
- def reset(self):
- self.seennl = 0
- self.pendingcr = False
- if self.decoder is not None:
- self.decoder.reset()
-
- _LF = 1
- _CR = 2
- _CRLF = 4
-
- @property
- def newlines(self):
- return (None,
- "\n",
- "\r",
- ("\r", "\n"),
- "\r\n",
- ("\n", "\r\n"),
- ("\r", "\r\n"),
- ("\r", "\n", "\r\n")
- )[self.seennl]
-
-
-class TextIOWrapper(TextIOBase):
-
- r"""Character and line based layer over a BufferedIOBase object, buffer.
-
- encoding gives the name of the encoding that the stream will be
- decoded or encoded with. It defaults to locale.getpreferredencoding(False).
-
- errors determines the strictness of encoding and decoding (see the
- codecs.register) and defaults to "strict".
-
- newline can be None, '', '\n', '\r', or '\r\n'. It controls the
- handling of line endings. If it is None, universal newlines is
- enabled. With this enabled, on input, the lines endings '\n', '\r',
- or '\r\n' are translated to '\n' before being returned to the
- caller. Conversely, on output, '\n' is translated to the system
- default line separator, os.linesep. If newline is any other of its
- legal values, that newline becomes the newline when the file is read
- and it is returned untranslated. On output, '\n' is converted to the
- newline.
-
- If line_buffering is True, a call to flush is implied when a call to
- write contains a newline character.
- """
-
- _CHUNK_SIZE = 2048
-
- # Initialize _buffer as soon as possible since it's used by __del__()
- # which calls close()
- _buffer = None
-
- # The write_through argument has no effect here since this
- # implementation always writes through. The argument is present only
- # so that the signature can match the signature of the C version.
- def __init__(self, buffer, encoding=None, errors=None, newline=None,
- line_buffering=False, write_through=False):
- self._check_newline(newline)
- encoding = text_encoding(encoding)
-
- if encoding == "locale":
- try:
- encoding = os.device_encoding(buffer.fileno()) or "locale"
- except (AttributeError, UnsupportedOperation):
- pass
-
- if encoding == "locale":
- try:
- import locale
- except ImportError:
- # Importing locale may fail if Python is being built
- encoding = "utf-8"
- else:
- encoding = locale.getpreferredencoding(False)
-
- if not isinstance(encoding, str):
- raise ValueError("invalid encoding: %r" % encoding)
-
- if not codecs.lookup(encoding)._is_text_encoding:
- msg = ("%r is not a text encoding; "
- "use codecs.open() to handle arbitrary codecs")
- raise LookupError(msg % encoding)
-
- if errors is None:
- errors = "strict"
- else:
- if not isinstance(errors, str):
- raise ValueError("invalid errors: %r" % errors)
- if _CHECK_ERRORS:
- codecs.lookup_error(errors)
-
- self._buffer = buffer
- self._decoded_chars = '' # buffer for text returned from decoder
- self._decoded_chars_used = 0 # offset into _decoded_chars for read()
- self._snapshot = None # info for reconstructing decoder state
- self._seekable = self._telling = self.buffer.seekable()
- self._has_read1 = hasattr(self.buffer, 'read1')
- self._configure(encoding, errors, newline,
- line_buffering, write_through)
-
- def _check_newline(self, newline):
- if newline is not None and not isinstance(newline, str):
- raise TypeError("illegal newline type: %r" % (type(newline),))
- if newline not in (None, "", "\n", "\r", "\r\n"):
- raise ValueError("illegal newline value: %r" % (newline,))
-
- def _configure(self, encoding=None, errors=None, newline=None,
- line_buffering=False, write_through=False):
- self._encoding = encoding
- self._errors = errors
- self._encoder = None
- self._decoder = None
- self._b2cratio = 0.0
-
- self._readuniversal = not newline
- self._readtranslate = newline is None
- self._readnl = newline
- self._writetranslate = newline != ''
- self._writenl = newline or os.linesep
-
- self._line_buffering = line_buffering
- self._write_through = write_through
-
- # don't write a BOM in the middle of a file
- if self._seekable and self.writable():
- position = self.buffer.tell()
- if position != 0:
- try:
- self._get_encoder().setstate(0)
- except LookupError:
- # Sometimes the encoder doesn't exist
- pass
-
- # self._snapshot is either None, or a tuple (dec_flags, next_input)
- # where dec_flags is the second (integer) item of the decoder state
- # and next_input is the chunk of input bytes that comes next after the
- # snapshot point. We use this to reconstruct decoder states in tell().
-
- # Naming convention:
- # - "bytes_..." for integer variables that count input bytes
- # - "chars_..." for integer variables that count decoded characters
-
- def __repr__(self):
- result = "<{}.{}".format(self.__class__.__module__,
- self.__class__.__qualname__)
- try:
- name = self.name
- except AttributeError:
- pass
- else:
- result += " name={0!r}".format(name)
- try:
- mode = self.mode
- except AttributeError:
- pass
- else:
- result += " mode={0!r}".format(mode)
- return result + " encoding={0!r}>".format(self.encoding)
-
- @property
- def encoding(self):
- return self._encoding
-
- @property
- def errors(self):
- return self._errors
-
- @property
- def line_buffering(self):
- return self._line_buffering
-
- @property
- def write_through(self):
- return self._write_through
-
- @property
- def buffer(self):
- return self._buffer
-
- def reconfigure(self, *,
- encoding=None, errors=None, newline=Ellipsis,
- line_buffering=None, write_through=None):
- """Reconfigure the text stream with new parameters.
-
- This also flushes the stream.
- """
- if (self._decoder is not None
- and (encoding is not None or errors is not None
- or newline is not Ellipsis)):
- raise UnsupportedOperation(
- "It is not possible to set the encoding or newline of stream "
- "after the first read")
-
- if errors is None:
- if encoding is None:
- errors = self._errors
- else:
- errors = 'strict'
- elif not isinstance(errors, str):
- raise TypeError("invalid errors: %r" % errors)
-
- if encoding is None:
- encoding = self._encoding
- else:
- if not isinstance(encoding, str):
- raise TypeError("invalid encoding: %r" % encoding)
-
- if newline is Ellipsis:
- newline = self._readnl
- self._check_newline(newline)
-
- if line_buffering is None:
- line_buffering = self.line_buffering
- if write_through is None:
- write_through = self.write_through
-
- self.flush()
- self._configure(encoding, errors, newline,
- line_buffering, write_through)
-
- def seekable(self):
- if self.closed:
- raise ValueError("I/O operation on closed file.")
- return self._seekable
-
- def readable(self):
- return self.buffer.readable()
-
- def writable(self):
- return self.buffer.writable()
-
- def flush(self):
- self.buffer.flush()
- self._telling = self._seekable
-
- def close(self):
- if self.buffer is not None and not self.closed:
- try:
- self.flush()
- finally:
- self.buffer.close()
-
- @property
- def closed(self):
- return self.buffer.closed
-
- @property
- def name(self):
- return self.buffer.name
-
- def fileno(self):
- return self.buffer.fileno()
-
- def isatty(self):
- return self.buffer.isatty()
-
- def write(self, s):
- 'Write data, where s is a str'
- if self.closed:
- raise ValueError("write to closed file")
- if not isinstance(s, str):
- raise TypeError("can't write %s to text stream" %
- s.__class__.__name__)
- length = len(s)
- haslf = (self._writetranslate or self._line_buffering) and "\n" in s
- if haslf and self._writetranslate and self._writenl != "\n":
- s = s.replace("\n", self._writenl)
- encoder = self._encoder or self._get_encoder()
- # XXX What if we were just reading?
- b = encoder.encode(s)
- self.buffer.write(b)
- if self._line_buffering and (haslf or "\r" in s):
- self.flush()
- self._set_decoded_chars('')
- self._snapshot = None
- if self._decoder:
- self._decoder.reset()
- return length
-
- def _get_encoder(self):
- make_encoder = codecs.getincrementalencoder(self._encoding)
- self._encoder = make_encoder(self._errors)
- return self._encoder
-
- def _get_decoder(self):
- make_decoder = codecs.getincrementaldecoder(self._encoding)
- decoder = make_decoder(self._errors)
- if self._readuniversal:
- decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
- self._decoder = decoder
- return decoder
-
- # The following three methods implement an ADT for _decoded_chars.
- # Text returned from the decoder is buffered here until the client
- # requests it by calling our read() or readline() method.
- def _set_decoded_chars(self, chars):
- """Set the _decoded_chars buffer."""
- self._decoded_chars = chars
- self._decoded_chars_used = 0
-
- def _get_decoded_chars(self, n=None):
- """Advance into the _decoded_chars buffer."""
- offset = self._decoded_chars_used
- if n is None:
- chars = self._decoded_chars[offset:]
- else:
- chars = self._decoded_chars[offset:offset + n]
- self._decoded_chars_used += len(chars)
- return chars
-
- def _rewind_decoded_chars(self, n):
- """Rewind the _decoded_chars buffer."""
- if self._decoded_chars_used < n:
- raise AssertionError("rewind decoded_chars out of bounds")
- self._decoded_chars_used -= n
-
- def _read_chunk(self):
- """
- Read and decode the next chunk of data from the BufferedReader.
- """
-
- # The return value is True unless EOF was reached. The decoded
- # string is placed in self._decoded_chars (replacing its previous
- # value). The entire input chunk is sent to the decoder, though
- # some of it may remain buffered in the decoder, yet to be
- # converted.
-
- if self._decoder is None:
- raise ValueError("no decoder")
-
- if self._telling:
- # To prepare for tell(), we need to snapshot a point in the
- # file where the decoder's input buffer is empty.
-
- dec_buffer, dec_flags = self._decoder.getstate()
- # Given this, we know there was a valid snapshot point
- # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
-
- # Read a chunk, decode it, and put the result in self._decoded_chars.
- if self._has_read1:
- input_chunk = self.buffer.read1(self._CHUNK_SIZE)
- else:
- input_chunk = self.buffer.read(self._CHUNK_SIZE)
- eof = not input_chunk
- decoded_chars = self._decoder.decode(input_chunk, eof)
- self._set_decoded_chars(decoded_chars)
- if decoded_chars:
- self._b2cratio = len(input_chunk) / len(self._decoded_chars)
- else:
- self._b2cratio = 0.0
-
- if self._telling:
- # At the snapshot point, len(dec_buffer) bytes before the read,
- # the next input to be decoded is dec_buffer + input_chunk.
- self._snapshot = (dec_flags, dec_buffer + input_chunk)
-
- return not eof
-
- def _pack_cookie(self, position, dec_flags=0,
- bytes_to_feed=0, need_eof=False, chars_to_skip=0):
- # The meaning of a tell() cookie is: seek to position, set the
- # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
- # into the decoder with need_eof as the EOF flag, then skip
- # chars_to_skip characters of the decoded result. For most simple
- # decoders, tell() will often just give a byte offset in the file.
- return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
- (chars_to_skip<<192) | bool(need_eof)<<256)
-
- def _unpack_cookie(self, bigint):
- rest, position = divmod(bigint, 1<<64)
- rest, dec_flags = divmod(rest, 1<<64)
- rest, bytes_to_feed = divmod(rest, 1<<64)
- need_eof, chars_to_skip = divmod(rest, 1<<64)
- return position, dec_flags, bytes_to_feed, bool(need_eof), chars_to_skip
-
- def tell(self):
- if not self._seekable:
- raise UnsupportedOperation("underlying stream is not seekable")
- if not self._telling:
- raise OSError("telling position disabled by next() call")
- self.flush()
- position = self.buffer.tell()
- decoder = self._decoder
- if decoder is None or self._snapshot is None:
- if self._decoded_chars:
- # This should never happen.
- raise AssertionError("pending decoded text")
- return position
-
- # Skip backward to the snapshot point (see _read_chunk).
- dec_flags, next_input = self._snapshot
- position -= len(next_input)
-
- # How many decoded characters have been used up since the snapshot?
- chars_to_skip = self._decoded_chars_used
- if chars_to_skip == 0:
- # We haven't moved from the snapshot point.
- return self._pack_cookie(position, dec_flags)
-
- # Starting from the snapshot position, we will walk the decoder
- # forward until it gives us enough decoded characters.
- saved_state = decoder.getstate()
- try:
- # Fast search for an acceptable start point, close to our
- # current pos.
- # Rationale: calling decoder.decode() has a large overhead
- # regardless of chunk size; we want the number of such calls to
- # be O(1) in most situations (common decoders, sensible input).
- # Actually, it will be exactly 1 for fixed-size codecs (all
- # 8-bit codecs, also UTF-16 and UTF-32).
- skip_bytes = int(self._b2cratio * chars_to_skip)
- skip_back = 1
- assert skip_bytes <= len(next_input)
- while skip_bytes > 0:
- decoder.setstate((b'', dec_flags))
- # Decode up to temptative start point
- n = len(decoder.decode(next_input[:skip_bytes]))
- if n <= chars_to_skip:
- b, d = decoder.getstate()
- if not b:
- # Before pos and no bytes buffered in decoder => OK
- dec_flags = d
- chars_to_skip -= n
- break
- # Skip back by buffered amount and reset heuristic
- skip_bytes -= len(b)
- skip_back = 1
- else:
- # We're too far ahead, skip back a bit
- skip_bytes -= skip_back
- skip_back = skip_back * 2
- else:
- skip_bytes = 0
- decoder.setstate((b'', dec_flags))
-
- # Note our initial start point.
- start_pos = position + skip_bytes
- start_flags = dec_flags
- if chars_to_skip == 0:
- # We haven't moved from the start point.
- return self._pack_cookie(start_pos, start_flags)
-
- # Feed the decoder one byte at a time. As we go, note the
- # nearest "safe start point" before the current location
- # (a point where the decoder has nothing buffered, so seek()
- # can safely start from there and advance to this location).
- bytes_fed = 0
- need_eof = False
- # Chars decoded since `start_pos`
- chars_decoded = 0
- for i in range(skip_bytes, len(next_input)):
- bytes_fed += 1
- chars_decoded += len(decoder.decode(next_input[i:i+1]))
- dec_buffer, dec_flags = decoder.getstate()
- if not dec_buffer and chars_decoded <= chars_to_skip:
- # Decoder buffer is empty, so this is a safe start point.
- start_pos += bytes_fed
- chars_to_skip -= chars_decoded
- start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
- if chars_decoded >= chars_to_skip:
- break
- else:
- # We didn't get enough decoded data; signal EOF to get more.
- chars_decoded += len(decoder.decode(b'', final=True))
- need_eof = True
- if chars_decoded < chars_to_skip:
- raise OSError("can't reconstruct logical file position")
-
- # The returned cookie corresponds to the last safe start point.
- return self._pack_cookie(
- start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
- finally:
- decoder.setstate(saved_state)
-
- def truncate(self, pos=None):
- self.flush()
- if pos is None:
- pos = self.tell()
- return self.buffer.truncate(pos)
-
- def detach(self):
- if self.buffer is None:
- raise ValueError("buffer is already detached")
- self.flush()
- buffer = self._buffer
- self._buffer = None
- return buffer
-
- def seek(self, cookie, whence=0):
- def _reset_encoder(position):
- """Reset the encoder (merely useful for proper BOM handling)"""
- try:
- encoder = self._encoder or self._get_encoder()
- except LookupError:
- # Sometimes the encoder doesn't exist
- pass
- else:
- if position != 0:
- encoder.setstate(0)
- else:
- encoder.reset()
-
- if self.closed:
- raise ValueError("tell on closed file")
- if not self._seekable:
- raise UnsupportedOperation("underlying stream is not seekable")
- if whence == SEEK_CUR:
- if cookie != 0:
- raise UnsupportedOperation("can't do nonzero cur-relative seeks")
- # Seeking to the current position should attempt to
- # sync the underlying buffer with the current position.
- whence = 0
- cookie = self.tell()
- elif whence == SEEK_END:
- if cookie != 0:
- raise UnsupportedOperation("can't do nonzero end-relative seeks")
- self.flush()
- position = self.buffer.seek(0, whence)
- self._set_decoded_chars('')
- self._snapshot = None
- if self._decoder:
- self._decoder.reset()
- _reset_encoder(position)
- return position
- if whence != 0:
- raise ValueError("unsupported whence (%r)" % (whence,))
- if cookie < 0:
- raise ValueError("negative seek position %r" % (cookie,))
- self.flush()
-
- # The strategy of seek() is to go back to the safe start point
- # and replay the effect of read(chars_to_skip) from there.
- start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
- self._unpack_cookie(cookie)
-
- # Seek back to the safe start point.
- self.buffer.seek(start_pos)
- self._set_decoded_chars('')
- self._snapshot = None
-
- # Restore the decoder to its state from the safe start point.
- if cookie == 0 and self._decoder:
- self._decoder.reset()
- elif self._decoder or dec_flags or chars_to_skip:
- self._decoder = self._decoder or self._get_decoder()
- self._decoder.setstate((b'', dec_flags))
- self._snapshot = (dec_flags, b'')
-
- if chars_to_skip:
- # Just like _read_chunk, feed the decoder and save a snapshot.
- input_chunk = self.buffer.read(bytes_to_feed)
- self._set_decoded_chars(
- self._decoder.decode(input_chunk, need_eof))
- self._snapshot = (dec_flags, input_chunk)
-
- # Skip chars_to_skip of the decoded characters.
- if len(self._decoded_chars) < chars_to_skip:
- raise OSError("can't restore logical file position")
- self._decoded_chars_used = chars_to_skip
-
- _reset_encoder(cookie)
- return cookie
-
- def read(self, size=None):
- self._checkReadable()
- if size is None:
- size = -1
- else:
- try:
- size_index = size.__index__
- except AttributeError:
- raise TypeError(f"{size!r} is not an integer")
- else:
- size = size_index()
- decoder = self._decoder or self._get_decoder()
- if size < 0:
- # Read everything.
- result = (self._get_decoded_chars() +
- decoder.decode(self.buffer.read(), final=True))
- self._set_decoded_chars('')
- self._snapshot = None
- return result
- else:
- # Keep reading chunks until we have size characters to return.
- eof = False
- result = self._get_decoded_chars(size)
- while len(result) < size and not eof:
- eof = not self._read_chunk()
- result += self._get_decoded_chars(size - len(result))
- return result
-
- def __next__(self):
- self._telling = False
- line = self.readline()
- if not line:
- self._snapshot = None
- self._telling = self._seekable
- raise StopIteration
- return line
-
- def readline(self, size=None):
- if self.closed:
- raise ValueError("read from closed file")
- if size is None:
- size = -1
- else:
- try:
- size_index = size.__index__
- except AttributeError:
- raise TypeError(f"{size!r} is not an integer")
- else:
- size = size_index()
-
- # Grab all the decoded text (we will rewind any extra bits later).
- line = self._get_decoded_chars()
-
- start = 0
- # Make the decoder if it doesn't already exist.
- if not self._decoder:
- self._get_decoder()
-
- pos = endpos = None
- while True:
- if self._readtranslate:
- # Newlines are already translated, only search for \n
- pos = line.find('\n', start)
- if pos >= 0:
- endpos = pos + 1
- break
- else:
- start = len(line)
-
- elif self._readuniversal:
- # Universal newline search. Find any of \r, \r\n, \n
- # The decoder ensures that \r\n are not split in two pieces
-
- # In C we'd look for these in parallel of course.
- nlpos = line.find("\n", start)
- crpos = line.find("\r", start)
- if crpos == -1:
- if nlpos == -1:
- # Nothing found
- start = len(line)
- else:
- # Found \n
- endpos = nlpos + 1
- break
- elif nlpos == -1:
- # Found lone \r
- endpos = crpos + 1
- break
- elif nlpos < crpos:
- # Found \n
- endpos = nlpos + 1
- break
- elif nlpos == crpos + 1:
- # Found \r\n
- endpos = crpos + 2
- break
- else:
- # Found \r
- endpos = crpos + 1
- break
- else:
- # non-universal
- pos = line.find(self._readnl)
- if pos >= 0:
- endpos = pos + len(self._readnl)
- break
-
- if size >= 0 and len(line) >= size:
- endpos = size # reached length size
- break
-
- # No line ending seen yet - get more data'
- while self._read_chunk():
- if self._decoded_chars:
- break
- if self._decoded_chars:
- line += self._get_decoded_chars()
- else:
- # end of file
- self._set_decoded_chars('')
- self._snapshot = None
- return line
-
- if size >= 0 and endpos > size:
- endpos = size # don't exceed size
-
- # Rewind _decoded_chars to just after the line ending we found.
- self._rewind_decoded_chars(len(line) - endpos)
- return line[:endpos]
-
- @property
- def newlines(self):
- return self._decoder.newlines if self._decoder else None
-
-
-class StringIO(TextIOWrapper):
- """Text I/O implementation using an in-memory buffer.
-
- The initial_value argument sets the value of object. The newline
- argument is like the one of TextIOWrapper's constructor.
- """
-
- def __init__(self, initial_value="", newline="\n"):
- super(StringIO, self).__init__(BytesIO(),
- encoding="utf-8",
- errors="surrogatepass",
- newline=newline)
- # Issue #5645: make universal newlines semantics the same as in the
- # C version, even under Windows.
- if newline is None:
- self._writetranslate = False
- if initial_value is not None:
- if not isinstance(initial_value, str):
- raise TypeError("initial_value must be str or None, not {0}"
- .format(type(initial_value).__name__))
- self.write(initial_value)
- self.seek(0)
-
- def getvalue(self):
- self.flush()
- decoder = self._decoder or self._get_decoder()
- old_state = decoder.getstate()
- decoder.reset()
- try:
- return decoder.decode(self.buffer.getvalue(), final=True)
- finally:
- decoder.setstate(old_state)
-
- def __repr__(self):
- # TextIOWrapper tells the encoding in its repr. In StringIO,
- # that's an implementation detail.
- return object.__repr__(self)
-
- @property
- def errors(self):
- return None
-
- @property
- def encoding(self):
- return None
-
- def detach(self):
- # This doesn't make sense on StringIO.
- self._unsupported("detach")
diff --git a/lib/python3.10/_sysconfigdata__linux_x86_64-linux-gnu.py b/lib/python3.10/_sysconfigdata__linux_x86_64-linux-gnu.py
deleted file mode 100644
index 6c1f378..0000000
--- a/lib/python3.10/_sysconfigdata__linux_x86_64-linux-gnu.py
+++ /dev/null
@@ -1,803 +0,0 @@
-# system configuration generated and used by the sysconfig module
-build_time_vars = {'ABIFLAGS': '',
- 'AC_APPLE_UNIVERSAL_BUILD': 0,
- 'AIX_BUILDDATE': 0,
- 'AIX_GENUINE_CPLUSPLUS': 0,
- 'ALIGNOF_LONG': 8,
- 'ALIGNOF_SIZE_T': 8,
- 'ALT_SOABI': 0,
- 'ANDROID_API_LEVEL': 0,
- 'AR': 'ar',
- 'ARFLAGS': 'rcs',
- 'BASECFLAGS': '-Wno-unused-result -Wsign-compare',
- 'BASECPPFLAGS': '-IObjects -IInclude -IPython',
- 'BASEMODLIBS': '',
- 'BINDIR': '/tmpfs/src/git/out/python3/install/bin',
- 'BINLIBDEST': '/tmpfs/src/git/out/python3/install/lib/python3.10',
- 'BLDLIBRARY': '-L. -lpython3.10',
- 'BLDSHARED': 'gcc -pthread -shared -Wno-unused-command-line-argument -s '
- '-Wl,-rpath,\\$ORIGIN/../lib -Wl,--as-needed '
- '-L/tmpfs/src/git/out/libffi/install/lib64 '
- '-Wl,--exclude-libs=libffi.a',
- 'BUILDEXE': '',
- 'BUILDPYTHON': 'python',
- 'BUILD_GNU_TYPE': 'x86_64-pc-linux-gnu',
- 'BYTESTR_DEPS': '\\',
- 'CC': 'gcc -pthread',
- 'CCSHARED': '-fPIC',
- 'CFLAGS': '-Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall '
- '-Wno-unused-command-line-argument',
- 'CFLAGSFORSHARED': '-fPIC',
- 'CFLAGS_ALIASING': '',
- 'CFLAGS_NODIST': '',
- 'CONFIGFILES': 'configure configure.ac acconfig.h pyconfig.h.in '
- 'Makefile.pre.in',
- 'CONFIGURE_CFLAGS': '-Wno-unused-command-line-argument',
- 'CONFIGURE_CFLAGS_NODIST': '-std=c99 -Wextra -Wno-unused-result '
- '-Wno-unused-parameter '
- '-Wno-missing-field-initializers '
- '-Werror=implicit-function-declaration '
- '-fvisibility=hidden',
- 'CONFIGURE_CPPFLAGS': '',
- 'CONFIGURE_LDFLAGS': '-Wno-unused-command-line-argument -s '
- '-Wl,-rpath,\\$ORIGIN/../lib -Wl,--as-needed '
- '-L/tmpfs/src/git/out/libffi/install/lib64 '
- '-Wl,--exclude-libs=libffi.a',
- 'CONFIGURE_LDFLAGS_NODIST': '',
- 'CONFIG_ARGS': "'--prefix=/tmpfs/src/git/out/python3/install' "
- "'--enable-shared' '--with-ensurepip=install' "
- "'CFLAGS=-Wno-unused-command-line-argument' "
- "'LDFLAGS=-Wno-unused-command-line-argument -s "
- '-Wl,-rpath,\\$ORIGIN/../lib -Wl,--as-needed '
- '-L/tmpfs/src/git/out/libffi/install/lib64 '
- "-Wl,--exclude-libs=libffi.a' "
- "'PKG_CONFIG_PATH=/tmpfs/src/git/out/libffi/install/lib/pkgconfig'",
- 'CONFINCLUDEDIR': '/tmpfs/src/git/out/python3/install/include',
- 'CONFINCLUDEPY': '/tmpfs/src/git/out/python3/install/include/python3.10',
- 'COREPYTHONPATH': '',
- 'COVERAGE_INFO': '/tmpfs/src/git/out/python3/build/coverage.info',
- 'COVERAGE_REPORT': '/tmpfs/src/git/out/python3/build/lcov-report',
- 'COVERAGE_REPORT_OPTIONS': '--no-branch-coverage --title "CPython lcov '
- 'report"',
- 'CPPFLAGS': '-IObjects -IInclude -IPython -I. '
- '-I/tmpfs/src/git/external/python/cpython3/Include',
- 'CXX': 'g++',
- 'DESTDIRS': '/tmpfs/src/git/out/python3/install '
- '/tmpfs/src/git/out/python3/install/lib '
- '/tmpfs/src/git/out/python3/install/lib/python3.10 '
- '/tmpfs/src/git/out/python3/install/lib/python3.10/lib-dynload',
- 'DESTLIB': '/tmpfs/src/git/out/python3/install/lib/python3.10',
- 'DESTPATH': '',
- 'DESTSHARED': '/tmpfs/src/git/out/python3/install/lib/python3.10/lib-dynload',
- 'DFLAGS': '',
- 'DIRMODE': 755,
- 'DIST': 'README.rst ChangeLog configure configure.ac acconfig.h pyconfig.h.in '
- 'Makefile.pre.in Include Lib Misc Ext-dummy',
- 'DISTDIRS': 'Include Lib Misc Ext-dummy',
- 'DISTFILES': 'README.rst ChangeLog configure configure.ac acconfig.h '
- 'pyconfig.h.in Makefile.pre.in',
- 'DLINCLDIR': '.',
- 'DLLLIBRARY': '',
- 'DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754': 0,
- 'DOUBLE_IS_BIG_ENDIAN_IEEE754': 0,
- 'DOUBLE_IS_LITTLE_ENDIAN_IEEE754': 1,
- 'DTRACE': '',
- 'DTRACE_DEPS': '\\',
- 'DTRACE_HEADERS': '',
- 'DTRACE_OBJS': '',
- 'DYNLOADFILE': 'dynload_shlib.o',
- 'ENABLE_IPV6': 1,
- 'ENSUREPIP': 'install',
- 'EXE': '',
- 'EXEMODE': 755,
- 'EXPERIMENTAL_ISOLATED_SUBINTERPRETERS': 0,
- 'EXPORTSFROM': '',
- 'EXPORTSYMS': '',
- 'EXTRATESTOPTS': '',
- 'EXTRA_CFLAGS': '',
- 'EXT_SUFFIX': '.cpython-310-x86_64-linux-gnu.so',
- 'FILEMODE': 644,
- 'FLOAT_WORDS_BIGENDIAN': 0,
- 'FLOCK_NEEDS_LIBBSD': 0,
- 'GETPGRP_HAVE_ARG': 0,
- 'GITBRANCH': 'git --git-dir /tmpfs/src/git/external/python/cpython3/.git '
- 'name-rev --name-only HEAD',
- 'GITTAG': 'git --git-dir /tmpfs/src/git/external/python/cpython3/.git '
- 'describe --all --always --dirty',
- 'GITVERSION': 'git --git-dir /tmpfs/src/git/external/python/cpython3/.git '
- 'rev-parse --short HEAD',
- 'GNULD': 'yes',
- 'HAVE_ACCEPT4': 1,
- 'HAVE_ACOSH': 1,
- 'HAVE_ADDRINFO': 1,
- 'HAVE_ALARM': 1,
- 'HAVE_ALIGNED_REQUIRED': 0,
- 'HAVE_ALLOCA_H': 1,
- 'HAVE_ALTZONE': 0,
- 'HAVE_ASINH': 1,
- 'HAVE_ASM_TYPES_H': 1,
- 'HAVE_ATANH': 1,
- 'HAVE_BIND_TEXTDOMAIN_CODESET': 1,
- 'HAVE_BLUETOOTH_BLUETOOTH_H': 0,
- 'HAVE_BLUETOOTH_H': 0,
- 'HAVE_BROKEN_MBSTOWCS': 0,
- 'HAVE_BROKEN_NICE': 0,
- 'HAVE_BROKEN_PIPE_BUF': 0,
- 'HAVE_BROKEN_POLL': 0,
- 'HAVE_BROKEN_POSIX_SEMAPHORES': 0,
- 'HAVE_BROKEN_PTHREAD_SIGMASK': 0,
- 'HAVE_BROKEN_SEM_GETVALUE': 0,
- 'HAVE_BROKEN_UNSETENV': 0,
- 'HAVE_BUILTIN_ATOMIC': 1,
- 'HAVE_CHFLAGS': 0,
- 'HAVE_CHOWN': 1,
- 'HAVE_CHROOT': 1,
- 'HAVE_CLOCK': 1,
- 'HAVE_CLOCK_GETRES': 1,
- 'HAVE_CLOCK_GETTIME': 1,
- 'HAVE_CLOCK_SETTIME': 1,
- 'HAVE_CLOSE_RANGE': 0,
- 'HAVE_COMPUTED_GOTOS': 1,
- 'HAVE_CONFSTR': 1,
- 'HAVE_CONIO_H': 0,
- 'HAVE_COPYSIGN': 1,
- 'HAVE_COPY_FILE_RANGE': 0,
- 'HAVE_CRYPT_H': 1,
- 'HAVE_CRYPT_R': 1,
- 'HAVE_CTERMID': 1,
- 'HAVE_CTERMID_R': 0,
- 'HAVE_CURSES_FILTER': 1,
- 'HAVE_CURSES_H': 1,
- 'HAVE_CURSES_HAS_KEY': 1,
- 'HAVE_CURSES_IMMEDOK': 1,
- 'HAVE_CURSES_IS_PAD': 1,
- 'HAVE_CURSES_IS_TERM_RESIZED': 1,
- 'HAVE_CURSES_RESIZETERM': 1,
- 'HAVE_CURSES_RESIZE_TERM': 1,
- 'HAVE_CURSES_SYNCOK': 1,
- 'HAVE_CURSES_TYPEAHEAD': 1,
- 'HAVE_CURSES_USE_ENV': 1,
- 'HAVE_CURSES_WCHGAT': 1,
- 'HAVE_DECL_ISFINITE': 1,
- 'HAVE_DECL_ISINF': 1,
- 'HAVE_DECL_ISNAN': 1,
- 'HAVE_DECL_RTLD_DEEPBIND': 1,
- 'HAVE_DECL_RTLD_GLOBAL': 1,
- 'HAVE_DECL_RTLD_LAZY': 1,
- 'HAVE_DECL_RTLD_LOCAL': 1,
- 'HAVE_DECL_RTLD_MEMBER': 0,
- 'HAVE_DECL_RTLD_NODELETE': 1,
- 'HAVE_DECL_RTLD_NOLOAD': 1,
- 'HAVE_DECL_RTLD_NOW': 1,
- 'HAVE_DECL_TZNAME': 0,
- 'HAVE_DEVICE_MACROS': 1,
- 'HAVE_DEV_PTC': 0,
- 'HAVE_DEV_PTMX': 1,
- 'HAVE_DIRECT_H': 0,
- 'HAVE_DIRENT_D_TYPE': 1,
- 'HAVE_DIRENT_H': 1,
- 'HAVE_DIRFD': 1,
- 'HAVE_DLFCN_H': 1,
- 'HAVE_DLOPEN': 1,
- 'HAVE_DUP2': 1,
- 'HAVE_DUP3': 1,
- 'HAVE_DYLD_SHARED_CACHE_CONTAINS_PATH': 0,
- 'HAVE_DYNAMIC_LOADING': 1,
- 'HAVE_ENDIAN_H': 1,
- 'HAVE_EPOLL': 1,
- 'HAVE_EPOLL_CREATE1': 1,
- 'HAVE_ERF': 1,
- 'HAVE_ERFC': 1,
- 'HAVE_ERRNO_H': 1,
- 'HAVE_EVENTFD': 1,
- 'HAVE_EXECV': 1,
- 'HAVE_EXPLICIT_BZERO': 0,
- 'HAVE_EXPLICIT_MEMSET': 0,
- 'HAVE_EXPM1': 1,
- 'HAVE_FACCESSAT': 1,
- 'HAVE_FCHDIR': 1,
- 'HAVE_FCHMOD': 1,
- 'HAVE_FCHMODAT': 1,
- 'HAVE_FCHOWN': 1,
- 'HAVE_FCHOWNAT': 1,
- 'HAVE_FCNTL_H': 1,
- 'HAVE_FDATASYNC': 1,
- 'HAVE_FDOPENDIR': 1,
- 'HAVE_FDWALK': 0,
- 'HAVE_FEXECVE': 1,
- 'HAVE_FINITE': 1,
- 'HAVE_FLOCK': 1,
- 'HAVE_FORK': 1,
- 'HAVE_FORKPTY': 1,
- 'HAVE_FPATHCONF': 1,
- 'HAVE_FSEEK64': 0,
- 'HAVE_FSEEKO': 1,
- 'HAVE_FSTATAT': 1,
- 'HAVE_FSTATVFS': 1,
- 'HAVE_FSYNC': 1,
- 'HAVE_FTELL64': 0,
- 'HAVE_FTELLO': 1,
- 'HAVE_FTIME': 1,
- 'HAVE_FTRUNCATE': 1,
- 'HAVE_FUTIMENS': 1,
- 'HAVE_FUTIMES': 1,
- 'HAVE_FUTIMESAT': 1,
- 'HAVE_GAI_STRERROR': 1,
- 'HAVE_GAMMA': 1,
- 'HAVE_GCC_ASM_FOR_MC68881': 0,
- 'HAVE_GCC_ASM_FOR_X64': 1,
- 'HAVE_GCC_ASM_FOR_X87': 1,
- 'HAVE_GCC_UINT128_T': 1,
- 'HAVE_GETADDRINFO': 1,
- 'HAVE_GETC_UNLOCKED': 1,
- 'HAVE_GETENTROPY': 0,
- 'HAVE_GETGRGID_R': 1,
- 'HAVE_GETGRNAM_R': 1,
- 'HAVE_GETGROUPLIST': 1,
- 'HAVE_GETGROUPS': 1,
- 'HAVE_GETHOSTBYNAME': 0,
- 'HAVE_GETHOSTBYNAME_R': 1,
- 'HAVE_GETHOSTBYNAME_R_3_ARG': 0,
- 'HAVE_GETHOSTBYNAME_R_5_ARG': 0,
- 'HAVE_GETHOSTBYNAME_R_6_ARG': 1,
- 'HAVE_GETITIMER': 1,
- 'HAVE_GETLOADAVG': 1,
- 'HAVE_GETLOGIN': 1,
- 'HAVE_GETNAMEINFO': 1,
- 'HAVE_GETPAGESIZE': 1,
- 'HAVE_GETPEERNAME': 1,
- 'HAVE_GETPGID': 1,
- 'HAVE_GETPGRP': 1,
- 'HAVE_GETPID': 1,
- 'HAVE_GETPRIORITY': 1,
- 'HAVE_GETPWENT': 1,
- 'HAVE_GETPWNAM_R': 1,
- 'HAVE_GETPWUID_R': 1,
- 'HAVE_GETRANDOM': 0,
- 'HAVE_GETRANDOM_SYSCALL': 1,
- 'HAVE_GETRESGID': 1,
- 'HAVE_GETRESUID': 1,
- 'HAVE_GETSID': 1,
- 'HAVE_GETSPENT': 1,
- 'HAVE_GETSPNAM': 1,
- 'HAVE_GETWD': 1,
- 'HAVE_GLIBC_MEMMOVE_BUG': 0,
- 'HAVE_GRP_H': 1,
- 'HAVE_HSTRERROR': 1,
- 'HAVE_HTOLE64': 1,
- 'HAVE_HYPOT': 1,
- 'HAVE_IEEEFP_H': 0,
- 'HAVE_IF_NAMEINDEX': 1,
- 'HAVE_INET_ATON': 1,
- 'HAVE_INET_PTON': 1,
- 'HAVE_INITGROUPS': 1,
- 'HAVE_INTTYPES_H': 1,
- 'HAVE_IO_H': 0,
- 'HAVE_IPA_PURE_CONST_BUG': 0,
- 'HAVE_KILL': 1,
- 'HAVE_KILLPG': 1,
- 'HAVE_KQUEUE': 0,
- 'HAVE_LANGINFO_H': 1,
- 'HAVE_LARGEFILE_SUPPORT': 0,
- 'HAVE_LCHFLAGS': 0,
- 'HAVE_LCHMOD': 0,
- 'HAVE_LCHOWN': 1,
- 'HAVE_LGAMMA': 1,
- 'HAVE_LIBDL': 1,
- 'HAVE_LIBDLD': 0,
- 'HAVE_LIBIEEE': 0,
- 'HAVE_LIBINTL_H': 1,
- 'HAVE_LIBREADLINE': 0,
- 'HAVE_LIBRESOLV': 0,
- 'HAVE_LIBSENDFILE': 0,
- 'HAVE_LIBUTIL_H': 0,
- 'HAVE_LIBUUID': 0,
- 'HAVE_LINK': 1,
- 'HAVE_LINKAT': 1,
- 'HAVE_LINUX_AUXVEC_H': 1,
- 'HAVE_LINUX_CAN_BCM_H': 1,
- 'HAVE_LINUX_CAN_H': 1,
- 'HAVE_LINUX_CAN_J1939_H': 0,
- 'HAVE_LINUX_CAN_RAW_FD_FRAMES': 1,
- 'HAVE_LINUX_CAN_RAW_H': 1,
- 'HAVE_LINUX_CAN_RAW_JOIN_FILTERS': 1,
- 'HAVE_LINUX_MEMFD_H': 1,
- 'HAVE_LINUX_NETLINK_H': 1,
- 'HAVE_LINUX_QRTR_H': 0,
- 'HAVE_LINUX_RANDOM_H': 1,
- 'HAVE_LINUX_TIPC_H': 1,
- 'HAVE_LINUX_VM_SOCKETS_H': 1,
- 'HAVE_LINUX_WAIT_H': 1,
- 'HAVE_LOCKF': 1,
- 'HAVE_LOG1P': 1,
- 'HAVE_LOG2': 1,
- 'HAVE_LONG_DOUBLE': 1,
- 'HAVE_LSTAT': 1,
- 'HAVE_LUTIMES': 1,
- 'HAVE_MADVISE': 1,
- 'HAVE_MAKEDEV': 1,
- 'HAVE_MBRTOWC': 1,
- 'HAVE_MEMFD_CREATE': 0,
- 'HAVE_MEMORY_H': 1,
- 'HAVE_MEMRCHR': 1,
- 'HAVE_MKDIRAT': 1,
- 'HAVE_MKFIFO': 1,
- 'HAVE_MKFIFOAT': 1,
- 'HAVE_MKNOD': 1,
- 'HAVE_MKNODAT': 1,
- 'HAVE_MKTIME': 1,
- 'HAVE_MMAP': 1,
- 'HAVE_MREMAP': 1,
- 'HAVE_NCURSES_H': 1,
- 'HAVE_NDIR_H': 0,
- 'HAVE_NETPACKET_PACKET_H': 1,
- 'HAVE_NET_IF_H': 1,
- 'HAVE_NICE': 1,
- 'HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION': 0,
- 'HAVE_OPENAT': 1,
- 'HAVE_OPENPTY': 1,
- 'HAVE_PATHCONF': 1,
- 'HAVE_PAUSE': 1,
- 'HAVE_PIPE2': 1,
- 'HAVE_PLOCK': 0,
- 'HAVE_POLL': 1,
- 'HAVE_POLL_H': 1,
- 'HAVE_POSIX_FADVISE': 1,
- 'HAVE_POSIX_FALLOCATE': 1,
- 'HAVE_POSIX_SPAWN': 1,
- 'HAVE_POSIX_SPAWNP': 1,
- 'HAVE_PREAD': 1,
- 'HAVE_PREADV': 1,
- 'HAVE_PREADV2': 0,
- 'HAVE_PRLIMIT': 1,
- 'HAVE_PROCESS_H': 0,
- 'HAVE_PROTOTYPES': 1,
- 'HAVE_PTHREAD_CONDATTR_SETCLOCK': 1,
- 'HAVE_PTHREAD_DESTRUCTOR': 0,
- 'HAVE_PTHREAD_GETCPUCLOCKID': 1,
- 'HAVE_PTHREAD_H': 1,
- 'HAVE_PTHREAD_INIT': 0,
- 'HAVE_PTHREAD_KILL': 1,
- 'HAVE_PTHREAD_SIGMASK': 1,
- 'HAVE_PTY_H': 1,
- 'HAVE_PWRITE': 1,
- 'HAVE_PWRITEV': 1,
- 'HAVE_PWRITEV2': 0,
- 'HAVE_READLINK': 1,
- 'HAVE_READLINKAT': 1,
- 'HAVE_READV': 1,
- 'HAVE_REALPATH': 1,
- 'HAVE_RENAMEAT': 1,
- 'HAVE_RL_APPEND_HISTORY': 0,
- 'HAVE_RL_CATCH_SIGNAL': 0,
- 'HAVE_RL_COMPLETION_APPEND_CHARACTER': 0,
- 'HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK': 0,
- 'HAVE_RL_COMPLETION_MATCHES': 0,
- 'HAVE_RL_COMPLETION_SUPPRESS_APPEND': 0,
- 'HAVE_RL_PRE_INPUT_HOOK': 0,
- 'HAVE_RL_RESIZE_TERMINAL': 0,
- 'HAVE_ROUND': 1,
- 'HAVE_RTPSPAWN': 0,
- 'HAVE_SCHED_GET_PRIORITY_MAX': 1,
- 'HAVE_SCHED_H': 1,
- 'HAVE_SCHED_RR_GET_INTERVAL': 1,
- 'HAVE_SCHED_SETAFFINITY': 1,
- 'HAVE_SCHED_SETPARAM': 1,
- 'HAVE_SCHED_SETSCHEDULER': 1,
- 'HAVE_SEM_CLOCKWAIT': 0,
- 'HAVE_SEM_GETVALUE': 1,
- 'HAVE_SEM_OPEN': 1,
- 'HAVE_SEM_TIMEDWAIT': 1,
- 'HAVE_SEM_UNLINK': 1,
- 'HAVE_SENDFILE': 1,
- 'HAVE_SETEGID': 1,
- 'HAVE_SETEUID': 1,
- 'HAVE_SETGID': 1,
- 'HAVE_SETGROUPS': 1,
- 'HAVE_SETHOSTNAME': 1,
- 'HAVE_SETITIMER': 1,
- 'HAVE_SETLOCALE': 1,
- 'HAVE_SETPGID': 1,
- 'HAVE_SETPGRP': 1,
- 'HAVE_SETPRIORITY': 1,
- 'HAVE_SETREGID': 1,
- 'HAVE_SETRESGID': 1,
- 'HAVE_SETRESUID': 1,
- 'HAVE_SETREUID': 1,
- 'HAVE_SETSID': 1,
- 'HAVE_SETUID': 1,
- 'HAVE_SETVBUF': 1,
- 'HAVE_SHADOW_H': 1,
- 'HAVE_SHM_OPEN': 1,
- 'HAVE_SHM_UNLINK': 1,
- 'HAVE_SIGACTION': 1,
- 'HAVE_SIGALTSTACK': 1,
- 'HAVE_SIGFILLSET': 1,
- 'HAVE_SIGINFO_T_SI_BAND': 1,
- 'HAVE_SIGINTERRUPT': 1,
- 'HAVE_SIGNAL_H': 1,
- 'HAVE_SIGPENDING': 1,
- 'HAVE_SIGRELSE': 1,
- 'HAVE_SIGTIMEDWAIT': 1,
- 'HAVE_SIGWAIT': 1,
- 'HAVE_SIGWAITINFO': 1,
- 'HAVE_SNPRINTF': 1,
- 'HAVE_SOCKADDR_ALG': 1,
- 'HAVE_SOCKADDR_SA_LEN': 0,
- 'HAVE_SOCKADDR_STORAGE': 1,
- 'HAVE_SOCKETPAIR': 1,
- 'HAVE_SPAWN_H': 1,
- 'HAVE_SPLICE': 1,
- 'HAVE_SSIZE_T': 1,
- 'HAVE_STATVFS': 1,
- 'HAVE_STAT_TV_NSEC': 1,
- 'HAVE_STAT_TV_NSEC2': 0,
- 'HAVE_STDARG_PROTOTYPES': 1,
- 'HAVE_STDINT_H': 1,
- 'HAVE_STDLIB_H': 1,
- 'HAVE_STD_ATOMIC': 0,
- 'HAVE_STRFTIME': 1,
- 'HAVE_STRINGS_H': 1,
- 'HAVE_STRING_H': 1,
- 'HAVE_STRLCPY': 0,
- 'HAVE_STROPTS_H': 0,
- 'HAVE_STRSIGNAL': 1,
- 'HAVE_STRUCT_PASSWD_PW_GECOS': 1,
- 'HAVE_STRUCT_PASSWD_PW_PASSWD': 1,
- 'HAVE_STRUCT_STAT_ST_BIRTHTIME': 0,
- 'HAVE_STRUCT_STAT_ST_BLKSIZE': 1,
- 'HAVE_STRUCT_STAT_ST_BLOCKS': 1,
- 'HAVE_STRUCT_STAT_ST_FLAGS': 0,
- 'HAVE_STRUCT_STAT_ST_GEN': 0,
- 'HAVE_STRUCT_STAT_ST_RDEV': 1,
- 'HAVE_STRUCT_TM_TM_ZONE': 1,
- 'HAVE_SYMLINK': 1,
- 'HAVE_SYMLINKAT': 1,
- 'HAVE_SYNC': 1,
- 'HAVE_SYSCONF': 1,
- 'HAVE_SYSEXITS_H': 1,
- 'HAVE_SYS_AUDIOIO_H': 0,
- 'HAVE_SYS_BSDTTY_H': 0,
- 'HAVE_SYS_DEVPOLL_H': 0,
- 'HAVE_SYS_DIR_H': 0,
- 'HAVE_SYS_ENDIAN_H': 0,
- 'HAVE_SYS_EPOLL_H': 1,
- 'HAVE_SYS_EVENTFD_H': 1,
- 'HAVE_SYS_EVENT_H': 0,
- 'HAVE_SYS_FILE_H': 1,
- 'HAVE_SYS_IOCTL_H': 1,
- 'HAVE_SYS_KERN_CONTROL_H': 0,
- 'HAVE_SYS_LOADAVG_H': 0,
- 'HAVE_SYS_LOCK_H': 0,
- 'HAVE_SYS_MEMFD_H': 0,
- 'HAVE_SYS_MKDEV_H': 0,
- 'HAVE_SYS_MMAN_H': 1,
- 'HAVE_SYS_MODEM_H': 0,
- 'HAVE_SYS_NDIR_H': 0,
- 'HAVE_SYS_PARAM_H': 1,
- 'HAVE_SYS_POLL_H': 1,
- 'HAVE_SYS_RANDOM_H': 0,
- 'HAVE_SYS_RESOURCE_H': 1,
- 'HAVE_SYS_SELECT_H': 1,
- 'HAVE_SYS_SENDFILE_H': 1,
- 'HAVE_SYS_SOCKET_H': 1,
- 'HAVE_SYS_STATVFS_H': 1,
- 'HAVE_SYS_STAT_H': 1,
- 'HAVE_SYS_SYSCALL_H': 1,
- 'HAVE_SYS_SYSMACROS_H': 1,
- 'HAVE_SYS_SYS_DOMAIN_H': 0,
- 'HAVE_SYS_TERMIO_H': 0,
- 'HAVE_SYS_TIMES_H': 1,
- 'HAVE_SYS_TIME_H': 1,
- 'HAVE_SYS_TYPES_H': 1,
- 'HAVE_SYS_UIO_H': 1,
- 'HAVE_SYS_UN_H': 1,
- 'HAVE_SYS_UTSNAME_H': 1,
- 'HAVE_SYS_WAIT_H': 1,
- 'HAVE_SYS_XATTR_H': 1,
- 'HAVE_TCGETPGRP': 1,
- 'HAVE_TCSETPGRP': 1,
- 'HAVE_TEMPNAM': 1,
- 'HAVE_TERMIOS_H': 1,
- 'HAVE_TERM_H': 1,
- 'HAVE_TGAMMA': 1,
- 'HAVE_TIMEGM': 1,
- 'HAVE_TIMES': 1,
- 'HAVE_TMPFILE': 1,
- 'HAVE_TMPNAM': 1,
- 'HAVE_TMPNAM_R': 1,
- 'HAVE_TM_ZONE': 1,
- 'HAVE_TRUNCATE': 1,
- 'HAVE_TZNAME': 0,
- 'HAVE_UCS4_TCL': 0,
- 'HAVE_UNAME': 1,
- 'HAVE_UNISTD_H': 1,
- 'HAVE_UNLINKAT': 1,
- 'HAVE_USABLE_WCHAR_T': 0,
- 'HAVE_UTIL_H': 0,
- 'HAVE_UTIMENSAT': 1,
- 'HAVE_UTIMES': 1,
- 'HAVE_UTIME_H': 1,
- 'HAVE_UUID_CREATE': 0,
- 'HAVE_UUID_ENC_BE': 0,
- 'HAVE_UUID_GENERATE_TIME_SAFE': 0,
- 'HAVE_UUID_H': 0,
- 'HAVE_UUID_UUID_H': 0,
- 'HAVE_VFORK': 1,
- 'HAVE_WAIT3': 1,
- 'HAVE_WAIT4': 1,
- 'HAVE_WAITID': 1,
- 'HAVE_WAITPID': 1,
- 'HAVE_WCHAR_H': 1,
- 'HAVE_WCSCOLL': 1,
- 'HAVE_WCSFTIME': 1,
- 'HAVE_WCSXFRM': 1,
- 'HAVE_WMEMCMP': 1,
- 'HAVE_WORKING_TZSET': 1,
- 'HAVE_WRITEV': 1,
- 'HAVE_ZLIB_COPY': 1,
- 'HAVE__GETPTY': 0,
- 'HOST_GNU_TYPE': 'x86_64-pc-linux-gnu',
- 'INCLDIRSTOMAKE': '/tmpfs/src/git/out/python3/install/include '
- '/tmpfs/src/git/out/python3/install/include '
- '/tmpfs/src/git/out/python3/install/include/python3.10 '
- '/tmpfs/src/git/out/python3/install/include/python3.10',
- 'INCLUDEDIR': '/tmpfs/src/git/out/python3/install/include',
- 'INCLUDEPY': '/tmpfs/src/git/out/python3/install/include/python3.10',
- 'INSTALL': '/usr/bin/install -c',
- 'INSTALL_DATA': '/usr/bin/install -c -m 644',
- 'INSTALL_PROGRAM': '/usr/bin/install -c',
- 'INSTALL_SCRIPT': '/usr/bin/install -c',
- 'INSTALL_SHARED': '/usr/bin/install -c -m 755',
- 'INSTSONAME': 'libpython3.10.so.1.0',
- 'IO_H': 'Modules/_io/_iomodule.h',
- 'IO_OBJS': '\\',
- 'LDCXXSHARED': 'g++ -shared',
- 'LDFLAGS': '-Wno-unused-command-line-argument -s -Wl,-rpath,\\$ORIGIN/../lib '
- '-Wl,--as-needed -L/tmpfs/src/git/out/libffi/install/lib64 '
- '-Wl,--exclude-libs=libffi.a',
- 'LDFLAGS_NODIST': '',
- 'LDLIBRARY': 'libpython3.10.so',
- 'LDLIBRARYDIR': '',
- 'LDSHARED': 'gcc -pthread -shared -Wno-unused-command-line-argument -s '
- '-Wl,-rpath,\\$ORIGIN/../lib -Wl,--as-needed '
- '-L/tmpfs/src/git/out/libffi/install/lib64 '
- '-Wl,--exclude-libs=libffi.a',
- 'LDVERSION': '3.10',
- 'LIBC': '',
- 'LIBDEST': '/tmpfs/src/git/out/python3/install/lib/python3.10',
- 'LIBDIR': '/tmpfs/src/git/out/python3/install/lib',
- 'LIBFFI_INCLUDEDIR': '/tmpfs/src/git/out/libffi/install/include',
- 'LIBM': '-lm',
- 'LIBOBJDIR': 'Python/',
- 'LIBOBJS': '',
- 'LIBPC': '/tmpfs/src/git/out/python3/install/lib/pkgconfig',
- 'LIBPL': '/tmpfs/src/git/out/python3/install/lib/python3.10/config-3.10-x86_64-linux-gnu',
- 'LIBPYTHON': '',
- 'LIBRARY': 'libpython3.10.a',
- 'LIBRARY_DEPS': 'libpython3.10.a libpython3.10.so libpython3.so',
- 'LIBRARY_OBJS': '\\',
- 'LIBRARY_OBJS_OMIT_FROZEN': '\\',
- 'LIBS': '-lcrypt -lpthread -ldl -lutil -lm',
- 'LIBSUBDIRS': 'asyncio \\',
- 'LINKCC': 'gcc -pthread',
- 'LINKFORSHARED': '-Xlinker -export-dynamic',
- 'LIPO_32BIT_FLAGS': '',
- 'LIPO_INTEL64_FLAGS': '',
- 'LLVM_PROF_ERR': 'no',
- 'LLVM_PROF_FILE': '',
- 'LLVM_PROF_MERGER': 'true',
- 'LN': 'ln',
- 'LOCALMODLIBS': '',
- 'MACHDEP': 'linux',
- 'MACHDEP_OBJS': '',
- 'MACHDESTLIB': '/tmpfs/src/git/out/python3/install/lib/python3.10',
- 'MACOSX_DEPLOYMENT_TARGET': '',
- 'MAINCC': 'gcc -pthread',
- 'MAJOR_IN_MKDEV': 0,
- 'MAJOR_IN_SYSMACROS': 0,
- 'MAKESETUP': '/tmpfs/src/git/external/python/cpython3/Modules/makesetup',
- 'MANDIR': '/tmpfs/src/git/out/python3/install/share/man',
- 'MKDIR_P': '/usr/bin/mkdir -p',
- 'MODBUILT_NAMES': 'posix errno pwd _sre _codecs _weakref _functools '
- '_operator _collections _abc itertools atexit _signal '
- '_stat time _thread _locale _io faulthandler '
- '_tracemalloc _symtable xxsubtype',
- 'MODDISABLED_NAMES': '',
- 'MODLIBS': '',
- 'MODOBJS': 'Modules/posixmodule.o Modules/errnomodule.o '
- 'Modules/pwdmodule.o Modules/_sre.o Modules/_codecsmodule.o '
- 'Modules/_weakref.o Modules/_functoolsmodule.o '
- 'Modules/_operator.o Modules/_collectionsmodule.o '
- 'Modules/_abc.o Modules/itertoolsmodule.o '
- 'Modules/atexitmodule.o Modules/signalmodule.o Modules/_stat.o '
- 'Modules/timemodule.o Modules/_threadmodule.o '
- 'Modules/_localemodule.o Modules/_iomodule.o Modules/iobase.o '
- 'Modules/fileio.o Modules/bytesio.o Modules/bufferedio.o '
- 'Modules/textio.o Modules/stringio.o Modules/faulthandler.o '
- 'Modules/_tracemalloc.o Modules/symtablemodule.o '
- 'Modules/xxsubtype.o',
- 'MODULE_OBJS': '\\',
- 'MULTIARCH': 'x86_64-linux-gnu',
- 'MULTIARCH_CPPFLAGS': '-DMULTIARCH=\\"x86_64-linux-gnu\\"',
- 'MVWDELCH_IS_EXPRESSION': 1,
- 'NO_AS_NEEDED': '-Wl,--no-as-needed',
- 'OBJECT_OBJS': '\\',
- 'OPENSSL_INCLUDES': '',
- 'OPENSSL_LDFLAGS': '',
- 'OPENSSL_LIBS': '',
- 'OPENSSL_RPATH': '',
- 'OPT': '-DNDEBUG -g -fwrapv -O3 -Wall',
- 'OTHER_LIBTOOL_OPT': '',
- 'PACKAGE_BUGREPORT': 0,
- 'PACKAGE_NAME': 0,
- 'PACKAGE_STRING': 0,
- 'PACKAGE_TARNAME': 0,
- 'PACKAGE_URL': 0,
- 'PACKAGE_VERSION': 0,
- 'PARSER_HEADERS': '\\',
- 'PARSER_OBJS': '\\ \\ Parser/myreadline.o Parser/tokenizer.o',
- 'PEGEN_HEADERS': '\\',
- 'PEGEN_OBJS': '\\',
- 'PGO_PROF_GEN_FLAG': '-fprofile-generate',
- 'PGO_PROF_USE_FLAG': '-fprofile-use -fprofile-correction',
- 'PLATLIBDIR': 'lib',
- 'POBJS': '\\',
- 'POSIX_SEMAPHORES_NOT_ENABLED': 0,
- 'PROFILE_TASK': '-m test --pgo --timeout=1200',
- 'PTHREAD_KEY_T_IS_COMPATIBLE_WITH_INT': 1,
- 'PTHREAD_SYSTEM_SCHED_SUPPORTED': 1,
- 'PURIFY': '',
- 'PY3LIBRARY': 'libpython3.so',
- 'PYLONG_BITS_IN_DIGIT': 0,
- 'PYTHON': 'python',
- 'PYTHONFRAMEWORK': '',
- 'PYTHONFRAMEWORKDIR': 'no-framework',
- 'PYTHONFRAMEWORKINSTALLDIR': '',
- 'PYTHONFRAMEWORKPREFIX': '',
- 'PYTHONPATH': '',
- 'PYTHON_FOR_BUILD': './python -E',
- 'PYTHON_FOR_REGEN': '',
- 'PYTHON_HEADERS': '\\',
- 'PYTHON_OBJS': '\\',
- 'PY_BUILTIN_HASHLIB_HASHES': '"md5,sha1,sha256,sha512,sha3,blake2"',
- 'PY_BUILTIN_MODULE_CFLAGS': '-Wno-unused-result -Wsign-compare -DNDEBUG -g '
- '-fwrapv -O3 -Wall '
- '-Wno-unused-command-line-argument -std=c99 '
- '-Wextra -Wno-unused-result -Wno-unused-parameter '
- '-Wno-missing-field-initializers '
- '-Werror=implicit-function-declaration '
- '-fvisibility=hidden '
- '-I/tmpfs/src/git/external/python/cpython3/Include/internal '
- '-IObjects -IInclude -IPython -I. '
- '-I/tmpfs/src/git/external/python/cpython3/Include '
- '-fPIC -DPy_BUILD_CORE_BUILTIN',
- 'PY_CFLAGS': '-Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall '
- '-Wno-unused-command-line-argument',
- 'PY_CFLAGS_NODIST': '-std=c99 -Wextra -Wno-unused-result '
- '-Wno-unused-parameter -Wno-missing-field-initializers '
- '-Werror=implicit-function-declaration '
- '-fvisibility=hidden '
- '-I/tmpfs/src/git/external/python/cpython3/Include/internal',
- 'PY_COERCE_C_LOCALE': 1,
- 'PY_CORE_CFLAGS': '-Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 '
- '-Wall -Wno-unused-command-line-argument -std=c99 -Wextra '
- '-Wno-unused-result -Wno-unused-parameter '
- '-Wno-missing-field-initializers '
- '-Werror=implicit-function-declaration -fvisibility=hidden '
- '-I/tmpfs/src/git/external/python/cpython3/Include/internal '
- '-IObjects -IInclude -IPython -I. '
- '-I/tmpfs/src/git/external/python/cpython3/Include -fPIC '
- '-DPy_BUILD_CORE',
- 'PY_CORE_LDFLAGS': '-Wno-unused-command-line-argument -s '
- '-Wl,-rpath,\\$ORIGIN/../lib -Wl,--as-needed '
- '-L/tmpfs/src/git/out/libffi/install/lib64 '
- '-Wl,--exclude-libs=libffi.a',
- 'PY_CPPFLAGS': '-IObjects -IInclude -IPython -I. '
- '-I/tmpfs/src/git/external/python/cpython3/Include',
- 'PY_ENABLE_SHARED': 1,
- 'PY_FORMAT_SIZE_T': '"z"',
- 'PY_LDFLAGS': '-Wno-unused-command-line-argument -s '
- '-Wl,-rpath,\\$ORIGIN/../lib -Wl,--as-needed '
- '-L/tmpfs/src/git/out/libffi/install/lib64 '
- '-Wl,--exclude-libs=libffi.a',
- 'PY_LDFLAGS_NODIST': '',
- 'PY_SSL_DEFAULT_CIPHERS': 1,
- 'PY_SSL_DEFAULT_CIPHER_STRING': 0,
- 'PY_STDMODULE_CFLAGS': '-Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv '
- '-O3 -Wall -Wno-unused-command-line-argument -std=c99 '
- '-Wextra -Wno-unused-result -Wno-unused-parameter '
- '-Wno-missing-field-initializers '
- '-Werror=implicit-function-declaration '
- '-fvisibility=hidden '
- '-I/tmpfs/src/git/external/python/cpython3/Include/internal '
- '-IObjects -IInclude -IPython -I. '
- '-I/tmpfs/src/git/external/python/cpython3/Include '
- '-fPIC',
- 'Py_DEBUG': 0,
- 'Py_ENABLE_SHARED': 1,
- 'Py_HASH_ALGORITHM': 0,
- 'Py_TRACE_REFS': 0,
- 'QUICKTESTOPTS': '-x test_subprocess test_io test_lib2to3 \\',
- 'READELF': 'readelf',
- 'RESSRCDIR': 'Mac/Resources/framework',
- 'RETSIGTYPE': 'void',
- 'RUNSHARED': 'LD_LIBRARY_PATH=/tmpfs/src/git/out/python3/build',
- 'SCRIPTDIR': '/tmpfs/src/git/out/python3/install/lib',
- 'SETPGRP_HAVE_ARG': 0,
- 'SHELL': '/bin/sh',
- 'SHLIBS': '-lcrypt -lpthread -ldl -lutil -lm',
- 'SHLIB_SUFFIX': '.so',
- 'SHM_NEEDS_LIBRT': 1,
- 'SIGNED_RIGHT_SHIFT_ZERO_FILLS': 0,
- 'SITEPATH': '',
- 'SIZEOF_DOUBLE': 8,
- 'SIZEOF_FLOAT': 4,
- 'SIZEOF_FPOS_T': 16,
- 'SIZEOF_INT': 4,
- 'SIZEOF_LONG': 8,
- 'SIZEOF_LONG_DOUBLE': 16,
- 'SIZEOF_LONG_LONG': 8,
- 'SIZEOF_OFF_T': 8,
- 'SIZEOF_PID_T': 4,
- 'SIZEOF_PTHREAD_KEY_T': 4,
- 'SIZEOF_PTHREAD_T': 8,
- 'SIZEOF_SHORT': 2,
- 'SIZEOF_SIZE_T': 8,
- 'SIZEOF_TIME_T': 8,
- 'SIZEOF_UINTPTR_T': 8,
- 'SIZEOF_VOID_P': 8,
- 'SIZEOF_WCHAR_T': 4,
- 'SIZEOF__BOOL': 1,
- 'SOABI': 'cpython-310-x86_64-linux-gnu',
- 'SRCDIRS': 'Parser Objects Python Modules Modules/_io Programs',
- 'SRC_GDB_HOOKS': '/tmpfs/src/git/external/python/cpython3/Tools/gdb/libpython.py',
- 'STATIC_LIBPYTHON': 1,
- 'STDC_HEADERS': 1,
- 'STRICT_SYSV_CURSES': "/* Don't use ncurses extensions */",
- 'STRIPFLAG': '-s',
- 'SUBDIRS': '',
- 'SUBDIRSTOO': 'Include Lib Misc',
- 'SYSLIBS': '-lm',
- 'SYS_SELECT_WITH_SYS_TIME': 1,
- 'TCLTK_INCLUDES': '',
- 'TCLTK_LIBS': '',
- 'TESTOPTS': '',
- 'TESTPATH': '',
- 'TESTPYTHON': 'LD_LIBRARY_PATH=/tmpfs/src/git/out/python3/build ./python',
- 'TESTPYTHONOPTS': '',
- 'TESTRUNNER': 'LD_LIBRARY_PATH=/tmpfs/src/git/out/python3/build ./python '
- '/tmpfs/src/git/external/python/cpython3/Tools/scripts/run_tests.py',
- 'TESTSUBDIRS': 'ctypes/test \\',
- 'TESTTIMEOUT': 1200,
- 'TEST_MODULES': 'yes',
- 'THREAD_STACK_SIZE': 0,
- 'TIMEMODULE_LIB': 0,
- 'TIME_WITH_SYS_TIME': 1,
- 'TM_IN_SYS_TIME': 0,
- 'TZPATH': '/usr/share/zoneinfo:/usr/lib/zoneinfo:/usr/share/lib/zoneinfo:/etc/zoneinfo',
- 'UNICODE_DEPS': '\\',
- 'UNIVERSALSDK': '',
- 'UPDATE_FILE': '/tmpfs/src/git/external/python/cpython3/Tools/scripts/update_file.py',
- 'USE_COMPUTED_GOTOS': 0,
- 'VERSION': '3.10',
- 'VPATH': '/tmpfs/src/git/external/python/cpython3',
- 'WHEEL_PKG_DIR': '',
- 'WINDOW_HAS_FLAGS': 1,
- 'WITH_DECIMAL_CONTEXTVAR': 1,
- 'WITH_DOC_STRINGS': 1,
- 'WITH_DTRACE': 0,
- 'WITH_DYLD': 0,
- 'WITH_EDITLINE': 0,
- 'WITH_LIBINTL': 0,
- 'WITH_NEXT_FRAMEWORK': 0,
- 'WITH_PYMALLOC': 1,
- 'WITH_VALGRIND': 0,
- 'X87_DOUBLE_ROUNDING': 0,
- 'XMLLIBSUBDIRS': 'xml xml/dom xml/etree xml/parsers xml/sax',
- 'abs_builddir': '/tmpfs/src/git/out/python3/build',
- 'abs_srcdir': '/tmpfs/src/git/external/python/cpython3',
- 'datarootdir': '/tmpfs/src/git/out/python3/install/share',
- 'exec_prefix': '/tmpfs/src/git/out/python3/install',
- 'prefix': '/tmpfs/src/git/out/python3/install',
- 'srcdir': '/tmpfs/src/git/external/python/cpython3'}
diff --git a/lib/python3.10/_weakrefset.py b/lib/python3.10/_weakrefset.py
deleted file mode 100644
index 2a27684..0000000
--- a/lib/python3.10/_weakrefset.py
+++ /dev/null
@@ -1,206 +0,0 @@
-# Access WeakSet through the weakref module.
-# This code is separated-out because it is needed
-# by abc.py to load everything else at startup.
-
-from _weakref import ref
-from types import GenericAlias
-
-__all__ = ['WeakSet']
-
-
-class _IterationGuard:
- # This context manager registers itself in the current iterators of the
- # weak container, such as to delay all removals until the context manager
- # exits.
- # This technique should be relatively thread-safe (since sets are).
-
- def __init__(self, weakcontainer):
- # Don't create cycles
- self.weakcontainer = ref(weakcontainer)
-
- def __enter__(self):
- w = self.weakcontainer()
- if w is not None:
- w._iterating.add(self)
- return self
-
- def __exit__(self, e, t, b):
- w = self.weakcontainer()
- if w is not None:
- s = w._iterating
- s.remove(self)
- if not s:
- w._commit_removals()
-
-
-class WeakSet:
- def __init__(self, data=None):
- self.data = set()
- def _remove(item, selfref=ref(self)):
- self = selfref()
- if self is not None:
- if self._iterating:
- self._pending_removals.append(item)
- else:
- self.data.discard(item)
- self._remove = _remove
- # A list of keys to be removed
- self._pending_removals = []
- self._iterating = set()
- if data is not None:
- self.update(data)
-
- def _commit_removals(self):
- pop = self._pending_removals.pop
- discard = self.data.discard
- while True:
- try:
- item = pop()
- except IndexError:
- return
- discard(item)
-
- def __iter__(self):
- with _IterationGuard(self):
- for itemref in self.data:
- item = itemref()
- if item is not None:
- # Caveat: the iterator will keep a strong reference to
- # `item` until it is resumed or closed.
- yield item
-
- def __len__(self):
- return len(self.data) - len(self._pending_removals)
-
- def __contains__(self, item):
- try:
- wr = ref(item)
- except TypeError:
- return False
- return wr in self.data
-
- def __reduce__(self):
- return (self.__class__, (list(self),),
- getattr(self, '__dict__', None))
-
- def add(self, item):
- if self._pending_removals:
- self._commit_removals()
- self.data.add(ref(item, self._remove))
-
- def clear(self):
- if self._pending_removals:
- self._commit_removals()
- self.data.clear()
-
- def copy(self):
- return self.__class__(self)
-
- def pop(self):
- if self._pending_removals:
- self._commit_removals()
- while True:
- try:
- itemref = self.data.pop()
- except KeyError:
- raise KeyError('pop from empty WeakSet') from None
- item = itemref()
- if item is not None:
- return item
-
- def remove(self, item):
- if self._pending_removals:
- self._commit_removals()
- self.data.remove(ref(item))
-
- def discard(self, item):
- if self._pending_removals:
- self._commit_removals()
- self.data.discard(ref(item))
-
- def update(self, other):
- if self._pending_removals:
- self._commit_removals()
- for element in other:
- self.add(element)
-
- def __ior__(self, other):
- self.update(other)
- return self
-
- def difference(self, other):
- newset = self.copy()
- newset.difference_update(other)
- return newset
- __sub__ = difference
-
- def difference_update(self, other):
- self.__isub__(other)
- def __isub__(self, other):
- if self._pending_removals:
- self._commit_removals()
- if self is other:
- self.data.clear()
- else:
- self.data.difference_update(ref(item) for item in other)
- return self
-
- def intersection(self, other):
- return self.__class__(item for item in other if item in self)
- __and__ = intersection
-
- def intersection_update(self, other):
- self.__iand__(other)
- def __iand__(self, other):
- if self._pending_removals:
- self._commit_removals()
- self.data.intersection_update(ref(item) for item in other)
- return self
-
- def issubset(self, other):
- return self.data.issubset(ref(item) for item in other)
- __le__ = issubset
-
- def __lt__(self, other):
- return self.data < set(map(ref, other))
-
- def issuperset(self, other):
- return self.data.issuperset(ref(item) for item in other)
- __ge__ = issuperset
-
- def __gt__(self, other):
- return self.data > set(map(ref, other))
-
- def __eq__(self, other):
- if not isinstance(other, self.__class__):
- return NotImplemented
- return self.data == set(map(ref, other))
-
- def symmetric_difference(self, other):
- newset = self.copy()
- newset.symmetric_difference_update(other)
- return newset
- __xor__ = symmetric_difference
-
- def symmetric_difference_update(self, other):
- self.__ixor__(other)
- def __ixor__(self, other):
- if self._pending_removals:
- self._commit_removals()
- if self is other:
- self.data.clear()
- else:
- self.data.symmetric_difference_update(ref(item, self._remove) for item in other)
- return self
-
- def union(self, other):
- return self.__class__(e for s in (self, other) for e in s)
- __or__ = union
-
- def isdisjoint(self, other):
- return len(self.intersection(other)) == 0
-
- def __repr__(self):
- return repr(self.data)
-
- __class_getitem__ = classmethod(GenericAlias)
diff --git a/lib/python3.10/abc.py b/lib/python3.10/abc.py
deleted file mode 100644
index 3c552ce..0000000
--- a/lib/python3.10/abc.py
+++ /dev/null
@@ -1,188 +0,0 @@
-# Copyright 2007 Google, Inc. All Rights Reserved.
-# Licensed to PSF under a Contributor Agreement.
-
-"""Abstract Base Classes (ABCs) according to PEP 3119."""
-
-
-def abstractmethod(funcobj):
- """A decorator indicating abstract methods.
-
- Requires that the metaclass is ABCMeta or derived from it. A
- class that has a metaclass derived from ABCMeta cannot be
- instantiated unless all of its abstract methods are overridden.
- The abstract methods can be called using any of the normal
- 'super' call mechanisms. abstractmethod() may be used to declare
- abstract methods for properties and descriptors.
-
- Usage:
-
- class C(metaclass=ABCMeta):
- @abstractmethod
- def my_abstract_method(self, ...):
- ...
- """
- funcobj.__isabstractmethod__ = True
- return funcobj
-
-
-class abstractclassmethod(classmethod):
- """A decorator indicating abstract classmethods.
-
- Deprecated, use 'classmethod' with 'abstractmethod' instead:
-
- class C(ABC):
- @classmethod
- @abstractmethod
- def my_abstract_classmethod(cls, ...):
- ...
-
- """
-
- __isabstractmethod__ = True
-
- def __init__(self, callable):
- callable.__isabstractmethod__ = True
- super().__init__(callable)
-
-
-class abstractstaticmethod(staticmethod):
- """A decorator indicating abstract staticmethods.
-
- Deprecated, use 'staticmethod' with 'abstractmethod' instead:
-
- class C(ABC):
- @staticmethod
- @abstractmethod
- def my_abstract_staticmethod(...):
- ...
-
- """
-
- __isabstractmethod__ = True
-
- def __init__(self, callable):
- callable.__isabstractmethod__ = True
- super().__init__(callable)
-
-
-class abstractproperty(property):
- """A decorator indicating abstract properties.
-
- Deprecated, use 'property' with 'abstractmethod' instead:
-
- class C(ABC):
- @property
- @abstractmethod
- def my_abstract_property(self):
- ...
-
- """
-
- __isabstractmethod__ = True
-
-
-try:
- from _abc import (get_cache_token, _abc_init, _abc_register,
- _abc_instancecheck, _abc_subclasscheck, _get_dump,
- _reset_registry, _reset_caches)
-except ImportError:
- from _py_abc import ABCMeta, get_cache_token
- ABCMeta.__module__ = 'abc'
-else:
- class ABCMeta(type):
- """Metaclass for defining Abstract Base Classes (ABCs).
-
- Use this metaclass to create an ABC. An ABC can be subclassed
- directly, and then acts as a mix-in class. You can also register
- unrelated concrete classes (even built-in classes) and unrelated
- ABCs as 'virtual subclasses' -- these and their descendants will
- be considered subclasses of the registering ABC by the built-in
- issubclass() function, but the registering ABC won't show up in
- their MRO (Method Resolution Order) nor will method
- implementations defined by the registering ABC be callable (not
- even via super()).
- """
- def __new__(mcls, name, bases, namespace, **kwargs):
- cls = super().__new__(mcls, name, bases, namespace, **kwargs)
- _abc_init(cls)
- return cls
-
- def register(cls, subclass):
- """Register a virtual subclass of an ABC.
-
- Returns the subclass, to allow usage as a class decorator.
- """
- return _abc_register(cls, subclass)
-
- def __instancecheck__(cls, instance):
- """Override for isinstance(instance, cls)."""
- return _abc_instancecheck(cls, instance)
-
- def __subclasscheck__(cls, subclass):
- """Override for issubclass(subclass, cls)."""
- return _abc_subclasscheck(cls, subclass)
-
- def _dump_registry(cls, file=None):
- """Debug helper to print the ABC registry."""
- print(f"Class: {cls.__module__}.{cls.__qualname__}", file=file)
- print(f"Inv. counter: {get_cache_token()}", file=file)
- (_abc_registry, _abc_cache, _abc_negative_cache,
- _abc_negative_cache_version) = _get_dump(cls)
- print(f"_abc_registry: {_abc_registry!r}", file=file)
- print(f"_abc_cache: {_abc_cache!r}", file=file)
- print(f"_abc_negative_cache: {_abc_negative_cache!r}", file=file)
- print(f"_abc_negative_cache_version: {_abc_negative_cache_version!r}",
- file=file)
-
- def _abc_registry_clear(cls):
- """Clear the registry (for debugging or testing)."""
- _reset_registry(cls)
-
- def _abc_caches_clear(cls):
- """Clear the caches (for debugging or testing)."""
- _reset_caches(cls)
-
-
-def update_abstractmethods(cls):
- """Recalculate the set of abstract methods of an abstract class.
-
- If a class has had one of its abstract methods implemented after the
- class was created, the method will not be considered implemented until
- this function is called. Alternatively, if a new abstract method has been
- added to the class, it will only be considered an abstract method of the
- class after this function is called.
-
- This function should be called before any use is made of the class,
- usually in class decorators that add methods to the subject class.
-
- Returns cls, to allow usage as a class decorator.
-
- If cls is not an instance of ABCMeta, does nothing.
- """
- if not hasattr(cls, '__abstractmethods__'):
- # We check for __abstractmethods__ here because cls might by a C
- # implementation or a python implementation (especially during
- # testing), and we want to handle both cases.
- return cls
-
- abstracts = set()
- # Check the existing abstract methods of the parents, keep only the ones
- # that are not implemented.
- for scls in cls.__bases__:
- for name in getattr(scls, '__abstractmethods__', ()):
- value = getattr(cls, name, None)
- if getattr(value, "__isabstractmethod__", False):
- abstracts.add(name)
- # Also add any other newly added abstract methods.
- for name, value in cls.__dict__.items():
- if getattr(value, "__isabstractmethod__", False):
- abstracts.add(name)
- cls.__abstractmethods__ = frozenset(abstracts)
- return cls
-
-
-class ABC(metaclass=ABCMeta):
- """Helper class that provides a standard way to create an ABC using
- inheritance.
- """
- __slots__ = ()
diff --git a/lib/python3.10/aifc.py b/lib/python3.10/aifc.py
deleted file mode 100644
index ed5da7d..0000000
--- a/lib/python3.10/aifc.py
+++ /dev/null
@@ -1,947 +0,0 @@
-"""Stuff to parse AIFF-C and AIFF files.
-
-Unless explicitly stated otherwise, the description below is true
-both for AIFF-C files and AIFF files.
-
-An AIFF-C file has the following structure.
-
- +-----------------+
- | FORM |
- +-----------------+
- | <size> |
- +----+------------+
- | | AIFC |
- | +------------+
- | | <chunks> |
- | | . |
- | | . |
- | | . |
- +----+------------+
-
-An AIFF file has the string "AIFF" instead of "AIFC".
-
-A chunk consists of an identifier (4 bytes) followed by a size (4 bytes,
-big endian order), followed by the data. The size field does not include
-the size of the 8 byte header.
-
-The following chunk types are recognized.
-
- FVER
- <version number of AIFF-C defining document> (AIFF-C only).
- MARK
- <# of markers> (2 bytes)
- list of markers:
- <marker ID> (2 bytes, must be > 0)
- <position> (4 bytes)
- <marker name> ("pstring")
- COMM
- <# of channels> (2 bytes)
- <# of sound frames> (4 bytes)
- <size of the samples> (2 bytes)
- <sampling frequency> (10 bytes, IEEE 80-bit extended
- floating point)
- in AIFF-C files only:
- <compression type> (4 bytes)
- <human-readable version of compression type> ("pstring")
- SSND
- <offset> (4 bytes, not used by this program)
- <blocksize> (4 bytes, not used by this program)
- <sound data>
-
-A pstring consists of 1 byte length, a string of characters, and 0 or 1
-byte pad to make the total length even.
-
-Usage.
-
-Reading AIFF files:
- f = aifc.open(file, 'r')
-where file is either the name of a file or an open file pointer.
-The open file pointer must have methods read(), seek(), and close().
-In some types of audio files, if the setpos() method is not used,
-the seek() method is not necessary.
-
-This returns an instance of a class with the following public methods:
- getnchannels() -- returns number of audio channels (1 for
- mono, 2 for stereo)
- getsampwidth() -- returns sample width in bytes
- getframerate() -- returns sampling frequency
- getnframes() -- returns number of audio frames
- getcomptype() -- returns compression type ('NONE' for AIFF files)
- getcompname() -- returns human-readable version of
- compression type ('not compressed' for AIFF files)
- getparams() -- returns a namedtuple consisting of all of the
- above in the above order
- getmarkers() -- get the list of marks in the audio file or None
- if there are no marks
- getmark(id) -- get mark with the specified id (raises an error
- if the mark does not exist)
- readframes(n) -- returns at most n frames of audio
- rewind() -- rewind to the beginning of the audio stream
- setpos(pos) -- seek to the specified position
- tell() -- return the current position
- close() -- close the instance (make it unusable)
-The position returned by tell(), the position given to setpos() and
-the position of marks are all compatible and have nothing to do with
-the actual position in the file.
-The close() method is called automatically when the class instance
-is destroyed.
-
-Writing AIFF files:
- f = aifc.open(file, 'w')
-where file is either the name of a file or an open file pointer.
-The open file pointer must have methods write(), tell(), seek(), and
-close().
-
-This returns an instance of a class with the following public methods:
- aiff() -- create an AIFF file (AIFF-C default)
- aifc() -- create an AIFF-C file
- setnchannels(n) -- set the number of channels
- setsampwidth(n) -- set the sample width
- setframerate(n) -- set the frame rate
- setnframes(n) -- set the number of frames
- setcomptype(type, name)
- -- set the compression type and the
- human-readable compression type
- setparams(tuple)
- -- set all parameters at once
- setmark(id, pos, name)
- -- add specified mark to the list of marks
- tell() -- return current position in output file (useful
- in combination with setmark())
- writeframesraw(data)
- -- write audio frames without pathing up the
- file header
- writeframes(data)
- -- write audio frames and patch up the file header
- close() -- patch up the file header and close the
- output file
-You should set the parameters before the first writeframesraw or
-writeframes. The total number of frames does not need to be set,
-but when it is set to the correct value, the header does not have to
-be patched up.
-It is best to first set all parameters, perhaps possibly the
-compression type, and then write audio frames using writeframesraw.
-When all frames have been written, either call writeframes(b'') or
-close() to patch up the sizes in the header.
-Marks can be added anytime. If there are any marks, you must call
-close() after all frames have been written.
-The close() method is called automatically when the class instance
-is destroyed.
-
-When a file is opened with the extension '.aiff', an AIFF file is
-written, otherwise an AIFF-C file is written. This default can be
-changed by calling aiff() or aifc() before the first writeframes or
-writeframesraw.
-"""
-
-import struct
-import builtins
-import warnings
-
-__all__ = ["Error", "open"]
-
-class Error(Exception):
- pass
-
-_AIFC_version = 0xA2805140 # Version 1 of AIFF-C
-
-def _read_long(file):
- try:
- return struct.unpack('>l', file.read(4))[0]
- except struct.error:
- raise EOFError from None
-
-def _read_ulong(file):
- try:
- return struct.unpack('>L', file.read(4))[0]
- except struct.error:
- raise EOFError from None
-
-def _read_short(file):
- try:
- return struct.unpack('>h', file.read(2))[0]
- except struct.error:
- raise EOFError from None
-
-def _read_ushort(file):
- try:
- return struct.unpack('>H', file.read(2))[0]
- except struct.error:
- raise EOFError from None
-
-def _read_string(file):
- length = ord(file.read(1))
- if length == 0:
- data = b''
- else:
- data = file.read(length)
- if length & 1 == 0:
- dummy = file.read(1)
- return data
-
-_HUGE_VAL = 1.79769313486231e+308 # See <limits.h>
-
-def _read_float(f): # 10 bytes
- expon = _read_short(f) # 2 bytes
- sign = 1
- if expon < 0:
- sign = -1
- expon = expon + 0x8000
- himant = _read_ulong(f) # 4 bytes
- lomant = _read_ulong(f) # 4 bytes
- if expon == himant == lomant == 0:
- f = 0.0
- elif expon == 0x7FFF:
- f = _HUGE_VAL
- else:
- expon = expon - 16383
- f = (himant * 0x100000000 + lomant) * pow(2.0, expon - 63)
- return sign * f
-
-def _write_short(f, x):
- f.write(struct.pack('>h', x))
-
-def _write_ushort(f, x):
- f.write(struct.pack('>H', x))
-
-def _write_long(f, x):
- f.write(struct.pack('>l', x))
-
-def _write_ulong(f, x):
- f.write(struct.pack('>L', x))
-
-def _write_string(f, s):
- if len(s) > 255:
- raise ValueError("string exceeds maximum pstring length")
- f.write(struct.pack('B', len(s)))
- f.write(s)
- if len(s) & 1 == 0:
- f.write(b'\x00')
-
-def _write_float(f, x):
- import math
- if x < 0:
- sign = 0x8000
- x = x * -1
- else:
- sign = 0
- if x == 0:
- expon = 0
- himant = 0
- lomant = 0
- else:
- fmant, expon = math.frexp(x)
- if expon > 16384 or fmant >= 1 or fmant != fmant: # Infinity or NaN
- expon = sign|0x7FFF
- himant = 0
- lomant = 0
- else: # Finite
- expon = expon + 16382
- if expon < 0: # denormalized
- fmant = math.ldexp(fmant, expon)
- expon = 0
- expon = expon | sign
- fmant = math.ldexp(fmant, 32)
- fsmant = math.floor(fmant)
- himant = int(fsmant)
- fmant = math.ldexp(fmant - fsmant, 32)
- fsmant = math.floor(fmant)
- lomant = int(fsmant)
- _write_ushort(f, expon)
- _write_ulong(f, himant)
- _write_ulong(f, lomant)
-
-from chunk import Chunk
-from collections import namedtuple
-
-_aifc_params = namedtuple('_aifc_params',
- 'nchannels sampwidth framerate nframes comptype compname')
-
-_aifc_params.nchannels.__doc__ = 'Number of audio channels (1 for mono, 2 for stereo)'
-_aifc_params.sampwidth.__doc__ = 'Sample width in bytes'
-_aifc_params.framerate.__doc__ = 'Sampling frequency'
-_aifc_params.nframes.__doc__ = 'Number of audio frames'
-_aifc_params.comptype.__doc__ = 'Compression type ("NONE" for AIFF files)'
-_aifc_params.compname.__doc__ = ("""\
-A human-readable version of the compression type
-('not compressed' for AIFF files)""")
-
-
-class Aifc_read:
- # Variables used in this class:
- #
- # These variables are available to the user though appropriate
- # methods of this class:
- # _file -- the open file with methods read(), close(), and seek()
- # set through the __init__() method
- # _nchannels -- the number of audio channels
- # available through the getnchannels() method
- # _nframes -- the number of audio frames
- # available through the getnframes() method
- # _sampwidth -- the number of bytes per audio sample
- # available through the getsampwidth() method
- # _framerate -- the sampling frequency
- # available through the getframerate() method
- # _comptype -- the AIFF-C compression type ('NONE' if AIFF)
- # available through the getcomptype() method
- # _compname -- the human-readable AIFF-C compression type
- # available through the getcomptype() method
- # _markers -- the marks in the audio file
- # available through the getmarkers() and getmark()
- # methods
- # _soundpos -- the position in the audio stream
- # available through the tell() method, set through the
- # setpos() method
- #
- # These variables are used internally only:
- # _version -- the AIFF-C version number
- # _decomp -- the decompressor from builtin module cl
- # _comm_chunk_read -- 1 iff the COMM chunk has been read
- # _aifc -- 1 iff reading an AIFF-C file
- # _ssnd_seek_needed -- 1 iff positioned correctly in audio
- # file for readframes()
- # _ssnd_chunk -- instantiation of a chunk class for the SSND chunk
- # _framesize -- size of one frame in the file
-
- _file = None # Set here since __del__ checks it
-
- def initfp(self, file):
- self._version = 0
- self._convert = None
- self._markers = []
- self._soundpos = 0
- self._file = file
- chunk = Chunk(file)
- if chunk.getname() != b'FORM':
- raise Error('file does not start with FORM id')
- formdata = chunk.read(4)
- if formdata == b'AIFF':
- self._aifc = 0
- elif formdata == b'AIFC':
- self._aifc = 1
- else:
- raise Error('not an AIFF or AIFF-C file')
- self._comm_chunk_read = 0
- self._ssnd_chunk = None
- while 1:
- self._ssnd_seek_needed = 1
- try:
- chunk = Chunk(self._file)
- except EOFError:
- break
- chunkname = chunk.getname()
- if chunkname == b'COMM':
- self._read_comm_chunk(chunk)
- self._comm_chunk_read = 1
- elif chunkname == b'SSND':
- self._ssnd_chunk = chunk
- dummy = chunk.read(8)
- self._ssnd_seek_needed = 0
- elif chunkname == b'FVER':
- self._version = _read_ulong(chunk)
- elif chunkname == b'MARK':
- self._readmark(chunk)
- chunk.skip()
- if not self._comm_chunk_read or not self._ssnd_chunk:
- raise Error('COMM chunk and/or SSND chunk missing')
-
- def __init__(self, f):
- if isinstance(f, str):
- file_object = builtins.open(f, 'rb')
- try:
- self.initfp(file_object)
- except:
- file_object.close()
- raise
- else:
- # assume it is an open file object already
- self.initfp(f)
-
- def __enter__(self):
- return self
-
- def __exit__(self, *args):
- self.close()
-
- #
- # User visible methods.
- #
- def getfp(self):
- return self._file
-
- def rewind(self):
- self._ssnd_seek_needed = 1
- self._soundpos = 0
-
- def close(self):
- file = self._file
- if file is not None:
- self._file = None
- file.close()
-
- def tell(self):
- return self._soundpos
-
- def getnchannels(self):
- return self._nchannels
-
- def getnframes(self):
- return self._nframes
-
- def getsampwidth(self):
- return self._sampwidth
-
- def getframerate(self):
- return self._framerate
-
- def getcomptype(self):
- return self._comptype
-
- def getcompname(self):
- return self._compname
-
-## def getversion(self):
-## return self._version
-
- def getparams(self):
- return _aifc_params(self.getnchannels(), self.getsampwidth(),
- self.getframerate(), self.getnframes(),
- self.getcomptype(), self.getcompname())
-
- def getmarkers(self):
- if len(self._markers) == 0:
- return None
- return self._markers
-
- def getmark(self, id):
- for marker in self._markers:
- if id == marker[0]:
- return marker
- raise Error('marker {0!r} does not exist'.format(id))
-
- def setpos(self, pos):
- if pos < 0 or pos > self._nframes:
- raise Error('position not in range')
- self._soundpos = pos
- self._ssnd_seek_needed = 1
-
- def readframes(self, nframes):
- if self._ssnd_seek_needed:
- self._ssnd_chunk.seek(0)
- dummy = self._ssnd_chunk.read(8)
- pos = self._soundpos * self._framesize
- if pos:
- self._ssnd_chunk.seek(pos + 8)
- self._ssnd_seek_needed = 0
- if nframes == 0:
- return b''
- data = self._ssnd_chunk.read(nframes * self._framesize)
- if self._convert and data:
- data = self._convert(data)
- self._soundpos = self._soundpos + len(data) // (self._nchannels
- * self._sampwidth)
- return data
-
- #
- # Internal methods.
- #
-
- def _alaw2lin(self, data):
- import audioop
- return audioop.alaw2lin(data, 2)
-
- def _ulaw2lin(self, data):
- import audioop
- return audioop.ulaw2lin(data, 2)
-
- def _adpcm2lin(self, data):
- import audioop
- if not hasattr(self, '_adpcmstate'):
- # first time
- self._adpcmstate = None
- data, self._adpcmstate = audioop.adpcm2lin(data, 2, self._adpcmstate)
- return data
-
- def _read_comm_chunk(self, chunk):
- self._nchannels = _read_short(chunk)
- self._nframes = _read_long(chunk)
- self._sampwidth = (_read_short(chunk) + 7) // 8
- self._framerate = int(_read_float(chunk))
- if self._sampwidth <= 0:
- raise Error('bad sample width')
- if self._nchannels <= 0:
- raise Error('bad # of channels')
- self._framesize = self._nchannels * self._sampwidth
- if self._aifc:
- #DEBUG: SGI's soundeditor produces a bad size :-(
- kludge = 0
- if chunk.chunksize == 18:
- kludge = 1
- warnings.warn('Warning: bad COMM chunk size')
- chunk.chunksize = 23
- #DEBUG end
- self._comptype = chunk.read(4)
- #DEBUG start
- if kludge:
- length = ord(chunk.file.read(1))
- if length & 1 == 0:
- length = length + 1
- chunk.chunksize = chunk.chunksize + length
- chunk.file.seek(-1, 1)
- #DEBUG end
- self._compname = _read_string(chunk)
- if self._comptype != b'NONE':
- if self._comptype == b'G722':
- self._convert = self._adpcm2lin
- elif self._comptype in (b'ulaw', b'ULAW'):
- self._convert = self._ulaw2lin
- elif self._comptype in (b'alaw', b'ALAW'):
- self._convert = self._alaw2lin
- else:
- raise Error('unsupported compression type')
- self._sampwidth = 2
- else:
- self._comptype = b'NONE'
- self._compname = b'not compressed'
-
- def _readmark(self, chunk):
- nmarkers = _read_short(chunk)
- # Some files appear to contain invalid counts.
- # Cope with this by testing for EOF.
- try:
- for i in range(nmarkers):
- id = _read_short(chunk)
- pos = _read_long(chunk)
- name = _read_string(chunk)
- if pos or name:
- # some files appear to have
- # dummy markers consisting of
- # a position 0 and name ''
- self._markers.append((id, pos, name))
- except EOFError:
- w = ('Warning: MARK chunk contains only %s marker%s instead of %s' %
- (len(self._markers), '' if len(self._markers) == 1 else 's',
- nmarkers))
- warnings.warn(w)
-
-class Aifc_write:
- # Variables used in this class:
- #
- # These variables are user settable through appropriate methods
- # of this class:
- # _file -- the open file with methods write(), close(), tell(), seek()
- # set through the __init__() method
- # _comptype -- the AIFF-C compression type ('NONE' in AIFF)
- # set through the setcomptype() or setparams() method
- # _compname -- the human-readable AIFF-C compression type
- # set through the setcomptype() or setparams() method
- # _nchannels -- the number of audio channels
- # set through the setnchannels() or setparams() method
- # _sampwidth -- the number of bytes per audio sample
- # set through the setsampwidth() or setparams() method
- # _framerate -- the sampling frequency
- # set through the setframerate() or setparams() method
- # _nframes -- the number of audio frames written to the header
- # set through the setnframes() or setparams() method
- # _aifc -- whether we're writing an AIFF-C file or an AIFF file
- # set through the aifc() method, reset through the
- # aiff() method
- #
- # These variables are used internally only:
- # _version -- the AIFF-C version number
- # _comp -- the compressor from builtin module cl
- # _nframeswritten -- the number of audio frames actually written
- # _datalength -- the size of the audio samples written to the header
- # _datawritten -- the size of the audio samples actually written
-
- _file = None # Set here since __del__ checks it
-
- def __init__(self, f):
- if isinstance(f, str):
- file_object = builtins.open(f, 'wb')
- try:
- self.initfp(file_object)
- except:
- file_object.close()
- raise
-
- # treat .aiff file extensions as non-compressed audio
- if f.endswith('.aiff'):
- self._aifc = 0
- else:
- # assume it is an open file object already
- self.initfp(f)
-
- def initfp(self, file):
- self._file = file
- self._version = _AIFC_version
- self._comptype = b'NONE'
- self._compname = b'not compressed'
- self._convert = None
- self._nchannels = 0
- self._sampwidth = 0
- self._framerate = 0
- self._nframes = 0
- self._nframeswritten = 0
- self._datawritten = 0
- self._datalength = 0
- self._markers = []
- self._marklength = 0
- self._aifc = 1 # AIFF-C is default
-
- def __del__(self):
- self.close()
-
- def __enter__(self):
- return self
-
- def __exit__(self, *args):
- self.close()
-
- #
- # User visible methods.
- #
- def aiff(self):
- if self._nframeswritten:
- raise Error('cannot change parameters after starting to write')
- self._aifc = 0
-
- def aifc(self):
- if self._nframeswritten:
- raise Error('cannot change parameters after starting to write')
- self._aifc = 1
-
- def setnchannels(self, nchannels):
- if self._nframeswritten:
- raise Error('cannot change parameters after starting to write')
- if nchannels < 1:
- raise Error('bad # of channels')
- self._nchannels = nchannels
-
- def getnchannels(self):
- if not self._nchannels:
- raise Error('number of channels not set')
- return self._nchannels
-
- def setsampwidth(self, sampwidth):
- if self._nframeswritten:
- raise Error('cannot change parameters after starting to write')
- if sampwidth < 1 or sampwidth > 4:
- raise Error('bad sample width')
- self._sampwidth = sampwidth
-
- def getsampwidth(self):
- if not self._sampwidth:
- raise Error('sample width not set')
- return self._sampwidth
-
- def setframerate(self, framerate):
- if self._nframeswritten:
- raise Error('cannot change parameters after starting to write')
- if framerate <= 0:
- raise Error('bad frame rate')
- self._framerate = framerate
-
- def getframerate(self):
- if not self._framerate:
- raise Error('frame rate not set')
- return self._framerate
-
- def setnframes(self, nframes):
- if self._nframeswritten:
- raise Error('cannot change parameters after starting to write')
- self._nframes = nframes
-
- def getnframes(self):
- return self._nframeswritten
-
- def setcomptype(self, comptype, compname):
- if self._nframeswritten:
- raise Error('cannot change parameters after starting to write')
- if comptype not in (b'NONE', b'ulaw', b'ULAW',
- b'alaw', b'ALAW', b'G722'):
- raise Error('unsupported compression type')
- self._comptype = comptype
- self._compname = compname
-
- def getcomptype(self):
- return self._comptype
-
- def getcompname(self):
- return self._compname
-
-## def setversion(self, version):
-## if self._nframeswritten:
-## raise Error, 'cannot change parameters after starting to write'
-## self._version = version
-
- def setparams(self, params):
- nchannels, sampwidth, framerate, nframes, comptype, compname = params
- if self._nframeswritten:
- raise Error('cannot change parameters after starting to write')
- if comptype not in (b'NONE', b'ulaw', b'ULAW',
- b'alaw', b'ALAW', b'G722'):
- raise Error('unsupported compression type')
- self.setnchannels(nchannels)
- self.setsampwidth(sampwidth)
- self.setframerate(framerate)
- self.setnframes(nframes)
- self.setcomptype(comptype, compname)
-
- def getparams(self):
- if not self._nchannels or not self._sampwidth or not self._framerate:
- raise Error('not all parameters set')
- return _aifc_params(self._nchannels, self._sampwidth, self._framerate,
- self._nframes, self._comptype, self._compname)
-
- def setmark(self, id, pos, name):
- if id <= 0:
- raise Error('marker ID must be > 0')
- if pos < 0:
- raise Error('marker position must be >= 0')
- if not isinstance(name, bytes):
- raise Error('marker name must be bytes')
- for i in range(len(self._markers)):
- if id == self._markers[i][0]:
- self._markers[i] = id, pos, name
- return
- self._markers.append((id, pos, name))
-
- def getmark(self, id):
- for marker in self._markers:
- if id == marker[0]:
- return marker
- raise Error('marker {0!r} does not exist'.format(id))
-
- def getmarkers(self):
- if len(self._markers) == 0:
- return None
- return self._markers
-
- def tell(self):
- return self._nframeswritten
-
- def writeframesraw(self, data):
- if not isinstance(data, (bytes, bytearray)):
- data = memoryview(data).cast('B')
- self._ensure_header_written(len(data))
- nframes = len(data) // (self._sampwidth * self._nchannels)
- if self._convert:
- data = self._convert(data)
- self._file.write(data)
- self._nframeswritten = self._nframeswritten + nframes
- self._datawritten = self._datawritten + len(data)
-
- def writeframes(self, data):
- self.writeframesraw(data)
- if self._nframeswritten != self._nframes or \
- self._datalength != self._datawritten:
- self._patchheader()
-
- def close(self):
- if self._file is None:
- return
- try:
- self._ensure_header_written(0)
- if self._datawritten & 1:
- # quick pad to even size
- self._file.write(b'\x00')
- self._datawritten = self._datawritten + 1
- self._writemarkers()
- if self._nframeswritten != self._nframes or \
- self._datalength != self._datawritten or \
- self._marklength:
- self._patchheader()
- finally:
- # Prevent ref cycles
- self._convert = None
- f = self._file
- self._file = None
- f.close()
-
- #
- # Internal methods.
- #
-
- def _lin2alaw(self, data):
- import audioop
- return audioop.lin2alaw(data, 2)
-
- def _lin2ulaw(self, data):
- import audioop
- return audioop.lin2ulaw(data, 2)
-
- def _lin2adpcm(self, data):
- import audioop
- if not hasattr(self, '_adpcmstate'):
- self._adpcmstate = None
- data, self._adpcmstate = audioop.lin2adpcm(data, 2, self._adpcmstate)
- return data
-
- def _ensure_header_written(self, datasize):
- if not self._nframeswritten:
- if self._comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'):
- if not self._sampwidth:
- self._sampwidth = 2
- if self._sampwidth != 2:
- raise Error('sample width must be 2 when compressing '
- 'with ulaw/ULAW, alaw/ALAW or G7.22 (ADPCM)')
- if not self._nchannels:
- raise Error('# channels not specified')
- if not self._sampwidth:
- raise Error('sample width not specified')
- if not self._framerate:
- raise Error('sampling rate not specified')
- self._write_header(datasize)
-
- def _init_compression(self):
- if self._comptype == b'G722':
- self._convert = self._lin2adpcm
- elif self._comptype in (b'ulaw', b'ULAW'):
- self._convert = self._lin2ulaw
- elif self._comptype in (b'alaw', b'ALAW'):
- self._convert = self._lin2alaw
-
- def _write_header(self, initlength):
- if self._aifc and self._comptype != b'NONE':
- self._init_compression()
- self._file.write(b'FORM')
- if not self._nframes:
- self._nframes = initlength // (self._nchannels * self._sampwidth)
- self._datalength = self._nframes * self._nchannels * self._sampwidth
- if self._datalength & 1:
- self._datalength = self._datalength + 1
- if self._aifc:
- if self._comptype in (b'ulaw', b'ULAW', b'alaw', b'ALAW'):
- self._datalength = self._datalength // 2
- if self._datalength & 1:
- self._datalength = self._datalength + 1
- elif self._comptype == b'G722':
- self._datalength = (self._datalength + 3) // 4
- if self._datalength & 1:
- self._datalength = self._datalength + 1
- try:
- self._form_length_pos = self._file.tell()
- except (AttributeError, OSError):
- self._form_length_pos = None
- commlength = self._write_form_length(self._datalength)
- if self._aifc:
- self._file.write(b'AIFC')
- self._file.write(b'FVER')
- _write_ulong(self._file, 4)
- _write_ulong(self._file, self._version)
- else:
- self._file.write(b'AIFF')
- self._file.write(b'COMM')
- _write_ulong(self._file, commlength)
- _write_short(self._file, self._nchannels)
- if self._form_length_pos is not None:
- self._nframes_pos = self._file.tell()
- _write_ulong(self._file, self._nframes)
- if self._comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'):
- _write_short(self._file, 8)
- else:
- _write_short(self._file, self._sampwidth * 8)
- _write_float(self._file, self._framerate)
- if self._aifc:
- self._file.write(self._comptype)
- _write_string(self._file, self._compname)
- self._file.write(b'SSND')
- if self._form_length_pos is not None:
- self._ssnd_length_pos = self._file.tell()
- _write_ulong(self._file, self._datalength + 8)
- _write_ulong(self._file, 0)
- _write_ulong(self._file, 0)
-
- def _write_form_length(self, datalength):
- if self._aifc:
- commlength = 18 + 5 + len(self._compname)
- if commlength & 1:
- commlength = commlength + 1
- verslength = 12
- else:
- commlength = 18
- verslength = 0
- _write_ulong(self._file, 4 + verslength + self._marklength + \
- 8 + commlength + 16 + datalength)
- return commlength
-
- def _patchheader(self):
- curpos = self._file.tell()
- if self._datawritten & 1:
- datalength = self._datawritten + 1
- self._file.write(b'\x00')
- else:
- datalength = self._datawritten
- if datalength == self._datalength and \
- self._nframes == self._nframeswritten and \
- self._marklength == 0:
- self._file.seek(curpos, 0)
- return
- self._file.seek(self._form_length_pos, 0)
- dummy = self._write_form_length(datalength)
- self._file.seek(self._nframes_pos, 0)
- _write_ulong(self._file, self._nframeswritten)
- self._file.seek(self._ssnd_length_pos, 0)
- _write_ulong(self._file, datalength + 8)
- self._file.seek(curpos, 0)
- self._nframes = self._nframeswritten
- self._datalength = datalength
-
- def _writemarkers(self):
- if len(self._markers) == 0:
- return
- self._file.write(b'MARK')
- length = 2
- for marker in self._markers:
- id, pos, name = marker
- length = length + len(name) + 1 + 6
- if len(name) & 1 == 0:
- length = length + 1
- _write_ulong(self._file, length)
- self._marklength = length + 8
- _write_short(self._file, len(self._markers))
- for marker in self._markers:
- id, pos, name = marker
- _write_short(self._file, id)
- _write_ulong(self._file, pos)
- _write_string(self._file, name)
-
-def open(f, mode=None):
- if mode is None:
- if hasattr(f, 'mode'):
- mode = f.mode
- else:
- mode = 'rb'
- if mode in ('r', 'rb'):
- return Aifc_read(f)
- elif mode in ('w', 'wb'):
- return Aifc_write(f)
- else:
- raise Error("mode must be 'r', 'rb', 'w', or 'wb'")
-
-
-if __name__ == '__main__':
- import sys
- if not sys.argv[1:]:
- sys.argv.append('/usr/demos/data/audio/bach.aiff')
- fn = sys.argv[1]
- with open(fn, 'r') as f:
- print("Reading", fn)
- print("nchannels =", f.getnchannels())
- print("nframes =", f.getnframes())
- print("sampwidth =", f.getsampwidth())
- print("framerate =", f.getframerate())
- print("comptype =", f.getcomptype())
- print("compname =", f.getcompname())
- if sys.argv[2:]:
- gn = sys.argv[2]
- print("Writing", gn)
- with open(gn, 'w') as g:
- g.setparams(f.getparams())
- while 1:
- data = f.readframes(1024)
- if not data:
- break
- g.writeframes(data)
- print("Done.")
diff --git a/lib/python3.10/argparse.py b/lib/python3.10/argparse.py
deleted file mode 100644
index 2c0dd85..0000000
--- a/lib/python3.10/argparse.py
+++ /dev/null
@@ -1,2582 +0,0 @@
-# Author: Steven J. Bethard <steven.bethard@gmail.com>.
-# New maintainer as of 29 August 2019: Raymond Hettinger <raymond.hettinger@gmail.com>
-
-"""Command-line parsing library
-
-This module is an optparse-inspired command-line parsing library that:
-
- - handles both optional and positional arguments
- - produces highly informative usage messages
- - supports parsers that dispatch to sub-parsers
-
-The following is a simple usage example that sums integers from the
-command-line and writes the result to a file::
-
- parser = argparse.ArgumentParser(
- description='sum the integers at the command line')
- parser.add_argument(
- 'integers', metavar='int', nargs='+', type=int,
- help='an integer to be summed')
- parser.add_argument(
- '--log', default=sys.stdout, type=argparse.FileType('w'),
- help='the file where the sum should be written')
- args = parser.parse_args()
- args.log.write('%s' % sum(args.integers))
- args.log.close()
-
-The module contains the following public classes:
-
- - ArgumentParser -- The main entry point for command-line parsing. As the
- example above shows, the add_argument() method is used to populate
- the parser with actions for optional and positional arguments. Then
- the parse_args() method is invoked to convert the args at the
- command-line into an object with attributes.
-
- - ArgumentError -- The exception raised by ArgumentParser objects when
- there are errors with the parser's actions. Errors raised while
- parsing the command-line are caught by ArgumentParser and emitted
- as command-line messages.
-
- - FileType -- A factory for defining types of files to be created. As the
- example above shows, instances of FileType are typically passed as
- the type= argument of add_argument() calls.
-
- - Action -- The base class for parser actions. Typically actions are
- selected by passing strings like 'store_true' or 'append_const' to
- the action= argument of add_argument(). However, for greater
- customization of ArgumentParser actions, subclasses of Action may
- be defined and passed as the action= argument.
-
- - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
- ArgumentDefaultsHelpFormatter -- Formatter classes which
- may be passed as the formatter_class= argument to the
- ArgumentParser constructor. HelpFormatter is the default,
- RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
- not to change the formatting for help text, and
- ArgumentDefaultsHelpFormatter adds information about argument defaults
- to the help.
-
-All other classes in this module are considered implementation details.
-(Also note that HelpFormatter and RawDescriptionHelpFormatter are only
-considered public as object names -- the API of the formatter objects is
-still considered an implementation detail.)
-"""
-
-__version__ = '1.1'
-__all__ = [
- 'ArgumentParser',
- 'ArgumentError',
- 'ArgumentTypeError',
- 'BooleanOptionalAction',
- 'FileType',
- 'HelpFormatter',
- 'ArgumentDefaultsHelpFormatter',
- 'RawDescriptionHelpFormatter',
- 'RawTextHelpFormatter',
- 'MetavarTypeHelpFormatter',
- 'Namespace',
- 'Action',
- 'ONE_OR_MORE',
- 'OPTIONAL',
- 'PARSER',
- 'REMAINDER',
- 'SUPPRESS',
- 'ZERO_OR_MORE',
-]
-
-
-import os as _os
-import re as _re
-import sys as _sys
-
-from gettext import gettext as _, ngettext
-
-SUPPRESS = '==SUPPRESS=='
-
-OPTIONAL = '?'
-ZERO_OR_MORE = '*'
-ONE_OR_MORE = '+'
-PARSER = 'A...'
-REMAINDER = '...'
-_UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'
-
-# =============================
-# Utility functions and classes
-# =============================
-
-class _AttributeHolder(object):
- """Abstract base class that provides __repr__.
-
- The __repr__ method returns a string in the format::
- ClassName(attr=name, attr=name, ...)
- The attributes are determined either by a class-level attribute,
- '_kwarg_names', or by inspecting the instance __dict__.
- """
-
- def __repr__(self):
- type_name = type(self).__name__
- arg_strings = []
- star_args = {}
- for arg in self._get_args():
- arg_strings.append(repr(arg))
- for name, value in self._get_kwargs():
- if name.isidentifier():
- arg_strings.append('%s=%r' % (name, value))
- else:
- star_args[name] = value
- if star_args:
- arg_strings.append('**%s' % repr(star_args))
- return '%s(%s)' % (type_name, ', '.join(arg_strings))
-
- def _get_kwargs(self):
- return list(self.__dict__.items())
-
- def _get_args(self):
- return []
-
-
-def _copy_items(items):
- if items is None:
- return []
- # The copy module is used only in the 'append' and 'append_const'
- # actions, and it is needed only when the default value isn't a list.
- # Delay its import for speeding up the common case.
- if type(items) is list:
- return items[:]
- import copy
- return copy.copy(items)
-
-
-# ===============
-# Formatting Help
-# ===============
-
-class HelpFormatter(object):
- """Formatter for generating usage messages and argument help strings.
-
- Only the name of this class is considered a public API. All the methods
- provided by the class are considered an implementation detail.
- """
-
- def __init__(self,
- prog,
- indent_increment=2,
- max_help_position=24,
- width=None):
-
- # default setting for width
- if width is None:
- import shutil
- width = shutil.get_terminal_size().columns
- width -= 2
-
- self._prog = prog
- self._indent_increment = indent_increment
- self._max_help_position = min(max_help_position,
- max(width - 20, indent_increment * 2))
- self._width = width
-
- self._current_indent = 0
- self._level = 0
- self._action_max_length = 0
-
- self._root_section = self._Section(self, None)
- self._current_section = self._root_section
-
- self._whitespace_matcher = _re.compile(r'\s+', _re.ASCII)
- self._long_break_matcher = _re.compile(r'\n\n\n+')
-
- # ===============================
- # Section and indentation methods
- # ===============================
- def _indent(self):
- self._current_indent += self._indent_increment
- self._level += 1
-
- def _dedent(self):
- self._current_indent -= self._indent_increment
- assert self._current_indent >= 0, 'Indent decreased below 0.'
- self._level -= 1
-
- class _Section(object):
-
- def __init__(self, formatter, parent, heading=None):
- self.formatter = formatter
- self.parent = parent
- self.heading = heading
- self.items = []
-
- def format_help(self):
- # format the indented section
- if self.parent is not None:
- self.formatter._indent()
- join = self.formatter._join_parts
- item_help = join([func(*args) for func, args in self.items])
- if self.parent is not None:
- self.formatter._dedent()
-
- # return nothing if the section was empty
- if not item_help:
- return ''
-
- # add the heading if the section was non-empty
- if self.heading is not SUPPRESS and self.heading is not None:
- current_indent = self.formatter._current_indent
- heading = '%*s%s:\n' % (current_indent, '', self.heading)
- else:
- heading = ''
-
- # join the section-initial newline, the heading and the help
- return join(['\n', heading, item_help, '\n'])
-
- def _add_item(self, func, args):
- self._current_section.items.append((func, args))
-
- # ========================
- # Message building methods
- # ========================
- def start_section(self, heading):
- self._indent()
- section = self._Section(self, self._current_section, heading)
- self._add_item(section.format_help, [])
- self._current_section = section
-
- def end_section(self):
- self._current_section = self._current_section.parent
- self._dedent()
-
- def add_text(self, text):
- if text is not SUPPRESS and text is not None:
- self._add_item(self._format_text, [text])
-
- def add_usage(self, usage, actions, groups, prefix=None):
- if usage is not SUPPRESS:
- args = usage, actions, groups, prefix
- self._add_item(self._format_usage, args)
-
- def add_argument(self, action):
- if action.help is not SUPPRESS:
-
- # find all invocations
- get_invocation = self._format_action_invocation
- invocations = [get_invocation(action)]
- for subaction in self._iter_indented_subactions(action):
- invocations.append(get_invocation(subaction))
-
- # update the maximum item length
- invocation_length = max(map(len, invocations))
- action_length = invocation_length + self._current_indent
- self._action_max_length = max(self._action_max_length,
- action_length)
-
- # add the item to the list
- self._add_item(self._format_action, [action])
-
- def add_arguments(self, actions):
- for action in actions:
- self.add_argument(action)
-
- # =======================
- # Help-formatting methods
- # =======================
- def format_help(self):
- help = self._root_section.format_help()
- if help:
- help = self._long_break_matcher.sub('\n\n', help)
- help = help.strip('\n') + '\n'
- return help
-
- def _join_parts(self, part_strings):
- return ''.join([part
- for part in part_strings
- if part and part is not SUPPRESS])
-
- def _format_usage(self, usage, actions, groups, prefix):
- if prefix is None:
- prefix = _('usage: ')
-
- # if usage is specified, use that
- if usage is not None:
- usage = usage % dict(prog=self._prog)
-
- # if no optionals or positionals are available, usage is just prog
- elif usage is None and not actions:
- usage = '%(prog)s' % dict(prog=self._prog)
-
- # if optionals and positionals are available, calculate usage
- elif usage is None:
- prog = '%(prog)s' % dict(prog=self._prog)
-
- # split optionals from positionals
- optionals = []
- positionals = []
- for action in actions:
- if action.option_strings:
- optionals.append(action)
- else:
- positionals.append(action)
-
- # build full usage string
- format = self._format_actions_usage
- action_usage = format(optionals + positionals, groups)
- usage = ' '.join([s for s in [prog, action_usage] if s])
-
- # wrap the usage parts if it's too long
- text_width = self._width - self._current_indent
- if len(prefix) + len(usage) > text_width:
-
- # break usage into wrappable parts
- part_regexp = (
- r'\(.*?\)+(?=\s|$)|'
- r'\[.*?\]+(?=\s|$)|'
- r'\S+'
- )
- opt_usage = format(optionals, groups)
- pos_usage = format(positionals, groups)
- opt_parts = _re.findall(part_regexp, opt_usage)
- pos_parts = _re.findall(part_regexp, pos_usage)
- assert ' '.join(opt_parts) == opt_usage
- assert ' '.join(pos_parts) == pos_usage
-
- # helper for wrapping lines
- def get_lines(parts, indent, prefix=None):
- lines = []
- line = []
- if prefix is not None:
- line_len = len(prefix) - 1
- else:
- line_len = len(indent) - 1
- for part in parts:
- if line_len + 1 + len(part) > text_width and line:
- lines.append(indent + ' '.join(line))
- line = []
- line_len = len(indent) - 1
- line.append(part)
- line_len += len(part) + 1
- if line:
- lines.append(indent + ' '.join(line))
- if prefix is not None:
- lines[0] = lines[0][len(indent):]
- return lines
-
- # if prog is short, follow it with optionals or positionals
- if len(prefix) + len(prog) <= 0.75 * text_width:
- indent = ' ' * (len(prefix) + len(prog) + 1)
- if opt_parts:
- lines = get_lines([prog] + opt_parts, indent, prefix)
- lines.extend(get_lines(pos_parts, indent))
- elif pos_parts:
- lines = get_lines([prog] + pos_parts, indent, prefix)
- else:
- lines = [prog]
-
- # if prog is long, put it on its own line
- else:
- indent = ' ' * len(prefix)
- parts = opt_parts + pos_parts
- lines = get_lines(parts, indent)
- if len(lines) > 1:
- lines = []
- lines.extend(get_lines(opt_parts, indent))
- lines.extend(get_lines(pos_parts, indent))
- lines = [prog] + lines
-
- # join lines into usage
- usage = '\n'.join(lines)
-
- # prefix with 'usage:'
- return '%s%s\n\n' % (prefix, usage)
-
- def _format_actions_usage(self, actions, groups):
- # find group indices and identify actions in groups
- group_actions = set()
- inserts = {}
- for group in groups:
- if not group._group_actions:
- raise ValueError(f'empty group {group}')
-
- try:
- start = actions.index(group._group_actions[0])
- except ValueError:
- continue
- else:
- end = start + len(group._group_actions)
- if actions[start:end] == group._group_actions:
- for action in group._group_actions:
- group_actions.add(action)
- if not group.required:
- if start in inserts:
- inserts[start] += ' ['
- else:
- inserts[start] = '['
- if end in inserts:
- inserts[end] += ']'
- else:
- inserts[end] = ']'
- else:
- if start in inserts:
- inserts[start] += ' ('
- else:
- inserts[start] = '('
- if end in inserts:
- inserts[end] += ')'
- else:
- inserts[end] = ')'
- for i in range(start + 1, end):
- inserts[i] = '|'
-
- # collect all actions format strings
- parts = []
- for i, action in enumerate(actions):
-
- # suppressed arguments are marked with None
- # remove | separators for suppressed arguments
- if action.help is SUPPRESS:
- parts.append(None)
- if inserts.get(i) == '|':
- inserts.pop(i)
- elif inserts.get(i + 1) == '|':
- inserts.pop(i + 1)
-
- # produce all arg strings
- elif not action.option_strings:
- default = self._get_default_metavar_for_positional(action)
- part = self._format_args(action, default)
-
- # if it's in a group, strip the outer []
- if action in group_actions:
- if part[0] == '[' and part[-1] == ']':
- part = part[1:-1]
-
- # add the action string to the list
- parts.append(part)
-
- # produce the first way to invoke the option in brackets
- else:
- option_string = action.option_strings[0]
-
- # if the Optional doesn't take a value, format is:
- # -s or --long
- if action.nargs == 0:
- part = action.format_usage()
-
- # if the Optional takes a value, format is:
- # -s ARGS or --long ARGS
- else:
- default = self._get_default_metavar_for_optional(action)
- args_string = self._format_args(action, default)
- part = '%s %s' % (option_string, args_string)
-
- # make it look optional if it's not required or in a group
- if not action.required and action not in group_actions:
- part = '[%s]' % part
-
- # add the action string to the list
- parts.append(part)
-
- # insert things at the necessary indices
- for i in sorted(inserts, reverse=True):
- parts[i:i] = [inserts[i]]
-
- # join all the action items with spaces
- text = ' '.join([item for item in parts if item is not None])
-
- # clean up separators for mutually exclusive groups
- open = r'[\[(]'
- close = r'[\])]'
- text = _re.sub(r'(%s) ' % open, r'\1', text)
- text = _re.sub(r' (%s)' % close, r'\1', text)
- text = _re.sub(r'%s *%s' % (open, close), r'', text)
- text = _re.sub(r'\(([^|]*)\)', r'\1', text)
- text = text.strip()
-
- # return the text
- return text
-
- def _format_text(self, text):
- if '%(prog)' in text:
- text = text % dict(prog=self._prog)
- text_width = max(self._width - self._current_indent, 11)
- indent = ' ' * self._current_indent
- return self._fill_text(text, text_width, indent) + '\n\n'
-
- def _format_action(self, action):
- # determine the required width and the entry label
- help_position = min(self._action_max_length + 2,
- self._max_help_position)
- help_width = max(self._width - help_position, 11)
- action_width = help_position - self._current_indent - 2
- action_header = self._format_action_invocation(action)
-
- # no help; start on same line and add a final newline
- if not action.help:
- tup = self._current_indent, '', action_header
- action_header = '%*s%s\n' % tup
-
- # short action name; start on the same line and pad two spaces
- elif len(action_header) <= action_width:
- tup = self._current_indent, '', action_width, action_header
- action_header = '%*s%-*s ' % tup
- indent_first = 0
-
- # long action name; start on the next line
- else:
- tup = self._current_indent, '', action_header
- action_header = '%*s%s\n' % tup
- indent_first = help_position
-
- # collect the pieces of the action help
- parts = [action_header]
-
- # if there was help for the action, add lines of help text
- if action.help and action.help.strip():
- help_text = self._expand_help(action)
- if help_text:
- help_lines = self._split_lines(help_text, help_width)
- parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
- for line in help_lines[1:]:
- parts.append('%*s%s\n' % (help_position, '', line))
-
- # or add a newline if the description doesn't end with one
- elif not action_header.endswith('\n'):
- parts.append('\n')
-
- # if there are any sub-actions, add their help as well
- for subaction in self._iter_indented_subactions(action):
- parts.append(self._format_action(subaction))
-
- # return a single string
- return self._join_parts(parts)
-
- def _format_action_invocation(self, action):
- if not action.option_strings:
- default = self._get_default_metavar_for_positional(action)
- metavar, = self._metavar_formatter(action, default)(1)
- return metavar
-
- else:
- parts = []
-
- # if the Optional doesn't take a value, format is:
- # -s, --long
- if action.nargs == 0:
- parts.extend(action.option_strings)
-
- # if the Optional takes a value, format is:
- # -s ARGS, --long ARGS
- else:
- default = self._get_default_metavar_for_optional(action)
- args_string = self._format_args(action, default)
- for option_string in action.option_strings:
- parts.append('%s %s' % (option_string, args_string))
-
- return ', '.join(parts)
-
- def _metavar_formatter(self, action, default_metavar):
- if action.metavar is not None:
- result = action.metavar
- elif action.choices is not None:
- choice_strs = [str(choice) for choice in action.choices]
- result = '{%s}' % ','.join(choice_strs)
- else:
- result = default_metavar
-
- def format(tuple_size):
- if isinstance(result, tuple):
- return result
- else:
- return (result, ) * tuple_size
- return format
-
- def _format_args(self, action, default_metavar):
- get_metavar = self._metavar_formatter(action, default_metavar)
- if action.nargs is None:
- result = '%s' % get_metavar(1)
- elif action.nargs == OPTIONAL:
- result = '[%s]' % get_metavar(1)
- elif action.nargs == ZERO_OR_MORE:
- metavar = get_metavar(1)
- if len(metavar) == 2:
- result = '[%s [%s ...]]' % metavar
- else:
- result = '[%s ...]' % metavar
- elif action.nargs == ONE_OR_MORE:
- result = '%s [%s ...]' % get_metavar(2)
- elif action.nargs == REMAINDER:
- result = '...'
- elif action.nargs == PARSER:
- result = '%s ...' % get_metavar(1)
- elif action.nargs == SUPPRESS:
- result = ''
- else:
- try:
- formats = ['%s' for _ in range(action.nargs)]
- except TypeError:
- raise ValueError("invalid nargs value") from None
- result = ' '.join(formats) % get_metavar(action.nargs)
- return result
-
- def _expand_help(self, action):
- params = dict(vars(action), prog=self._prog)
- for name in list(params):
- if params[name] is SUPPRESS:
- del params[name]
- for name in list(params):
- if hasattr(params[name], '__name__'):
- params[name] = params[name].__name__
- if params.get('choices') is not None:
- choices_str = ', '.join([str(c) for c in params['choices']])
- params['choices'] = choices_str
- return self._get_help_string(action) % params
-
- def _iter_indented_subactions(self, action):
- try:
- get_subactions = action._get_subactions
- except AttributeError:
- pass
- else:
- self._indent()
- yield from get_subactions()
- self._dedent()
-
- def _split_lines(self, text, width):
- text = self._whitespace_matcher.sub(' ', text).strip()
- # The textwrap module is used only for formatting help.
- # Delay its import for speeding up the common usage of argparse.
- import textwrap
- return textwrap.wrap(text, width)
-
- def _fill_text(self, text, width, indent):
- text = self._whitespace_matcher.sub(' ', text).strip()
- import textwrap
- return textwrap.fill(text, width,
- initial_indent=indent,
- subsequent_indent=indent)
-
- def _get_help_string(self, action):
- return action.help
-
- def _get_default_metavar_for_optional(self, action):
- return action.dest.upper()
-
- def _get_default_metavar_for_positional(self, action):
- return action.dest
-
-
-class RawDescriptionHelpFormatter(HelpFormatter):
- """Help message formatter which retains any formatting in descriptions.
-
- Only the name of this class is considered a public API. All the methods
- provided by the class are considered an implementation detail.
- """
-
- def _fill_text(self, text, width, indent):
- return ''.join(indent + line for line in text.splitlines(keepends=True))
-
-
-class RawTextHelpFormatter(RawDescriptionHelpFormatter):
- """Help message formatter which retains formatting of all help text.
-
- Only the name of this class is considered a public API. All the methods
- provided by the class are considered an implementation detail.
- """
-
- def _split_lines(self, text, width):
- return text.splitlines()
-
-
-class ArgumentDefaultsHelpFormatter(HelpFormatter):
- """Help message formatter which adds default values to argument help.
-
- Only the name of this class is considered a public API. All the methods
- provided by the class are considered an implementation detail.
- """
-
- def _get_help_string(self, action):
- help = action.help
- if '%(default)' not in action.help:
- if action.default is not SUPPRESS:
- defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
- if action.option_strings or action.nargs in defaulting_nargs:
- help += ' (default: %(default)s)'
- return help
-
-
-class MetavarTypeHelpFormatter(HelpFormatter):
- """Help message formatter which uses the argument 'type' as the default
- metavar value (instead of the argument 'dest')
-
- Only the name of this class is considered a public API. All the methods
- provided by the class are considered an implementation detail.
- """
-
- def _get_default_metavar_for_optional(self, action):
- return action.type.__name__
-
- def _get_default_metavar_for_positional(self, action):
- return action.type.__name__
-
-
-
-# =====================
-# Options and Arguments
-# =====================
-
-def _get_action_name(argument):
- if argument is None:
- return None
- elif argument.option_strings:
- return '/'.join(argument.option_strings)
- elif argument.metavar not in (None, SUPPRESS):
- return argument.metavar
- elif argument.dest not in (None, SUPPRESS):
- return argument.dest
- elif argument.choices:
- return '{' + ','.join(argument.choices) + '}'
- else:
- return None
-
-
-class ArgumentError(Exception):
- """An error from creating or using an argument (optional or positional).
-
- The string value of this exception is the message, augmented with
- information about the argument that caused it.
- """
-
- def __init__(self, argument, message):
- self.argument_name = _get_action_name(argument)
- self.message = message
-
- def __str__(self):
- if self.argument_name is None:
- format = '%(message)s'
- else:
- format = 'argument %(argument_name)s: %(message)s'
- return format % dict(message=self.message,
- argument_name=self.argument_name)
-
-
-class ArgumentTypeError(Exception):
- """An error from trying to convert a command line string to a type."""
- pass
-
-
-# ==============
-# Action classes
-# ==============
-
-class Action(_AttributeHolder):
- """Information about how to convert command line strings to Python objects.
-
- Action objects are used by an ArgumentParser to represent the information
- needed to parse a single argument from one or more strings from the
- command line. The keyword arguments to the Action constructor are also
- all attributes of Action instances.
-
- Keyword Arguments:
-
- - option_strings -- A list of command-line option strings which
- should be associated with this action.
-
- - dest -- The name of the attribute to hold the created object(s)
-
- - nargs -- The number of command-line arguments that should be
- consumed. By default, one argument will be consumed and a single
- value will be produced. Other values include:
- - N (an integer) consumes N arguments (and produces a list)
- - '?' consumes zero or one arguments
- - '*' consumes zero or more arguments (and produces a list)
- - '+' consumes one or more arguments (and produces a list)
- Note that the difference between the default and nargs=1 is that
- with the default, a single value will be produced, while with
- nargs=1, a list containing a single value will be produced.
-
- - const -- The value to be produced if the option is specified and the
- option uses an action that takes no values.
-
- - default -- The value to be produced if the option is not specified.
-
- - type -- A callable that accepts a single string argument, and
- returns the converted value. The standard Python types str, int,
- float, and complex are useful examples of such callables. If None,
- str is used.
-
- - choices -- A container of values that should be allowed. If not None,
- after a command-line argument has been converted to the appropriate
- type, an exception will be raised if it is not a member of this
- collection.
-
- - required -- True if the action must always be specified at the
- command line. This is only meaningful for optional command-line
- arguments.
-
- - help -- The help string describing the argument.
-
- - metavar -- The name to be used for the option's argument with the
- help string. If None, the 'dest' value will be used as the name.
- """
-
- def __init__(self,
- option_strings,
- dest,
- nargs=None,
- const=None,
- default=None,
- type=None,
- choices=None,
- required=False,
- help=None,
- metavar=None):
- self.option_strings = option_strings
- self.dest = dest
- self.nargs = nargs
- self.const = const
- self.default = default
- self.type = type
- self.choices = choices
- self.required = required
- self.help = help
- self.metavar = metavar
-
- def _get_kwargs(self):
- names = [
- 'option_strings',
- 'dest',
- 'nargs',
- 'const',
- 'default',
- 'type',
- 'choices',
- 'help',
- 'metavar',
- ]
- return [(name, getattr(self, name)) for name in names]
-
- def format_usage(self):
- return self.option_strings[0]
-
- def __call__(self, parser, namespace, values, option_string=None):
- raise NotImplementedError(_('.__call__() not defined'))
-
-class BooleanOptionalAction(Action):
- def __init__(self,
- option_strings,
- dest,
- default=None,
- type=None,
- choices=None,
- required=False,
- help=None,
- metavar=None):
-
- _option_strings = []
- for option_string in option_strings:
- _option_strings.append(option_string)
-
- if option_string.startswith('--'):
- option_string = '--no-' + option_string[2:]
- _option_strings.append(option_string)
-
- if help is not None and default is not None and default is not SUPPRESS:
- help += " (default: %(default)s)"
-
- super().__init__(
- option_strings=_option_strings,
- dest=dest,
- nargs=0,
- default=default,
- type=type,
- choices=choices,
- required=required,
- help=help,
- metavar=metavar)
-
- def __call__(self, parser, namespace, values, option_string=None):
- if option_string in self.option_strings:
- setattr(namespace, self.dest, not option_string.startswith('--no-'))
-
- def format_usage(self):
- return ' | '.join(self.option_strings)
-
-
-class _StoreAction(Action):
-
- def __init__(self,
- option_strings,
- dest,
- nargs=None,
- const=None,
- default=None,
- type=None,
- choices=None,
- required=False,
- help=None,
- metavar=None):
- if nargs == 0:
- raise ValueError('nargs for store actions must be != 0; if you '
- 'have nothing to store, actions such as store '
- 'true or store const may be more appropriate')
- if const is not None and nargs != OPTIONAL:
- raise ValueError('nargs must be %r to supply const' % OPTIONAL)
- super(_StoreAction, self).__init__(
- option_strings=option_strings,
- dest=dest,
- nargs=nargs,
- const=const,
- default=default,
- type=type,
- choices=choices,
- required=required,
- help=help,
- metavar=metavar)
-
- def __call__(self, parser, namespace, values, option_string=None):
- setattr(namespace, self.dest, values)
-
-
-class _StoreConstAction(Action):
-
- def __init__(self,
- option_strings,
- dest,
- const,
- default=None,
- required=False,
- help=None,
- metavar=None):
- super(_StoreConstAction, self).__init__(
- option_strings=option_strings,
- dest=dest,
- nargs=0,
- const=const,
- default=default,
- required=required,
- help=help)
-
- def __call__(self, parser, namespace, values, option_string=None):
- setattr(namespace, self.dest, self.const)
-
-
-class _StoreTrueAction(_StoreConstAction):
-
- def __init__(self,
- option_strings,
- dest,
- default=False,
- required=False,
- help=None):
- super(_StoreTrueAction, self).__init__(
- option_strings=option_strings,
- dest=dest,
- const=True,
- default=default,
- required=required,
- help=help)
-
-
-class _StoreFalseAction(_StoreConstAction):
-
- def __init__(self,
- option_strings,
- dest,
- default=True,
- required=False,
- help=None):
- super(_StoreFalseAction, self).__init__(
- option_strings=option_strings,
- dest=dest,
- const=False,
- default=default,
- required=required,
- help=help)
-
-
-class _AppendAction(Action):
-
- def __init__(self,
- option_strings,
- dest,
- nargs=None,
- const=None,
- default=None,
- type=None,
- choices=None,
- required=False,
- help=None,
- metavar=None):
- if nargs == 0:
- raise ValueError('nargs for append actions must be != 0; if arg '
- 'strings are not supplying the value to append, '
- 'the append const action may be more appropriate')
- if const is not None and nargs != OPTIONAL:
- raise ValueError('nargs must be %r to supply const' % OPTIONAL)
- super(_AppendAction, self).__init__(
- option_strings=option_strings,
- dest=dest,
- nargs=nargs,
- const=const,
- default=default,
- type=type,
- choices=choices,
- required=required,
- help=help,
- metavar=metavar)
-
- def __call__(self, parser, namespace, values, option_string=None):
- items = getattr(namespace, self.dest, None)
- items = _copy_items(items)
- items.append(values)
- setattr(namespace, self.dest, items)
-
-
-class _AppendConstAction(Action):
-
- def __init__(self,
- option_strings,
- dest,
- const,
- default=None,
- required=False,
- help=None,
- metavar=None):
- super(_AppendConstAction, self).__init__(
- option_strings=option_strings,
- dest=dest,
- nargs=0,
- const=const,
- default=default,
- required=required,
- help=help,
- metavar=metavar)
-
- def __call__(self, parser, namespace, values, option_string=None):
- items = getattr(namespace, self.dest, None)
- items = _copy_items(items)
- items.append(self.const)
- setattr(namespace, self.dest, items)
-
-
-class _CountAction(Action):
-
- def __init__(self,
- option_strings,
- dest,
- default=None,
- required=False,
- help=None):
- super(_CountAction, self).__init__(
- option_strings=option_strings,
- dest=dest,
- nargs=0,
- default=default,
- required=required,
- help=help)
-
- def __call__(self, parser, namespace, values, option_string=None):
- count = getattr(namespace, self.dest, None)
- if count is None:
- count = 0
- setattr(namespace, self.dest, count + 1)
-
-
-class _HelpAction(Action):
-
- def __init__(self,
- option_strings,
- dest=SUPPRESS,
- default=SUPPRESS,
- help=None):
- super(_HelpAction, self).__init__(
- option_strings=option_strings,
- dest=dest,
- default=default,
- nargs=0,
- help=help)
-
- def __call__(self, parser, namespace, values, option_string=None):
- parser.print_help()
- parser.exit()
-
-
-class _VersionAction(Action):
-
- def __init__(self,
- option_strings,
- version=None,
- dest=SUPPRESS,
- default=SUPPRESS,
- help="show program's version number and exit"):
- super(_VersionAction, self).__init__(
- option_strings=option_strings,
- dest=dest,
- default=default,
- nargs=0,
- help=help)
- self.version = version
-
- def __call__(self, parser, namespace, values, option_string=None):
- version = self.version
- if version is None:
- version = parser.version
- formatter = parser._get_formatter()
- formatter.add_text(version)
- parser._print_message(formatter.format_help(), _sys.stdout)
- parser.exit()
-
-
-class _SubParsersAction(Action):
-
- class _ChoicesPseudoAction(Action):
-
- def __init__(self, name, aliases, help):
- metavar = dest = name
- if aliases:
- metavar += ' (%s)' % ', '.join(aliases)
- sup = super(_SubParsersAction._ChoicesPseudoAction, self)
- sup.__init__(option_strings=[], dest=dest, help=help,
- metavar=metavar)
-
- def __init__(self,
- option_strings,
- prog,
- parser_class,
- dest=SUPPRESS,
- required=False,
- help=None,
- metavar=None):
-
- self._prog_prefix = prog
- self._parser_class = parser_class
- self._name_parser_map = {}
- self._choices_actions = []
-
- super(_SubParsersAction, self).__init__(
- option_strings=option_strings,
- dest=dest,
- nargs=PARSER,
- choices=self._name_parser_map,
- required=required,
- help=help,
- metavar=metavar)
-
- def add_parser(self, name, **kwargs):
- # set prog from the existing prefix
- if kwargs.get('prog') is None:
- kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
-
- aliases = kwargs.pop('aliases', ())
-
- # create a pseudo-action to hold the choice help
- if 'help' in kwargs:
- help = kwargs.pop('help')
- choice_action = self._ChoicesPseudoAction(name, aliases, help)
- self._choices_actions.append(choice_action)
-
- # create the parser and add it to the map
- parser = self._parser_class(**kwargs)
- self._name_parser_map[name] = parser
-
- # make parser available under aliases also
- for alias in aliases:
- self._name_parser_map[alias] = parser
-
- return parser
-
- def _get_subactions(self):
- return self._choices_actions
-
- def __call__(self, parser, namespace, values, option_string=None):
- parser_name = values[0]
- arg_strings = values[1:]
-
- # set the parser name if requested
- if self.dest is not SUPPRESS:
- setattr(namespace, self.dest, parser_name)
-
- # select the parser
- try:
- parser = self._name_parser_map[parser_name]
- except KeyError:
- args = {'parser_name': parser_name,
- 'choices': ', '.join(self._name_parser_map)}
- msg = _('unknown parser %(parser_name)r (choices: %(choices)s)') % args
- raise ArgumentError(self, msg)
-
- # parse all the remaining options into the namespace
- # store any unrecognized options on the object, so that the top
- # level parser can decide what to do with them
-
- # In case this subparser defines new defaults, we parse them
- # in a new namespace object and then update the original
- # namespace for the relevant parts.
- subnamespace, arg_strings = parser.parse_known_args(arg_strings, None)
- for key, value in vars(subnamespace).items():
- setattr(namespace, key, value)
-
- if arg_strings:
- vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
- getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
-
-class _ExtendAction(_AppendAction):
- def __call__(self, parser, namespace, values, option_string=None):
- items = getattr(namespace, self.dest, None)
- items = _copy_items(items)
- items.extend(values)
- setattr(namespace, self.dest, items)
-
-# ==============
-# Type classes
-# ==============
-
-class FileType(object):
- """Factory for creating file object types
-
- Instances of FileType are typically passed as type= arguments to the
- ArgumentParser add_argument() method.
-
- Keyword Arguments:
- - mode -- A string indicating how the file is to be opened. Accepts the
- same values as the builtin open() function.
- - bufsize -- The file's desired buffer size. Accepts the same values as
- the builtin open() function.
- - encoding -- The file's encoding. Accepts the same values as the
- builtin open() function.
- - errors -- A string indicating how encoding and decoding errors are to
- be handled. Accepts the same value as the builtin open() function.
- """
-
- def __init__(self, mode='r', bufsize=-1, encoding=None, errors=None):
- self._mode = mode
- self._bufsize = bufsize
- self._encoding = encoding
- self._errors = errors
-
- def __call__(self, string):
- # the special argument "-" means sys.std{in,out}
- if string == '-':
- if 'r' in self._mode:
- return _sys.stdin.buffer if 'b' in self._mode else _sys.stdin
- elif any(c in self._mode for c in 'wax'):
- return _sys.stdout.buffer if 'b' in self._mode else _sys.stdout
- else:
- msg = _('argument "-" with mode %r') % self._mode
- raise ValueError(msg)
-
- # all other arguments are used as file names
- try:
- return open(string, self._mode, self._bufsize, self._encoding,
- self._errors)
- except OSError as e:
- args = {'filename': string, 'error': e}
- message = _("can't open '%(filename)s': %(error)s")
- raise ArgumentTypeError(message % args)
-
- def __repr__(self):
- args = self._mode, self._bufsize
- kwargs = [('encoding', self._encoding), ('errors', self._errors)]
- args_str = ', '.join([repr(arg) for arg in args if arg != -1] +
- ['%s=%r' % (kw, arg) for kw, arg in kwargs
- if arg is not None])
- return '%s(%s)' % (type(self).__name__, args_str)
-
-# ===========================
-# Optional and Positional Parsing
-# ===========================
-
-class Namespace(_AttributeHolder):
- """Simple object for storing attributes.
-
- Implements equality by attribute names and values, and provides a simple
- string representation.
- """
-
- def __init__(self, **kwargs):
- for name in kwargs:
- setattr(self, name, kwargs[name])
-
- def __eq__(self, other):
- if not isinstance(other, Namespace):
- return NotImplemented
- return vars(self) == vars(other)
-
- def __contains__(self, key):
- return key in self.__dict__
-
-
-class _ActionsContainer(object):
-
- def __init__(self,
- description,
- prefix_chars,
- argument_default,
- conflict_handler):
- super(_ActionsContainer, self).__init__()
-
- self.description = description
- self.argument_default = argument_default
- self.prefix_chars = prefix_chars
- self.conflict_handler = conflict_handler
-
- # set up registries
- self._registries = {}
-
- # register actions
- self.register('action', None, _StoreAction)
- self.register('action', 'store', _StoreAction)
- self.register('action', 'store_const', _StoreConstAction)
- self.register('action', 'store_true', _StoreTrueAction)
- self.register('action', 'store_false', _StoreFalseAction)
- self.register('action', 'append', _AppendAction)
- self.register('action', 'append_const', _AppendConstAction)
- self.register('action', 'count', _CountAction)
- self.register('action', 'help', _HelpAction)
- self.register('action', 'version', _VersionAction)
- self.register('action', 'parsers', _SubParsersAction)
- self.register('action', 'extend', _ExtendAction)
-
- # raise an exception if the conflict handler is invalid
- self._get_handler()
-
- # action storage
- self._actions = []
- self._option_string_actions = {}
-
- # groups
- self._action_groups = []
- self._mutually_exclusive_groups = []
-
- # defaults storage
- self._defaults = {}
-
- # determines whether an "option" looks like a negative number
- self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
-
- # whether or not there are any optionals that look like negative
- # numbers -- uses a list so it can be shared and edited
- self._has_negative_number_optionals = []
-
- # ====================
- # Registration methods
- # ====================
- def register(self, registry_name, value, object):
- registry = self._registries.setdefault(registry_name, {})
- registry[value] = object
-
- def _registry_get(self, registry_name, value, default=None):
- return self._registries[registry_name].get(value, default)
-
- # ==================================
- # Namespace default accessor methods
- # ==================================
- def set_defaults(self, **kwargs):
- self._defaults.update(kwargs)
-
- # if these defaults match any existing arguments, replace
- # the previous default on the object with the new one
- for action in self._actions:
- if action.dest in kwargs:
- action.default = kwargs[action.dest]
-
- def get_default(self, dest):
- for action in self._actions:
- if action.dest == dest and action.default is not None:
- return action.default
- return self._defaults.get(dest, None)
-
-
- # =======================
- # Adding argument actions
- # =======================
- def add_argument(self, *args, **kwargs):
- """
- add_argument(dest, ..., name=value, ...)
- add_argument(option_string, option_string, ..., name=value, ...)
- """
-
- # if no positional args are supplied or only one is supplied and
- # it doesn't look like an option string, parse a positional
- # argument
- chars = self.prefix_chars
- if not args or len(args) == 1 and args[0][0] not in chars:
- if args and 'dest' in kwargs:
- raise ValueError('dest supplied twice for positional argument')
- kwargs = self._get_positional_kwargs(*args, **kwargs)
-
- # otherwise, we're adding an optional argument
- else:
- kwargs = self._get_optional_kwargs(*args, **kwargs)
-
- # if no default was supplied, use the parser-level default
- if 'default' not in kwargs:
- dest = kwargs['dest']
- if dest in self._defaults:
- kwargs['default'] = self._defaults[dest]
- elif self.argument_default is not None:
- kwargs['default'] = self.argument_default
-
- # create the action object, and add it to the parser
- action_class = self._pop_action_class(kwargs)
- if not callable(action_class):
- raise ValueError('unknown action "%s"' % (action_class,))
- action = action_class(**kwargs)
-
- # raise an error if the action type is not callable
- type_func = self._registry_get('type', action.type, action.type)
- if not callable(type_func):
- raise ValueError('%r is not callable' % (type_func,))
-
- if type_func is FileType:
- raise ValueError('%r is a FileType class object, instance of it'
- ' must be passed' % (type_func,))
-
- # raise an error if the metavar does not match the type
- if hasattr(self, "_get_formatter"):
- try:
- self._get_formatter()._format_args(action, None)
- except TypeError:
- raise ValueError("length of metavar tuple does not match nargs")
-
- return self._add_action(action)
-
- def add_argument_group(self, *args, **kwargs):
- group = _ArgumentGroup(self, *args, **kwargs)
- self._action_groups.append(group)
- return group
-
- def add_mutually_exclusive_group(self, **kwargs):
- group = _MutuallyExclusiveGroup(self, **kwargs)
- self._mutually_exclusive_groups.append(group)
- return group
-
- def _add_action(self, action):
- # resolve any conflicts
- self._check_conflict(action)
-
- # add to actions list
- self._actions.append(action)
- action.container = self
-
- # index the action by any option strings it has
- for option_string in action.option_strings:
- self._option_string_actions[option_string] = action
-
- # set the flag if any option strings look like negative numbers
- for option_string in action.option_strings:
- if self._negative_number_matcher.match(option_string):
- if not self._has_negative_number_optionals:
- self._has_negative_number_optionals.append(True)
-
- # return the created action
- return action
-
- def _remove_action(self, action):
- self._actions.remove(action)
-
- def _add_container_actions(self, container):
- # collect groups by titles
- title_group_map = {}
- for group in self._action_groups:
- if group.title in title_group_map:
- msg = _('cannot merge actions - two groups are named %r')
- raise ValueError(msg % (group.title))
- title_group_map[group.title] = group
-
- # map each action to its group
- group_map = {}
- for group in container._action_groups:
-
- # if a group with the title exists, use that, otherwise
- # create a new group matching the container's group
- if group.title not in title_group_map:
- title_group_map[group.title] = self.add_argument_group(
- title=group.title,
- description=group.description,
- conflict_handler=group.conflict_handler)
-
- # map the actions to their new group
- for action in group._group_actions:
- group_map[action] = title_group_map[group.title]
-
- # add container's mutually exclusive groups
- # NOTE: if add_mutually_exclusive_group ever gains title= and
- # description= then this code will need to be expanded as above
- for group in container._mutually_exclusive_groups:
- mutex_group = self.add_mutually_exclusive_group(
- required=group.required)
-
- # map the actions to their new mutex group
- for action in group._group_actions:
- group_map[action] = mutex_group
-
- # add all actions to this container or their group
- for action in container._actions:
- group_map.get(action, self)._add_action(action)
-
- def _get_positional_kwargs(self, dest, **kwargs):
- # make sure required is not specified
- if 'required' in kwargs:
- msg = _("'required' is an invalid argument for positionals")
- raise TypeError(msg)
-
- # mark positional arguments as required if at least one is
- # always required
- if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
- kwargs['required'] = True
- if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
- kwargs['required'] = True
-
- # return the keyword arguments with no option strings
- return dict(kwargs, dest=dest, option_strings=[])
-
- def _get_optional_kwargs(self, *args, **kwargs):
- # determine short and long option strings
- option_strings = []
- long_option_strings = []
- for option_string in args:
- # error on strings that don't start with an appropriate prefix
- if not option_string[0] in self.prefix_chars:
- args = {'option': option_string,
- 'prefix_chars': self.prefix_chars}
- msg = _('invalid option string %(option)r: '
- 'must start with a character %(prefix_chars)r')
- raise ValueError(msg % args)
-
- # strings starting with two prefix characters are long options
- option_strings.append(option_string)
- if len(option_string) > 1 and option_string[1] in self.prefix_chars:
- long_option_strings.append(option_string)
-
- # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
- dest = kwargs.pop('dest', None)
- if dest is None:
- if long_option_strings:
- dest_option_string = long_option_strings[0]
- else:
- dest_option_string = option_strings[0]
- dest = dest_option_string.lstrip(self.prefix_chars)
- if not dest:
- msg = _('dest= is required for options like %r')
- raise ValueError(msg % option_string)
- dest = dest.replace('-', '_')
-
- # return the updated keyword arguments
- return dict(kwargs, dest=dest, option_strings=option_strings)
-
- def _pop_action_class(self, kwargs, default=None):
- action = kwargs.pop('action', default)
- return self._registry_get('action', action, action)
-
- def _get_handler(self):
- # determine function from conflict handler string
- handler_func_name = '_handle_conflict_%s' % self.conflict_handler
- try:
- return getattr(self, handler_func_name)
- except AttributeError:
- msg = _('invalid conflict_resolution value: %r')
- raise ValueError(msg % self.conflict_handler)
-
- def _check_conflict(self, action):
-
- # find all options that conflict with this option
- confl_optionals = []
- for option_string in action.option_strings:
- if option_string in self._option_string_actions:
- confl_optional = self._option_string_actions[option_string]
- confl_optionals.append((option_string, confl_optional))
-
- # resolve any conflicts
- if confl_optionals:
- conflict_handler = self._get_handler()
- conflict_handler(action, confl_optionals)
-
- def _handle_conflict_error(self, action, conflicting_actions):
- message = ngettext('conflicting option string: %s',
- 'conflicting option strings: %s',
- len(conflicting_actions))
- conflict_string = ', '.join([option_string
- for option_string, action
- in conflicting_actions])
- raise ArgumentError(action, message % conflict_string)
-
- def _handle_conflict_resolve(self, action, conflicting_actions):
-
- # remove all conflicting options
- for option_string, action in conflicting_actions:
-
- # remove the conflicting option
- action.option_strings.remove(option_string)
- self._option_string_actions.pop(option_string, None)
-
- # if the option now has no option string, remove it from the
- # container holding it
- if not action.option_strings:
- action.container._remove_action(action)
-
-
-class _ArgumentGroup(_ActionsContainer):
-
- def __init__(self, container, title=None, description=None, **kwargs):
- # add any missing keyword arguments by checking the container
- update = kwargs.setdefault
- update('conflict_handler', container.conflict_handler)
- update('prefix_chars', container.prefix_chars)
- update('argument_default', container.argument_default)
- super_init = super(_ArgumentGroup, self).__init__
- super_init(description=description, **kwargs)
-
- # group attributes
- self.title = title
- self._group_actions = []
-
- # share most attributes with the container
- self._registries = container._registries
- self._actions = container._actions
- self._option_string_actions = container._option_string_actions
- self._defaults = container._defaults
- self._has_negative_number_optionals = \
- container._has_negative_number_optionals
- self._mutually_exclusive_groups = container._mutually_exclusive_groups
-
- def _add_action(self, action):
- action = super(_ArgumentGroup, self)._add_action(action)
- self._group_actions.append(action)
- return action
-
- def _remove_action(self, action):
- super(_ArgumentGroup, self)._remove_action(action)
- self._group_actions.remove(action)
-
-
-class _MutuallyExclusiveGroup(_ArgumentGroup):
-
- def __init__(self, container, required=False):
- super(_MutuallyExclusiveGroup, self).__init__(container)
- self.required = required
- self._container = container
-
- def _add_action(self, action):
- if action.required:
- msg = _('mutually exclusive arguments must be optional')
- raise ValueError(msg)
- action = self._container._add_action(action)
- self._group_actions.append(action)
- return action
-
- def _remove_action(self, action):
- self._container._remove_action(action)
- self._group_actions.remove(action)
-
-
-class ArgumentParser(_AttributeHolder, _ActionsContainer):
- """Object for parsing command line strings into Python objects.
-
- Keyword Arguments:
- - prog -- The name of the program (default:
- ``os.path.basename(sys.argv[0])``)
- - usage -- A usage message (default: auto-generated from arguments)
- - description -- A description of what the program does
- - epilog -- Text following the argument descriptions
- - parents -- Parsers whose arguments should be copied into this one
- - formatter_class -- HelpFormatter class for printing help messages
- - prefix_chars -- Characters that prefix optional arguments
- - fromfile_prefix_chars -- Characters that prefix files containing
- additional arguments
- - argument_default -- The default value for all arguments
- - conflict_handler -- String indicating how to handle conflicts
- - add_help -- Add a -h/-help option
- - allow_abbrev -- Allow long options to be abbreviated unambiguously
- - exit_on_error -- Determines whether or not ArgumentParser exits with
- error info when an error occurs
- """
-
- def __init__(self,
- prog=None,
- usage=None,
- description=None,
- epilog=None,
- parents=[],
- formatter_class=HelpFormatter,
- prefix_chars='-',
- fromfile_prefix_chars=None,
- argument_default=None,
- conflict_handler='error',
- add_help=True,
- allow_abbrev=True,
- exit_on_error=True):
-
- superinit = super(ArgumentParser, self).__init__
- superinit(description=description,
- prefix_chars=prefix_chars,
- argument_default=argument_default,
- conflict_handler=conflict_handler)
-
- # default setting for prog
- if prog is None:
- prog = _os.path.basename(_sys.argv[0])
-
- self.prog = prog
- self.usage = usage
- self.epilog = epilog
- self.formatter_class = formatter_class
- self.fromfile_prefix_chars = fromfile_prefix_chars
- self.add_help = add_help
- self.allow_abbrev = allow_abbrev
- self.exit_on_error = exit_on_error
-
- add_group = self.add_argument_group
- self._positionals = add_group(_('positional arguments'))
- self._optionals = add_group(_('options'))
- self._subparsers = None
-
- # register types
- def identity(string):
- return string
- self.register('type', None, identity)
-
- # add help argument if necessary
- # (using explicit default to override global argument_default)
- default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
- if self.add_help:
- self.add_argument(
- default_prefix+'h', default_prefix*2+'help',
- action='help', default=SUPPRESS,
- help=_('show this help message and exit'))
-
- # add parent arguments and defaults
- for parent in parents:
- self._add_container_actions(parent)
- try:
- defaults = parent._defaults
- except AttributeError:
- pass
- else:
- self._defaults.update(defaults)
-
- # =======================
- # Pretty __repr__ methods
- # =======================
- def _get_kwargs(self):
- names = [
- 'prog',
- 'usage',
- 'description',
- 'formatter_class',
- 'conflict_handler',
- 'add_help',
- ]
- return [(name, getattr(self, name)) for name in names]
-
- # ==================================
- # Optional/Positional adding methods
- # ==================================
- def add_subparsers(self, **kwargs):
- if self._subparsers is not None:
- self.error(_('cannot have multiple subparser arguments'))
-
- # add the parser class to the arguments if it's not present
- kwargs.setdefault('parser_class', type(self))
-
- if 'title' in kwargs or 'description' in kwargs:
- title = _(kwargs.pop('title', 'subcommands'))
- description = _(kwargs.pop('description', None))
- self._subparsers = self.add_argument_group(title, description)
- else:
- self._subparsers = self._positionals
-
- # prog defaults to the usage message of this parser, skipping
- # optional arguments and with no "usage:" prefix
- if kwargs.get('prog') is None:
- formatter = self._get_formatter()
- positionals = self._get_positional_actions()
- groups = self._mutually_exclusive_groups
- formatter.add_usage(self.usage, positionals, groups, '')
- kwargs['prog'] = formatter.format_help().strip()
-
- # create the parsers action and add it to the positionals list
- parsers_class = self._pop_action_class(kwargs, 'parsers')
- action = parsers_class(option_strings=[], **kwargs)
- self._subparsers._add_action(action)
-
- # return the created parsers action
- return action
-
- def _add_action(self, action):
- if action.option_strings:
- self._optionals._add_action(action)
- else:
- self._positionals._add_action(action)
- return action
-
- def _get_optional_actions(self):
- return [action
- for action in self._actions
- if action.option_strings]
-
- def _get_positional_actions(self):
- return [action
- for action in self._actions
- if not action.option_strings]
-
- # =====================================
- # Command line argument parsing methods
- # =====================================
- def parse_args(self, args=None, namespace=None):
- args, argv = self.parse_known_args(args, namespace)
- if argv:
- msg = _('unrecognized arguments: %s')
- self.error(msg % ' '.join(argv))
- return args
-
- def parse_known_args(self, args=None, namespace=None):
- if args is None:
- # args default to the system args
- args = _sys.argv[1:]
- else:
- # make sure that args are mutable
- args = list(args)
-
- # default Namespace built from parser defaults
- if namespace is None:
- namespace = Namespace()
-
- # add any action defaults that aren't present
- for action in self._actions:
- if action.dest is not SUPPRESS:
- if not hasattr(namespace, action.dest):
- if action.default is not SUPPRESS:
- setattr(namespace, action.dest, action.default)
-
- # add any parser defaults that aren't present
- for dest in self._defaults:
- if not hasattr(namespace, dest):
- setattr(namespace, dest, self._defaults[dest])
-
- # parse the arguments and exit if there are any errors
- if self.exit_on_error:
- try:
- namespace, args = self._parse_known_args(args, namespace)
- except ArgumentError:
- err = _sys.exc_info()[1]
- self.error(str(err))
- else:
- namespace, args = self._parse_known_args(args, namespace)
-
- if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
- args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
- delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
- return namespace, args
-
- def _parse_known_args(self, arg_strings, namespace):
- # replace arg strings that are file references
- if self.fromfile_prefix_chars is not None:
- arg_strings = self._read_args_from_files(arg_strings)
-
- # map all mutually exclusive arguments to the other arguments
- # they can't occur with
- action_conflicts = {}
- for mutex_group in self._mutually_exclusive_groups:
- group_actions = mutex_group._group_actions
- for i, mutex_action in enumerate(mutex_group._group_actions):
- conflicts = action_conflicts.setdefault(mutex_action, [])
- conflicts.extend(group_actions[:i])
- conflicts.extend(group_actions[i + 1:])
-
- # find all option indices, and determine the arg_string_pattern
- # which has an 'O' if there is an option at an index,
- # an 'A' if there is an argument, or a '-' if there is a '--'
- option_string_indices = {}
- arg_string_pattern_parts = []
- arg_strings_iter = iter(arg_strings)
- for i, arg_string in enumerate(arg_strings_iter):
-
- # all args after -- are non-options
- if arg_string == '--':
- arg_string_pattern_parts.append('-')
- for arg_string in arg_strings_iter:
- arg_string_pattern_parts.append('A')
-
- # otherwise, add the arg to the arg strings
- # and note the index if it was an option
- else:
- option_tuple = self._parse_optional(arg_string)
- if option_tuple is None:
- pattern = 'A'
- else:
- option_string_indices[i] = option_tuple
- pattern = 'O'
- arg_string_pattern_parts.append(pattern)
-
- # join the pieces together to form the pattern
- arg_strings_pattern = ''.join(arg_string_pattern_parts)
-
- # converts arg strings to the appropriate and then takes the action
- seen_actions = set()
- seen_non_default_actions = set()
-
- def take_action(action, argument_strings, option_string=None):
- seen_actions.add(action)
- argument_values = self._get_values(action, argument_strings)
-
- # error if this argument is not allowed with other previously
- # seen arguments, assuming that actions that use the default
- # value don't really count as "present"
- if argument_values is not action.default:
- seen_non_default_actions.add(action)
- for conflict_action in action_conflicts.get(action, []):
- if conflict_action in seen_non_default_actions:
- msg = _('not allowed with argument %s')
- action_name = _get_action_name(conflict_action)
- raise ArgumentError(action, msg % action_name)
-
- # take the action if we didn't receive a SUPPRESS value
- # (e.g. from a default)
- if argument_values is not SUPPRESS:
- action(self, namespace, argument_values, option_string)
-
- # function to convert arg_strings into an optional action
- def consume_optional(start_index):
-
- # get the optional identified at this index
- option_tuple = option_string_indices[start_index]
- action, option_string, explicit_arg = option_tuple
-
- # identify additional optionals in the same arg string
- # (e.g. -xyz is the same as -x -y -z if no args are required)
- match_argument = self._match_argument
- action_tuples = []
- while True:
-
- # if we found no optional action, skip it
- if action is None:
- extras.append(arg_strings[start_index])
- return start_index + 1
-
- # if there is an explicit argument, try to match the
- # optional's string arguments to only this
- if explicit_arg is not None:
- arg_count = match_argument(action, 'A')
-
- # if the action is a single-dash option and takes no
- # arguments, try to parse more single-dash options out
- # of the tail of the option string
- chars = self.prefix_chars
- if arg_count == 0 and option_string[1] not in chars:
- action_tuples.append((action, [], option_string))
- char = option_string[0]
- option_string = char + explicit_arg[0]
- new_explicit_arg = explicit_arg[1:] or None
- optionals_map = self._option_string_actions
- if option_string in optionals_map:
- action = optionals_map[option_string]
- explicit_arg = new_explicit_arg
- else:
- msg = _('ignored explicit argument %r')
- raise ArgumentError(action, msg % explicit_arg)
-
- # if the action expect exactly one argument, we've
- # successfully matched the option; exit the loop
- elif arg_count == 1:
- stop = start_index + 1
- args = [explicit_arg]
- action_tuples.append((action, args, option_string))
- break
-
- # error if a double-dash option did not use the
- # explicit argument
- else:
- msg = _('ignored explicit argument %r')
- raise ArgumentError(action, msg % explicit_arg)
-
- # if there is no explicit argument, try to match the
- # optional's string arguments with the following strings
- # if successful, exit the loop
- else:
- start = start_index + 1
- selected_patterns = arg_strings_pattern[start:]
- arg_count = match_argument(action, selected_patterns)
- stop = start + arg_count
- args = arg_strings[start:stop]
- action_tuples.append((action, args, option_string))
- break
-
- # add the Optional to the list and return the index at which
- # the Optional's string args stopped
- assert action_tuples
- for action, args, option_string in action_tuples:
- take_action(action, args, option_string)
- return stop
-
- # the list of Positionals left to be parsed; this is modified
- # by consume_positionals()
- positionals = self._get_positional_actions()
-
- # function to convert arg_strings into positional actions
- def consume_positionals(start_index):
- # match as many Positionals as possible
- match_partial = self._match_arguments_partial
- selected_pattern = arg_strings_pattern[start_index:]
- arg_counts = match_partial(positionals, selected_pattern)
-
- # slice off the appropriate arg strings for each Positional
- # and add the Positional and its args to the list
- for action, arg_count in zip(positionals, arg_counts):
- args = arg_strings[start_index: start_index + arg_count]
- start_index += arg_count
- take_action(action, args)
-
- # slice off the Positionals that we just parsed and return the
- # index at which the Positionals' string args stopped
- positionals[:] = positionals[len(arg_counts):]
- return start_index
-
- # consume Positionals and Optionals alternately, until we have
- # passed the last option string
- extras = []
- start_index = 0
- if option_string_indices:
- max_option_string_index = max(option_string_indices)
- else:
- max_option_string_index = -1
- while start_index <= max_option_string_index:
-
- # consume any Positionals preceding the next option
- next_option_string_index = min([
- index
- for index in option_string_indices
- if index >= start_index])
- if start_index != next_option_string_index:
- positionals_end_index = consume_positionals(start_index)
-
- # only try to parse the next optional if we didn't consume
- # the option string during the positionals parsing
- if positionals_end_index > start_index:
- start_index = positionals_end_index
- continue
- else:
- start_index = positionals_end_index
-
- # if we consumed all the positionals we could and we're not
- # at the index of an option string, there were extra arguments
- if start_index not in option_string_indices:
- strings = arg_strings[start_index:next_option_string_index]
- extras.extend(strings)
- start_index = next_option_string_index
-
- # consume the next optional and any arguments for it
- start_index = consume_optional(start_index)
-
- # consume any positionals following the last Optional
- stop_index = consume_positionals(start_index)
-
- # if we didn't consume all the argument strings, there were extras
- extras.extend(arg_strings[stop_index:])
-
- # make sure all required actions were present and also convert
- # action defaults which were not given as arguments
- required_actions = []
- for action in self._actions:
- if action not in seen_actions:
- if action.required:
- required_actions.append(_get_action_name(action))
- else:
- # Convert action default now instead of doing it before
- # parsing arguments to avoid calling convert functions
- # twice (which may fail) if the argument was given, but
- # only if it was defined already in the namespace
- if (action.default is not None and
- isinstance(action.default, str) and
- hasattr(namespace, action.dest) and
- action.default is getattr(namespace, action.dest)):
- setattr(namespace, action.dest,
- self._get_value(action, action.default))
-
- if required_actions:
- self.error(_('the following arguments are required: %s') %
- ', '.join(required_actions))
-
- # make sure all required groups had one option present
- for group in self._mutually_exclusive_groups:
- if group.required:
- for action in group._group_actions:
- if action in seen_non_default_actions:
- break
-
- # if no actions were used, report the error
- else:
- names = [_get_action_name(action)
- for action in group._group_actions
- if action.help is not SUPPRESS]
- msg = _('one of the arguments %s is required')
- self.error(msg % ' '.join(names))
-
- # return the updated namespace and the extra arguments
- return namespace, extras
-
- def _read_args_from_files(self, arg_strings):
- # expand arguments referencing files
- new_arg_strings = []
- for arg_string in arg_strings:
-
- # for regular arguments, just add them back into the list
- if not arg_string or arg_string[0] not in self.fromfile_prefix_chars:
- new_arg_strings.append(arg_string)
-
- # replace arguments referencing files with the file content
- else:
- try:
- with open(arg_string[1:]) as args_file:
- arg_strings = []
- for arg_line in args_file.read().splitlines():
- for arg in self.convert_arg_line_to_args(arg_line):
- arg_strings.append(arg)
- arg_strings = self._read_args_from_files(arg_strings)
- new_arg_strings.extend(arg_strings)
- except OSError:
- err = _sys.exc_info()[1]
- self.error(str(err))
-
- # return the modified argument list
- return new_arg_strings
-
- def convert_arg_line_to_args(self, arg_line):
- return [arg_line]
-
- def _match_argument(self, action, arg_strings_pattern):
- # match the pattern for this action to the arg strings
- nargs_pattern = self._get_nargs_pattern(action)
- match = _re.match(nargs_pattern, arg_strings_pattern)
-
- # raise an exception if we weren't able to find a match
- if match is None:
- nargs_errors = {
- None: _('expected one argument'),
- OPTIONAL: _('expected at most one argument'),
- ONE_OR_MORE: _('expected at least one argument'),
- }
- msg = nargs_errors.get(action.nargs)
- if msg is None:
- msg = ngettext('expected %s argument',
- 'expected %s arguments',
- action.nargs) % action.nargs
- raise ArgumentError(action, msg)
-
- # return the number of arguments matched
- return len(match.group(1))
-
- def _match_arguments_partial(self, actions, arg_strings_pattern):
- # progressively shorten the actions list by slicing off the
- # final actions until we find a match
- result = []
- for i in range(len(actions), 0, -1):
- actions_slice = actions[:i]
- pattern = ''.join([self._get_nargs_pattern(action)
- for action in actions_slice])
- match = _re.match(pattern, arg_strings_pattern)
- if match is not None:
- result.extend([len(string) for string in match.groups()])
- break
-
- # return the list of arg string counts
- return result
-
- def _parse_optional(self, arg_string):
- # if it's an empty string, it was meant to be a positional
- if not arg_string:
- return None
-
- # if it doesn't start with a prefix, it was meant to be positional
- if not arg_string[0] in self.prefix_chars:
- return None
-
- # if the option string is present in the parser, return the action
- if arg_string in self._option_string_actions:
- action = self._option_string_actions[arg_string]
- return action, arg_string, None
-
- # if it's just a single character, it was meant to be positional
- if len(arg_string) == 1:
- return None
-
- # if the option string before the "=" is present, return the action
- if '=' in arg_string:
- option_string, explicit_arg = arg_string.split('=', 1)
- if option_string in self._option_string_actions:
- action = self._option_string_actions[option_string]
- return action, option_string, explicit_arg
-
- # search through all possible prefixes of the option string
- # and all actions in the parser for possible interpretations
- option_tuples = self._get_option_tuples(arg_string)
-
- # if multiple actions match, the option string was ambiguous
- if len(option_tuples) > 1:
- options = ', '.join([option_string
- for action, option_string, explicit_arg in option_tuples])
- args = {'option': arg_string, 'matches': options}
- msg = _('ambiguous option: %(option)s could match %(matches)s')
- self.error(msg % args)
-
- # if exactly one action matched, this segmentation is good,
- # so return the parsed action
- elif len(option_tuples) == 1:
- option_tuple, = option_tuples
- return option_tuple
-
- # if it was not found as an option, but it looks like a negative
- # number, it was meant to be positional
- # unless there are negative-number-like options
- if self._negative_number_matcher.match(arg_string):
- if not self._has_negative_number_optionals:
- return None
-
- # if it contains a space, it was meant to be a positional
- if ' ' in arg_string:
- return None
-
- # it was meant to be an optional but there is no such option
- # in this parser (though it might be a valid option in a subparser)
- return None, arg_string, None
-
- def _get_option_tuples(self, option_string):
- result = []
-
- # option strings starting with two prefix characters are only
- # split at the '='
- chars = self.prefix_chars
- if option_string[0] in chars and option_string[1] in chars:
- if self.allow_abbrev:
- if '=' in option_string:
- option_prefix, explicit_arg = option_string.split('=', 1)
- else:
- option_prefix = option_string
- explicit_arg = None
- for option_string in self._option_string_actions:
- if option_string.startswith(option_prefix):
- action = self._option_string_actions[option_string]
- tup = action, option_string, explicit_arg
- result.append(tup)
-
- # single character options can be concatenated with their arguments
- # but multiple character options always have to have their argument
- # separate
- elif option_string[0] in chars and option_string[1] not in chars:
- option_prefix = option_string
- explicit_arg = None
- short_option_prefix = option_string[:2]
- short_explicit_arg = option_string[2:]
-
- for option_string in self._option_string_actions:
- if option_string == short_option_prefix:
- action = self._option_string_actions[option_string]
- tup = action, option_string, short_explicit_arg
- result.append(tup)
- elif option_string.startswith(option_prefix):
- action = self._option_string_actions[option_string]
- tup = action, option_string, explicit_arg
- result.append(tup)
-
- # shouldn't ever get here
- else:
- self.error(_('unexpected option string: %s') % option_string)
-
- # return the collected option tuples
- return result
-
- def _get_nargs_pattern(self, action):
- # in all examples below, we have to allow for '--' args
- # which are represented as '-' in the pattern
- nargs = action.nargs
-
- # the default (None) is assumed to be a single argument
- if nargs is None:
- nargs_pattern = '(-*A-*)'
-
- # allow zero or one arguments
- elif nargs == OPTIONAL:
- nargs_pattern = '(-*A?-*)'
-
- # allow zero or more arguments
- elif nargs == ZERO_OR_MORE:
- nargs_pattern = '(-*[A-]*)'
-
- # allow one or more arguments
- elif nargs == ONE_OR_MORE:
- nargs_pattern = '(-*A[A-]*)'
-
- # allow any number of options or arguments
- elif nargs == REMAINDER:
- nargs_pattern = '([-AO]*)'
-
- # allow one argument followed by any number of options or arguments
- elif nargs == PARSER:
- nargs_pattern = '(-*A[-AO]*)'
-
- # suppress action, like nargs=0
- elif nargs == SUPPRESS:
- nargs_pattern = '(-*-*)'
-
- # all others should be integers
- else:
- nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
-
- # if this is an optional action, -- is not allowed
- if action.option_strings:
- nargs_pattern = nargs_pattern.replace('-*', '')
- nargs_pattern = nargs_pattern.replace('-', '')
-
- # return the pattern
- return nargs_pattern
-
- # ========================
- # Alt command line argument parsing, allowing free intermix
- # ========================
-
- def parse_intermixed_args(self, args=None, namespace=None):
- args, argv = self.parse_known_intermixed_args(args, namespace)
- if argv:
- msg = _('unrecognized arguments: %s')
- self.error(msg % ' '.join(argv))
- return args
-
- def parse_known_intermixed_args(self, args=None, namespace=None):
- # returns a namespace and list of extras
- #
- # positional can be freely intermixed with optionals. optionals are
- # first parsed with all positional arguments deactivated. The 'extras'
- # are then parsed. If the parser definition is incompatible with the
- # intermixed assumptions (e.g. use of REMAINDER, subparsers) a
- # TypeError is raised.
- #
- # positionals are 'deactivated' by setting nargs and default to
- # SUPPRESS. This blocks the addition of that positional to the
- # namespace
-
- positionals = self._get_positional_actions()
- a = [action for action in positionals
- if action.nargs in [PARSER, REMAINDER]]
- if a:
- raise TypeError('parse_intermixed_args: positional arg'
- ' with nargs=%s'%a[0].nargs)
-
- if [action.dest for group in self._mutually_exclusive_groups
- for action in group._group_actions if action in positionals]:
- raise TypeError('parse_intermixed_args: positional in'
- ' mutuallyExclusiveGroup')
-
- try:
- save_usage = self.usage
- try:
- if self.usage is None:
- # capture the full usage for use in error messages
- self.usage = self.format_usage()[7:]
- for action in positionals:
- # deactivate positionals
- action.save_nargs = action.nargs
- # action.nargs = 0
- action.nargs = SUPPRESS
- action.save_default = action.default
- action.default = SUPPRESS
- namespace, remaining_args = self.parse_known_args(args,
- namespace)
- for action in positionals:
- # remove the empty positional values from namespace
- if (hasattr(namespace, action.dest)
- and getattr(namespace, action.dest)==[]):
- from warnings import warn
- warn('Do not expect %s in %s' % (action.dest, namespace))
- delattr(namespace, action.dest)
- finally:
- # restore nargs and usage before exiting
- for action in positionals:
- action.nargs = action.save_nargs
- action.default = action.save_default
- optionals = self._get_optional_actions()
- try:
- # parse positionals. optionals aren't normally required, but
- # they could be, so make sure they aren't.
- for action in optionals:
- action.save_required = action.required
- action.required = False
- for group in self._mutually_exclusive_groups:
- group.save_required = group.required
- group.required = False
- namespace, extras = self.parse_known_args(remaining_args,
- namespace)
- finally:
- # restore parser values before exiting
- for action in optionals:
- action.required = action.save_required
- for group in self._mutually_exclusive_groups:
- group.required = group.save_required
- finally:
- self.usage = save_usage
- return namespace, extras
-
- # ========================
- # Value conversion methods
- # ========================
- def _get_values(self, action, arg_strings):
- # for everything but PARSER, REMAINDER args, strip out first '--'
- if action.nargs not in [PARSER, REMAINDER]:
- try:
- arg_strings.remove('--')
- except ValueError:
- pass
-
- # optional argument produces a default when not present
- if not arg_strings and action.nargs == OPTIONAL:
- if action.option_strings:
- value = action.const
- else:
- value = action.default
- if isinstance(value, str):
- value = self._get_value(action, value)
- self._check_value(action, value)
-
- # when nargs='*' on a positional, if there were no command-line
- # args, use the default if it is anything other than None
- elif (not arg_strings and action.nargs == ZERO_OR_MORE and
- not action.option_strings):
- if action.default is not None:
- value = action.default
- else:
- value = arg_strings
- self._check_value(action, value)
-
- # single argument or optional argument produces a single value
- elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
- arg_string, = arg_strings
- value = self._get_value(action, arg_string)
- self._check_value(action, value)
-
- # REMAINDER arguments convert all values, checking none
- elif action.nargs == REMAINDER:
- value = [self._get_value(action, v) for v in arg_strings]
-
- # PARSER arguments convert all values, but check only the first
- elif action.nargs == PARSER:
- value = [self._get_value(action, v) for v in arg_strings]
- self._check_value(action, value[0])
-
- # SUPPRESS argument does not put anything in the namespace
- elif action.nargs == SUPPRESS:
- value = SUPPRESS
-
- # all other types of nargs produce a list
- else:
- value = [self._get_value(action, v) for v in arg_strings]
- for v in value:
- self._check_value(action, v)
-
- # return the converted value
- return value
-
- def _get_value(self, action, arg_string):
- type_func = self._registry_get('type', action.type, action.type)
- if not callable(type_func):
- msg = _('%r is not callable')
- raise ArgumentError(action, msg % type_func)
-
- # convert the value to the appropriate type
- try:
- result = type_func(arg_string)
-
- # ArgumentTypeErrors indicate errors
- except ArgumentTypeError:
- name = getattr(action.type, '__name__', repr(action.type))
- msg = str(_sys.exc_info()[1])
- raise ArgumentError(action, msg)
-
- # TypeErrors or ValueErrors also indicate errors
- except (TypeError, ValueError):
- name = getattr(action.type, '__name__', repr(action.type))
- args = {'type': name, 'value': arg_string}
- msg = _('invalid %(type)s value: %(value)r')
- raise ArgumentError(action, msg % args)
-
- # return the converted value
- return result
-
- def _check_value(self, action, value):
- # converted value must be one of the choices (if specified)
- if action.choices is not None and value not in action.choices:
- args = {'value': value,
- 'choices': ', '.join(map(repr, action.choices))}
- msg = _('invalid choice: %(value)r (choose from %(choices)s)')
- raise ArgumentError(action, msg % args)
-
- # =======================
- # Help-formatting methods
- # =======================
- def format_usage(self):
- formatter = self._get_formatter()
- formatter.add_usage(self.usage, self._actions,
- self._mutually_exclusive_groups)
- return formatter.format_help()
-
- def format_help(self):
- formatter = self._get_formatter()
-
- # usage
- formatter.add_usage(self.usage, self._actions,
- self._mutually_exclusive_groups)
-
- # description
- formatter.add_text(self.description)
-
- # positionals, optionals and user-defined groups
- for action_group in self._action_groups:
- formatter.start_section(action_group.title)
- formatter.add_text(action_group.description)
- formatter.add_arguments(action_group._group_actions)
- formatter.end_section()
-
- # epilog
- formatter.add_text(self.epilog)
-
- # determine help from format above
- return formatter.format_help()
-
- def _get_formatter(self):
- return self.formatter_class(prog=self.prog)
-
- # =====================
- # Help-printing methods
- # =====================
- def print_usage(self, file=None):
- if file is None:
- file = _sys.stdout
- self._print_message(self.format_usage(), file)
-
- def print_help(self, file=None):
- if file is None:
- file = _sys.stdout
- self._print_message(self.format_help(), file)
-
- def _print_message(self, message, file=None):
- if message:
- if file is None:
- file = _sys.stderr
- file.write(message)
-
- # ===============
- # Exiting methods
- # ===============
- def exit(self, status=0, message=None):
- if message:
- self._print_message(message, _sys.stderr)
- _sys.exit(status)
-
- def error(self, message):
- """error(message: string)
-
- Prints a usage message incorporating the message to stderr and
- exits.
-
- If you override this in a subclass, it should not return -- it
- should either exit or raise an exception.
- """
- self.print_usage(_sys.stderr)
- args = {'prog': self.prog, 'message': message}
- self.exit(2, _('%(prog)s: error: %(message)s\n') % args)
diff --git a/lib/python3.10/ast.py b/lib/python3.10/ast.py
deleted file mode 100644
index f4d2f6e..0000000
--- a/lib/python3.10/ast.py
+++ /dev/null
@@ -1,1701 +0,0 @@
-"""
- ast
- ~~~
-
- The `ast` module helps Python applications to process trees of the Python
- abstract syntax grammar. The abstract syntax itself might change with
- each Python release; this module helps to find out programmatically what
- the current grammar looks like and allows modifications of it.
-
- An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as
- a flag to the `compile()` builtin function or by using the `parse()`
- function from this module. The result will be a tree of objects whose
- classes all inherit from `ast.AST`.
-
- A modified abstract syntax tree can be compiled into a Python code object
- using the built-in `compile()` function.
-
- Additionally various helper functions are provided that make working with
- the trees simpler. The main intention of the helper functions and this
- module in general is to provide an easy to use interface for libraries
- that work tightly with the python syntax (template engines for example).
-
-
- :copyright: Copyright 2008 by Armin Ronacher.
- :license: Python License.
-"""
-import sys
-from _ast import *
-from contextlib import contextmanager, nullcontext
-from enum import IntEnum, auto
-
-
-def parse(source, filename='<unknown>', mode='exec', *,
- type_comments=False, feature_version=None):
- """
- Parse the source into an AST node.
- Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).
- Pass type_comments=True to get back type comments where the syntax allows.
- """
- flags = PyCF_ONLY_AST
- if type_comments:
- flags |= PyCF_TYPE_COMMENTS
- if isinstance(feature_version, tuple):
- major, minor = feature_version # Should be a 2-tuple.
- assert major == 3
- feature_version = minor
- elif feature_version is None:
- feature_version = -1
- # Else it should be an int giving the minor version for 3.x.
- return compile(source, filename, mode, flags,
- _feature_version=feature_version)
-
-
-def literal_eval(node_or_string):
- """
- Safely evaluate an expression node or a string containing a Python
- expression. The string or node provided may only consist of the following
- Python literal structures: strings, bytes, numbers, tuples, lists, dicts,
- sets, booleans, and None.
- """
- if isinstance(node_or_string, str):
- node_or_string = parse(node_or_string.lstrip(" \t"), mode='eval')
- if isinstance(node_or_string, Expression):
- node_or_string = node_or_string.body
- def _raise_malformed_node(node):
- msg = "malformed node or string"
- if lno := getattr(node, 'lineno', None):
- msg += f' on line {lno}'
- raise ValueError(msg + f': {node!r}')
- def _convert_num(node):
- if not isinstance(node, Constant) or type(node.value) not in (int, float, complex):
- _raise_malformed_node(node)
- return node.value
- def _convert_signed_num(node):
- if isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)):
- operand = _convert_num(node.operand)
- if isinstance(node.op, UAdd):
- return + operand
- else:
- return - operand
- return _convert_num(node)
- def _convert(node):
- if isinstance(node, Constant):
- return node.value
- elif isinstance(node, Tuple):
- return tuple(map(_convert, node.elts))
- elif isinstance(node, List):
- return list(map(_convert, node.elts))
- elif isinstance(node, Set):
- return set(map(_convert, node.elts))
- elif (isinstance(node, Call) and isinstance(node.func, Name) and
- node.func.id == 'set' and node.args == node.keywords == []):
- return set()
- elif isinstance(node, Dict):
- if len(node.keys) != len(node.values):
- _raise_malformed_node(node)
- return dict(zip(map(_convert, node.keys),
- map(_convert, node.values)))
- elif isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)):
- left = _convert_signed_num(node.left)
- right = _convert_num(node.right)
- if isinstance(left, (int, float)) and isinstance(right, complex):
- if isinstance(node.op, Add):
- return left + right
- else:
- return left - right
- return _convert_signed_num(node)
- return _convert(node_or_string)
-
-
-def dump(node, annotate_fields=True, include_attributes=False, *, indent=None):
- """
- Return a formatted dump of the tree in node. This is mainly useful for
- debugging purposes. If annotate_fields is true (by default),
- the returned string will show the names and the values for fields.
- If annotate_fields is false, the result string will be more compact by
- omitting unambiguous field names. Attributes such as line
- numbers and column offsets are not dumped by default. If this is wanted,
- include_attributes can be set to true. If indent is a non-negative
- integer or string, then the tree will be pretty-printed with that indent
- level. None (the default) selects the single line representation.
- """
- def _format(node, level=0):
- if indent is not None:
- level += 1
- prefix = '\n' + indent * level
- sep = ',\n' + indent * level
- else:
- prefix = ''
- sep = ', '
- if isinstance(node, AST):
- cls = type(node)
- args = []
- allsimple = True
- keywords = annotate_fields
- for name in node._fields:
- try:
- value = getattr(node, name)
- except AttributeError:
- keywords = True
- continue
- if value is None and getattr(cls, name, ...) is None:
- keywords = True
- continue
- value, simple = _format(value, level)
- allsimple = allsimple and simple
- if keywords:
- args.append('%s=%s' % (name, value))
- else:
- args.append(value)
- if include_attributes and node._attributes:
- for name in node._attributes:
- try:
- value = getattr(node, name)
- except AttributeError:
- continue
- if value is None and getattr(cls, name, ...) is None:
- continue
- value, simple = _format(value, level)
- allsimple = allsimple and simple
- args.append('%s=%s' % (name, value))
- if allsimple and len(args) <= 3:
- return '%s(%s)' % (node.__class__.__name__, ', '.join(args)), not args
- return '%s(%s%s)' % (node.__class__.__name__, prefix, sep.join(args)), False
- elif isinstance(node, list):
- if not node:
- return '[]', True
- return '[%s%s]' % (prefix, sep.join(_format(x, level)[0] for x in node)), False
- return repr(node), True
-
- if not isinstance(node, AST):
- raise TypeError('expected AST, got %r' % node.__class__.__name__)
- if indent is not None and not isinstance(indent, str):
- indent = ' ' * indent
- return _format(node)[0]
-
-
-def copy_location(new_node, old_node):
- """
- Copy source location (`lineno`, `col_offset`, `end_lineno`, and `end_col_offset`
- attributes) from *old_node* to *new_node* if possible, and return *new_node*.
- """
- for attr in 'lineno', 'col_offset', 'end_lineno', 'end_col_offset':
- if attr in old_node._attributes and attr in new_node._attributes:
- value = getattr(old_node, attr, None)
- # end_lineno and end_col_offset are optional attributes, and they
- # should be copied whether the value is None or not.
- if value is not None or (
- hasattr(old_node, attr) and attr.startswith("end_")
- ):
- setattr(new_node, attr, value)
- return new_node
-
-
-def fix_missing_locations(node):
- """
- When you compile a node tree with compile(), the compiler expects lineno and
- col_offset attributes for every node that supports them. This is rather
- tedious to fill in for generated nodes, so this helper adds these attributes
- recursively where not already set, by setting them to the values of the
- parent node. It works recursively starting at *node*.
- """
- def _fix(node, lineno, col_offset, end_lineno, end_col_offset):
- if 'lineno' in node._attributes:
- if not hasattr(node, 'lineno'):
- node.lineno = lineno
- else:
- lineno = node.lineno
- if 'end_lineno' in node._attributes:
- if getattr(node, 'end_lineno', None) is None:
- node.end_lineno = end_lineno
- else:
- end_lineno = node.end_lineno
- if 'col_offset' in node._attributes:
- if not hasattr(node, 'col_offset'):
- node.col_offset = col_offset
- else:
- col_offset = node.col_offset
- if 'end_col_offset' in node._attributes:
- if getattr(node, 'end_col_offset', None) is None:
- node.end_col_offset = end_col_offset
- else:
- end_col_offset = node.end_col_offset
- for child in iter_child_nodes(node):
- _fix(child, lineno, col_offset, end_lineno, end_col_offset)
- _fix(node, 1, 0, 1, 0)
- return node
-
-
-def increment_lineno(node, n=1):
- """
- Increment the line number and end line number of each node in the tree
- starting at *node* by *n*. This is useful to "move code" to a different
- location in a file.
- """
- for child in walk(node):
- if 'lineno' in child._attributes:
- child.lineno = getattr(child, 'lineno', 0) + n
- if (
- "end_lineno" in child._attributes
- and (end_lineno := getattr(child, "end_lineno", 0)) is not None
- ):
- child.end_lineno = end_lineno + n
- return node
-
-
-def iter_fields(node):
- """
- Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
- that is present on *node*.
- """
- for field in node._fields:
- try:
- yield field, getattr(node, field)
- except AttributeError:
- pass
-
-
-def iter_child_nodes(node):
- """
- Yield all direct child nodes of *node*, that is, all fields that are nodes
- and all items of fields that are lists of nodes.
- """
- for name, field in iter_fields(node):
- if isinstance(field, AST):
- yield field
- elif isinstance(field, list):
- for item in field:
- if isinstance(item, AST):
- yield item
-
-
-def get_docstring(node, clean=True):
- """
- Return the docstring for the given node or None if no docstring can
- be found. If the node provided does not have docstrings a TypeError
- will be raised.
-
- If *clean* is `True`, all tabs are expanded to spaces and any whitespace
- that can be uniformly removed from the second line onwards is removed.
- """
- if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)):
- raise TypeError("%r can't have docstrings" % node.__class__.__name__)
- if not(node.body and isinstance(node.body[0], Expr)):
- return None
- node = node.body[0].value
- if isinstance(node, Str):
- text = node.s
- elif isinstance(node, Constant) and isinstance(node.value, str):
- text = node.value
- else:
- return None
- if clean:
- import inspect
- text = inspect.cleandoc(text)
- return text
-
-
-def _splitlines_no_ff(source):
- """Split a string into lines ignoring form feed and other chars.
-
- This mimics how the Python parser splits source code.
- """
- idx = 0
- lines = []
- next_line = ''
- while idx < len(source):
- c = source[idx]
- next_line += c
- idx += 1
- # Keep \r\n together
- if c == '\r' and idx < len(source) and source[idx] == '\n':
- next_line += '\n'
- idx += 1
- if c in '\r\n':
- lines.append(next_line)
- next_line = ''
-
- if next_line:
- lines.append(next_line)
- return lines
-
-
-def _pad_whitespace(source):
- r"""Replace all chars except '\f\t' in a line with spaces."""
- result = ''
- for c in source:
- if c in '\f\t':
- result += c
- else:
- result += ' '
- return result
-
-
-def get_source_segment(source, node, *, padded=False):
- """Get source code segment of the *source* that generated *node*.
-
- If some location information (`lineno`, `end_lineno`, `col_offset`,
- or `end_col_offset`) is missing, return None.
-
- If *padded* is `True`, the first line of a multi-line statement will
- be padded with spaces to match its original position.
- """
- try:
- if node.end_lineno is None or node.end_col_offset is None:
- return None
- lineno = node.lineno - 1
- end_lineno = node.end_lineno - 1
- col_offset = node.col_offset
- end_col_offset = node.end_col_offset
- except AttributeError:
- return None
-
- lines = _splitlines_no_ff(source)
- if end_lineno == lineno:
- return lines[lineno].encode()[col_offset:end_col_offset].decode()
-
- if padded:
- padding = _pad_whitespace(lines[lineno].encode()[:col_offset].decode())
- else:
- padding = ''
-
- first = padding + lines[lineno].encode()[col_offset:].decode()
- last = lines[end_lineno].encode()[:end_col_offset].decode()
- lines = lines[lineno+1:end_lineno]
-
- lines.insert(0, first)
- lines.append(last)
- return ''.join(lines)
-
-
-def walk(node):
- """
- Recursively yield all descendant nodes in the tree starting at *node*
- (including *node* itself), in no specified order. This is useful if you
- only want to modify nodes in place and don't care about the context.
- """
- from collections import deque
- todo = deque([node])
- while todo:
- node = todo.popleft()
- todo.extend(iter_child_nodes(node))
- yield node
-
-
-class NodeVisitor(object):
- """
- A node visitor base class that walks the abstract syntax tree and calls a
- visitor function for every node found. This function may return a value
- which is forwarded by the `visit` method.
-
- This class is meant to be subclassed, with the subclass adding visitor
- methods.
-
- Per default the visitor functions for the nodes are ``'visit_'`` +
- class name of the node. So a `TryFinally` node visit function would
- be `visit_TryFinally`. This behavior can be changed by overriding
- the `visit` method. If no visitor function exists for a node
- (return value `None`) the `generic_visit` visitor is used instead.
-
- Don't use the `NodeVisitor` if you want to apply changes to nodes during
- traversing. For this a special visitor exists (`NodeTransformer`) that
- allows modifications.
- """
-
- def visit(self, node):
- """Visit a node."""
- method = 'visit_' + node.__class__.__name__
- visitor = getattr(self, method, self.generic_visit)
- return visitor(node)
-
- def generic_visit(self, node):
- """Called if no explicit visitor function exists for a node."""
- for field, value in iter_fields(node):
- if isinstance(value, list):
- for item in value:
- if isinstance(item, AST):
- self.visit(item)
- elif isinstance(value, AST):
- self.visit(value)
-
- def visit_Constant(self, node):
- value = node.value
- type_name = _const_node_type_names.get(type(value))
- if type_name is None:
- for cls, name in _const_node_type_names.items():
- if isinstance(value, cls):
- type_name = name
- break
- if type_name is not None:
- method = 'visit_' + type_name
- try:
- visitor = getattr(self, method)
- except AttributeError:
- pass
- else:
- import warnings
- warnings.warn(f"{method} is deprecated; add visit_Constant",
- DeprecationWarning, 2)
- return visitor(node)
- return self.generic_visit(node)
-
-
-class NodeTransformer(NodeVisitor):
- """
- A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
- allows modification of nodes.
-
- The `NodeTransformer` will walk the AST and use the return value of the
- visitor methods to replace or remove the old node. If the return value of
- the visitor method is ``None``, the node will be removed from its location,
- otherwise it is replaced with the return value. The return value may be the
- original node in which case no replacement takes place.
-
- Here is an example transformer that rewrites all occurrences of name lookups
- (``foo``) to ``data['foo']``::
-
- class RewriteName(NodeTransformer):
-
- def visit_Name(self, node):
- return Subscript(
- value=Name(id='data', ctx=Load()),
- slice=Constant(value=node.id),
- ctx=node.ctx
- )
-
- Keep in mind that if the node you're operating on has child nodes you must
- either transform the child nodes yourself or call the :meth:`generic_visit`
- method for the node first.
-
- For nodes that were part of a collection of statements (that applies to all
- statement nodes), the visitor may also return a list of nodes rather than
- just a single node.
-
- Usually you use the transformer like this::
-
- node = YourTransformer().visit(node)
- """
-
- def generic_visit(self, node):
- for field, old_value in iter_fields(node):
- if isinstance(old_value, list):
- new_values = []
- for value in old_value:
- if isinstance(value, AST):
- value = self.visit(value)
- if value is None:
- continue
- elif not isinstance(value, AST):
- new_values.extend(value)
- continue
- new_values.append(value)
- old_value[:] = new_values
- elif isinstance(old_value, AST):
- new_node = self.visit(old_value)
- if new_node is None:
- delattr(node, field)
- else:
- setattr(node, field, new_node)
- return node
-
-
-# If the ast module is loaded more than once, only add deprecated methods once
-if not hasattr(Constant, 'n'):
- # The following code is for backward compatibility.
- # It will be removed in future.
-
- def _getter(self):
- """Deprecated. Use value instead."""
- return self.value
-
- def _setter(self, value):
- self.value = value
-
- Constant.n = property(_getter, _setter)
- Constant.s = property(_getter, _setter)
-
-class _ABC(type):
-
- def __init__(cls, *args):
- cls.__doc__ = """Deprecated AST node class. Use ast.Constant instead"""
-
- def __instancecheck__(cls, inst):
- if not isinstance(inst, Constant):
- return False
- if cls in _const_types:
- try:
- value = inst.value
- except AttributeError:
- return False
- else:
- return (
- isinstance(value, _const_types[cls]) and
- not isinstance(value, _const_types_not.get(cls, ()))
- )
- return type.__instancecheck__(cls, inst)
-
-def _new(cls, *args, **kwargs):
- for key in kwargs:
- if key not in cls._fields:
- # arbitrary keyword arguments are accepted
- continue
- pos = cls._fields.index(key)
- if pos < len(args):
- raise TypeError(f"{cls.__name__} got multiple values for argument {key!r}")
- if cls in _const_types:
- return Constant(*args, **kwargs)
- return Constant.__new__(cls, *args, **kwargs)
-
-class Num(Constant, metaclass=_ABC):
- _fields = ('n',)
- __new__ = _new
-
-class Str(Constant, metaclass=_ABC):
- _fields = ('s',)
- __new__ = _new
-
-class Bytes(Constant, metaclass=_ABC):
- _fields = ('s',)
- __new__ = _new
-
-class NameConstant(Constant, metaclass=_ABC):
- __new__ = _new
-
-class Ellipsis(Constant, metaclass=_ABC):
- _fields = ()
-
- def __new__(cls, *args, **kwargs):
- if cls is Ellipsis:
- return Constant(..., *args, **kwargs)
- return Constant.__new__(cls, *args, **kwargs)
-
-_const_types = {
- Num: (int, float, complex),
- Str: (str,),
- Bytes: (bytes,),
- NameConstant: (type(None), bool),
- Ellipsis: (type(...),),
-}
-_const_types_not = {
- Num: (bool,),
-}
-
-_const_node_type_names = {
- bool: 'NameConstant', # should be before int
- type(None): 'NameConstant',
- int: 'Num',
- float: 'Num',
- complex: 'Num',
- str: 'Str',
- bytes: 'Bytes',
- type(...): 'Ellipsis',
-}
-
-class slice(AST):
- """Deprecated AST node class."""
-
-class Index(slice):
- """Deprecated AST node class. Use the index value directly instead."""
- def __new__(cls, value, **kwargs):
- return value
-
-class ExtSlice(slice):
- """Deprecated AST node class. Use ast.Tuple instead."""
- def __new__(cls, dims=(), **kwargs):
- return Tuple(list(dims), Load(), **kwargs)
-
-# If the ast module is loaded more than once, only add deprecated methods once
-if not hasattr(Tuple, 'dims'):
- # The following code is for backward compatibility.
- # It will be removed in future.
-
- def _dims_getter(self):
- """Deprecated. Use elts instead."""
- return self.elts
-
- def _dims_setter(self, value):
- self.elts = value
-
- Tuple.dims = property(_dims_getter, _dims_setter)
-
-class Suite(mod):
- """Deprecated AST node class. Unused in Python 3."""
-
-class AugLoad(expr_context):
- """Deprecated AST node class. Unused in Python 3."""
-
-class AugStore(expr_context):
- """Deprecated AST node class. Unused in Python 3."""
-
-class Param(expr_context):
- """Deprecated AST node class. Unused in Python 3."""
-
-
-# Large float and imaginary literals get turned into infinities in the AST.
-# We unparse those infinities to INFSTR.
-_INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1)
-
-class _Precedence(IntEnum):
- """Precedence table that originated from python grammar."""
-
- TUPLE = auto()
- YIELD = auto() # 'yield', 'yield from'
- TEST = auto() # 'if'-'else', 'lambda'
- OR = auto() # 'or'
- AND = auto() # 'and'
- NOT = auto() # 'not'
- CMP = auto() # '<', '>', '==', '>=', '<=', '!=',
- # 'in', 'not in', 'is', 'is not'
- EXPR = auto()
- BOR = EXPR # '|'
- BXOR = auto() # '^'
- BAND = auto() # '&'
- SHIFT = auto() # '<<', '>>'
- ARITH = auto() # '+', '-'
- TERM = auto() # '*', '@', '/', '%', '//'
- FACTOR = auto() # unary '+', '-', '~'
- POWER = auto() # '**'
- AWAIT = auto() # 'await'
- ATOM = auto()
-
- def next(self):
- try:
- return self.__class__(self + 1)
- except ValueError:
- return self
-
-
-_SINGLE_QUOTES = ("'", '"')
-_MULTI_QUOTES = ('"""', "'''")
-_ALL_QUOTES = (*_SINGLE_QUOTES, *_MULTI_QUOTES)
-
-class _Unparser(NodeVisitor):
- """Methods in this class recursively traverse an AST and
- output source code for the abstract syntax; original formatting
- is disregarded."""
-
- def __init__(self, *, _avoid_backslashes=False):
- self._source = []
- self._buffer = []
- self._precedences = {}
- self._type_ignores = {}
- self._indent = 0
- self._avoid_backslashes = _avoid_backslashes
-
- def interleave(self, inter, f, seq):
- """Call f on each item in seq, calling inter() in between."""
- seq = iter(seq)
- try:
- f(next(seq))
- except StopIteration:
- pass
- else:
- for x in seq:
- inter()
- f(x)
-
- def items_view(self, traverser, items):
- """Traverse and separate the given *items* with a comma and append it to
- the buffer. If *items* is a single item sequence, a trailing comma
- will be added."""
- if len(items) == 1:
- traverser(items[0])
- self.write(",")
- else:
- self.interleave(lambda: self.write(", "), traverser, items)
-
- def maybe_newline(self):
- """Adds a newline if it isn't the start of generated source"""
- if self._source:
- self.write("\n")
-
- def fill(self, text=""):
- """Indent a piece of text and append it, according to the current
- indentation level"""
- self.maybe_newline()
- self.write(" " * self._indent + text)
-
- def write(self, text):
- """Append a piece of text"""
- self._source.append(text)
-
- def buffer_writer(self, text):
- self._buffer.append(text)
-
- @property
- def buffer(self):
- value = "".join(self._buffer)
- self._buffer.clear()
- return value
-
- @contextmanager
- def block(self, *, extra = None):
- """A context manager for preparing the source for blocks. It adds
- the character':', increases the indentation on enter and decreases
- the indentation on exit. If *extra* is given, it will be directly
- appended after the colon character.
- """
- self.write(":")
- if extra:
- self.write(extra)
- self._indent += 1
- yield
- self._indent -= 1
-
- @contextmanager
- def delimit(self, start, end):
- """A context manager for preparing the source for expressions. It adds
- *start* to the buffer and enters, after exit it adds *end*."""
-
- self.write(start)
- yield
- self.write(end)
-
- def delimit_if(self, start, end, condition):
- if condition:
- return self.delimit(start, end)
- else:
- return nullcontext()
-
- def require_parens(self, precedence, node):
- """Shortcut to adding precedence related parens"""
- return self.delimit_if("(", ")", self.get_precedence(node) > precedence)
-
- def get_precedence(self, node):
- return self._precedences.get(node, _Precedence.TEST)
-
- def set_precedence(self, precedence, *nodes):
- for node in nodes:
- self._precedences[node] = precedence
-
- def get_raw_docstring(self, node):
- """If a docstring node is found in the body of the *node* parameter,
- return that docstring node, None otherwise.
-
- Logic mirrored from ``_PyAST_GetDocString``."""
- if not isinstance(
- node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)
- ) or len(node.body) < 1:
- return None
- node = node.body[0]
- if not isinstance(node, Expr):
- return None
- node = node.value
- if isinstance(node, Constant) and isinstance(node.value, str):
- return node
-
- def get_type_comment(self, node):
- comment = self._type_ignores.get(node.lineno) or node.type_comment
- if comment is not None:
- return f" # type: {comment}"
-
- def traverse(self, node):
- if isinstance(node, list):
- for item in node:
- self.traverse(item)
- else:
- super().visit(node)
-
- # Note: as visit() resets the output text, do NOT rely on
- # NodeVisitor.generic_visit to handle any nodes (as it calls back in to
- # the subclass visit() method, which resets self._source to an empty list)
- def visit(self, node):
- """Outputs a source code string that, if converted back to an ast
- (using ast.parse) will generate an AST equivalent to *node*"""
- self._source = []
- self.traverse(node)
- return "".join(self._source)
-
- def _write_docstring_and_traverse_body(self, node):
- if (docstring := self.get_raw_docstring(node)):
- self._write_docstring(docstring)
- self.traverse(node.body[1:])
- else:
- self.traverse(node.body)
-
- def visit_Module(self, node):
- self._type_ignores = {
- ignore.lineno: f"ignore{ignore.tag}"
- for ignore in node.type_ignores
- }
- self._write_docstring_and_traverse_body(node)
- self._type_ignores.clear()
-
- def visit_FunctionType(self, node):
- with self.delimit("(", ")"):
- self.interleave(
- lambda: self.write(", "), self.traverse, node.argtypes
- )
-
- self.write(" -> ")
- self.traverse(node.returns)
-
- def visit_Expr(self, node):
- self.fill()
- self.set_precedence(_Precedence.YIELD, node.value)
- self.traverse(node.value)
-
- def visit_NamedExpr(self, node):
- with self.require_parens(_Precedence.TUPLE, node):
- self.set_precedence(_Precedence.ATOM, node.target, node.value)
- self.traverse(node.target)
- self.write(" := ")
- self.traverse(node.value)
-
- def visit_Import(self, node):
- self.fill("import ")
- self.interleave(lambda: self.write(", "), self.traverse, node.names)
-
- def visit_ImportFrom(self, node):
- self.fill("from ")
- self.write("." * node.level)
- if node.module:
- self.write(node.module)
- self.write(" import ")
- self.interleave(lambda: self.write(", "), self.traverse, node.names)
-
- def visit_Assign(self, node):
- self.fill()
- for target in node.targets:
- self.traverse(target)
- self.write(" = ")
- self.traverse(node.value)
- if type_comment := self.get_type_comment(node):
- self.write(type_comment)
-
- def visit_AugAssign(self, node):
- self.fill()
- self.traverse(node.target)
- self.write(" " + self.binop[node.op.__class__.__name__] + "= ")
- self.traverse(node.value)
-
- def visit_AnnAssign(self, node):
- self.fill()
- with self.delimit_if("(", ")", not node.simple and isinstance(node.target, Name)):
- self.traverse(node.target)
- self.write(": ")
- self.traverse(node.annotation)
- if node.value:
- self.write(" = ")
- self.traverse(node.value)
-
- def visit_Return(self, node):
- self.fill("return")
- if node.value:
- self.write(" ")
- self.traverse(node.value)
-
- def visit_Pass(self, node):
- self.fill("pass")
-
- def visit_Break(self, node):
- self.fill("break")
-
- def visit_Continue(self, node):
- self.fill("continue")
-
- def visit_Delete(self, node):
- self.fill("del ")
- self.interleave(lambda: self.write(", "), self.traverse, node.targets)
-
- def visit_Assert(self, node):
- self.fill("assert ")
- self.traverse(node.test)
- if node.msg:
- self.write(", ")
- self.traverse(node.msg)
-
- def visit_Global(self, node):
- self.fill("global ")
- self.interleave(lambda: self.write(", "), self.write, node.names)
-
- def visit_Nonlocal(self, node):
- self.fill("nonlocal ")
- self.interleave(lambda: self.write(", "), self.write, node.names)
-
- def visit_Await(self, node):
- with self.require_parens(_Precedence.AWAIT, node):
- self.write("await")
- if node.value:
- self.write(" ")
- self.set_precedence(_Precedence.ATOM, node.value)
- self.traverse(node.value)
-
- def visit_Yield(self, node):
- with self.require_parens(_Precedence.YIELD, node):
- self.write("yield")
- if node.value:
- self.write(" ")
- self.set_precedence(_Precedence.ATOM, node.value)
- self.traverse(node.value)
-
- def visit_YieldFrom(self, node):
- with self.require_parens(_Precedence.YIELD, node):
- self.write("yield from ")
- if not node.value:
- raise ValueError("Node can't be used without a value attribute.")
- self.set_precedence(_Precedence.ATOM, node.value)
- self.traverse(node.value)
-
- def visit_Raise(self, node):
- self.fill("raise")
- if not node.exc:
- if node.cause:
- raise ValueError(f"Node can't use cause without an exception.")
- return
- self.write(" ")
- self.traverse(node.exc)
- if node.cause:
- self.write(" from ")
- self.traverse(node.cause)
-
- def visit_Try(self, node):
- self.fill("try")
- with self.block():
- self.traverse(node.body)
- for ex in node.handlers:
- self.traverse(ex)
- if node.orelse:
- self.fill("else")
- with self.block():
- self.traverse(node.orelse)
- if node.finalbody:
- self.fill("finally")
- with self.block():
- self.traverse(node.finalbody)
-
- def visit_ExceptHandler(self, node):
- self.fill("except")
- if node.type:
- self.write(" ")
- self.traverse(node.type)
- if node.name:
- self.write(" as ")
- self.write(node.name)
- with self.block():
- self.traverse(node.body)
-
- def visit_ClassDef(self, node):
- self.maybe_newline()
- for deco in node.decorator_list:
- self.fill("@")
- self.traverse(deco)
- self.fill("class " + node.name)
- with self.delimit_if("(", ")", condition = node.bases or node.keywords):
- comma = False
- for e in node.bases:
- if comma:
- self.write(", ")
- else:
- comma = True
- self.traverse(e)
- for e in node.keywords:
- if comma:
- self.write(", ")
- else:
- comma = True
- self.traverse(e)
-
- with self.block():
- self._write_docstring_and_traverse_body(node)
-
- def visit_FunctionDef(self, node):
- self._function_helper(node, "def")
-
- def visit_AsyncFunctionDef(self, node):
- self._function_helper(node, "async def")
-
- def _function_helper(self, node, fill_suffix):
- self.maybe_newline()
- for deco in node.decorator_list:
- self.fill("@")
- self.traverse(deco)
- def_str = fill_suffix + " " + node.name
- self.fill(def_str)
- with self.delimit("(", ")"):
- self.traverse(node.args)
- if node.returns:
- self.write(" -> ")
- self.traverse(node.returns)
- with self.block(extra=self.get_type_comment(node)):
- self._write_docstring_and_traverse_body(node)
-
- def visit_For(self, node):
- self._for_helper("for ", node)
-
- def visit_AsyncFor(self, node):
- self._for_helper("async for ", node)
-
- def _for_helper(self, fill, node):
- self.fill(fill)
- self.traverse(node.target)
- self.write(" in ")
- self.traverse(node.iter)
- with self.block(extra=self.get_type_comment(node)):
- self.traverse(node.body)
- if node.orelse:
- self.fill("else")
- with self.block():
- self.traverse(node.orelse)
-
- def visit_If(self, node):
- self.fill("if ")
- self.traverse(node.test)
- with self.block():
- self.traverse(node.body)
- # collapse nested ifs into equivalent elifs.
- while node.orelse and len(node.orelse) == 1 and isinstance(node.orelse[0], If):
- node = node.orelse[0]
- self.fill("elif ")
- self.traverse(node.test)
- with self.block():
- self.traverse(node.body)
- # final else
- if node.orelse:
- self.fill("else")
- with self.block():
- self.traverse(node.orelse)
-
- def visit_While(self, node):
- self.fill("while ")
- self.traverse(node.test)
- with self.block():
- self.traverse(node.body)
- if node.orelse:
- self.fill("else")
- with self.block():
- self.traverse(node.orelse)
-
- def visit_With(self, node):
- self.fill("with ")
- self.interleave(lambda: self.write(", "), self.traverse, node.items)
- with self.block(extra=self.get_type_comment(node)):
- self.traverse(node.body)
-
- def visit_AsyncWith(self, node):
- self.fill("async with ")
- self.interleave(lambda: self.write(", "), self.traverse, node.items)
- with self.block(extra=self.get_type_comment(node)):
- self.traverse(node.body)
-
- def _str_literal_helper(
- self, string, *, quote_types=_ALL_QUOTES, escape_special_whitespace=False
- ):
- """Helper for writing string literals, minimizing escapes.
- Returns the tuple (string literal to write, possible quote types).
- """
- def escape_char(c):
- # \n and \t are non-printable, but we only escape them if
- # escape_special_whitespace is True
- if not escape_special_whitespace and c in "\n\t":
- return c
- # Always escape backslashes and other non-printable characters
- if c == "\\" or not c.isprintable():
- return c.encode("unicode_escape").decode("ascii")
- return c
-
- escaped_string = "".join(map(escape_char, string))
- possible_quotes = quote_types
- if "\n" in escaped_string:
- possible_quotes = [q for q in possible_quotes if q in _MULTI_QUOTES]
- possible_quotes = [q for q in possible_quotes if q not in escaped_string]
- if not possible_quotes:
- # If there aren't any possible_quotes, fallback to using repr
- # on the original string. Try to use a quote from quote_types,
- # e.g., so that we use triple quotes for docstrings.
- string = repr(string)
- quote = next((q for q in quote_types if string[0] in q), string[0])
- return string[1:-1], [quote]
- if escaped_string:
- # Sort so that we prefer '''"''' over """\""""
- possible_quotes.sort(key=lambda q: q[0] == escaped_string[-1])
- # If we're using triple quotes and we'd need to escape a final
- # quote, escape it
- if possible_quotes[0][0] == escaped_string[-1]:
- assert len(possible_quotes[0]) == 3
- escaped_string = escaped_string[:-1] + "\\" + escaped_string[-1]
- return escaped_string, possible_quotes
-
- def _write_str_avoiding_backslashes(self, string, *, quote_types=_ALL_QUOTES):
- """Write string literal value with a best effort attempt to avoid backslashes."""
- string, quote_types = self._str_literal_helper(string, quote_types=quote_types)
- quote_type = quote_types[0]
- self.write(f"{quote_type}{string}{quote_type}")
-
- def visit_JoinedStr(self, node):
- self.write("f")
- if self._avoid_backslashes:
- self._fstring_JoinedStr(node, self.buffer_writer)
- self._write_str_avoiding_backslashes(self.buffer)
- return
-
- # If we don't need to avoid backslashes globally (i.e., we only need
- # to avoid them inside FormattedValues), it's cosmetically preferred
- # to use escaped whitespace. That is, it's preferred to use backslashes
- # for cases like: f"{x}\n". To accomplish this, we keep track of what
- # in our buffer corresponds to FormattedValues and what corresponds to
- # Constant parts of the f-string, and allow escapes accordingly.
- buffer = []
- for value in node.values:
- meth = getattr(self, "_fstring_" + type(value).__name__)
- meth(value, self.buffer_writer)
- buffer.append((self.buffer, isinstance(value, Constant)))
- new_buffer = []
- quote_types = _ALL_QUOTES
- for value, is_constant in buffer:
- # Repeatedly narrow down the list of possible quote_types
- value, quote_types = self._str_literal_helper(
- value, quote_types=quote_types,
- escape_special_whitespace=is_constant
- )
- new_buffer.append(value)
- value = "".join(new_buffer)
- quote_type = quote_types[0]
- self.write(f"{quote_type}{value}{quote_type}")
-
- def visit_FormattedValue(self, node):
- self.write("f")
- self._fstring_FormattedValue(node, self.buffer_writer)
- self._write_str_avoiding_backslashes(self.buffer)
-
- def _fstring_JoinedStr(self, node, write):
- for value in node.values:
- meth = getattr(self, "_fstring_" + type(value).__name__)
- meth(value, write)
-
- def _fstring_Constant(self, node, write):
- if not isinstance(node.value, str):
- raise ValueError("Constants inside JoinedStr should be a string.")
- value = node.value.replace("{", "{{").replace("}", "}}")
- write(value)
-
- def _fstring_FormattedValue(self, node, write):
- write("{")
- unparser = type(self)(_avoid_backslashes=True)
- unparser.set_precedence(_Precedence.TEST.next(), node.value)
- expr = unparser.visit(node.value)
- if expr.startswith("{"):
- write(" ") # Separate pair of opening brackets as "{ {"
- if "\\" in expr:
- raise ValueError("Unable to avoid backslash in f-string expression part")
- write(expr)
- if node.conversion != -1:
- conversion = chr(node.conversion)
- if conversion not in "sra":
- raise ValueError("Unknown f-string conversion.")
- write(f"!{conversion}")
- if node.format_spec:
- write(":")
- meth = getattr(self, "_fstring_" + type(node.format_spec).__name__)
- meth(node.format_spec, write)
- write("}")
-
- def visit_Name(self, node):
- self.write(node.id)
-
- def _write_docstring(self, node):
- self.fill()
- if node.kind == "u":
- self.write("u")
- self._write_str_avoiding_backslashes(node.value, quote_types=_MULTI_QUOTES)
-
- def _write_constant(self, value):
- if isinstance(value, (float, complex)):
- # Substitute overflowing decimal literal for AST infinities,
- # and inf - inf for NaNs.
- self.write(
- repr(value)
- .replace("inf", _INFSTR)
- .replace("nan", f"({_INFSTR}-{_INFSTR})")
- )
- elif self._avoid_backslashes and isinstance(value, str):
- self._write_str_avoiding_backslashes(value)
- else:
- self.write(repr(value))
-
- def visit_Constant(self, node):
- value = node.value
- if isinstance(value, tuple):
- with self.delimit("(", ")"):
- self.items_view(self._write_constant, value)
- elif value is ...:
- self.write("...")
- else:
- if node.kind == "u":
- self.write("u")
- self._write_constant(node.value)
-
- def visit_List(self, node):
- with self.delimit("[", "]"):
- self.interleave(lambda: self.write(", "), self.traverse, node.elts)
-
- def visit_ListComp(self, node):
- with self.delimit("[", "]"):
- self.traverse(node.elt)
- for gen in node.generators:
- self.traverse(gen)
-
- def visit_GeneratorExp(self, node):
- with self.delimit("(", ")"):
- self.traverse(node.elt)
- for gen in node.generators:
- self.traverse(gen)
-
- def visit_SetComp(self, node):
- with self.delimit("{", "}"):
- self.traverse(node.elt)
- for gen in node.generators:
- self.traverse(gen)
-
- def visit_DictComp(self, node):
- with self.delimit("{", "}"):
- self.traverse(node.key)
- self.write(": ")
- self.traverse(node.value)
- for gen in node.generators:
- self.traverse(gen)
-
- def visit_comprehension(self, node):
- if node.is_async:
- self.write(" async for ")
- else:
- self.write(" for ")
- self.set_precedence(_Precedence.TUPLE, node.target)
- self.traverse(node.target)
- self.write(" in ")
- self.set_precedence(_Precedence.TEST.next(), node.iter, *node.ifs)
- self.traverse(node.iter)
- for if_clause in node.ifs:
- self.write(" if ")
- self.traverse(if_clause)
-
- def visit_IfExp(self, node):
- with self.require_parens(_Precedence.TEST, node):
- self.set_precedence(_Precedence.TEST.next(), node.body, node.test)
- self.traverse(node.body)
- self.write(" if ")
- self.traverse(node.test)
- self.write(" else ")
- self.set_precedence(_Precedence.TEST, node.orelse)
- self.traverse(node.orelse)
-
- def visit_Set(self, node):
- if node.elts:
- with self.delimit("{", "}"):
- self.interleave(lambda: self.write(", "), self.traverse, node.elts)
- else:
- # `{}` would be interpreted as a dictionary literal, and
- # `set` might be shadowed. Thus:
- self.write('{*()}')
-
- def visit_Dict(self, node):
- def write_key_value_pair(k, v):
- self.traverse(k)
- self.write(": ")
- self.traverse(v)
-
- def write_item(item):
- k, v = item
- if k is None:
- # for dictionary unpacking operator in dicts {**{'y': 2}}
- # see PEP 448 for details
- self.write("**")
- self.set_precedence(_Precedence.EXPR, v)
- self.traverse(v)
- else:
- write_key_value_pair(k, v)
-
- with self.delimit("{", "}"):
- self.interleave(
- lambda: self.write(", "), write_item, zip(node.keys, node.values)
- )
-
- def visit_Tuple(self, node):
- with self.delimit("(", ")"):
- self.items_view(self.traverse, node.elts)
-
- unop = {"Invert": "~", "Not": "not", "UAdd": "+", "USub": "-"}
- unop_precedence = {
- "not": _Precedence.NOT,
- "~": _Precedence.FACTOR,
- "+": _Precedence.FACTOR,
- "-": _Precedence.FACTOR,
- }
-
- def visit_UnaryOp(self, node):
- operator = self.unop[node.op.__class__.__name__]
- operator_precedence = self.unop_precedence[operator]
- with self.require_parens(operator_precedence, node):
- self.write(operator)
- # factor prefixes (+, -, ~) shouldn't be seperated
- # from the value they belong, (e.g: +1 instead of + 1)
- if operator_precedence is not _Precedence.FACTOR:
- self.write(" ")
- self.set_precedence(operator_precedence, node.operand)
- self.traverse(node.operand)
-
- binop = {
- "Add": "+",
- "Sub": "-",
- "Mult": "*",
- "MatMult": "@",
- "Div": "/",
- "Mod": "%",
- "LShift": "<<",
- "RShift": ">>",
- "BitOr": "|",
- "BitXor": "^",
- "BitAnd": "&",
- "FloorDiv": "//",
- "Pow": "**",
- }
-
- binop_precedence = {
- "+": _Precedence.ARITH,
- "-": _Precedence.ARITH,
- "*": _Precedence.TERM,
- "@": _Precedence.TERM,
- "/": _Precedence.TERM,
- "%": _Precedence.TERM,
- "<<": _Precedence.SHIFT,
- ">>": _Precedence.SHIFT,
- "|": _Precedence.BOR,
- "^": _Precedence.BXOR,
- "&": _Precedence.BAND,
- "//": _Precedence.TERM,
- "**": _Precedence.POWER,
- }
-
- binop_rassoc = frozenset(("**",))
- def visit_BinOp(self, node):
- operator = self.binop[node.op.__class__.__name__]
- operator_precedence = self.binop_precedence[operator]
- with self.require_parens(operator_precedence, node):
- if operator in self.binop_rassoc:
- left_precedence = operator_precedence.next()
- right_precedence = operator_precedence
- else:
- left_precedence = operator_precedence
- right_precedence = operator_precedence.next()
-
- self.set_precedence(left_precedence, node.left)
- self.traverse(node.left)
- self.write(f" {operator} ")
- self.set_precedence(right_precedence, node.right)
- self.traverse(node.right)
-
- cmpops = {
- "Eq": "==",
- "NotEq": "!=",
- "Lt": "<",
- "LtE": "<=",
- "Gt": ">",
- "GtE": ">=",
- "Is": "is",
- "IsNot": "is not",
- "In": "in",
- "NotIn": "not in",
- }
-
- def visit_Compare(self, node):
- with self.require_parens(_Precedence.CMP, node):
- self.set_precedence(_Precedence.CMP.next(), node.left, *node.comparators)
- self.traverse(node.left)
- for o, e in zip(node.ops, node.comparators):
- self.write(" " + self.cmpops[o.__class__.__name__] + " ")
- self.traverse(e)
-
- boolops = {"And": "and", "Or": "or"}
- boolop_precedence = {"and": _Precedence.AND, "or": _Precedence.OR}
-
- def visit_BoolOp(self, node):
- operator = self.boolops[node.op.__class__.__name__]
- operator_precedence = self.boolop_precedence[operator]
-
- def increasing_level_traverse(node):
- nonlocal operator_precedence
- operator_precedence = operator_precedence.next()
- self.set_precedence(operator_precedence, node)
- self.traverse(node)
-
- with self.require_parens(operator_precedence, node):
- s = f" {operator} "
- self.interleave(lambda: self.write(s), increasing_level_traverse, node.values)
-
- def visit_Attribute(self, node):
- self.set_precedence(_Precedence.ATOM, node.value)
- self.traverse(node.value)
- # Special case: 3.__abs__() is a syntax error, so if node.value
- # is an integer literal then we need to either parenthesize
- # it or add an extra space to get 3 .__abs__().
- if isinstance(node.value, Constant) and isinstance(node.value.value, int):
- self.write(" ")
- self.write(".")
- self.write(node.attr)
-
- def visit_Call(self, node):
- self.set_precedence(_Precedence.ATOM, node.func)
- self.traverse(node.func)
- with self.delimit("(", ")"):
- comma = False
- for e in node.args:
- if comma:
- self.write(", ")
- else:
- comma = True
- self.traverse(e)
- for e in node.keywords:
- if comma:
- self.write(", ")
- else:
- comma = True
- self.traverse(e)
-
- def visit_Subscript(self, node):
- def is_simple_tuple(slice_value):
- # when unparsing a non-empty tuple, the parentheses can be safely
- # omitted if there aren't any elements that explicitly requires
- # parentheses (such as starred expressions).
- return (
- isinstance(slice_value, Tuple)
- and slice_value.elts
- and not any(isinstance(elt, Starred) for elt in slice_value.elts)
- )
-
- self.set_precedence(_Precedence.ATOM, node.value)
- self.traverse(node.value)
- with self.delimit("[", "]"):
- if is_simple_tuple(node.slice):
- self.items_view(self.traverse, node.slice.elts)
- else:
- self.traverse(node.slice)
-
- def visit_Starred(self, node):
- self.write("*")
- self.set_precedence(_Precedence.EXPR, node.value)
- self.traverse(node.value)
-
- def visit_Ellipsis(self, node):
- self.write("...")
-
- def visit_Slice(self, node):
- if node.lower:
- self.traverse(node.lower)
- self.write(":")
- if node.upper:
- self.traverse(node.upper)
- if node.step:
- self.write(":")
- self.traverse(node.step)
-
- def visit_Match(self, node):
- self.fill("match ")
- self.traverse(node.subject)
- with self.block():
- for case in node.cases:
- self.traverse(case)
-
- def visit_arg(self, node):
- self.write(node.arg)
- if node.annotation:
- self.write(": ")
- self.traverse(node.annotation)
-
- def visit_arguments(self, node):
- first = True
- # normal arguments
- all_args = node.posonlyargs + node.args
- defaults = [None] * (len(all_args) - len(node.defaults)) + node.defaults
- for index, elements in enumerate(zip(all_args, defaults), 1):
- a, d = elements
- if first:
- first = False
- else:
- self.write(", ")
- self.traverse(a)
- if d:
- self.write("=")
- self.traverse(d)
- if index == len(node.posonlyargs):
- self.write(", /")
-
- # varargs, or bare '*' if no varargs but keyword-only arguments present
- if node.vararg or node.kwonlyargs:
- if first:
- first = False
- else:
- self.write(", ")
- self.write("*")
- if node.vararg:
- self.write(node.vararg.arg)
- if node.vararg.annotation:
- self.write(": ")
- self.traverse(node.vararg.annotation)
-
- # keyword-only arguments
- if node.kwonlyargs:
- for a, d in zip(node.kwonlyargs, node.kw_defaults):
- self.write(", ")
- self.traverse(a)
- if d:
- self.write("=")
- self.traverse(d)
-
- # kwargs
- if node.kwarg:
- if first:
- first = False
- else:
- self.write(", ")
- self.write("**" + node.kwarg.arg)
- if node.kwarg.annotation:
- self.write(": ")
- self.traverse(node.kwarg.annotation)
-
- def visit_keyword(self, node):
- if node.arg is None:
- self.write("**")
- else:
- self.write(node.arg)
- self.write("=")
- self.traverse(node.value)
-
- def visit_Lambda(self, node):
- with self.require_parens(_Precedence.TEST, node):
- self.write("lambda ")
- self.traverse(node.args)
- self.write(": ")
- self.set_precedence(_Precedence.TEST, node.body)
- self.traverse(node.body)
-
- def visit_alias(self, node):
- self.write(node.name)
- if node.asname:
- self.write(" as " + node.asname)
-
- def visit_withitem(self, node):
- self.traverse(node.context_expr)
- if node.optional_vars:
- self.write(" as ")
- self.traverse(node.optional_vars)
-
- def visit_match_case(self, node):
- self.fill("case ")
- self.traverse(node.pattern)
- if node.guard:
- self.write(" if ")
- self.traverse(node.guard)
- with self.block():
- self.traverse(node.body)
-
- def visit_MatchValue(self, node):
- self.traverse(node.value)
-
- def visit_MatchSingleton(self, node):
- self._write_constant(node.value)
-
- def visit_MatchSequence(self, node):
- with self.delimit("[", "]"):
- self.interleave(
- lambda: self.write(", "), self.traverse, node.patterns
- )
-
- def visit_MatchStar(self, node):
- name = node.name
- if name is None:
- name = "_"
- self.write(f"*{name}")
-
- def visit_MatchMapping(self, node):
- def write_key_pattern_pair(pair):
- k, p = pair
- self.traverse(k)
- self.write(": ")
- self.traverse(p)
-
- with self.delimit("{", "}"):
- keys = node.keys
- self.interleave(
- lambda: self.write(", "),
- write_key_pattern_pair,
- zip(keys, node.patterns, strict=True),
- )
- rest = node.rest
- if rest is not None:
- if keys:
- self.write(", ")
- self.write(f"**{rest}")
-
- def visit_MatchClass(self, node):
- self.set_precedence(_Precedence.ATOM, node.cls)
- self.traverse(node.cls)
- with self.delimit("(", ")"):
- patterns = node.patterns
- self.interleave(
- lambda: self.write(", "), self.traverse, patterns
- )
- attrs = node.kwd_attrs
- if attrs:
- def write_attr_pattern(pair):
- attr, pattern = pair
- self.write(f"{attr}=")
- self.traverse(pattern)
-
- if patterns:
- self.write(", ")
- self.interleave(
- lambda: self.write(", "),
- write_attr_pattern,
- zip(attrs, node.kwd_patterns, strict=True),
- )
-
- def visit_MatchAs(self, node):
- name = node.name
- pattern = node.pattern
- if name is None:
- self.write("_")
- elif pattern is None:
- self.write(node.name)
- else:
- with self.require_parens(_Precedence.TEST, node):
- self.set_precedence(_Precedence.BOR, node.pattern)
- self.traverse(node.pattern)
- self.write(f" as {node.name}")
-
- def visit_MatchOr(self, node):
- with self.require_parens(_Precedence.BOR, node):
- self.set_precedence(_Precedence.BOR.next(), *node.patterns)
- self.interleave(lambda: self.write(" | "), self.traverse, node.patterns)
-
-def unparse(ast_obj):
- unparser = _Unparser()
- return unparser.visit(ast_obj)
-
-
-def main():
- import argparse
-
- parser = argparse.ArgumentParser(prog='python -m ast')
- parser.add_argument('infile', type=argparse.FileType(mode='rb'), nargs='?',
- default='-',
- help='the file to parse; defaults to stdin')
- parser.add_argument('-m', '--mode', default='exec',
- choices=('exec', 'single', 'eval', 'func_type'),
- help='specify what kind of code must be parsed')
- parser.add_argument('--no-type-comments', default=True, action='store_false',
- help="don't add information about type comments")
- parser.add_argument('-a', '--include-attributes', action='store_true',
- help='include attributes such as line numbers and '
- 'column offsets')
- parser.add_argument('-i', '--indent', type=int, default=3,
- help='indentation of nodes (number of spaces)')
- args = parser.parse_args()
-
- with args.infile as infile:
- source = infile.read()
- tree = parse(source, args.infile.name, args.mode, type_comments=args.no_type_comments)
- print(dump(tree, include_attributes=args.include_attributes, indent=args.indent))
-
-if __name__ == '__main__':
- main()
diff --git a/lib/python3.10/asynchat.py b/lib/python3.10/asynchat.py
deleted file mode 100644
index de26ffa..0000000
--- a/lib/python3.10/asynchat.py
+++ /dev/null
@@ -1,315 +0,0 @@
-# -*- Mode: Python; tab-width: 4 -*-
-# Id: asynchat.py,v 2.26 2000/09/07 22:29:26 rushing Exp
-# Author: Sam Rushing <rushing@nightmare.com>
-
-# ======================================================================
-# Copyright 1996 by Sam Rushing
-#
-# All Rights Reserved
-#
-# Permission to use, copy, modify, and distribute this software and
-# its documentation for any purpose and without fee is hereby
-# granted, provided that the above copyright notice appear in all
-# copies and that both that copyright notice and this permission
-# notice appear in supporting documentation, and that the name of Sam
-# Rushing not be used in advertising or publicity pertaining to
-# distribution of the software without specific, written prior
-# permission.
-#
-# SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
-# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
-# NO EVENT SHALL SAM RUSHING 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.
-# ======================================================================
-
-r"""A class supporting chat-style (command/response) protocols.
-
-This class adds support for 'chat' style protocols - where one side
-sends a 'command', and the other sends a response (examples would be
-the common internet protocols - smtp, nntp, ftp, etc..).
-
-The handle_read() method looks at the input stream for the current
-'terminator' (usually '\r\n' for single-line responses, '\r\n.\r\n'
-for multi-line output), calling self.found_terminator() on its
-receipt.
-
-for example:
-Say you build an async nntp client using this class. At the start
-of the connection, you'll have self.terminator set to '\r\n', in
-order to process the single-line greeting. Just before issuing a
-'LIST' command you'll set it to '\r\n.\r\n'. The output of the LIST
-command will be accumulated (using your own 'collect_incoming_data'
-method) up to the terminator, and then control will be returned to
-you - by calling your self.found_terminator() method.
-"""
-import asyncore
-from collections import deque
-
-from warnings import warn
-warn(
- 'The asynchat module is deprecated. '
- 'The recommended replacement is asyncio',
- DeprecationWarning,
- stacklevel=2)
-
-
-
-class async_chat(asyncore.dispatcher):
- """This is an abstract class. You must derive from this class, and add
- the two methods collect_incoming_data() and found_terminator()"""
-
- # these are overridable defaults
-
- ac_in_buffer_size = 65536
- ac_out_buffer_size = 65536
-
- # we don't want to enable the use of encoding by default, because that is a
- # sign of an application bug that we don't want to pass silently
-
- use_encoding = 0
- encoding = 'latin-1'
-
- def __init__(self, sock=None, map=None):
- # for string terminator matching
- self.ac_in_buffer = b''
-
- # we use a list here rather than io.BytesIO for a few reasons...
- # del lst[:] is faster than bio.truncate(0)
- # lst = [] is faster than bio.truncate(0)
- self.incoming = []
-
- # we toss the use of the "simple producer" and replace it with
- # a pure deque, which the original fifo was a wrapping of
- self.producer_fifo = deque()
- asyncore.dispatcher.__init__(self, sock, map)
-
- def collect_incoming_data(self, data):
- raise NotImplementedError("must be implemented in subclass")
-
- def _collect_incoming_data(self, data):
- self.incoming.append(data)
-
- def _get_data(self):
- d = b''.join(self.incoming)
- del self.incoming[:]
- return d
-
- def found_terminator(self):
- raise NotImplementedError("must be implemented in subclass")
-
- def set_terminator(self, term):
- """Set the input delimiter.
-
- Can be a fixed string of any length, an integer, or None.
- """
- if isinstance(term, str) and self.use_encoding:
- term = bytes(term, self.encoding)
- elif isinstance(term, int) and term < 0:
- raise ValueError('the number of received bytes must be positive')
- self.terminator = term
-
- def get_terminator(self):
- return self.terminator
-
- # grab some more data from the socket,
- # throw it to the collector method,
- # check for the terminator,
- # if found, transition to the next state.
-
- def handle_read(self):
-
- try:
- data = self.recv(self.ac_in_buffer_size)
- except BlockingIOError:
- return
- except OSError:
- self.handle_error()
- return
-
- if isinstance(data, str) and self.use_encoding:
- data = bytes(str, self.encoding)
- self.ac_in_buffer = self.ac_in_buffer + data
-
- # Continue to search for self.terminator in self.ac_in_buffer,
- # while calling self.collect_incoming_data. The while loop
- # is necessary because we might read several data+terminator
- # combos with a single recv(4096).
-
- while self.ac_in_buffer:
- lb = len(self.ac_in_buffer)
- terminator = self.get_terminator()
- if not terminator:
- # no terminator, collect it all
- self.collect_incoming_data(self.ac_in_buffer)
- self.ac_in_buffer = b''
- elif isinstance(terminator, int):
- # numeric terminator
- n = terminator
- if lb < n:
- self.collect_incoming_data(self.ac_in_buffer)
- self.ac_in_buffer = b''
- self.terminator = self.terminator - lb
- else:
- self.collect_incoming_data(self.ac_in_buffer[:n])
- self.ac_in_buffer = self.ac_in_buffer[n:]
- self.terminator = 0
- self.found_terminator()
- else:
- # 3 cases:
- # 1) end of buffer matches terminator exactly:
- # collect data, transition
- # 2) end of buffer matches some prefix:
- # collect data to the prefix
- # 3) end of buffer does not match any prefix:
- # collect data
- terminator_len = len(terminator)
- index = self.ac_in_buffer.find(terminator)
- if index != -1:
- # we found the terminator
- if index > 0:
- # don't bother reporting the empty string
- # (source of subtle bugs)
- self.collect_incoming_data(self.ac_in_buffer[:index])
- self.ac_in_buffer = self.ac_in_buffer[index+terminator_len:]
- # This does the Right Thing if the terminator
- # is changed here.
- self.found_terminator()
- else:
- # check for a prefix of the terminator
- index = find_prefix_at_end(self.ac_in_buffer, terminator)
- if index:
- if index != lb:
- # we found a prefix, collect up to the prefix
- self.collect_incoming_data(self.ac_in_buffer[:-index])
- self.ac_in_buffer = self.ac_in_buffer[-index:]
- break
- else:
- # no prefix, collect it all
- self.collect_incoming_data(self.ac_in_buffer)
- self.ac_in_buffer = b''
-
- def handle_write(self):
- self.initiate_send()
-
- def handle_close(self):
- self.close()
-
- def push(self, data):
- if not isinstance(data, (bytes, bytearray, memoryview)):
- raise TypeError('data argument must be byte-ish (%r)',
- type(data))
- sabs = self.ac_out_buffer_size
- if len(data) > sabs:
- for i in range(0, len(data), sabs):
- self.producer_fifo.append(data[i:i+sabs])
- else:
- self.producer_fifo.append(data)
- self.initiate_send()
-
- def push_with_producer(self, producer):
- self.producer_fifo.append(producer)
- self.initiate_send()
-
- def readable(self):
- "predicate for inclusion in the readable for select()"
- # cannot use the old predicate, it violates the claim of the
- # set_terminator method.
-
- # return (len(self.ac_in_buffer) <= self.ac_in_buffer_size)
- return 1
-
- def writable(self):
- "predicate for inclusion in the writable for select()"
- return self.producer_fifo or (not self.connected)
-
- def close_when_done(self):
- "automatically close this channel once the outgoing queue is empty"
- self.producer_fifo.append(None)
-
- def initiate_send(self):
- while self.producer_fifo and self.connected:
- first = self.producer_fifo[0]
- # handle empty string/buffer or None entry
- if not first:
- del self.producer_fifo[0]
- if first is None:
- self.handle_close()
- return
-
- # handle classic producer behavior
- obs = self.ac_out_buffer_size
- try:
- data = first[:obs]
- except TypeError:
- data = first.more()
- if data:
- self.producer_fifo.appendleft(data)
- else:
- del self.producer_fifo[0]
- continue
-
- if isinstance(data, str) and self.use_encoding:
- data = bytes(data, self.encoding)
-
- # send the data
- try:
- num_sent = self.send(data)
- except OSError:
- self.handle_error()
- return
-
- if num_sent:
- if num_sent < len(data) or obs < len(first):
- self.producer_fifo[0] = first[num_sent:]
- else:
- del self.producer_fifo[0]
- # we tried to send some actual data
- return
-
- def discard_buffers(self):
- # Emergencies only!
- self.ac_in_buffer = b''
- del self.incoming[:]
- self.producer_fifo.clear()
-
-
-class simple_producer:
-
- def __init__(self, data, buffer_size=512):
- self.data = data
- self.buffer_size = buffer_size
-
- def more(self):
- if len(self.data) > self.buffer_size:
- result = self.data[:self.buffer_size]
- self.data = self.data[self.buffer_size:]
- return result
- else:
- result = self.data
- self.data = b''
- return result
-
-
-# Given 'haystack', see if any prefix of 'needle' is at its end. This
-# assumes an exact match has already been checked. Return the number of
-# characters matched.
-# for example:
-# f_p_a_e("qwerty\r", "\r\n") => 1
-# f_p_a_e("qwertydkjf", "\r\n") => 0
-# f_p_a_e("qwerty\r\n", "\r\n") => <undefined>
-
-# this could maybe be made faster with a computed regex?
-# [answer: no; circa Python-2.0, Jan 2001]
-# new python: 28961/s
-# old python: 18307/s
-# re: 12820/s
-# regex: 14035/s
-
-def find_prefix_at_end(haystack, needle):
- l = len(needle) - 1
- while l and not haystack.endswith(needle[:l]):
- l -= 1
- return l
diff --git a/lib/python3.10/asyncio/__init__.py b/lib/python3.10/asyncio/__init__.py
deleted file mode 100644
index 200b14c..0000000
--- a/lib/python3.10/asyncio/__init__.py
+++ /dev/null
@@ -1,43 +0,0 @@
-"""The asyncio package, tracking PEP 3156."""
-
-# flake8: noqa
-
-import sys
-
-# This relies on each of the submodules having an __all__ variable.
-from .base_events import *
-from .coroutines import *
-from .events import *
-from .exceptions import *
-from .futures import *
-from .locks import *
-from .protocols import *
-from .runners import *
-from .queues import *
-from .streams import *
-from .subprocess import *
-from .tasks import *
-from .threads import *
-from .transports import *
-
-__all__ = (base_events.__all__ +
- coroutines.__all__ +
- events.__all__ +
- exceptions.__all__ +
- futures.__all__ +
- locks.__all__ +
- protocols.__all__ +
- runners.__all__ +
- queues.__all__ +
- streams.__all__ +
- subprocess.__all__ +
- tasks.__all__ +
- threads.__all__ +
- transports.__all__)
-
-if sys.platform == 'win32': # pragma: no cover
- from .windows_events import *
- __all__ += windows_events.__all__
-else:
- from .unix_events import * # pragma: no cover
- __all__ += unix_events.__all__
diff --git a/lib/python3.10/asyncio/base_events.py b/lib/python3.10/asyncio/base_events.py
deleted file mode 100644
index 952da11..0000000
--- a/lib/python3.10/asyncio/base_events.py
+++ /dev/null
@@ -1,1921 +0,0 @@
-"""Base implementation of event loop.
-
-The event loop can be broken up into a multiplexer (the part
-responsible for notifying us of I/O events) and the event loop proper,
-which wraps a multiplexer with functionality for scheduling callbacks,
-immediately or at a given time in the future.
-
-Whenever a public API takes a callback, subsequent positional
-arguments will be passed to the callback if/when it is called. This
-avoids the proliferation of trivial lambdas implementing closures.
-Keyword arguments for the callback are not supported; this is a
-conscious design decision, leaving the door open for keyword arguments
-to modify the meaning of the API call itself.
-"""
-
-import collections
-import collections.abc
-import concurrent.futures
-import functools
-import heapq
-import itertools
-import os
-import socket
-import stat
-import subprocess
-import threading
-import time
-import traceback
-import sys
-import warnings
-import weakref
-
-try:
- import ssl
-except ImportError: # pragma: no cover
- ssl = None
-
-from . import constants
-from . import coroutines
-from . import events
-from . import exceptions
-from . import futures
-from . import protocols
-from . import sslproto
-from . import staggered
-from . import tasks
-from . import transports
-from . import trsock
-from .log import logger
-
-
-__all__ = 'BaseEventLoop','Server',
-
-
-# Minimum number of _scheduled timer handles before cleanup of
-# cancelled handles is performed.
-_MIN_SCHEDULED_TIMER_HANDLES = 100
-
-# Minimum fraction of _scheduled timer handles that are cancelled
-# before cleanup of cancelled handles is performed.
-_MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5
-
-
-_HAS_IPv6 = hasattr(socket, 'AF_INET6')
-
-# Maximum timeout passed to select to avoid OS limitations
-MAXIMUM_SELECT_TIMEOUT = 24 * 3600
-
-# Used for deprecation and removal of `loop.create_datagram_endpoint()`'s
-# *reuse_address* parameter
-_unset = object()
-
-
-def _format_handle(handle):
- cb = handle._callback
- if isinstance(getattr(cb, '__self__', None), tasks.Task):
- # format the task
- return repr(cb.__self__)
- else:
- return str(handle)
-
-
-def _format_pipe(fd):
- if fd == subprocess.PIPE:
- return '<pipe>'
- elif fd == subprocess.STDOUT:
- return '<stdout>'
- else:
- return repr(fd)
-
-
-def _set_reuseport(sock):
- if not hasattr(socket, 'SO_REUSEPORT'):
- raise ValueError('reuse_port not supported by socket module')
- else:
- try:
- sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
- except OSError:
- raise ValueError('reuse_port not supported by socket module, '
- 'SO_REUSEPORT defined but not implemented.')
-
-
-def _ipaddr_info(host, port, family, type, proto, flowinfo=0, scopeid=0):
- # Try to skip getaddrinfo if "host" is already an IP. Users might have
- # handled name resolution in their own code and pass in resolved IPs.
- if not hasattr(socket, 'inet_pton'):
- return
-
- if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
- host is None:
- return None
-
- if type == socket.SOCK_STREAM:
- proto = socket.IPPROTO_TCP
- elif type == socket.SOCK_DGRAM:
- proto = socket.IPPROTO_UDP
- else:
- return None
-
- if port is None:
- port = 0
- elif isinstance(port, bytes) and port == b'':
- port = 0
- elif isinstance(port, str) and port == '':
- port = 0
- else:
- # If port's a service name like "http", don't skip getaddrinfo.
- try:
- port = int(port)
- except (TypeError, ValueError):
- return None
-
- if family == socket.AF_UNSPEC:
- afs = [socket.AF_INET]
- if _HAS_IPv6:
- afs.append(socket.AF_INET6)
- else:
- afs = [family]
-
- if isinstance(host, bytes):
- host = host.decode('idna')
- if '%' in host:
- # Linux's inet_pton doesn't accept an IPv6 zone index after host,
- # like '::1%lo0'.
- return None
-
- for af in afs:
- try:
- socket.inet_pton(af, host)
- # The host has already been resolved.
- if _HAS_IPv6 and af == socket.AF_INET6:
- return af, type, proto, '', (host, port, flowinfo, scopeid)
- else:
- return af, type, proto, '', (host, port)
- except OSError:
- pass
-
- # "host" is not an IP address.
- return None
-
-
-def _interleave_addrinfos(addrinfos, first_address_family_count=1):
- """Interleave list of addrinfo tuples by family."""
- # Group addresses by family
- addrinfos_by_family = collections.OrderedDict()
- for addr in addrinfos:
- family = addr[0]
- if family not in addrinfos_by_family:
- addrinfos_by_family[family] = []
- addrinfos_by_family[family].append(addr)
- addrinfos_lists = list(addrinfos_by_family.values())
-
- reordered = []
- if first_address_family_count > 1:
- reordered.extend(addrinfos_lists[0][:first_address_family_count - 1])
- del addrinfos_lists[0][:first_address_family_count - 1]
- reordered.extend(
- a for a in itertools.chain.from_iterable(
- itertools.zip_longest(*addrinfos_lists)
- ) if a is not None)
- return reordered
-
-
-def _run_until_complete_cb(fut):
- if not fut.cancelled():
- exc = fut.exception()
- if isinstance(exc, (SystemExit, KeyboardInterrupt)):
- # Issue #22429: run_forever() already finished, no need to
- # stop it.
- return
- futures._get_loop(fut).stop()
-
-
-if hasattr(socket, 'TCP_NODELAY'):
- def _set_nodelay(sock):
- if (sock.family in {socket.AF_INET, socket.AF_INET6} and
- sock.type == socket.SOCK_STREAM and
- sock.proto == socket.IPPROTO_TCP):
- sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
-else:
- def _set_nodelay(sock):
- pass
-
-
-def _check_ssl_socket(sock):
- if ssl is not None and isinstance(sock, ssl.SSLSocket):
- raise TypeError("Socket cannot be of type SSLSocket")
-
-
-class _SendfileFallbackProtocol(protocols.Protocol):
- def __init__(self, transp):
- if not isinstance(transp, transports._FlowControlMixin):
- raise TypeError("transport should be _FlowControlMixin instance")
- self._transport = transp
- self._proto = transp.get_protocol()
- self._should_resume_reading = transp.is_reading()
- self._should_resume_writing = transp._protocol_paused
- transp.pause_reading()
- transp.set_protocol(self)
- if self._should_resume_writing:
- self._write_ready_fut = self._transport._loop.create_future()
- else:
- self._write_ready_fut = None
-
- async def drain(self):
- if self._transport.is_closing():
- raise ConnectionError("Connection closed by peer")
- fut = self._write_ready_fut
- if fut is None:
- return
- await fut
-
- def connection_made(self, transport):
- raise RuntimeError("Invalid state: "
- "connection should have been established already.")
-
- def connection_lost(self, exc):
- if self._write_ready_fut is not None:
- # Never happens if peer disconnects after sending the whole content
- # Thus disconnection is always an exception from user perspective
- if exc is None:
- self._write_ready_fut.set_exception(
- ConnectionError("Connection is closed by peer"))
- else:
- self._write_ready_fut.set_exception(exc)
- self._proto.connection_lost(exc)
-
- def pause_writing(self):
- if self._write_ready_fut is not None:
- return
- self._write_ready_fut = self._transport._loop.create_future()
-
- def resume_writing(self):
- if self._write_ready_fut is None:
- return
- self._write_ready_fut.set_result(False)
- self._write_ready_fut = None
-
- def data_received(self, data):
- raise RuntimeError("Invalid state: reading should be paused")
-
- def eof_received(self):
- raise RuntimeError("Invalid state: reading should be paused")
-
- async def restore(self):
- self._transport.set_protocol(self._proto)
- if self._should_resume_reading:
- self._transport.resume_reading()
- if self._write_ready_fut is not None:
- # Cancel the future.
- # Basically it has no effect because protocol is switched back,
- # no code should wait for it anymore.
- self._write_ready_fut.cancel()
- if self._should_resume_writing:
- self._proto.resume_writing()
-
-
-class Server(events.AbstractServer):
-
- def __init__(self, loop, sockets, protocol_factory, ssl_context, backlog,
- ssl_handshake_timeout):
- self._loop = loop
- self._sockets = sockets
- self._active_count = 0
- self._waiters = []
- self._protocol_factory = protocol_factory
- self._backlog = backlog
- self._ssl_context = ssl_context
- self._ssl_handshake_timeout = ssl_handshake_timeout
- self._serving = False
- self._serving_forever_fut = None
-
- def __repr__(self):
- return f'<{self.__class__.__name__} sockets={self.sockets!r}>'
-
- def _attach(self):
- assert self._sockets is not None
- self._active_count += 1
-
- def _detach(self):
- assert self._active_count > 0
- self._active_count -= 1
- if self._active_count == 0 and self._sockets is None:
- self._wakeup()
-
- def _wakeup(self):
- waiters = self._waiters
- self._waiters = None
- for waiter in waiters:
- if not waiter.done():
- waiter.set_result(waiter)
-
- def _start_serving(self):
- if self._serving:
- return
- self._serving = True
- for sock in self._sockets:
- sock.listen(self._backlog)
- self._loop._start_serving(
- self._protocol_factory, sock, self._ssl_context,
- self, self._backlog, self._ssl_handshake_timeout)
-
- def get_loop(self):
- return self._loop
-
- def is_serving(self):
- return self._serving
-
- @property
- def sockets(self):
- if self._sockets is None:
- return ()
- return tuple(trsock.TransportSocket(s) for s in self._sockets)
-
- def close(self):
- sockets = self._sockets
- if sockets is None:
- return
- self._sockets = None
-
- for sock in sockets:
- self._loop._stop_serving(sock)
-
- self._serving = False
-
- if (self._serving_forever_fut is not None and
- not self._serving_forever_fut.done()):
- self._serving_forever_fut.cancel()
- self._serving_forever_fut = None
-
- if self._active_count == 0:
- self._wakeup()
-
- async def start_serving(self):
- self._start_serving()
- # Skip one loop iteration so that all 'loop.add_reader'
- # go through.
- await tasks.sleep(0)
-
- async def serve_forever(self):
- if self._serving_forever_fut is not None:
- raise RuntimeError(
- f'server {self!r} is already being awaited on serve_forever()')
- if self._sockets is None:
- raise RuntimeError(f'server {self!r} is closed')
-
- self._start_serving()
- self._serving_forever_fut = self._loop.create_future()
-
- try:
- await self._serving_forever_fut
- except exceptions.CancelledError:
- try:
- self.close()
- await self.wait_closed()
- finally:
- raise
- finally:
- self._serving_forever_fut = None
-
- async def wait_closed(self):
- if self._sockets is None or self._waiters is None:
- return
- waiter = self._loop.create_future()
- self._waiters.append(waiter)
- await waiter
-
-
-class BaseEventLoop(events.AbstractEventLoop):
-
- def __init__(self):
- self._timer_cancelled_count = 0
- self._closed = False
- self._stopping = False
- self._ready = collections.deque()
- self._scheduled = []
- self._default_executor = None
- self._internal_fds = 0
- # Identifier of the thread running the event loop, or None if the
- # event loop is not running
- self._thread_id = None
- self._clock_resolution = time.get_clock_info('monotonic').resolution
- self._exception_handler = None
- self.set_debug(coroutines._is_debug_mode())
- # In debug mode, if the execution of a callback or a step of a task
- # exceed this duration in seconds, the slow callback/task is logged.
- self.slow_callback_duration = 0.1
- self._current_handle = None
- self._task_factory = None
- self._coroutine_origin_tracking_enabled = False
- self._coroutine_origin_tracking_saved_depth = None
-
- # A weak set of all asynchronous generators that are
- # being iterated by the loop.
- self._asyncgens = weakref.WeakSet()
- # Set to True when `loop.shutdown_asyncgens` is called.
- self._asyncgens_shutdown_called = False
- # Set to True when `loop.shutdown_default_executor` is called.
- self._executor_shutdown_called = False
-
- def __repr__(self):
- return (
- f'<{self.__class__.__name__} running={self.is_running()} '
- f'closed={self.is_closed()} debug={self.get_debug()}>'
- )
-
- def create_future(self):
- """Create a Future object attached to the loop."""
- return futures.Future(loop=self)
-
- def create_task(self, coro, *, name=None):
- """Schedule a coroutine object.
-
- Return a task object.
- """
- self._check_closed()
- if self._task_factory is None:
- task = tasks.Task(coro, loop=self, name=name)
- if task._source_traceback:
- del task._source_traceback[-1]
- else:
- task = self._task_factory(self, coro)
- tasks._set_task_name(task, name)
-
- return task
-
- def set_task_factory(self, factory):
- """Set a task factory that will be used by loop.create_task().
-
- If factory is None the default task factory will be set.
-
- If factory is a callable, it should have a signature matching
- '(loop, coro)', where 'loop' will be a reference to the active
- event loop, 'coro' will be a coroutine object. The callable
- must return a Future.
- """
- if factory is not None and not callable(factory):
- raise TypeError('task factory must be a callable or None')
- self._task_factory = factory
-
- def get_task_factory(self):
- """Return a task factory, or None if the default one is in use."""
- return self._task_factory
-
- def _make_socket_transport(self, sock, protocol, waiter=None, *,
- extra=None, server=None):
- """Create socket transport."""
- raise NotImplementedError
-
- def _make_ssl_transport(
- self, rawsock, protocol, sslcontext, waiter=None,
- *, server_side=False, server_hostname=None,
- extra=None, server=None,
- ssl_handshake_timeout=None,
- call_connection_made=True):
- """Create SSL transport."""
- raise NotImplementedError
-
- def _make_datagram_transport(self, sock, protocol,
- address=None, waiter=None, extra=None):
- """Create datagram transport."""
- raise NotImplementedError
-
- def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
- extra=None):
- """Create read pipe transport."""
- raise NotImplementedError
-
- def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
- extra=None):
- """Create write pipe transport."""
- raise NotImplementedError
-
- async def _make_subprocess_transport(self, protocol, args, shell,
- stdin, stdout, stderr, bufsize,
- extra=None, **kwargs):
- """Create subprocess transport."""
- raise NotImplementedError
-
- def _write_to_self(self):
- """Write a byte to self-pipe, to wake up the event loop.
-
- This may be called from a different thread.
-
- The subclass is responsible for implementing the self-pipe.
- """
- raise NotImplementedError
-
- def _process_events(self, event_list):
- """Process selector events."""
- raise NotImplementedError
-
- def _check_closed(self):
- if self._closed:
- raise RuntimeError('Event loop is closed')
-
- def _check_default_executor(self):
- if self._executor_shutdown_called:
- raise RuntimeError('Executor shutdown has been called')
-
- def _asyncgen_finalizer_hook(self, agen):
- self._asyncgens.discard(agen)
- if not self.is_closed():
- self.call_soon_threadsafe(self.create_task, agen.aclose())
-
- def _asyncgen_firstiter_hook(self, agen):
- if self._asyncgens_shutdown_called:
- warnings.warn(
- f"asynchronous generator {agen!r} was scheduled after "
- f"loop.shutdown_asyncgens() call",
- ResourceWarning, source=self)
-
- self._asyncgens.add(agen)
-
- async def shutdown_asyncgens(self):
- """Shutdown all active asynchronous generators."""
- self._asyncgens_shutdown_called = True
-
- if not len(self._asyncgens):
- # If Python version is <3.6 or we don't have any asynchronous
- # generators alive.
- return
-
- closing_agens = list(self._asyncgens)
- self._asyncgens.clear()
-
- results = await tasks.gather(
- *[ag.aclose() for ag in closing_agens],
- return_exceptions=True)
-
- for result, agen in zip(results, closing_agens):
- if isinstance(result, Exception):
- self.call_exception_handler({
- 'message': f'an error occurred during closing of '
- f'asynchronous generator {agen!r}',
- 'exception': result,
- 'asyncgen': agen
- })
-
- async def shutdown_default_executor(self):
- """Schedule the shutdown of the default executor."""
- self._executor_shutdown_called = True
- if self._default_executor is None:
- return
- future = self.create_future()
- thread = threading.Thread(target=self._do_shutdown, args=(future,))
- thread.start()
- try:
- await future
- finally:
- thread.join()
-
- def _do_shutdown(self, future):
- try:
- self._default_executor.shutdown(wait=True)
- self.call_soon_threadsafe(future.set_result, None)
- except Exception as ex:
- self.call_soon_threadsafe(future.set_exception, ex)
-
- def _check_running(self):
- if self.is_running():
- raise RuntimeError('This event loop is already running')
- if events._get_running_loop() is not None:
- raise RuntimeError(
- 'Cannot run the event loop while another loop is running')
-
- def run_forever(self):
- """Run until stop() is called."""
- self._check_closed()
- self._check_running()
- self._set_coroutine_origin_tracking(self._debug)
- self._thread_id = threading.get_ident()
-
- old_agen_hooks = sys.get_asyncgen_hooks()
- sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
- finalizer=self._asyncgen_finalizer_hook)
- try:
- events._set_running_loop(self)
- while True:
- self._run_once()
- if self._stopping:
- break
- finally:
- self._stopping = False
- self._thread_id = None
- events._set_running_loop(None)
- self._set_coroutine_origin_tracking(False)
- sys.set_asyncgen_hooks(*old_agen_hooks)
-
- def run_until_complete(self, future):
- """Run until the Future is done.
-
- If the argument is a coroutine, it is wrapped in a Task.
-
- WARNING: It would be disastrous to call run_until_complete()
- with the same coroutine twice -- it would wrap it in two
- different Tasks and that can't be good.
-
- Return the Future's result, or raise its exception.
- """
- self._check_closed()
- self._check_running()
-
- new_task = not futures.isfuture(future)
- future = tasks.ensure_future(future, loop=self)
- if new_task:
- # An exception is raised if the future didn't complete, so there
- # is no need to log the "destroy pending task" message
- future._log_destroy_pending = False
-
- future.add_done_callback(_run_until_complete_cb)
- try:
- self.run_forever()
- except:
- if new_task and future.done() and not future.cancelled():
- # The coroutine raised a BaseException. Consume the exception
- # to not log a warning, the caller doesn't have access to the
- # local task.
- future.exception()
- raise
- finally:
- future.remove_done_callback(_run_until_complete_cb)
- if not future.done():
- raise RuntimeError('Event loop stopped before Future completed.')
-
- return future.result()
-
- def stop(self):
- """Stop running the event loop.
-
- Every callback already scheduled will still run. This simply informs
- run_forever to stop looping after a complete iteration.
- """
- self._stopping = True
-
- def close(self):
- """Close the event loop.
-
- This clears the queues and shuts down the executor,
- but does not wait for the executor to finish.
-
- The event loop must not be running.
- """
- if self.is_running():
- raise RuntimeError("Cannot close a running event loop")
- if self._closed:
- return
- if self._debug:
- logger.debug("Close %r", self)
- self._closed = True
- self._ready.clear()
- self._scheduled.clear()
- self._executor_shutdown_called = True
- executor = self._default_executor
- if executor is not None:
- self._default_executor = None
- executor.shutdown(wait=False)
-
- def is_closed(self):
- """Returns True if the event loop was closed."""
- return self._closed
-
- def __del__(self, _warn=warnings.warn):
- if not self.is_closed():
- _warn(f"unclosed event loop {self!r}", ResourceWarning, source=self)
- if not self.is_running():
- self.close()
-
- def is_running(self):
- """Returns True if the event loop is running."""
- return (self._thread_id is not None)
-
- def time(self):
- """Return the time according to the event loop's clock.
-
- This is a float expressed in seconds since an epoch, but the
- epoch, precision, accuracy and drift are unspecified and may
- differ per event loop.
- """
- return time.monotonic()
-
- def call_later(self, delay, callback, *args, context=None):
- """Arrange for a callback to be called at a given time.
-
- Return a Handle: an opaque object with a cancel() method that
- can be used to cancel the call.
-
- The delay can be an int or float, expressed in seconds. It is
- always relative to the current time.
-
- Each callback will be called exactly once. If two callbacks
- are scheduled for exactly the same time, it undefined which
- will be called first.
-
- Any positional arguments after the callback will be passed to
- the callback when it is called.
- """
- timer = self.call_at(self.time() + delay, callback, *args,
- context=context)
- if timer._source_traceback:
- del timer._source_traceback[-1]
- return timer
-
- def call_at(self, when, callback, *args, context=None):
- """Like call_later(), but uses an absolute time.
-
- Absolute time corresponds to the event loop's time() method.
- """
- self._check_closed()
- if self._debug:
- self._check_thread()
- self._check_callback(callback, 'call_at')
- timer = events.TimerHandle(when, callback, args, self, context)
- if timer._source_traceback:
- del timer._source_traceback[-1]
- heapq.heappush(self._scheduled, timer)
- timer._scheduled = True
- return timer
-
- def call_soon(self, callback, *args, context=None):
- """Arrange for a callback to be called as soon as possible.
-
- This operates as a FIFO queue: callbacks are called in the
- order in which they are registered. Each callback will be
- called exactly once.
-
- Any positional arguments after the callback will be passed to
- the callback when it is called.
- """
- self._check_closed()
- if self._debug:
- self._check_thread()
- self._check_callback(callback, 'call_soon')
- handle = self._call_soon(callback, args, context)
- if handle._source_traceback:
- del handle._source_traceback[-1]
- return handle
-
- def _check_callback(self, callback, method):
- if (coroutines.iscoroutine(callback) or
- coroutines.iscoroutinefunction(callback)):
- raise TypeError(
- f"coroutines cannot be used with {method}()")
- if not callable(callback):
- raise TypeError(
- f'a callable object was expected by {method}(), '
- f'got {callback!r}')
-
- def _call_soon(self, callback, args, context):
- handle = events.Handle(callback, args, self, context)
- if handle._source_traceback:
- del handle._source_traceback[-1]
- self._ready.append(handle)
- return handle
-
- def _check_thread(self):
- """Check that the current thread is the thread running the event loop.
-
- Non-thread-safe methods of this class make this assumption and will
- likely behave incorrectly when the assumption is violated.
-
- Should only be called when (self._debug == True). The caller is
- responsible for checking this condition for performance reasons.
- """
- if self._thread_id is None:
- return
- thread_id = threading.get_ident()
- if thread_id != self._thread_id:
- raise RuntimeError(
- "Non-thread-safe operation invoked on an event loop other "
- "than the current one")
-
- def call_soon_threadsafe(self, callback, *args, context=None):
- """Like call_soon(), but thread-safe."""
- self._check_closed()
- if self._debug:
- self._check_callback(callback, 'call_soon_threadsafe')
- handle = self._call_soon(callback, args, context)
- if handle._source_traceback:
- del handle._source_traceback[-1]
- self._write_to_self()
- return handle
-
- def run_in_executor(self, executor, func, *args):
- self._check_closed()
- if self._debug:
- self._check_callback(func, 'run_in_executor')
- if executor is None:
- executor = self._default_executor
- # Only check when the default executor is being used
- self._check_default_executor()
- if executor is None:
- executor = concurrent.futures.ThreadPoolExecutor(
- thread_name_prefix='asyncio'
- )
- self._default_executor = executor
- return futures.wrap_future(
- executor.submit(func, *args), loop=self)
-
- def set_default_executor(self, executor):
- if not isinstance(executor, concurrent.futures.ThreadPoolExecutor):
- warnings.warn(
- 'Using the default executor that is not an instance of '
- 'ThreadPoolExecutor is deprecated and will be prohibited '
- 'in Python 3.9',
- DeprecationWarning, 2)
- self._default_executor = executor
-
- def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
- msg = [f"{host}:{port!r}"]
- if family:
- msg.append(f'family={family!r}')
- if type:
- msg.append(f'type={type!r}')
- if proto:
- msg.append(f'proto={proto!r}')
- if flags:
- msg.append(f'flags={flags!r}')
- msg = ', '.join(msg)
- logger.debug('Get address info %s', msg)
-
- t0 = self.time()
- addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
- dt = self.time() - t0
-
- msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
- if dt >= self.slow_callback_duration:
- logger.info(msg)
- else:
- logger.debug(msg)
- return addrinfo
-
- async def getaddrinfo(self, host, port, *,
- family=0, type=0, proto=0, flags=0):
- if self._debug:
- getaddr_func = self._getaddrinfo_debug
- else:
- getaddr_func = socket.getaddrinfo
-
- return await self.run_in_executor(
- None, getaddr_func, host, port, family, type, proto, flags)
-
- async def getnameinfo(self, sockaddr, flags=0):
- return await self.run_in_executor(
- None, socket.getnameinfo, sockaddr, flags)
-
- async def sock_sendfile(self, sock, file, offset=0, count=None,
- *, fallback=True):
- if self._debug and sock.gettimeout() != 0:
- raise ValueError("the socket must be non-blocking")
- _check_ssl_socket(sock)
- self._check_sendfile_params(sock, file, offset, count)
- try:
- return await self._sock_sendfile_native(sock, file,
- offset, count)
- except exceptions.SendfileNotAvailableError as exc:
- if not fallback:
- raise
- return await self._sock_sendfile_fallback(sock, file,
- offset, count)
-
- async def _sock_sendfile_native(self, sock, file, offset, count):
- # NB: sendfile syscall is not supported for SSL sockets and
- # non-mmap files even if sendfile is supported by OS
- raise exceptions.SendfileNotAvailableError(
- f"syscall sendfile is not available for socket {sock!r} "
- "and file {file!r} combination")
-
- async def _sock_sendfile_fallback(self, sock, file, offset, count):
- if offset:
- file.seek(offset)
- blocksize = (
- min(count, constants.SENDFILE_FALLBACK_READBUFFER_SIZE)
- if count else constants.SENDFILE_FALLBACK_READBUFFER_SIZE
- )
- buf = bytearray(blocksize)
- total_sent = 0
- try:
- while True:
- if count:
- blocksize = min(count - total_sent, blocksize)
- if blocksize <= 0:
- break
- view = memoryview(buf)[:blocksize]
- read = await self.run_in_executor(None, file.readinto, view)
- if not read:
- break # EOF
- await self.sock_sendall(sock, view[:read])
- total_sent += read
- return total_sent
- finally:
- if total_sent > 0 and hasattr(file, 'seek'):
- file.seek(offset + total_sent)
-
- def _check_sendfile_params(self, sock, file, offset, count):
- if 'b' not in getattr(file, 'mode', 'b'):
- raise ValueError("file should be opened in binary mode")
- if not sock.type == socket.SOCK_STREAM:
- raise ValueError("only SOCK_STREAM type sockets are supported")
- if count is not None:
- if not isinstance(count, int):
- raise TypeError(
- "count must be a positive integer (got {!r})".format(count))
- if count <= 0:
- raise ValueError(
- "count must be a positive integer (got {!r})".format(count))
- if not isinstance(offset, int):
- raise TypeError(
- "offset must be a non-negative integer (got {!r})".format(
- offset))
- if offset < 0:
- raise ValueError(
- "offset must be a non-negative integer (got {!r})".format(
- offset))
-
- async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None):
- """Create, bind and connect one socket."""
- my_exceptions = []
- exceptions.append(my_exceptions)
- family, type_, proto, _, address = addr_info
- sock = None
- try:
- sock = socket.socket(family=family, type=type_, proto=proto)
- sock.setblocking(False)
- if local_addr_infos is not None:
- for _, _, _, _, laddr in local_addr_infos:
- try:
- sock.bind(laddr)
- break
- except OSError as exc:
- msg = (
- f'error while attempting to bind on '
- f'address {laddr!r}: '
- f'{exc.strerror.lower()}'
- )
- exc = OSError(exc.errno, msg)
- my_exceptions.append(exc)
- else: # all bind attempts failed
- raise my_exceptions.pop()
- await self.sock_connect(sock, address)
- return sock
- except OSError as exc:
- my_exceptions.append(exc)
- if sock is not None:
- sock.close()
- raise
- except:
- if sock is not None:
- sock.close()
- raise
-
- async def create_connection(
- self, protocol_factory, host=None, port=None,
- *, ssl=None, family=0,
- proto=0, flags=0, sock=None,
- local_addr=None, server_hostname=None,
- ssl_handshake_timeout=None,
- happy_eyeballs_delay=None, interleave=None):
- """Connect to a TCP server.
-
- Create a streaming transport connection to a given internet host and
- port: socket family AF_INET or socket.AF_INET6 depending on host (or
- family if specified), socket type SOCK_STREAM. protocol_factory must be
- a callable returning a protocol instance.
-
- This method is a coroutine which will try to establish the connection
- in the background. When successful, the coroutine returns a
- (transport, protocol) pair.
- """
- if server_hostname is not None and not ssl:
- raise ValueError('server_hostname is only meaningful with ssl')
-
- if server_hostname is None and ssl:
- # Use host as default for server_hostname. It is an error
- # if host is empty or not set, e.g. when an
- # already-connected socket was passed or when only a port
- # is given. To avoid this error, you can pass
- # server_hostname='' -- this will bypass the hostname
- # check. (This also means that if host is a numeric
- # IP/IPv6 address, we will attempt to verify that exact
- # address; this will probably fail, but it is possible to
- # create a certificate for a specific IP address, so we
- # don't judge it here.)
- if not host:
- raise ValueError('You must set server_hostname '
- 'when using ssl without a host')
- server_hostname = host
-
- if ssl_handshake_timeout is not None and not ssl:
- raise ValueError(
- 'ssl_handshake_timeout is only meaningful with ssl')
-
- if sock is not None:
- _check_ssl_socket(sock)
-
- if happy_eyeballs_delay is not None and interleave is None:
- # If using happy eyeballs, default to interleave addresses by family
- interleave = 1
-
- if host is not None or port is not None:
- if sock is not None:
- raise ValueError(
- 'host/port and sock can not be specified at the same time')
-
- infos = await self._ensure_resolved(
- (host, port), family=family,
- type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self)
- if not infos:
- raise OSError('getaddrinfo() returned empty list')
-
- if local_addr is not None:
- laddr_infos = await self._ensure_resolved(
- local_addr, family=family,
- type=socket.SOCK_STREAM, proto=proto,
- flags=flags, loop=self)
- if not laddr_infos:
- raise OSError('getaddrinfo() returned empty list')
- else:
- laddr_infos = None
-
- if interleave:
- infos = _interleave_addrinfos(infos, interleave)
-
- exceptions = []
- if happy_eyeballs_delay is None:
- # not using happy eyeballs
- for addrinfo in infos:
- try:
- sock = await self._connect_sock(
- exceptions, addrinfo, laddr_infos)
- break
- except OSError:
- continue
- else: # using happy eyeballs
- sock, _, _ = await staggered.staggered_race(
- (functools.partial(self._connect_sock,
- exceptions, addrinfo, laddr_infos)
- for addrinfo in infos),
- happy_eyeballs_delay, loop=self)
-
- if sock is None:
- exceptions = [exc for sub in exceptions for exc in sub]
- if len(exceptions) == 1:
- raise exceptions[0]
- else:
- # If they all have the same str(), raise one.
- model = str(exceptions[0])
- if all(str(exc) == model for exc in exceptions):
- raise exceptions[0]
- # Raise a combined exception so the user can see all
- # the various error messages.
- raise OSError('Multiple exceptions: {}'.format(
- ', '.join(str(exc) for exc in exceptions)))
-
- else:
- if sock is None:
- raise ValueError(
- 'host and port was not specified and no sock specified')
- if sock.type != socket.SOCK_STREAM:
- # We allow AF_INET, AF_INET6, AF_UNIX as long as they
- # are SOCK_STREAM.
- # We support passing AF_UNIX sockets even though we have
- # a dedicated API for that: create_unix_connection.
- # Disallowing AF_UNIX in this method, breaks backwards
- # compatibility.
- raise ValueError(
- f'A Stream Socket was expected, got {sock!r}')
-
- transport, protocol = await self._create_connection_transport(
- sock, protocol_factory, ssl, server_hostname,
- ssl_handshake_timeout=ssl_handshake_timeout)
- if self._debug:
- # Get the socket from the transport because SSL transport closes
- # the old socket and creates a new SSL socket
- sock = transport.get_extra_info('socket')
- logger.debug("%r connected to %s:%r: (%r, %r)",
- sock, host, port, transport, protocol)
- return transport, protocol
-
- async def _create_connection_transport(
- self, sock, protocol_factory, ssl,
- server_hostname, server_side=False,
- ssl_handshake_timeout=None):
-
- sock.setblocking(False)
-
- protocol = protocol_factory()
- waiter = self.create_future()
- if ssl:
- sslcontext = None if isinstance(ssl, bool) else ssl
- transport = self._make_ssl_transport(
- sock, protocol, sslcontext, waiter,
- server_side=server_side, server_hostname=server_hostname,
- ssl_handshake_timeout=ssl_handshake_timeout)
- else:
- transport = self._make_socket_transport(sock, protocol, waiter)
-
- try:
- await waiter
- except:
- transport.close()
- raise
-
- return transport, protocol
-
- async def sendfile(self, transport, file, offset=0, count=None,
- *, fallback=True):
- """Send a file to transport.
-
- Return the total number of bytes which were sent.
-
- The method uses high-performance os.sendfile if available.
-
- file must be a regular file object opened in binary mode.
-
- offset tells from where to start reading the file. If specified,
- count is the total number of bytes to transmit as opposed to
- sending the file until EOF is reached. File position is updated on
- return or also in case of error in which case file.tell()
- can be used to figure out the number of bytes
- which were sent.
-
- fallback set to True makes asyncio to manually read and send
- the file when the platform does not support the sendfile syscall
- (e.g. Windows or SSL socket on Unix).
-
- Raise SendfileNotAvailableError if the system does not support
- sendfile syscall and fallback is False.
- """
- if transport.is_closing():
- raise RuntimeError("Transport is closing")
- mode = getattr(transport, '_sendfile_compatible',
- constants._SendfileMode.UNSUPPORTED)
- if mode is constants._SendfileMode.UNSUPPORTED:
- raise RuntimeError(
- f"sendfile is not supported for transport {transport!r}")
- if mode is constants._SendfileMode.TRY_NATIVE:
- try:
- return await self._sendfile_native(transport, file,
- offset, count)
- except exceptions.SendfileNotAvailableError as exc:
- if not fallback:
- raise
-
- if not fallback:
- raise RuntimeError(
- f"fallback is disabled and native sendfile is not "
- f"supported for transport {transport!r}")
-
- return await self._sendfile_fallback(transport, file,
- offset, count)
-
- async def _sendfile_native(self, transp, file, offset, count):
- raise exceptions.SendfileNotAvailableError(
- "sendfile syscall is not supported")
-
- async def _sendfile_fallback(self, transp, file, offset, count):
- if offset:
- file.seek(offset)
- blocksize = min(count, 16384) if count else 16384
- buf = bytearray(blocksize)
- total_sent = 0
- proto = _SendfileFallbackProtocol(transp)
- try:
- while True:
- if count:
- blocksize = min(count - total_sent, blocksize)
- if blocksize <= 0:
- return total_sent
- view = memoryview(buf)[:blocksize]
- read = await self.run_in_executor(None, file.readinto, view)
- if not read:
- return total_sent # EOF
- await proto.drain()
- transp.write(view[:read])
- total_sent += read
- finally:
- if total_sent > 0 and hasattr(file, 'seek'):
- file.seek(offset + total_sent)
- await proto.restore()
-
- async def start_tls(self, transport, protocol, sslcontext, *,
- server_side=False,
- server_hostname=None,
- ssl_handshake_timeout=None):
- """Upgrade transport to TLS.
-
- Return a new transport that *protocol* should start using
- immediately.
- """
- if ssl is None:
- raise RuntimeError('Python ssl module is not available')
-
- if not isinstance(sslcontext, ssl.SSLContext):
- raise TypeError(
- f'sslcontext is expected to be an instance of ssl.SSLContext, '
- f'got {sslcontext!r}')
-
- if not getattr(transport, '_start_tls_compatible', False):
- raise TypeError(
- f'transport {transport!r} is not supported by start_tls()')
-
- waiter = self.create_future()
- ssl_protocol = sslproto.SSLProtocol(
- self, protocol, sslcontext, waiter,
- server_side, server_hostname,
- ssl_handshake_timeout=ssl_handshake_timeout,
- call_connection_made=False)
-
- # Pause early so that "ssl_protocol.data_received()" doesn't
- # have a chance to get called before "ssl_protocol.connection_made()".
- transport.pause_reading()
-
- transport.set_protocol(ssl_protocol)
- conmade_cb = self.call_soon(ssl_protocol.connection_made, transport)
- resume_cb = self.call_soon(transport.resume_reading)
-
- try:
- await waiter
- except BaseException:
- transport.close()
- conmade_cb.cancel()
- resume_cb.cancel()
- raise
-
- return ssl_protocol._app_transport
-
- async def create_datagram_endpoint(self, protocol_factory,
- local_addr=None, remote_addr=None, *,
- family=0, proto=0, flags=0,
- reuse_address=_unset, reuse_port=None,
- allow_broadcast=None, sock=None):
- """Create datagram connection."""
- if sock is not None:
- if sock.type != socket.SOCK_DGRAM:
- raise ValueError(
- f'A UDP Socket was expected, got {sock!r}')
- if (local_addr or remote_addr or
- family or proto or flags or
- reuse_port or allow_broadcast):
- # show the problematic kwargs in exception msg
- opts = dict(local_addr=local_addr, remote_addr=remote_addr,
- family=family, proto=proto, flags=flags,
- reuse_address=reuse_address, reuse_port=reuse_port,
- allow_broadcast=allow_broadcast)
- problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
- raise ValueError(
- f'socket modifier keyword arguments can not be used '
- f'when sock is specified. ({problems})')
- sock.setblocking(False)
- r_addr = None
- else:
- if not (local_addr or remote_addr):
- if family == 0:
- raise ValueError('unexpected address family')
- addr_pairs_info = (((family, proto), (None, None)),)
- elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
- for addr in (local_addr, remote_addr):
- if addr is not None and not isinstance(addr, str):
- raise TypeError('string is expected')
-
- if local_addr and local_addr[0] not in (0, '\x00'):
- try:
- if stat.S_ISSOCK(os.stat(local_addr).st_mode):
- os.remove(local_addr)
- except FileNotFoundError:
- pass
- except OSError as err:
- # Directory may have permissions only to create socket.
- logger.error('Unable to check or remove stale UNIX '
- 'socket %r: %r',
- local_addr, err)
-
- addr_pairs_info = (((family, proto),
- (local_addr, remote_addr)), )
- else:
- # join address by (family, protocol)
- addr_infos = {} # Using order preserving dict
- for idx, addr in ((0, local_addr), (1, remote_addr)):
- if addr is not None:
- assert isinstance(addr, tuple) and len(addr) == 2, (
- '2-tuple is expected')
-
- infos = await self._ensure_resolved(
- addr, family=family, type=socket.SOCK_DGRAM,
- proto=proto, flags=flags, loop=self)
- if not infos:
- raise OSError('getaddrinfo() returned empty list')
-
- for fam, _, pro, _, address in infos:
- key = (fam, pro)
- if key not in addr_infos:
- addr_infos[key] = [None, None]
- addr_infos[key][idx] = address
-
- # each addr has to have info for each (family, proto) pair
- addr_pairs_info = [
- (key, addr_pair) for key, addr_pair in addr_infos.items()
- if not ((local_addr and addr_pair[0] is None) or
- (remote_addr and addr_pair[1] is None))]
-
- if not addr_pairs_info:
- raise ValueError('can not get address information')
-
- exceptions = []
-
- # bpo-37228
- if reuse_address is not _unset:
- if reuse_address:
- raise ValueError("Passing `reuse_address=True` is no "
- "longer supported, as the usage of "
- "SO_REUSEPORT in UDP poses a significant "
- "security concern.")
- else:
- warnings.warn("The *reuse_address* parameter has been "
- "deprecated as of 3.5.10 and is scheduled "
- "for removal in 3.11.", DeprecationWarning,
- stacklevel=2)
-
- for ((family, proto),
- (local_address, remote_address)) in addr_pairs_info:
- sock = None
- r_addr = None
- try:
- sock = socket.socket(
- family=family, type=socket.SOCK_DGRAM, proto=proto)
- if reuse_port:
- _set_reuseport(sock)
- if allow_broadcast:
- sock.setsockopt(
- socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
- sock.setblocking(False)
-
- if local_addr:
- sock.bind(local_address)
- if remote_addr:
- if not allow_broadcast:
- await self.sock_connect(sock, remote_address)
- r_addr = remote_address
- except OSError as exc:
- if sock is not None:
- sock.close()
- exceptions.append(exc)
- except:
- if sock is not None:
- sock.close()
- raise
- else:
- break
- else:
- raise exceptions[0]
-
- protocol = protocol_factory()
- waiter = self.create_future()
- transport = self._make_datagram_transport(
- sock, protocol, r_addr, waiter)
- if self._debug:
- if local_addr:
- logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
- "created: (%r, %r)",
- local_addr, remote_addr, transport, protocol)
- else:
- logger.debug("Datagram endpoint remote_addr=%r created: "
- "(%r, %r)",
- remote_addr, transport, protocol)
-
- try:
- await waiter
- except:
- transport.close()
- raise
-
- return transport, protocol
-
- async def _ensure_resolved(self, address, *,
- family=0, type=socket.SOCK_STREAM,
- proto=0, flags=0, loop):
- host, port = address[:2]
- info = _ipaddr_info(host, port, family, type, proto, *address[2:])
- if info is not None:
- # "host" is already a resolved IP.
- return [info]
- else:
- return await loop.getaddrinfo(host, port, family=family, type=type,
- proto=proto, flags=flags)
-
- async def _create_server_getaddrinfo(self, host, port, family, flags):
- infos = await self._ensure_resolved((host, port), family=family,
- type=socket.SOCK_STREAM,
- flags=flags, loop=self)
- if not infos:
- raise OSError(f'getaddrinfo({host!r}) returned empty list')
- return infos
-
- async def create_server(
- self, protocol_factory, host=None, port=None,
- *,
- family=socket.AF_UNSPEC,
- flags=socket.AI_PASSIVE,
- sock=None,
- backlog=100,
- ssl=None,
- reuse_address=None,
- reuse_port=None,
- ssl_handshake_timeout=None,
- start_serving=True):
- """Create a TCP server.
-
- The host parameter can be a string, in that case the TCP server is
- bound to host and port.
-
- The host parameter can also be a sequence of strings and in that case
- the TCP server is bound to all hosts of the sequence. If a host
- appears multiple times (possibly indirectly e.g. when hostnames
- resolve to the same IP address), the server is only bound once to that
- host.
-
- Return a Server object which can be used to stop the service.
-
- This method is a coroutine.
- """
- if isinstance(ssl, bool):
- raise TypeError('ssl argument must be an SSLContext or None')
-
- if ssl_handshake_timeout is not None and ssl is None:
- raise ValueError(
- 'ssl_handshake_timeout is only meaningful with ssl')
-
- if sock is not None:
- _check_ssl_socket(sock)
-
- if host is not None or port is not None:
- if sock is not None:
- raise ValueError(
- 'host/port and sock can not be specified at the same time')
-
- if reuse_address is None:
- reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
- sockets = []
- if host == '':
- hosts = [None]
- elif (isinstance(host, str) or
- not isinstance(host, collections.abc.Iterable)):
- hosts = [host]
- else:
- hosts = host
-
- fs = [self._create_server_getaddrinfo(host, port, family=family,
- flags=flags)
- for host in hosts]
- infos = await tasks.gather(*fs)
- infos = set(itertools.chain.from_iterable(infos))
-
- completed = False
- try:
- for res in infos:
- af, socktype, proto, canonname, sa = res
- try:
- sock = socket.socket(af, socktype, proto)
- except socket.error:
- # Assume it's a bad family/type/protocol combination.
- if self._debug:
- logger.warning('create_server() failed to create '
- 'socket.socket(%r, %r, %r)',
- af, socktype, proto, exc_info=True)
- continue
- sockets.append(sock)
- if reuse_address:
- sock.setsockopt(
- socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
- if reuse_port:
- _set_reuseport(sock)
- # Disable IPv4/IPv6 dual stack support (enabled by
- # default on Linux) which makes a single socket
- # listen on both address families.
- if (_HAS_IPv6 and
- af == socket.AF_INET6 and
- hasattr(socket, 'IPPROTO_IPV6')):
- sock.setsockopt(socket.IPPROTO_IPV6,
- socket.IPV6_V6ONLY,
- True)
- try:
- sock.bind(sa)
- except OSError as err:
- raise OSError(err.errno, 'error while attempting '
- 'to bind on address %r: %s'
- % (sa, err.strerror.lower())) from None
- completed = True
- finally:
- if not completed:
- for sock in sockets:
- sock.close()
- else:
- if sock is None:
- raise ValueError('Neither host/port nor sock were specified')
- if sock.type != socket.SOCK_STREAM:
- raise ValueError(f'A Stream Socket was expected, got {sock!r}')
- sockets = [sock]
-
- for sock in sockets:
- sock.setblocking(False)
-
- server = Server(self, sockets, protocol_factory,
- ssl, backlog, ssl_handshake_timeout)
- if start_serving:
- server._start_serving()
- # Skip one loop iteration so that all 'loop.add_reader'
- # go through.
- await tasks.sleep(0)
-
- if self._debug:
- logger.info("%r is serving", server)
- return server
-
- async def connect_accepted_socket(
- self, protocol_factory, sock,
- *, ssl=None,
- ssl_handshake_timeout=None):
- if sock.type != socket.SOCK_STREAM:
- raise ValueError(f'A Stream Socket was expected, got {sock!r}')
-
- if ssl_handshake_timeout is not None and not ssl:
- raise ValueError(
- 'ssl_handshake_timeout is only meaningful with ssl')
-
- if sock is not None:
- _check_ssl_socket(sock)
-
- transport, protocol = await self._create_connection_transport(
- sock, protocol_factory, ssl, '', server_side=True,
- ssl_handshake_timeout=ssl_handshake_timeout)
- if self._debug:
- # Get the socket from the transport because SSL transport closes
- # the old socket and creates a new SSL socket
- sock = transport.get_extra_info('socket')
- logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
- return transport, protocol
-
- async def connect_read_pipe(self, protocol_factory, pipe):
- protocol = protocol_factory()
- waiter = self.create_future()
- transport = self._make_read_pipe_transport(pipe, protocol, waiter)
-
- try:
- await waiter
- except:
- transport.close()
- raise
-
- if self._debug:
- logger.debug('Read pipe %r connected: (%r, %r)',
- pipe.fileno(), transport, protocol)
- return transport, protocol
-
- async def connect_write_pipe(self, protocol_factory, pipe):
- protocol = protocol_factory()
- waiter = self.create_future()
- transport = self._make_write_pipe_transport(pipe, protocol, waiter)
-
- try:
- await waiter
- except:
- transport.close()
- raise
-
- if self._debug:
- logger.debug('Write pipe %r connected: (%r, %r)',
- pipe.fileno(), transport, protocol)
- return transport, protocol
-
- def _log_subprocess(self, msg, stdin, stdout, stderr):
- info = [msg]
- if stdin is not None:
- info.append(f'stdin={_format_pipe(stdin)}')
- if stdout is not None and stderr == subprocess.STDOUT:
- info.append(f'stdout=stderr={_format_pipe(stdout)}')
- else:
- if stdout is not None:
- info.append(f'stdout={_format_pipe(stdout)}')
- if stderr is not None:
- info.append(f'stderr={_format_pipe(stderr)}')
- logger.debug(' '.join(info))
-
- async def subprocess_shell(self, protocol_factory, cmd, *,
- stdin=subprocess.PIPE,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- universal_newlines=False,
- shell=True, bufsize=0,
- encoding=None, errors=None, text=None,
- **kwargs):
- if not isinstance(cmd, (bytes, str)):
- raise ValueError("cmd must be a string")
- if universal_newlines:
- raise ValueError("universal_newlines must be False")
- if not shell:
- raise ValueError("shell must be True")
- if bufsize != 0:
- raise ValueError("bufsize must be 0")
- if text:
- raise ValueError("text must be False")
- if encoding is not None:
- raise ValueError("encoding must be None")
- if errors is not None:
- raise ValueError("errors must be None")
-
- protocol = protocol_factory()
- debug_log = None
- if self._debug:
- # don't log parameters: they may contain sensitive information
- # (password) and may be too long
- debug_log = 'run shell command %r' % cmd
- self._log_subprocess(debug_log, stdin, stdout, stderr)
- transport = await self._make_subprocess_transport(
- protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
- if self._debug and debug_log is not None:
- logger.info('%s: %r', debug_log, transport)
- return transport, protocol
-
- async def subprocess_exec(self, protocol_factory, program, *args,
- stdin=subprocess.PIPE, stdout=subprocess.PIPE,
- stderr=subprocess.PIPE, universal_newlines=False,
- shell=False, bufsize=0,
- encoding=None, errors=None, text=None,
- **kwargs):
- if universal_newlines:
- raise ValueError("universal_newlines must be False")
- if shell:
- raise ValueError("shell must be False")
- if bufsize != 0:
- raise ValueError("bufsize must be 0")
- if text:
- raise ValueError("text must be False")
- if encoding is not None:
- raise ValueError("encoding must be None")
- if errors is not None:
- raise ValueError("errors must be None")
-
- popen_args = (program,) + args
- protocol = protocol_factory()
- debug_log = None
- if self._debug:
- # don't log parameters: they may contain sensitive information
- # (password) and may be too long
- debug_log = f'execute program {program!r}'
- self._log_subprocess(debug_log, stdin, stdout, stderr)
- transport = await self._make_subprocess_transport(
- protocol, popen_args, False, stdin, stdout, stderr,
- bufsize, **kwargs)
- if self._debug and debug_log is not None:
- logger.info('%s: %r', debug_log, transport)
- return transport, protocol
-
- def get_exception_handler(self):
- """Return an exception handler, or None if the default one is in use.
- """
- return self._exception_handler
-
- def set_exception_handler(self, handler):
- """Set handler as the new event loop exception handler.
-
- If handler is None, the default exception handler will
- be set.
-
- If handler is a callable object, it should have a
- signature matching '(loop, context)', where 'loop'
- will be a reference to the active event loop, 'context'
- will be a dict object (see `call_exception_handler()`
- documentation for details about context).
- """
- if handler is not None and not callable(handler):
- raise TypeError(f'A callable object or None is expected, '
- f'got {handler!r}')
- self._exception_handler = handler
-
- def default_exception_handler(self, context):
- """Default exception handler.
-
- This is called when an exception occurs and no exception
- handler is set, and can be called by a custom exception
- handler that wants to defer to the default behavior.
-
- This default handler logs the error message and other
- context-dependent information. In debug mode, a truncated
- stack trace is also appended showing where the given object
- (e.g. a handle or future or task) was created, if any.
-
- The context parameter has the same meaning as in
- `call_exception_handler()`.
- """
- message = context.get('message')
- if not message:
- message = 'Unhandled exception in event loop'
-
- exception = context.get('exception')
- if exception is not None:
- exc_info = (type(exception), exception, exception.__traceback__)
- else:
- exc_info = False
-
- if ('source_traceback' not in context and
- self._current_handle is not None and
- self._current_handle._source_traceback):
- context['handle_traceback'] = \
- self._current_handle._source_traceback
-
- log_lines = [message]
- for key in sorted(context):
- if key in {'message', 'exception'}:
- continue
- value = context[key]
- if key == 'source_traceback':
- tb = ''.join(traceback.format_list(value))
- value = 'Object created at (most recent call last):\n'
- value += tb.rstrip()
- elif key == 'handle_traceback':
- tb = ''.join(traceback.format_list(value))
- value = 'Handle created at (most recent call last):\n'
- value += tb.rstrip()
- else:
- value = repr(value)
- log_lines.append(f'{key}: {value}')
-
- logger.error('\n'.join(log_lines), exc_info=exc_info)
-
- def call_exception_handler(self, context):
- """Call the current event loop's exception handler.
-
- The context argument is a dict containing the following keys:
-
- - 'message': Error message;
- - 'exception' (optional): Exception object;
- - 'future' (optional): Future instance;
- - 'task' (optional): Task instance;
- - 'handle' (optional): Handle instance;
- - 'protocol' (optional): Protocol instance;
- - 'transport' (optional): Transport instance;
- - 'socket' (optional): Socket instance;
- - 'asyncgen' (optional): Asynchronous generator that caused
- the exception.
-
- New keys maybe introduced in the future.
-
- Note: do not overload this method in an event loop subclass.
- For custom exception handling, use the
- `set_exception_handler()` method.
- """
- if self._exception_handler is None:
- try:
- self.default_exception_handler(context)
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException:
- # Second protection layer for unexpected errors
- # in the default implementation, as well as for subclassed
- # event loops with overloaded "default_exception_handler".
- logger.error('Exception in default exception handler',
- exc_info=True)
- else:
- try:
- self._exception_handler(self, context)
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- # Exception in the user set custom exception handler.
- try:
- # Let's try default handler.
- self.default_exception_handler({
- 'message': 'Unhandled error in exception handler',
- 'exception': exc,
- 'context': context,
- })
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException:
- # Guard 'default_exception_handler' in case it is
- # overloaded.
- logger.error('Exception in default exception handler '
- 'while handling an unexpected error '
- 'in custom exception handler',
- exc_info=True)
-
- def _add_callback(self, handle):
- """Add a Handle to _scheduled (TimerHandle) or _ready."""
- assert isinstance(handle, events.Handle), 'A Handle is required here'
- if handle._cancelled:
- return
- assert not isinstance(handle, events.TimerHandle)
- self._ready.append(handle)
-
- def _add_callback_signalsafe(self, handle):
- """Like _add_callback() but called from a signal handler."""
- self._add_callback(handle)
- self._write_to_self()
-
- def _timer_handle_cancelled(self, handle):
- """Notification that a TimerHandle has been cancelled."""
- if handle._scheduled:
- self._timer_cancelled_count += 1
-
- def _run_once(self):
- """Run one full iteration of the event loop.
-
- This calls all currently ready callbacks, polls for I/O,
- schedules the resulting callbacks, and finally schedules
- 'call_later' callbacks.
- """
-
- sched_count = len(self._scheduled)
- if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
- self._timer_cancelled_count / sched_count >
- _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
- # Remove delayed calls that were cancelled if their number
- # is too high
- new_scheduled = []
- for handle in self._scheduled:
- if handle._cancelled:
- handle._scheduled = False
- else:
- new_scheduled.append(handle)
-
- heapq.heapify(new_scheduled)
- self._scheduled = new_scheduled
- self._timer_cancelled_count = 0
- else:
- # Remove delayed calls that were cancelled from head of queue.
- while self._scheduled and self._scheduled[0]._cancelled:
- self._timer_cancelled_count -= 1
- handle = heapq.heappop(self._scheduled)
- handle._scheduled = False
-
- timeout = None
- if self._ready or self._stopping:
- timeout = 0
- elif self._scheduled:
- # Compute the desired timeout.
- when = self._scheduled[0]._when
- timeout = min(max(0, when - self.time()), MAXIMUM_SELECT_TIMEOUT)
-
- event_list = self._selector.select(timeout)
- self._process_events(event_list)
-
- # Handle 'later' callbacks that are ready.
- end_time = self.time() + self._clock_resolution
- while self._scheduled:
- handle = self._scheduled[0]
- if handle._when >= end_time:
- break
- handle = heapq.heappop(self._scheduled)
- handle._scheduled = False
- self._ready.append(handle)
-
- # This is the only place where callbacks are actually *called*.
- # All other places just add them to ready.
- # Note: We run all currently scheduled callbacks, but not any
- # callbacks scheduled by callbacks run this time around --
- # they will be run the next time (after another I/O poll).
- # Use an idiom that is thread-safe without using locks.
- ntodo = len(self._ready)
- for i in range(ntodo):
- handle = self._ready.popleft()
- if handle._cancelled:
- continue
- if self._debug:
- try:
- self._current_handle = handle
- t0 = self.time()
- handle._run()
- dt = self.time() - t0
- if dt >= self.slow_callback_duration:
- logger.warning('Executing %s took %.3f seconds',
- _format_handle(handle), dt)
- finally:
- self._current_handle = None
- else:
- handle._run()
- handle = None # Needed to break cycles when an exception occurs.
-
- def _set_coroutine_origin_tracking(self, enabled):
- if bool(enabled) == bool(self._coroutine_origin_tracking_enabled):
- return
-
- if enabled:
- self._coroutine_origin_tracking_saved_depth = (
- sys.get_coroutine_origin_tracking_depth())
- sys.set_coroutine_origin_tracking_depth(
- constants.DEBUG_STACK_DEPTH)
- else:
- sys.set_coroutine_origin_tracking_depth(
- self._coroutine_origin_tracking_saved_depth)
-
- self._coroutine_origin_tracking_enabled = enabled
-
- def get_debug(self):
- return self._debug
-
- def set_debug(self, enabled):
- self._debug = enabled
-
- if self.is_running():
- self.call_soon_threadsafe(self._set_coroutine_origin_tracking, enabled)
diff --git a/lib/python3.10/asyncio/base_futures.py b/lib/python3.10/asyncio/base_futures.py
deleted file mode 100644
index 2c01ac9..0000000
--- a/lib/python3.10/asyncio/base_futures.py
+++ /dev/null
@@ -1,80 +0,0 @@
-__all__ = ()
-
-import reprlib
-from _thread import get_ident
-
-from . import format_helpers
-
-# States for Future.
-_PENDING = 'PENDING'
-_CANCELLED = 'CANCELLED'
-_FINISHED = 'FINISHED'
-
-
-def isfuture(obj):
- """Check for a Future.
-
- This returns True when obj is a Future instance or is advertising
- itself as duck-type compatible by setting _asyncio_future_blocking.
- See comment in Future for more details.
- """
- return (hasattr(obj.__class__, '_asyncio_future_blocking') and
- obj._asyncio_future_blocking is not None)
-
-
-def _format_callbacks(cb):
- """helper function for Future.__repr__"""
- size = len(cb)
- if not size:
- cb = ''
-
- def format_cb(callback):
- return format_helpers._format_callback_source(callback, ())
-
- if size == 1:
- cb = format_cb(cb[0][0])
- elif size == 2:
- cb = '{}, {}'.format(format_cb(cb[0][0]), format_cb(cb[1][0]))
- elif size > 2:
- cb = '{}, <{} more>, {}'.format(format_cb(cb[0][0]),
- size - 2,
- format_cb(cb[-1][0]))
- return f'cb=[{cb}]'
-
-
-# bpo-42183: _repr_running is needed for repr protection
-# when a Future or Task result contains itself directly or indirectly.
-# The logic is borrowed from @reprlib.recursive_repr decorator.
-# Unfortunately, the direct decorator usage is impossible because of
-# AttributeError: '_asyncio.Task' object has no attribute '__module__' error.
-#
-# After fixing this thing we can return to the decorator based approach.
-_repr_running = set()
-
-
-def _future_repr_info(future):
- # (Future) -> str
- """helper function for Future.__repr__"""
- info = [future._state.lower()]
- if future._state == _FINISHED:
- if future._exception is not None:
- info.append(f'exception={future._exception!r}')
- else:
- key = id(future), get_ident()
- if key in _repr_running:
- result = '...'
- else:
- _repr_running.add(key)
- try:
- # use reprlib to limit the length of the output, especially
- # for very long strings
- result = reprlib.repr(future._result)
- finally:
- _repr_running.discard(key)
- info.append(f'result={result}')
- if future._callbacks:
- info.append(_format_callbacks(future._callbacks))
- if future._source_traceback:
- frame = future._source_traceback[-1]
- info.append(f'created at {frame[0]}:{frame[1]}')
- return info
diff --git a/lib/python3.10/asyncio/base_subprocess.py b/lib/python3.10/asyncio/base_subprocess.py
deleted file mode 100644
index 14d5051..0000000
--- a/lib/python3.10/asyncio/base_subprocess.py
+++ /dev/null
@@ -1,285 +0,0 @@
-import collections
-import subprocess
-import warnings
-
-from . import protocols
-from . import transports
-from .log import logger
-
-
-class BaseSubprocessTransport(transports.SubprocessTransport):
-
- def __init__(self, loop, protocol, args, shell,
- stdin, stdout, stderr, bufsize,
- waiter=None, extra=None, **kwargs):
- super().__init__(extra)
- self._closed = False
- self._protocol = protocol
- self._loop = loop
- self._proc = None
- self._pid = None
- self._returncode = None
- self._exit_waiters = []
- self._pending_calls = collections.deque()
- self._pipes = {}
- self._finished = False
-
- if stdin == subprocess.PIPE:
- self._pipes[0] = None
- if stdout == subprocess.PIPE:
- self._pipes[1] = None
- if stderr == subprocess.PIPE:
- self._pipes[2] = None
-
- # Create the child process: set the _proc attribute
- try:
- self._start(args=args, shell=shell, stdin=stdin, stdout=stdout,
- stderr=stderr, bufsize=bufsize, **kwargs)
- except:
- self.close()
- raise
-
- self._pid = self._proc.pid
- self._extra['subprocess'] = self._proc
-
- if self._loop.get_debug():
- if isinstance(args, (bytes, str)):
- program = args
- else:
- program = args[0]
- logger.debug('process %r created: pid %s',
- program, self._pid)
-
- self._loop.create_task(self._connect_pipes(waiter))
-
- def __repr__(self):
- info = [self.__class__.__name__]
- if self._closed:
- info.append('closed')
- if self._pid is not None:
- info.append(f'pid={self._pid}')
- if self._returncode is not None:
- info.append(f'returncode={self._returncode}')
- elif self._pid is not None:
- info.append('running')
- else:
- info.append('not started')
-
- stdin = self._pipes.get(0)
- if stdin is not None:
- info.append(f'stdin={stdin.pipe}')
-
- stdout = self._pipes.get(1)
- stderr = self._pipes.get(2)
- if stdout is not None and stderr is stdout:
- info.append(f'stdout=stderr={stdout.pipe}')
- else:
- if stdout is not None:
- info.append(f'stdout={stdout.pipe}')
- if stderr is not None:
- info.append(f'stderr={stderr.pipe}')
-
- return '<{}>'.format(' '.join(info))
-
- def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
- raise NotImplementedError
-
- def set_protocol(self, protocol):
- self._protocol = protocol
-
- def get_protocol(self):
- return self._protocol
-
- def is_closing(self):
- return self._closed
-
- def close(self):
- if self._closed:
- return
- self._closed = True
-
- for proto in self._pipes.values():
- if proto is None:
- continue
- proto.pipe.close()
-
- if (self._proc is not None and
- # has the child process finished?
- self._returncode is None and
- # the child process has finished, but the
- # transport hasn't been notified yet?
- self._proc.poll() is None):
-
- if self._loop.get_debug():
- logger.warning('Close running child process: kill %r', self)
-
- try:
- self._proc.kill()
- except ProcessLookupError:
- pass
-
- # Don't clear the _proc reference yet: _post_init() may still run
-
- def __del__(self, _warn=warnings.warn):
- if not self._closed:
- _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
- self.close()
-
- def get_pid(self):
- return self._pid
-
- def get_returncode(self):
- return self._returncode
-
- def get_pipe_transport(self, fd):
- if fd in self._pipes:
- return self._pipes[fd].pipe
- else:
- return None
-
- def _check_proc(self):
- if self._proc is None:
- raise ProcessLookupError()
-
- def send_signal(self, signal):
- self._check_proc()
- self._proc.send_signal(signal)
-
- def terminate(self):
- self._check_proc()
- self._proc.terminate()
-
- def kill(self):
- self._check_proc()
- self._proc.kill()
-
- async def _connect_pipes(self, waiter):
- try:
- proc = self._proc
- loop = self._loop
-
- if proc.stdin is not None:
- _, pipe = await loop.connect_write_pipe(
- lambda: WriteSubprocessPipeProto(self, 0),
- proc.stdin)
- self._pipes[0] = pipe
-
- if proc.stdout is not None:
- _, pipe = await loop.connect_read_pipe(
- lambda: ReadSubprocessPipeProto(self, 1),
- proc.stdout)
- self._pipes[1] = pipe
-
- if proc.stderr is not None:
- _, pipe = await loop.connect_read_pipe(
- lambda: ReadSubprocessPipeProto(self, 2),
- proc.stderr)
- self._pipes[2] = pipe
-
- assert self._pending_calls is not None
-
- loop.call_soon(self._protocol.connection_made, self)
- for callback, data in self._pending_calls:
- loop.call_soon(callback, *data)
- self._pending_calls = None
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- if waiter is not None and not waiter.cancelled():
- waiter.set_exception(exc)
- else:
- if waiter is not None and not waiter.cancelled():
- waiter.set_result(None)
-
- def _call(self, cb, *data):
- if self._pending_calls is not None:
- self._pending_calls.append((cb, data))
- else:
- self._loop.call_soon(cb, *data)
-
- def _pipe_connection_lost(self, fd, exc):
- self._call(self._protocol.pipe_connection_lost, fd, exc)
- self._try_finish()
-
- def _pipe_data_received(self, fd, data):
- self._call(self._protocol.pipe_data_received, fd, data)
-
- def _process_exited(self, returncode):
- assert returncode is not None, returncode
- assert self._returncode is None, self._returncode
- if self._loop.get_debug():
- logger.info('%r exited with return code %r', self, returncode)
- self._returncode = returncode
- if self._proc.returncode is None:
- # asyncio uses a child watcher: copy the status into the Popen
- # object. On Python 3.6, it is required to avoid a ResourceWarning.
- self._proc.returncode = returncode
- self._call(self._protocol.process_exited)
- self._try_finish()
-
- # wake up futures waiting for wait()
- for waiter in self._exit_waiters:
- if not waiter.cancelled():
- waiter.set_result(returncode)
- self._exit_waiters = None
-
- async def _wait(self):
- """Wait until the process exit and return the process return code.
-
- This method is a coroutine."""
- if self._returncode is not None:
- return self._returncode
-
- waiter = self._loop.create_future()
- self._exit_waiters.append(waiter)
- return await waiter
-
- def _try_finish(self):
- assert not self._finished
- if self._returncode is None:
- return
- if all(p is not None and p.disconnected
- for p in self._pipes.values()):
- self._finished = True
- self._call(self._call_connection_lost, None)
-
- def _call_connection_lost(self, exc):
- try:
- self._protocol.connection_lost(exc)
- finally:
- self._loop = None
- self._proc = None
- self._protocol = None
-
-
-class WriteSubprocessPipeProto(protocols.BaseProtocol):
-
- def __init__(self, proc, fd):
- self.proc = proc
- self.fd = fd
- self.pipe = None
- self.disconnected = False
-
- def connection_made(self, transport):
- self.pipe = transport
-
- def __repr__(self):
- return f'<{self.__class__.__name__} fd={self.fd} pipe={self.pipe!r}>'
-
- def connection_lost(self, exc):
- self.disconnected = True
- self.proc._pipe_connection_lost(self.fd, exc)
- self.proc = None
-
- def pause_writing(self):
- self.proc._protocol.pause_writing()
-
- def resume_writing(self):
- self.proc._protocol.resume_writing()
-
-
-class ReadSubprocessPipeProto(WriteSubprocessPipeProto,
- protocols.Protocol):
-
- def data_received(self, data):
- self.proc._pipe_data_received(self.fd, data)
diff --git a/lib/python3.10/asyncio/base_tasks.py b/lib/python3.10/asyncio/base_tasks.py
deleted file mode 100644
index 09bb171..0000000
--- a/lib/python3.10/asyncio/base_tasks.py
+++ /dev/null
@@ -1,85 +0,0 @@
-import linecache
-import traceback
-
-from . import base_futures
-from . import coroutines
-
-
-def _task_repr_info(task):
- info = base_futures._future_repr_info(task)
-
- if task._must_cancel:
- # replace status
- info[0] = 'cancelling'
-
- info.insert(1, 'name=%r' % task.get_name())
-
- coro = coroutines._format_coroutine(task._coro)
- info.insert(2, f'coro=<{coro}>')
-
- if task._fut_waiter is not None:
- info.insert(3, f'wait_for={task._fut_waiter!r}')
- return info
-
-
-def _task_get_stack(task, limit):
- frames = []
- if hasattr(task._coro, 'cr_frame'):
- # case 1: 'async def' coroutines
- f = task._coro.cr_frame
- elif hasattr(task._coro, 'gi_frame'):
- # case 2: legacy coroutines
- f = task._coro.gi_frame
- elif hasattr(task._coro, 'ag_frame'):
- # case 3: async generators
- f = task._coro.ag_frame
- else:
- # case 4: unknown objects
- f = None
- if f is not None:
- while f is not None:
- if limit is not None:
- if limit <= 0:
- break
- limit -= 1
- frames.append(f)
- f = f.f_back
- frames.reverse()
- elif task._exception is not None:
- tb = task._exception.__traceback__
- while tb is not None:
- if limit is not None:
- if limit <= 0:
- break
- limit -= 1
- frames.append(tb.tb_frame)
- tb = tb.tb_next
- return frames
-
-
-def _task_print_stack(task, limit, file):
- extracted_list = []
- checked = set()
- for f in task.get_stack(limit=limit):
- lineno = f.f_lineno
- co = f.f_code
- filename = co.co_filename
- name = co.co_name
- if filename not in checked:
- checked.add(filename)
- linecache.checkcache(filename)
- line = linecache.getline(filename, lineno, f.f_globals)
- extracted_list.append((filename, lineno, name, line))
-
- exc = task._exception
- if not extracted_list:
- print(f'No stack for {task!r}', file=file)
- elif exc is not None:
- print(f'Traceback for {task!r} (most recent call last):', file=file)
- else:
- print(f'Stack for {task!r} (most recent call last):', file=file)
-
- traceback.print_list(extracted_list, file=file)
- if exc is not None:
- for line in traceback.format_exception_only(exc.__class__, exc):
- print(line, file=file, end='')
diff --git a/lib/python3.10/asyncio/constants.py b/lib/python3.10/asyncio/constants.py
deleted file mode 100644
index 33feed6..0000000
--- a/lib/python3.10/asyncio/constants.py
+++ /dev/null
@@ -1,27 +0,0 @@
-import enum
-
-# After the connection is lost, log warnings after this many write()s.
-LOG_THRESHOLD_FOR_CONNLOST_WRITES = 5
-
-# Seconds to wait before retrying accept().
-ACCEPT_RETRY_DELAY = 1
-
-# Number of stack entries to capture in debug mode.
-# The larger the number, the slower the operation in debug mode
-# (see extract_stack() in format_helpers.py).
-DEBUG_STACK_DEPTH = 10
-
-# Number of seconds to wait for SSL handshake to complete
-# The default timeout matches that of Nginx.
-SSL_HANDSHAKE_TIMEOUT = 60.0
-
-# Used in sendfile fallback code. We use fallback for platforms
-# that don't support sendfile, or for TLS connections.
-SENDFILE_FALLBACK_READBUFFER_SIZE = 1024 * 256
-
-# The enum should be here to break circular dependencies between
-# base_events and sslproto
-class _SendfileMode(enum.Enum):
- UNSUPPORTED = enum.auto()
- TRY_NATIVE = enum.auto()
- FALLBACK = enum.auto()
diff --git a/lib/python3.10/asyncio/coroutines.py b/lib/python3.10/asyncio/coroutines.py
deleted file mode 100644
index 9664ea7..0000000
--- a/lib/python3.10/asyncio/coroutines.py
+++ /dev/null
@@ -1,269 +0,0 @@
-__all__ = 'coroutine', 'iscoroutinefunction', 'iscoroutine'
-
-import collections.abc
-import functools
-import inspect
-import os
-import sys
-import traceback
-import types
-import warnings
-
-from . import base_futures
-from . import constants
-from . import format_helpers
-from .log import logger
-
-
-def _is_debug_mode():
- # If you set _DEBUG to true, @coroutine will wrap the resulting
- # generator objects in a CoroWrapper instance (defined below). That
- # instance will log a message when the generator is never iterated
- # over, which may happen when you forget to use "await" or "yield from"
- # with a coroutine call.
- # Note that the value of the _DEBUG flag is taken
- # when the decorator is used, so to be of any use it must be set
- # before you define your coroutines. A downside of using this feature
- # is that tracebacks show entries for the CoroWrapper.__next__ method
- # when _DEBUG is true.
- return sys.flags.dev_mode or (not sys.flags.ignore_environment and
- bool(os.environ.get('PYTHONASYNCIODEBUG')))
-
-
-_DEBUG = _is_debug_mode()
-
-
-class CoroWrapper:
- # Wrapper for coroutine object in _DEBUG mode.
-
- def __init__(self, gen, func=None):
- assert inspect.isgenerator(gen) or inspect.iscoroutine(gen), gen
- self.gen = gen
- self.func = func # Used to unwrap @coroutine decorator
- self._source_traceback = format_helpers.extract_stack(sys._getframe(1))
- self.__name__ = getattr(gen, '__name__', None)
- self.__qualname__ = getattr(gen, '__qualname__', None)
-
- def __repr__(self):
- coro_repr = _format_coroutine(self)
- if self._source_traceback:
- frame = self._source_traceback[-1]
- coro_repr += f', created at {frame[0]}:{frame[1]}'
-
- return f'<{self.__class__.__name__} {coro_repr}>'
-
- def __iter__(self):
- return self
-
- def __next__(self):
- return self.gen.send(None)
-
- def send(self, value):
- return self.gen.send(value)
-
- def throw(self, type, value=None, traceback=None):
- return self.gen.throw(type, value, traceback)
-
- def close(self):
- return self.gen.close()
-
- @property
- def gi_frame(self):
- return self.gen.gi_frame
-
- @property
- def gi_running(self):
- return self.gen.gi_running
-
- @property
- def gi_code(self):
- return self.gen.gi_code
-
- def __await__(self):
- return self
-
- @property
- def gi_yieldfrom(self):
- return self.gen.gi_yieldfrom
-
- def __del__(self):
- # Be careful accessing self.gen.frame -- self.gen might not exist.
- gen = getattr(self, 'gen', None)
- frame = getattr(gen, 'gi_frame', None)
- if frame is not None and frame.f_lasti == -1:
- msg = f'{self!r} was never yielded from'
- tb = getattr(self, '_source_traceback', ())
- if tb:
- tb = ''.join(traceback.format_list(tb))
- msg += (f'\nCoroutine object created at '
- f'(most recent call last, truncated to '
- f'{constants.DEBUG_STACK_DEPTH} last lines):\n')
- msg += tb.rstrip()
- logger.error(msg)
-
-
-def coroutine(func):
- """Decorator to mark coroutines.
-
- If the coroutine is not yielded from before it is destroyed,
- an error message is logged.
- """
- warnings.warn('"@coroutine" decorator is deprecated since Python 3.8, use "async def" instead',
- DeprecationWarning,
- stacklevel=2)
- if inspect.iscoroutinefunction(func):
- # In Python 3.5 that's all we need to do for coroutines
- # defined with "async def".
- return func
-
- if inspect.isgeneratorfunction(func):
- coro = func
- else:
- @functools.wraps(func)
- def coro(*args, **kw):
- res = func(*args, **kw)
- if (base_futures.isfuture(res) or inspect.isgenerator(res) or
- isinstance(res, CoroWrapper)):
- res = yield from res
- else:
- # If 'res' is an awaitable, run it.
- try:
- await_meth = res.__await__
- except AttributeError:
- pass
- else:
- if isinstance(res, collections.abc.Awaitable):
- res = yield from await_meth()
- return res
-
- coro = types.coroutine(coro)
- if not _DEBUG:
- wrapper = coro
- else:
- @functools.wraps(func)
- def wrapper(*args, **kwds):
- w = CoroWrapper(coro(*args, **kwds), func=func)
- if w._source_traceback:
- del w._source_traceback[-1]
- # Python < 3.5 does not implement __qualname__
- # on generator objects, so we set it manually.
- # We use getattr as some callables (such as
- # functools.partial may lack __qualname__).
- w.__name__ = getattr(func, '__name__', None)
- w.__qualname__ = getattr(func, '__qualname__', None)
- return w
-
- wrapper._is_coroutine = _is_coroutine # For iscoroutinefunction().
- return wrapper
-
-
-# A marker for iscoroutinefunction.
-_is_coroutine = object()
-
-
-def iscoroutinefunction(func):
- """Return True if func is a decorated coroutine function."""
- return (inspect.iscoroutinefunction(func) or
- getattr(func, '_is_coroutine', None) is _is_coroutine)
-
-
-# Prioritize native coroutine check to speed-up
-# asyncio.iscoroutine.
-_COROUTINE_TYPES = (types.CoroutineType, types.GeneratorType,
- collections.abc.Coroutine, CoroWrapper)
-_iscoroutine_typecache = set()
-
-
-def iscoroutine(obj):
- """Return True if obj is a coroutine object."""
- if type(obj) in _iscoroutine_typecache:
- return True
-
- if isinstance(obj, _COROUTINE_TYPES):
- # Just in case we don't want to cache more than 100
- # positive types. That shouldn't ever happen, unless
- # someone stressing the system on purpose.
- if len(_iscoroutine_typecache) < 100:
- _iscoroutine_typecache.add(type(obj))
- return True
- else:
- return False
-
-
-def _format_coroutine(coro):
- assert iscoroutine(coro)
-
- is_corowrapper = isinstance(coro, CoroWrapper)
-
- def get_name(coro):
- # Coroutines compiled with Cython sometimes don't have
- # proper __qualname__ or __name__. While that is a bug
- # in Cython, asyncio shouldn't crash with an AttributeError
- # in its __repr__ functions.
- if is_corowrapper:
- return format_helpers._format_callback(coro.func, (), {})
-
- if hasattr(coro, '__qualname__') and coro.__qualname__:
- coro_name = coro.__qualname__
- elif hasattr(coro, '__name__') and coro.__name__:
- coro_name = coro.__name__
- else:
- # Stop masking Cython bugs, expose them in a friendly way.
- coro_name = f'<{type(coro).__name__} without __name__>'
- return f'{coro_name}()'
-
- def is_running(coro):
- try:
- return coro.cr_running
- except AttributeError:
- try:
- return coro.gi_running
- except AttributeError:
- return False
-
- coro_code = None
- if hasattr(coro, 'cr_code') and coro.cr_code:
- coro_code = coro.cr_code
- elif hasattr(coro, 'gi_code') and coro.gi_code:
- coro_code = coro.gi_code
-
- coro_name = get_name(coro)
-
- if not coro_code:
- # Built-in types might not have __qualname__ or __name__.
- if is_running(coro):
- return f'{coro_name} running'
- else:
- return coro_name
-
- coro_frame = None
- if hasattr(coro, 'gi_frame') and coro.gi_frame:
- coro_frame = coro.gi_frame
- elif hasattr(coro, 'cr_frame') and coro.cr_frame:
- coro_frame = coro.cr_frame
-
- # If Cython's coroutine has a fake code object without proper
- # co_filename -- expose that.
- filename = coro_code.co_filename or '<empty co_filename>'
-
- lineno = 0
- if (is_corowrapper and
- coro.func is not None and
- not inspect.isgeneratorfunction(coro.func)):
- source = format_helpers._get_function_source(coro.func)
- if source is not None:
- filename, lineno = source
- if coro_frame is None:
- coro_repr = f'{coro_name} done, defined at {filename}:{lineno}'
- else:
- coro_repr = f'{coro_name} running, defined at {filename}:{lineno}'
-
- elif coro_frame is not None:
- lineno = coro_frame.f_lineno
- coro_repr = f'{coro_name} running at {filename}:{lineno}'
-
- else:
- lineno = coro_code.co_firstlineno
- coro_repr = f'{coro_name} done, defined at {filename}:{lineno}'
-
- return coro_repr
diff --git a/lib/python3.10/asyncio/events.py b/lib/python3.10/asyncio/events.py
deleted file mode 100644
index 5ab1acc..0000000
--- a/lib/python3.10/asyncio/events.py
+++ /dev/null
@@ -1,818 +0,0 @@
-"""Event loop and event loop policy."""
-
-__all__ = (
- 'AbstractEventLoopPolicy',
- 'AbstractEventLoop', 'AbstractServer',
- 'Handle', 'TimerHandle',
- 'get_event_loop_policy', 'set_event_loop_policy',
- 'get_event_loop', 'set_event_loop', 'new_event_loop',
- 'get_child_watcher', 'set_child_watcher',
- '_set_running_loop', 'get_running_loop',
- '_get_running_loop',
-)
-
-import contextvars
-import os
-import socket
-import subprocess
-import sys
-import threading
-
-from . import format_helpers
-
-
-class Handle:
- """Object returned by callback registration methods."""
-
- __slots__ = ('_callback', '_args', '_cancelled', '_loop',
- '_source_traceback', '_repr', '__weakref__',
- '_context')
-
- def __init__(self, callback, args, loop, context=None):
- if context is None:
- context = contextvars.copy_context()
- self._context = context
- self._loop = loop
- self._callback = callback
- self._args = args
- self._cancelled = False
- self._repr = None
- if self._loop.get_debug():
- self._source_traceback = format_helpers.extract_stack(
- sys._getframe(1))
- else:
- self._source_traceback = None
-
- def _repr_info(self):
- info = [self.__class__.__name__]
- if self._cancelled:
- info.append('cancelled')
- if self._callback is not None:
- info.append(format_helpers._format_callback_source(
- self._callback, self._args))
- if self._source_traceback:
- frame = self._source_traceback[-1]
- info.append(f'created at {frame[0]}:{frame[1]}')
- return info
-
- def __repr__(self):
- if self._repr is not None:
- return self._repr
- info = self._repr_info()
- return '<{}>'.format(' '.join(info))
-
- def cancel(self):
- if not self._cancelled:
- self._cancelled = True
- if self._loop.get_debug():
- # Keep a representation in debug mode to keep callback and
- # parameters. For example, to log the warning
- # "Executing <Handle...> took 2.5 second"
- self._repr = repr(self)
- self._callback = None
- self._args = None
-
- def cancelled(self):
- return self._cancelled
-
- def _run(self):
- try:
- self._context.run(self._callback, *self._args)
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- cb = format_helpers._format_callback_source(
- self._callback, self._args)
- msg = f'Exception in callback {cb}'
- context = {
- 'message': msg,
- 'exception': exc,
- 'handle': self,
- }
- if self._source_traceback:
- context['source_traceback'] = self._source_traceback
- self._loop.call_exception_handler(context)
- self = None # Needed to break cycles when an exception occurs.
-
-
-class TimerHandle(Handle):
- """Object returned by timed callback registration methods."""
-
- __slots__ = ['_scheduled', '_when']
-
- def __init__(self, when, callback, args, loop, context=None):
- assert when is not None
- super().__init__(callback, args, loop, context)
- if self._source_traceback:
- del self._source_traceback[-1]
- self._when = when
- self._scheduled = False
-
- def _repr_info(self):
- info = super()._repr_info()
- pos = 2 if self._cancelled else 1
- info.insert(pos, f'when={self._when}')
- return info
-
- def __hash__(self):
- return hash(self._when)
-
- def __lt__(self, other):
- if isinstance(other, TimerHandle):
- return self._when < other._when
- return NotImplemented
-
- def __le__(self, other):
- if isinstance(other, TimerHandle):
- return self._when < other._when or self.__eq__(other)
- return NotImplemented
-
- def __gt__(self, other):
- if isinstance(other, TimerHandle):
- return self._when > other._when
- return NotImplemented
-
- def __ge__(self, other):
- if isinstance(other, TimerHandle):
- return self._when > other._when or self.__eq__(other)
- return NotImplemented
-
- def __eq__(self, other):
- if isinstance(other, TimerHandle):
- return (self._when == other._when and
- self._callback == other._callback and
- self._args == other._args and
- self._cancelled == other._cancelled)
- return NotImplemented
-
- def cancel(self):
- if not self._cancelled:
- self._loop._timer_handle_cancelled(self)
- super().cancel()
-
- def when(self):
- """Return a scheduled callback time.
-
- The time is an absolute timestamp, using the same time
- reference as loop.time().
- """
- return self._when
-
-
-class AbstractServer:
- """Abstract server returned by create_server()."""
-
- def close(self):
- """Stop serving. This leaves existing connections open."""
- raise NotImplementedError
-
- def get_loop(self):
- """Get the event loop the Server object is attached to."""
- raise NotImplementedError
-
- def is_serving(self):
- """Return True if the server is accepting connections."""
- raise NotImplementedError
-
- async def start_serving(self):
- """Start accepting connections.
-
- This method is idempotent, so it can be called when
- the server is already being serving.
- """
- raise NotImplementedError
-
- async def serve_forever(self):
- """Start accepting connections until the coroutine is cancelled.
-
- The server is closed when the coroutine is cancelled.
- """
- raise NotImplementedError
-
- async def wait_closed(self):
- """Coroutine to wait until service is closed."""
- raise NotImplementedError
-
- async def __aenter__(self):
- return self
-
- async def __aexit__(self, *exc):
- self.close()
- await self.wait_closed()
-
-
-class AbstractEventLoop:
- """Abstract event loop."""
-
- # Running and stopping the event loop.
-
- def run_forever(self):
- """Run the event loop until stop() is called."""
- raise NotImplementedError
-
- def run_until_complete(self, future):
- """Run the event loop until a Future is done.
-
- Return the Future's result, or raise its exception.
- """
- raise NotImplementedError
-
- def stop(self):
- """Stop the event loop as soon as reasonable.
-
- Exactly how soon that is may depend on the implementation, but
- no more I/O callbacks should be scheduled.
- """
- raise NotImplementedError
-
- def is_running(self):
- """Return whether the event loop is currently running."""
- raise NotImplementedError
-
- def is_closed(self):
- """Returns True if the event loop was closed."""
- raise NotImplementedError
-
- def close(self):
- """Close the loop.
-
- The loop should not be running.
-
- This is idempotent and irreversible.
-
- No other methods should be called after this one.
- """
- raise NotImplementedError
-
- async def shutdown_asyncgens(self):
- """Shutdown all active asynchronous generators."""
- raise NotImplementedError
-
- async def shutdown_default_executor(self):
- """Schedule the shutdown of the default executor."""
- raise NotImplementedError
-
- # Methods scheduling callbacks. All these return Handles.
-
- def _timer_handle_cancelled(self, handle):
- """Notification that a TimerHandle has been cancelled."""
- raise NotImplementedError
-
- def call_soon(self, callback, *args, context=None):
- return self.call_later(0, callback, *args, context=context)
-
- def call_later(self, delay, callback, *args, context=None):
- raise NotImplementedError
-
- def call_at(self, when, callback, *args, context=None):
- raise NotImplementedError
-
- def time(self):
- raise NotImplementedError
-
- def create_future(self):
- raise NotImplementedError
-
- # Method scheduling a coroutine object: create a task.
-
- def create_task(self, coro, *, name=None):
- raise NotImplementedError
-
- # Methods for interacting with threads.
-
- def call_soon_threadsafe(self, callback, *args, context=None):
- raise NotImplementedError
-
- def run_in_executor(self, executor, func, *args):
- raise NotImplementedError
-
- def set_default_executor(self, executor):
- raise NotImplementedError
-
- # Network I/O methods returning Futures.
-
- async def getaddrinfo(self, host, port, *,
- family=0, type=0, proto=0, flags=0):
- raise NotImplementedError
-
- async def getnameinfo(self, sockaddr, flags=0):
- raise NotImplementedError
-
- async def create_connection(
- self, protocol_factory, host=None, port=None,
- *, ssl=None, family=0, proto=0,
- flags=0, sock=None, local_addr=None,
- server_hostname=None,
- ssl_handshake_timeout=None,
- happy_eyeballs_delay=None, interleave=None):
- raise NotImplementedError
-
- async def create_server(
- self, protocol_factory, host=None, port=None,
- *, family=socket.AF_UNSPEC,
- flags=socket.AI_PASSIVE, sock=None, backlog=100,
- ssl=None, reuse_address=None, reuse_port=None,
- ssl_handshake_timeout=None,
- start_serving=True):
- """A coroutine which creates a TCP server bound to host and port.
-
- The return value is a Server object which can be used to stop
- the service.
-
- If host is an empty string or None all interfaces are assumed
- and a list of multiple sockets will be returned (most likely
- one for IPv4 and another one for IPv6). The host parameter can also be
- a sequence (e.g. list) of hosts to bind to.
-
- family can be set to either AF_INET or AF_INET6 to force the
- socket to use IPv4 or IPv6. If not set it will be determined
- from host (defaults to AF_UNSPEC).
-
- flags is a bitmask for getaddrinfo().
-
- sock can optionally be specified in order to use a preexisting
- socket object.
-
- backlog is the maximum number of queued connections passed to
- listen() (defaults to 100).
-
- ssl can be set to an SSLContext to enable SSL over the
- accepted connections.
-
- reuse_address tells the kernel to reuse a local socket in
- TIME_WAIT state, without waiting for its natural timeout to
- expire. If not specified will automatically be set to True on
- UNIX.
-
- reuse_port tells the kernel to allow this endpoint to be bound to
- the same port as other existing endpoints are bound to, so long as
- they all set this flag when being created. This option is not
- supported on Windows.
-
- ssl_handshake_timeout is the time in seconds that an SSL server
- will wait for completion of the SSL handshake before aborting the
- connection. Default is 60s.
-
- start_serving set to True (default) causes the created server
- to start accepting connections immediately. When set to False,
- the user should await Server.start_serving() or Server.serve_forever()
- to make the server to start accepting connections.
- """
- raise NotImplementedError
-
- async def sendfile(self, transport, file, offset=0, count=None,
- *, fallback=True):
- """Send a file through a transport.
-
- Return an amount of sent bytes.
- """
- raise NotImplementedError
-
- async def start_tls(self, transport, protocol, sslcontext, *,
- server_side=False,
- server_hostname=None,
- ssl_handshake_timeout=None):
- """Upgrade a transport to TLS.
-
- Return a new transport that *protocol* should start using
- immediately.
- """
- raise NotImplementedError
-
- async def create_unix_connection(
- self, protocol_factory, path=None, *,
- ssl=None, sock=None,
- server_hostname=None,
- ssl_handshake_timeout=None):
- raise NotImplementedError
-
- async def create_unix_server(
- self, protocol_factory, path=None, *,
- sock=None, backlog=100, ssl=None,
- ssl_handshake_timeout=None,
- start_serving=True):
- """A coroutine which creates a UNIX Domain Socket server.
-
- The return value is a Server object, which can be used to stop
- the service.
-
- path is a str, representing a file system path to bind the
- server socket to.
-
- sock can optionally be specified in order to use a preexisting
- socket object.
-
- backlog is the maximum number of queued connections passed to
- listen() (defaults to 100).
-
- ssl can be set to an SSLContext to enable SSL over the
- accepted connections.
-
- ssl_handshake_timeout is the time in seconds that an SSL server
- will wait for the SSL handshake to complete (defaults to 60s).
-
- start_serving set to True (default) causes the created server
- to start accepting connections immediately. When set to False,
- the user should await Server.start_serving() or Server.serve_forever()
- to make the server to start accepting connections.
- """
- raise NotImplementedError
-
- async def connect_accepted_socket(
- self, protocol_factory, sock,
- *, ssl=None,
- ssl_handshake_timeout=None):
- """Handle an accepted connection.
-
- This is used by servers that accept connections outside of
- asyncio, but use asyncio to handle connections.
-
- This method is a coroutine. When completed, the coroutine
- returns a (transport, protocol) pair.
- """
- raise NotImplementedError
-
- async def create_datagram_endpoint(self, protocol_factory,
- local_addr=None, remote_addr=None, *,
- family=0, proto=0, flags=0,
- reuse_address=None, reuse_port=None,
- allow_broadcast=None, sock=None):
- """A coroutine which creates a datagram endpoint.
-
- This method will try to establish the endpoint in the background.
- When successful, the coroutine returns a (transport, protocol) pair.
-
- protocol_factory must be a callable returning a protocol instance.
-
- socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
- host (or family if specified), socket type SOCK_DGRAM.
-
- reuse_address tells the kernel to reuse a local socket in
- TIME_WAIT state, without waiting for its natural timeout to
- expire. If not specified it will automatically be set to True on
- UNIX.
-
- reuse_port tells the kernel to allow this endpoint to be bound to
- the same port as other existing endpoints are bound to, so long as
- they all set this flag when being created. This option is not
- supported on Windows and some UNIX's. If the
- :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
- capability is unsupported.
-
- allow_broadcast tells the kernel to allow this endpoint to send
- messages to the broadcast address.
-
- sock can optionally be specified in order to use a preexisting
- socket object.
- """
- raise NotImplementedError
-
- # Pipes and subprocesses.
-
- async def connect_read_pipe(self, protocol_factory, pipe):
- """Register read pipe in event loop. Set the pipe to non-blocking mode.
-
- protocol_factory should instantiate object with Protocol interface.
- pipe is a file-like object.
- Return pair (transport, protocol), where transport supports the
- ReadTransport interface."""
- # The reason to accept file-like object instead of just file descriptor
- # is: we need to own pipe and close it at transport finishing
- # Can got complicated errors if pass f.fileno(),
- # close fd in pipe transport then close f and vice versa.
- raise NotImplementedError
-
- async def connect_write_pipe(self, protocol_factory, pipe):
- """Register write pipe in event loop.
-
- protocol_factory should instantiate object with BaseProtocol interface.
- Pipe is file-like object already switched to nonblocking.
- Return pair (transport, protocol), where transport support
- WriteTransport interface."""
- # The reason to accept file-like object instead of just file descriptor
- # is: we need to own pipe and close it at transport finishing
- # Can got complicated errors if pass f.fileno(),
- # close fd in pipe transport then close f and vice versa.
- raise NotImplementedError
-
- async def subprocess_shell(self, protocol_factory, cmd, *,
- stdin=subprocess.PIPE,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- **kwargs):
- raise NotImplementedError
-
- async def subprocess_exec(self, protocol_factory, *args,
- stdin=subprocess.PIPE,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- **kwargs):
- raise NotImplementedError
-
- # Ready-based callback registration methods.
- # The add_*() methods return None.
- # The remove_*() methods return True if something was removed,
- # False if there was nothing to delete.
-
- def add_reader(self, fd, callback, *args):
- raise NotImplementedError
-
- def remove_reader(self, fd):
- raise NotImplementedError
-
- def add_writer(self, fd, callback, *args):
- raise NotImplementedError
-
- def remove_writer(self, fd):
- raise NotImplementedError
-
- # Completion based I/O methods returning Futures.
-
- async def sock_recv(self, sock, nbytes):
- raise NotImplementedError
-
- async def sock_recv_into(self, sock, buf):
- raise NotImplementedError
-
- async def sock_sendall(self, sock, data):
- raise NotImplementedError
-
- async def sock_connect(self, sock, address):
- raise NotImplementedError
-
- async def sock_accept(self, sock):
- raise NotImplementedError
-
- async def sock_sendfile(self, sock, file, offset=0, count=None,
- *, fallback=None):
- raise NotImplementedError
-
- # Signal handling.
-
- def add_signal_handler(self, sig, callback, *args):
- raise NotImplementedError
-
- def remove_signal_handler(self, sig):
- raise NotImplementedError
-
- # Task factory.
-
- def set_task_factory(self, factory):
- raise NotImplementedError
-
- def get_task_factory(self):
- raise NotImplementedError
-
- # Error handlers.
-
- def get_exception_handler(self):
- raise NotImplementedError
-
- def set_exception_handler(self, handler):
- raise NotImplementedError
-
- def default_exception_handler(self, context):
- raise NotImplementedError
-
- def call_exception_handler(self, context):
- raise NotImplementedError
-
- # Debug flag management.
-
- def get_debug(self):
- raise NotImplementedError
-
- def set_debug(self, enabled):
- raise NotImplementedError
-
-
-class AbstractEventLoopPolicy:
- """Abstract policy for accessing the event loop."""
-
- def get_event_loop(self):
- """Get the event loop for the current context.
-
- Returns an event loop object implementing the BaseEventLoop interface,
- or raises an exception in case no event loop has been set for the
- current context and the current policy does not specify to create one.
-
- It should never return None."""
- raise NotImplementedError
-
- def set_event_loop(self, loop):
- """Set the event loop for the current context to loop."""
- raise NotImplementedError
-
- def new_event_loop(self):
- """Create and return a new event loop object according to this
- policy's rules. If there's need to set this loop as the event loop for
- the current context, set_event_loop must be called explicitly."""
- raise NotImplementedError
-
- # Child processes handling (Unix only).
-
- def get_child_watcher(self):
- "Get the watcher for child processes."
- raise NotImplementedError
-
- def set_child_watcher(self, watcher):
- """Set the watcher for child processes."""
- raise NotImplementedError
-
-
-class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
- """Default policy implementation for accessing the event loop.
-
- In this policy, each thread has its own event loop. However, we
- only automatically create an event loop by default for the main
- thread; other threads by default have no event loop.
-
- Other policies may have different rules (e.g. a single global
- event loop, or automatically creating an event loop per thread, or
- using some other notion of context to which an event loop is
- associated).
- """
-
- _loop_factory = None
-
- class _Local(threading.local):
- _loop = None
- _set_called = False
-
- def __init__(self):
- self._local = self._Local()
-
- def get_event_loop(self):
- """Get the event loop for the current context.
-
- Returns an instance of EventLoop or raises an exception.
- """
- if (self._local._loop is None and
- not self._local._set_called and
- threading.current_thread() is threading.main_thread()):
- self.set_event_loop(self.new_event_loop())
-
- if self._local._loop is None:
- raise RuntimeError('There is no current event loop in thread %r.'
- % threading.current_thread().name)
-
- return self._local._loop
-
- def set_event_loop(self, loop):
- """Set the event loop."""
- self._local._set_called = True
- assert loop is None or isinstance(loop, AbstractEventLoop)
- self._local._loop = loop
-
- def new_event_loop(self):
- """Create a new event loop.
-
- You must call set_event_loop() to make this the current event
- loop.
- """
- return self._loop_factory()
-
-
-# Event loop policy. The policy itself is always global, even if the
-# policy's rules say that there is an event loop per thread (or other
-# notion of context). The default policy is installed by the first
-# call to get_event_loop_policy().
-_event_loop_policy = None
-
-# Lock for protecting the on-the-fly creation of the event loop policy.
-_lock = threading.Lock()
-
-
-# A TLS for the running event loop, used by _get_running_loop.
-class _RunningLoop(threading.local):
- loop_pid = (None, None)
-
-
-_running_loop = _RunningLoop()
-
-
-def get_running_loop():
- """Return the running event loop. Raise a RuntimeError if there is none.
-
- This function is thread-specific.
- """
- # NOTE: this function is implemented in C (see _asynciomodule.c)
- loop = _get_running_loop()
- if loop is None:
- raise RuntimeError('no running event loop')
- return loop
-
-
-def _get_running_loop():
- """Return the running event loop or None.
-
- This is a low-level function intended to be used by event loops.
- This function is thread-specific.
- """
- # NOTE: this function is implemented in C (see _asynciomodule.c)
- running_loop, pid = _running_loop.loop_pid
- if running_loop is not None and pid == os.getpid():
- return running_loop
-
-
-def _set_running_loop(loop):
- """Set the running event loop.
-
- This is a low-level function intended to be used by event loops.
- This function is thread-specific.
- """
- # NOTE: this function is implemented in C (see _asynciomodule.c)
- _running_loop.loop_pid = (loop, os.getpid())
-
-
-def _init_event_loop_policy():
- global _event_loop_policy
- with _lock:
- if _event_loop_policy is None: # pragma: no branch
- from . import DefaultEventLoopPolicy
- _event_loop_policy = DefaultEventLoopPolicy()
-
-
-def get_event_loop_policy():
- """Get the current event loop policy."""
- if _event_loop_policy is None:
- _init_event_loop_policy()
- return _event_loop_policy
-
-
-def set_event_loop_policy(policy):
- """Set the current event loop policy.
-
- If policy is None, the default policy is restored."""
- global _event_loop_policy
- assert policy is None or isinstance(policy, AbstractEventLoopPolicy)
- _event_loop_policy = policy
-
-
-def get_event_loop():
- """Return an asyncio event loop.
-
- When called from a coroutine or a callback (e.g. scheduled with call_soon
- or similar API), this function will always return the running event loop.
-
- If there is no running event loop set, the function will return
- the result of `get_event_loop_policy().get_event_loop()` call.
- """
- # NOTE: this function is implemented in C (see _asynciomodule.c)
- return _py__get_event_loop()
-
-
-def _get_event_loop(stacklevel=3):
- current_loop = _get_running_loop()
- if current_loop is not None:
- return current_loop
- import warnings
- warnings.warn('There is no current event loop',
- DeprecationWarning, stacklevel=stacklevel)
- return get_event_loop_policy().get_event_loop()
-
-
-def set_event_loop(loop):
- """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
- get_event_loop_policy().set_event_loop(loop)
-
-
-def new_event_loop():
- """Equivalent to calling get_event_loop_policy().new_event_loop()."""
- return get_event_loop_policy().new_event_loop()
-
-
-def get_child_watcher():
- """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
- return get_event_loop_policy().get_child_watcher()
-
-
-def set_child_watcher(watcher):
- """Equivalent to calling
- get_event_loop_policy().set_child_watcher(watcher)."""
- return get_event_loop_policy().set_child_watcher(watcher)
-
-
-# Alias pure-Python implementations for testing purposes.
-_py__get_running_loop = _get_running_loop
-_py__set_running_loop = _set_running_loop
-_py_get_running_loop = get_running_loop
-_py_get_event_loop = get_event_loop
-_py__get_event_loop = _get_event_loop
-
-
-try:
- # get_event_loop() is one of the most frequently called
- # functions in asyncio. Pure Python implementation is
- # about 4 times slower than C-accelerated.
- from _asyncio import (_get_running_loop, _set_running_loop,
- get_running_loop, get_event_loop, _get_event_loop)
-except ImportError:
- pass
-else:
- # Alias C implementations for testing purposes.
- _c__get_running_loop = _get_running_loop
- _c__set_running_loop = _set_running_loop
- _c_get_running_loop = get_running_loop
- _c_get_event_loop = get_event_loop
- _c__get_event_loop = _get_event_loop
diff --git a/lib/python3.10/asyncio/exceptions.py b/lib/python3.10/asyncio/exceptions.py
deleted file mode 100644
index f07e448..0000000
--- a/lib/python3.10/asyncio/exceptions.py
+++ /dev/null
@@ -1,58 +0,0 @@
-"""asyncio exceptions."""
-
-
-__all__ = ('CancelledError', 'InvalidStateError', 'TimeoutError',
- 'IncompleteReadError', 'LimitOverrunError',
- 'SendfileNotAvailableError')
-
-
-class CancelledError(BaseException):
- """The Future or Task was cancelled."""
-
-
-class TimeoutError(Exception):
- """The operation exceeded the given deadline."""
-
-
-class InvalidStateError(Exception):
- """The operation is not allowed in this state."""
-
-
-class SendfileNotAvailableError(RuntimeError):
- """Sendfile syscall is not available.
-
- Raised if OS does not support sendfile syscall for given socket or
- file type.
- """
-
-
-class IncompleteReadError(EOFError):
- """
- Incomplete read error. Attributes:
-
- - partial: read bytes string before the end of stream was reached
- - expected: total number of expected bytes (or None if unknown)
- """
- def __init__(self, partial, expected):
- r_expected = 'undefined' if expected is None else repr(expected)
- super().__init__(f'{len(partial)} bytes read on a total of '
- f'{r_expected} expected bytes')
- self.partial = partial
- self.expected = expected
-
- def __reduce__(self):
- return type(self), (self.partial, self.expected)
-
-
-class LimitOverrunError(Exception):
- """Reached the buffer limit while looking for a separator.
-
- Attributes:
- - consumed: total number of to be consumed bytes.
- """
- def __init__(self, message, consumed):
- super().__init__(message)
- self.consumed = consumed
-
- def __reduce__(self):
- return type(self), (self.args[0], self.consumed)
diff --git a/lib/python3.10/asyncio/futures.py b/lib/python3.10/asyncio/futures.py
deleted file mode 100644
index 8e8cd87..0000000
--- a/lib/python3.10/asyncio/futures.py
+++ /dev/null
@@ -1,423 +0,0 @@
-"""A Future class similar to the one in PEP 3148."""
-
-__all__ = (
- 'Future', 'wrap_future', 'isfuture',
-)
-
-import concurrent.futures
-import contextvars
-import logging
-import sys
-from types import GenericAlias
-
-from . import base_futures
-from . import events
-from . import exceptions
-from . import format_helpers
-
-
-isfuture = base_futures.isfuture
-
-
-_PENDING = base_futures._PENDING
-_CANCELLED = base_futures._CANCELLED
-_FINISHED = base_futures._FINISHED
-
-
-STACK_DEBUG = logging.DEBUG - 1 # heavy-duty debugging
-
-
-class Future:
- """This class is *almost* compatible with concurrent.futures.Future.
-
- Differences:
-
- - This class is not thread-safe.
-
- - result() and exception() do not take a timeout argument and
- raise an exception when the future isn't done yet.
-
- - Callbacks registered with add_done_callback() are always called
- via the event loop's call_soon().
-
- - This class is not compatible with the wait() and as_completed()
- methods in the concurrent.futures package.
-
- (In Python 3.4 or later we may be able to unify the implementations.)
- """
-
- # Class variables serving as defaults for instance variables.
- _state = _PENDING
- _result = None
- _exception = None
- _loop = None
- _source_traceback = None
- _cancel_message = None
- # A saved CancelledError for later chaining as an exception context.
- _cancelled_exc = None
-
- # This field is used for a dual purpose:
- # - Its presence is a marker to declare that a class implements
- # the Future protocol (i.e. is intended to be duck-type compatible).
- # The value must also be not-None, to enable a subclass to declare
- # that it is not compatible by setting this to None.
- # - It is set by __iter__() below so that Task._step() can tell
- # the difference between
- # `await Future()` or`yield from Future()` (correct) vs.
- # `yield Future()` (incorrect).
- _asyncio_future_blocking = False
-
- __log_traceback = False
-
- def __init__(self, *, loop=None):
- """Initialize the future.
-
- The optional event_loop argument allows explicitly setting the event
- loop object used by the future. If it's not provided, the future uses
- the default event loop.
- """
- if loop is None:
- self._loop = events._get_event_loop()
- else:
- self._loop = loop
- self._callbacks = []
- if self._loop.get_debug():
- self._source_traceback = format_helpers.extract_stack(
- sys._getframe(1))
-
- _repr_info = base_futures._future_repr_info
-
- def __repr__(self):
- return '<{} {}>'.format(self.__class__.__name__,
- ' '.join(self._repr_info()))
-
- def __del__(self):
- if not self.__log_traceback:
- # set_exception() was not called, or result() or exception()
- # has consumed the exception
- return
- exc = self._exception
- context = {
- 'message':
- f'{self.__class__.__name__} exception was never retrieved',
- 'exception': exc,
- 'future': self,
- }
- if self._source_traceback:
- context['source_traceback'] = self._source_traceback
- self._loop.call_exception_handler(context)
-
- __class_getitem__ = classmethod(GenericAlias)
-
- @property
- def _log_traceback(self):
- return self.__log_traceback
-
- @_log_traceback.setter
- def _log_traceback(self, val):
- if val:
- raise ValueError('_log_traceback can only be set to False')
- self.__log_traceback = False
-
- def get_loop(self):
- """Return the event loop the Future is bound to."""
- loop = self._loop
- if loop is None:
- raise RuntimeError("Future object is not initialized.")
- return loop
-
- def _make_cancelled_error(self):
- """Create the CancelledError to raise if the Future is cancelled.
-
- This should only be called once when handling a cancellation since
- it erases the saved context exception value.
- """
- if self._cancel_message is None:
- exc = exceptions.CancelledError()
- else:
- exc = exceptions.CancelledError(self._cancel_message)
- exc.__context__ = self._cancelled_exc
- # Remove the reference since we don't need this anymore.
- self._cancelled_exc = None
- return exc
-
- def cancel(self, msg=None):
- """Cancel the future and schedule callbacks.
-
- If the future is already done or cancelled, return False. Otherwise,
- change the future's state to cancelled, schedule the callbacks and
- return True.
- """
- self.__log_traceback = False
- if self._state != _PENDING:
- return False
- self._state = _CANCELLED
- self._cancel_message = msg
- self.__schedule_callbacks()
- return True
-
- def __schedule_callbacks(self):
- """Internal: Ask the event loop to call all callbacks.
-
- The callbacks are scheduled to be called as soon as possible. Also
- clears the callback list.
- """
- callbacks = self._callbacks[:]
- if not callbacks:
- return
-
- self._callbacks[:] = []
- for callback, ctx in callbacks:
- self._loop.call_soon(callback, self, context=ctx)
-
- def cancelled(self):
- """Return True if the future was cancelled."""
- return self._state == _CANCELLED
-
- # Don't implement running(); see http://bugs.python.org/issue18699
-
- def done(self):
- """Return True if the future is done.
-
- Done means either that a result / exception are available, or that the
- future was cancelled.
- """
- return self._state != _PENDING
-
- def result(self):
- """Return the result this future represents.
-
- If the future has been cancelled, raises CancelledError. If the
- future's result isn't yet available, raises InvalidStateError. If
- the future is done and has an exception set, this exception is raised.
- """
- if self._state == _CANCELLED:
- exc = self._make_cancelled_error()
- raise exc
- if self._state != _FINISHED:
- raise exceptions.InvalidStateError('Result is not ready.')
- self.__log_traceback = False
- if self._exception is not None:
- raise self._exception
- return self._result
-
- def exception(self):
- """Return the exception that was set on this future.
-
- The exception (or None if no exception was set) is returned only if
- the future is done. If the future has been cancelled, raises
- CancelledError. If the future isn't done yet, raises
- InvalidStateError.
- """
- if self._state == _CANCELLED:
- exc = self._make_cancelled_error()
- raise exc
- if self._state != _FINISHED:
- raise exceptions.InvalidStateError('Exception is not set.')
- self.__log_traceback = False
- return self._exception
-
- def add_done_callback(self, fn, *, context=None):
- """Add a callback to be run when the future becomes done.
-
- The callback is called with a single argument - the future object. If
- the future is already done when this is called, the callback is
- scheduled with call_soon.
- """
- if self._state != _PENDING:
- self._loop.call_soon(fn, self, context=context)
- else:
- if context is None:
- context = contextvars.copy_context()
- self._callbacks.append((fn, context))
-
- # New method not in PEP 3148.
-
- def remove_done_callback(self, fn):
- """Remove all instances of a callback from the "call when done" list.
-
- Returns the number of callbacks removed.
- """
- filtered_callbacks = [(f, ctx)
- for (f, ctx) in self._callbacks
- if f != fn]
- removed_count = len(self._callbacks) - len(filtered_callbacks)
- if removed_count:
- self._callbacks[:] = filtered_callbacks
- return removed_count
-
- # So-called internal methods (note: no set_running_or_notify_cancel()).
-
- def set_result(self, result):
- """Mark the future done and set its result.
-
- If the future is already done when this method is called, raises
- InvalidStateError.
- """
- if self._state != _PENDING:
- raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
- self._result = result
- self._state = _FINISHED
- self.__schedule_callbacks()
-
- def set_exception(self, exception):
- """Mark the future done and set an exception.
-
- If the future is already done when this method is called, raises
- InvalidStateError.
- """
- if self._state != _PENDING:
- raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
- if isinstance(exception, type):
- exception = exception()
- if type(exception) is StopIteration:
- raise TypeError("StopIteration interacts badly with generators "
- "and cannot be raised into a Future")
- self._exception = exception
- self._state = _FINISHED
- self.__schedule_callbacks()
- self.__log_traceback = True
-
- def __await__(self):
- if not self.done():
- self._asyncio_future_blocking = True
- yield self # This tells Task to wait for completion.
- if not self.done():
- raise RuntimeError("await wasn't used with future")
- return self.result() # May raise too.
-
- __iter__ = __await__ # make compatible with 'yield from'.
-
-
-# Needed for testing purposes.
-_PyFuture = Future
-
-
-def _get_loop(fut):
- # Tries to call Future.get_loop() if it's available.
- # Otherwise fallbacks to using the old '_loop' property.
- try:
- get_loop = fut.get_loop
- except AttributeError:
- pass
- else:
- return get_loop()
- return fut._loop
-
-
-def _set_result_unless_cancelled(fut, result):
- """Helper setting the result only if the future was not cancelled."""
- if fut.cancelled():
- return
- fut.set_result(result)
-
-
-def _convert_future_exc(exc):
- exc_class = type(exc)
- if exc_class is concurrent.futures.CancelledError:
- return exceptions.CancelledError(*exc.args)
- elif exc_class is concurrent.futures.TimeoutError:
- return exceptions.TimeoutError(*exc.args)
- elif exc_class is concurrent.futures.InvalidStateError:
- return exceptions.InvalidStateError(*exc.args)
- else:
- return exc
-
-
-def _set_concurrent_future_state(concurrent, source):
- """Copy state from a future to a concurrent.futures.Future."""
- assert source.done()
- if source.cancelled():
- concurrent.cancel()
- if not concurrent.set_running_or_notify_cancel():
- return
- exception = source.exception()
- if exception is not None:
- concurrent.set_exception(_convert_future_exc(exception))
- else:
- result = source.result()
- concurrent.set_result(result)
-
-
-def _copy_future_state(source, dest):
- """Internal helper to copy state from another Future.
-
- The other Future may be a concurrent.futures.Future.
- """
- assert source.done()
- if dest.cancelled():
- return
- assert not dest.done()
- if source.cancelled():
- dest.cancel()
- else:
- exception = source.exception()
- if exception is not None:
- dest.set_exception(_convert_future_exc(exception))
- else:
- result = source.result()
- dest.set_result(result)
-
-
-def _chain_future(source, destination):
- """Chain two futures so that when one completes, so does the other.
-
- The result (or exception) of source will be copied to destination.
- If destination is cancelled, source gets cancelled too.
- Compatible with both asyncio.Future and concurrent.futures.Future.
- """
- if not isfuture(source) and not isinstance(source,
- concurrent.futures.Future):
- raise TypeError('A future is required for source argument')
- if not isfuture(destination) and not isinstance(destination,
- concurrent.futures.Future):
- raise TypeError('A future is required for destination argument')
- source_loop = _get_loop(source) if isfuture(source) else None
- dest_loop = _get_loop(destination) if isfuture(destination) else None
-
- def _set_state(future, other):
- if isfuture(future):
- _copy_future_state(other, future)
- else:
- _set_concurrent_future_state(future, other)
-
- def _call_check_cancel(destination):
- if destination.cancelled():
- if source_loop is None or source_loop is dest_loop:
- source.cancel()
- else:
- source_loop.call_soon_threadsafe(source.cancel)
-
- def _call_set_state(source):
- if (destination.cancelled() and
- dest_loop is not None and dest_loop.is_closed()):
- return
- if dest_loop is None or dest_loop is source_loop:
- _set_state(destination, source)
- else:
- dest_loop.call_soon_threadsafe(_set_state, destination, source)
-
- destination.add_done_callback(_call_check_cancel)
- source.add_done_callback(_call_set_state)
-
-
-def wrap_future(future, *, loop=None):
- """Wrap concurrent.futures.Future object."""
- if isfuture(future):
- return future
- assert isinstance(future, concurrent.futures.Future), \
- f'concurrent.futures.Future is expected, got {future!r}'
- if loop is None:
- loop = events._get_event_loop()
- new_future = loop.create_future()
- _chain_future(future, new_future)
- return new_future
-
-
-try:
- import _asyncio
-except ImportError:
- pass
-else:
- # _CFuture is needed for tests.
- Future = _CFuture = _asyncio.Future
diff --git a/lib/python3.10/asyncio/locks.py b/lib/python3.10/asyncio/locks.py
deleted file mode 100644
index 4fef64e..0000000
--- a/lib/python3.10/asyncio/locks.py
+++ /dev/null
@@ -1,418 +0,0 @@
-"""Synchronization primitives."""
-
-__all__ = ('Lock', 'Event', 'Condition', 'Semaphore', 'BoundedSemaphore')
-
-import collections
-
-from . import exceptions
-from . import mixins
-
-
-class _ContextManagerMixin:
- async def __aenter__(self):
- await self.acquire()
- # We have no use for the "as ..." clause in the with
- # statement for locks.
- return None
-
- async def __aexit__(self, exc_type, exc, tb):
- self.release()
-
-
-class Lock(_ContextManagerMixin, mixins._LoopBoundMixin):
- """Primitive lock objects.
-
- A primitive lock is a synchronization primitive that is not owned
- by a particular coroutine when locked. A primitive lock is in one
- of two states, 'locked' or 'unlocked'.
-
- It is created in the unlocked state. It has two basic methods,
- acquire() and release(). When the state is unlocked, acquire()
- changes the state to locked and returns immediately. When the
- state is locked, acquire() blocks until a call to release() in
- another coroutine changes it to unlocked, then the acquire() call
- resets it to locked and returns. The release() method should only
- be called in the locked state; it changes the state to unlocked
- and returns immediately. If an attempt is made to release an
- unlocked lock, a RuntimeError will be raised.
-
- When more than one coroutine is blocked in acquire() waiting for
- the state to turn to unlocked, only one coroutine proceeds when a
- release() call resets the state to unlocked; first coroutine which
- is blocked in acquire() is being processed.
-
- acquire() is a coroutine and should be called with 'await'.
-
- Locks also support the asynchronous context management protocol.
- 'async with lock' statement should be used.
-
- Usage:
-
- lock = Lock()
- ...
- await lock.acquire()
- try:
- ...
- finally:
- lock.release()
-
- Context manager usage:
-
- lock = Lock()
- ...
- async with lock:
- ...
-
- Lock objects can be tested for locking state:
-
- if not lock.locked():
- await lock.acquire()
- else:
- # lock is acquired
- ...
-
- """
-
- def __init__(self, *, loop=mixins._marker):
- super().__init__(loop=loop)
- self._waiters = None
- self._locked = False
-
- def __repr__(self):
- res = super().__repr__()
- extra = 'locked' if self._locked else 'unlocked'
- if self._waiters:
- extra = f'{extra}, waiters:{len(self._waiters)}'
- return f'<{res[1:-1]} [{extra}]>'
-
- def locked(self):
- """Return True if lock is acquired."""
- return self._locked
-
- async def acquire(self):
- """Acquire a lock.
-
- This method blocks until the lock is unlocked, then sets it to
- locked and returns True.
- """
- if (not self._locked and (self._waiters is None or
- all(w.cancelled() for w in self._waiters))):
- self._locked = True
- return True
-
- if self._waiters is None:
- self._waiters = collections.deque()
- fut = self._get_loop().create_future()
- self._waiters.append(fut)
-
- # Finally block should be called before the CancelledError
- # handling as we don't want CancelledError to call
- # _wake_up_first() and attempt to wake up itself.
- try:
- try:
- await fut
- finally:
- self._waiters.remove(fut)
- except exceptions.CancelledError:
- if not self._locked:
- self._wake_up_first()
- raise
-
- self._locked = True
- return True
-
- def release(self):
- """Release a lock.
-
- When the lock is locked, reset it to unlocked, and return.
- If any other coroutines are blocked waiting for the lock to become
- unlocked, allow exactly one of them to proceed.
-
- When invoked on an unlocked lock, a RuntimeError is raised.
-
- There is no return value.
- """
- if self._locked:
- self._locked = False
- self._wake_up_first()
- else:
- raise RuntimeError('Lock is not acquired.')
-
- def _wake_up_first(self):
- """Wake up the first waiter if it isn't done."""
- if not self._waiters:
- return
- try:
- fut = next(iter(self._waiters))
- except StopIteration:
- return
-
- # .done() necessarily means that a waiter will wake up later on and
- # either take the lock, or, if it was cancelled and lock wasn't
- # taken already, will hit this again and wake up a new waiter.
- if not fut.done():
- fut.set_result(True)
-
-
-class Event(mixins._LoopBoundMixin):
- """Asynchronous equivalent to threading.Event.
-
- Class implementing event objects. An event manages a flag that can be set
- to true with the set() method and reset to false with the clear() method.
- The wait() method blocks until the flag is true. The flag is initially
- false.
- """
-
- def __init__(self, *, loop=mixins._marker):
- super().__init__(loop=loop)
- self._waiters = collections.deque()
- self._value = False
-
- def __repr__(self):
- res = super().__repr__()
- extra = 'set' if self._value else 'unset'
- if self._waiters:
- extra = f'{extra}, waiters:{len(self._waiters)}'
- return f'<{res[1:-1]} [{extra}]>'
-
- def is_set(self):
- """Return True if and only if the internal flag is true."""
- return self._value
-
- def set(self):
- """Set the internal flag to true. All coroutines waiting for it to
- become true are awakened. Coroutine that call wait() once the flag is
- true will not block at all.
- """
- if not self._value:
- self._value = True
-
- for fut in self._waiters:
- if not fut.done():
- fut.set_result(True)
-
- def clear(self):
- """Reset the internal flag to false. Subsequently, coroutines calling
- wait() will block until set() is called to set the internal flag
- to true again."""
- self._value = False
-
- async def wait(self):
- """Block until the internal flag is true.
-
- If the internal flag is true on entry, return True
- immediately. Otherwise, block until another coroutine calls
- set() to set the flag to true, then return True.
- """
- if self._value:
- return True
-
- fut = self._get_loop().create_future()
- self._waiters.append(fut)
- try:
- await fut
- return True
- finally:
- self._waiters.remove(fut)
-
-
-class Condition(_ContextManagerMixin, mixins._LoopBoundMixin):
- """Asynchronous equivalent to threading.Condition.
-
- This class implements condition variable objects. A condition variable
- allows one or more coroutines to wait until they are notified by another
- coroutine.
-
- A new Lock object is created and used as the underlying lock.
- """
-
- def __init__(self, lock=None, *, loop=mixins._marker):
- super().__init__(loop=loop)
- if lock is None:
- lock = Lock()
-
- self._lock = lock
- # Export the lock's locked(), acquire() and release() methods.
- self.locked = lock.locked
- self.acquire = lock.acquire
- self.release = lock.release
-
- self._waiters = collections.deque()
-
- def __repr__(self):
- res = super().__repr__()
- extra = 'locked' if self.locked() else 'unlocked'
- if self._waiters:
- extra = f'{extra}, waiters:{len(self._waiters)}'
- return f'<{res[1:-1]} [{extra}]>'
-
- async def wait(self):
- """Wait until notified.
-
- If the calling coroutine has not acquired the lock when this
- method is called, a RuntimeError is raised.
-
- This method releases the underlying lock, and then blocks
- until it is awakened by a notify() or notify_all() call for
- the same condition variable in another coroutine. Once
- awakened, it re-acquires the lock and returns True.
- """
- if not self.locked():
- raise RuntimeError('cannot wait on un-acquired lock')
-
- self.release()
- try:
- fut = self._get_loop().create_future()
- self._waiters.append(fut)
- try:
- await fut
- return True
- finally:
- self._waiters.remove(fut)
-
- finally:
- # Must reacquire lock even if wait is cancelled
- cancelled = False
- while True:
- try:
- await self.acquire()
- break
- except exceptions.CancelledError:
- cancelled = True
-
- if cancelled:
- raise exceptions.CancelledError
-
- async def wait_for(self, predicate):
- """Wait until a predicate becomes true.
-
- The predicate should be a callable which result will be
- interpreted as a boolean value. The final predicate value is
- the return value.
- """
- result = predicate()
- while not result:
- await self.wait()
- result = predicate()
- return result
-
- def notify(self, n=1):
- """By default, wake up one coroutine waiting on this condition, if any.
- If the calling coroutine has not acquired the lock when this method
- is called, a RuntimeError is raised.
-
- This method wakes up at most n of the coroutines waiting for the
- condition variable; it is a no-op if no coroutines are waiting.
-
- Note: an awakened coroutine does not actually return from its
- wait() call until it can reacquire the lock. Since notify() does
- not release the lock, its caller should.
- """
- if not self.locked():
- raise RuntimeError('cannot notify on un-acquired lock')
-
- idx = 0
- for fut in self._waiters:
- if idx >= n:
- break
-
- if not fut.done():
- idx += 1
- fut.set_result(False)
-
- def notify_all(self):
- """Wake up all threads waiting on this condition. This method acts
- like notify(), but wakes up all waiting threads instead of one. If the
- calling thread has not acquired the lock when this method is called,
- a RuntimeError is raised.
- """
- self.notify(len(self._waiters))
-
-
-class Semaphore(_ContextManagerMixin, mixins._LoopBoundMixin):
- """A Semaphore implementation.
-
- A semaphore manages an internal counter which is decremented by each
- acquire() call and incremented by each release() call. The counter
- can never go below zero; when acquire() finds that it is zero, it blocks,
- waiting until some other thread calls release().
-
- Semaphores also support the context management protocol.
-
- The optional argument gives the initial value for the internal
- counter; it defaults to 1. If the value given is less than 0,
- ValueError is raised.
- """
-
- def __init__(self, value=1, *, loop=mixins._marker):
- super().__init__(loop=loop)
- if value < 0:
- raise ValueError("Semaphore initial value must be >= 0")
- self._value = value
- self._waiters = collections.deque()
-
- def __repr__(self):
- res = super().__repr__()
- extra = 'locked' if self.locked() else f'unlocked, value:{self._value}'
- if self._waiters:
- extra = f'{extra}, waiters:{len(self._waiters)}'
- return f'<{res[1:-1]} [{extra}]>'
-
- def _wake_up_next(self):
- while self._waiters:
- waiter = self._waiters.popleft()
- if not waiter.done():
- waiter.set_result(None)
- return
-
- def locked(self):
- """Returns True if semaphore can not be acquired immediately."""
- return self._value == 0
-
- async def acquire(self):
- """Acquire a semaphore.
-
- If the internal counter is larger than zero on entry,
- decrement it by one and return True immediately. If it is
- zero on entry, block, waiting until some other coroutine has
- called release() to make it larger than 0, and then return
- True.
- """
- while self._value <= 0:
- fut = self._get_loop().create_future()
- self._waiters.append(fut)
- try:
- await fut
- except:
- # See the similar code in Queue.get.
- fut.cancel()
- if self._value > 0 and not fut.cancelled():
- self._wake_up_next()
- raise
- self._value -= 1
- return True
-
- def release(self):
- """Release a semaphore, incrementing the internal counter by one.
- When it was zero on entry and another coroutine is waiting for it to
- become larger than zero again, wake up that coroutine.
- """
- self._value += 1
- self._wake_up_next()
-
-
-class BoundedSemaphore(Semaphore):
- """A bounded semaphore implementation.
-
- This raises ValueError in release() if it would increase the value
- above the initial value.
- """
-
- def __init__(self, value=1, *, loop=mixins._marker):
- self._bound_value = value
- super().__init__(value, loop=loop)
-
- def release(self):
- if self._value >= self._bound_value:
- raise ValueError('BoundedSemaphore released too many times')
- super().release()
diff --git a/lib/python3.10/asyncio/mixins.py b/lib/python3.10/asyncio/mixins.py
deleted file mode 100644
index 650df05..0000000
--- a/lib/python3.10/asyncio/mixins.py
+++ /dev/null
@@ -1,31 +0,0 @@
-"""Event loop mixins."""
-
-import threading
-from . import events
-
-_global_lock = threading.Lock()
-
-# Used as a sentinel for loop parameter
-_marker = object()
-
-
-class _LoopBoundMixin:
- _loop = None
-
- def __init__(self, *, loop=_marker):
- if loop is not _marker:
- raise TypeError(
- f'As of 3.10, the *loop* parameter was removed from '
- f'{type(self).__name__}() since it is no longer necessary'
- )
-
- def _get_loop(self):
- loop = events._get_running_loop()
-
- if self._loop is None:
- with _global_lock:
- if self._loop is None:
- self._loop = loop
- if loop is not self._loop:
- raise RuntimeError(f'{self!r} is bound to a different event loop')
- return loop
diff --git a/lib/python3.10/asyncio/proactor_events.py b/lib/python3.10/asyncio/proactor_events.py
deleted file mode 100644
index 411685b..0000000
--- a/lib/python3.10/asyncio/proactor_events.py
+++ /dev/null
@@ -1,871 +0,0 @@
-"""Event loop using a proactor and related classes.
-
-A proactor is a "notify-on-completion" multiplexer. Currently a
-proactor is only implemented on Windows with IOCP.
-"""
-
-__all__ = 'BaseProactorEventLoop',
-
-import io
-import os
-import socket
-import warnings
-import signal
-import threading
-import collections
-
-from . import base_events
-from . import constants
-from . import futures
-from . import exceptions
-from . import protocols
-from . import sslproto
-from . import transports
-from . import trsock
-from .log import logger
-
-
-def _set_socket_extra(transport, sock):
- transport._extra['socket'] = trsock.TransportSocket(sock)
-
- try:
- transport._extra['sockname'] = sock.getsockname()
- except socket.error:
- if transport._loop.get_debug():
- logger.warning(
- "getsockname() failed on %r", sock, exc_info=True)
-
- if 'peername' not in transport._extra:
- try:
- transport._extra['peername'] = sock.getpeername()
- except socket.error:
- # UDP sockets may not have a peer name
- transport._extra['peername'] = None
-
-
-class _ProactorBasePipeTransport(transports._FlowControlMixin,
- transports.BaseTransport):
- """Base class for pipe and socket transports."""
-
- def __init__(self, loop, sock, protocol, waiter=None,
- extra=None, server=None):
- super().__init__(extra, loop)
- self._set_extra(sock)
- self._sock = sock
- self.set_protocol(protocol)
- self._server = server
- self._buffer = None # None or bytearray.
- self._read_fut = None
- self._write_fut = None
- self._pending_write = 0
- self._conn_lost = 0
- self._closing = False # Set when close() called.
- self._eof_written = False
- if self._server is not None:
- self._server._attach()
- self._loop.call_soon(self._protocol.connection_made, self)
- if waiter is not None:
- # only wake up the waiter when connection_made() has been called
- self._loop.call_soon(futures._set_result_unless_cancelled,
- waiter, None)
-
- def __repr__(self):
- info = [self.__class__.__name__]
- if self._sock is None:
- info.append('closed')
- elif self._closing:
- info.append('closing')
- if self._sock is not None:
- info.append(f'fd={self._sock.fileno()}')
- if self._read_fut is not None:
- info.append(f'read={self._read_fut!r}')
- if self._write_fut is not None:
- info.append(f'write={self._write_fut!r}')
- if self._buffer:
- info.append(f'write_bufsize={len(self._buffer)}')
- if self._eof_written:
- info.append('EOF written')
- return '<{}>'.format(' '.join(info))
-
- def _set_extra(self, sock):
- self._extra['pipe'] = sock
-
- def set_protocol(self, protocol):
- self._protocol = protocol
-
- def get_protocol(self):
- return self._protocol
-
- def is_closing(self):
- return self._closing
-
- def close(self):
- if self._closing:
- return
- self._closing = True
- self._conn_lost += 1
- if not self._buffer and self._write_fut is None:
- self._loop.call_soon(self._call_connection_lost, None)
- if self._read_fut is not None:
- self._read_fut.cancel()
- self._read_fut = None
-
- def __del__(self, _warn=warnings.warn):
- if self._sock is not None:
- _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
- self.close()
-
- def _fatal_error(self, exc, message='Fatal error on pipe transport'):
- try:
- if isinstance(exc, OSError):
- if self._loop.get_debug():
- logger.debug("%r: %s", self, message, exc_info=True)
- else:
- self._loop.call_exception_handler({
- 'message': message,
- 'exception': exc,
- 'transport': self,
- 'protocol': self._protocol,
- })
- finally:
- self._force_close(exc)
-
- def _force_close(self, exc):
- if self._empty_waiter is not None and not self._empty_waiter.done():
- if exc is None:
- self._empty_waiter.set_result(None)
- else:
- self._empty_waiter.set_exception(exc)
- if self._closing:
- return
- self._closing = True
- self._conn_lost += 1
- if self._write_fut:
- self._write_fut.cancel()
- self._write_fut = None
- if self._read_fut:
- self._read_fut.cancel()
- self._read_fut = None
- self._pending_write = 0
- self._buffer = None
- self._loop.call_soon(self._call_connection_lost, exc)
-
- def _call_connection_lost(self, exc):
- try:
- self._protocol.connection_lost(exc)
- finally:
- # XXX If there is a pending overlapped read on the other
- # end then it may fail with ERROR_NETNAME_DELETED if we
- # just close our end. First calling shutdown() seems to
- # cure it, but maybe using DisconnectEx() would be better.
- if hasattr(self._sock, 'shutdown') and self._sock.fileno() != -1:
- self._sock.shutdown(socket.SHUT_RDWR)
- self._sock.close()
- self._sock = None
- server = self._server
- if server is not None:
- server._detach()
- self._server = None
-
- def get_write_buffer_size(self):
- size = self._pending_write
- if self._buffer is not None:
- size += len(self._buffer)
- return size
-
-
-class _ProactorReadPipeTransport(_ProactorBasePipeTransport,
- transports.ReadTransport):
- """Transport for read pipes."""
-
- def __init__(self, loop, sock, protocol, waiter=None,
- extra=None, server=None, buffer_size=65536):
- self._pending_data_length = -1
- self._paused = True
- super().__init__(loop, sock, protocol, waiter, extra, server)
-
- self._data = bytearray(buffer_size)
- self._loop.call_soon(self._loop_reading)
- self._paused = False
-
- def is_reading(self):
- return not self._paused and not self._closing
-
- def pause_reading(self):
- if self._closing or self._paused:
- return
- self._paused = True
-
- # bpo-33694: Don't cancel self._read_fut because cancelling an
- # overlapped WSASend() loss silently data with the current proactor
- # implementation.
- #
- # If CancelIoEx() fails with ERROR_NOT_FOUND, it means that WSASend()
- # completed (even if HasOverlappedIoCompleted() returns 0), but
- # Overlapped.cancel() currently silently ignores the ERROR_NOT_FOUND
- # error. Once the overlapped is ignored, the IOCP loop will ignores the
- # completion I/O event and so not read the result of the overlapped
- # WSARecv().
-
- if self._loop.get_debug():
- logger.debug("%r pauses reading", self)
-
- def resume_reading(self):
- if self._closing or not self._paused:
- return
-
- self._paused = False
- if self._read_fut is None:
- self._loop.call_soon(self._loop_reading, None)
-
- length = self._pending_data_length
- self._pending_data_length = -1
- if length > -1:
- # Call the protocol methode after calling _loop_reading(),
- # since the protocol can decide to pause reading again.
- self._loop.call_soon(self._data_received, self._data[:length], length)
-
- if self._loop.get_debug():
- logger.debug("%r resumes reading", self)
-
- def _eof_received(self):
- if self._loop.get_debug():
- logger.debug("%r received EOF", self)
-
- try:
- keep_open = self._protocol.eof_received()
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- self._fatal_error(
- exc, 'Fatal error: protocol.eof_received() call failed.')
- return
-
- if not keep_open:
- self.close()
-
- def _data_received(self, data, length):
- if self._paused:
- # Don't call any protocol method while reading is paused.
- # The protocol will be called on resume_reading().
- assert self._pending_data_length == -1
- self._pending_data_length = length
- return
-
- if length == 0:
- self._eof_received()
- return
-
- if isinstance(self._protocol, protocols.BufferedProtocol):
- try:
- protocols._feed_data_to_buffered_proto(self._protocol, data)
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- self._fatal_error(exc,
- 'Fatal error: protocol.buffer_updated() '
- 'call failed.')
- return
- else:
- self._protocol.data_received(data)
-
- def _loop_reading(self, fut=None):
- length = -1
- data = None
- try:
- if fut is not None:
- assert self._read_fut is fut or (self._read_fut is None and
- self._closing)
- self._read_fut = None
- if fut.done():
- # deliver data later in "finally" clause
- length = fut.result()
- if length == 0:
- # we got end-of-file so no need to reschedule a new read
- return
-
- data = self._data[:length]
- else:
- # the future will be replaced by next proactor.recv call
- fut.cancel()
-
- if self._closing:
- # since close() has been called we ignore any read data
- return
-
- # bpo-33694: buffer_updated() has currently no fast path because of
- # a data loss issue caused by overlapped WSASend() cancellation.
-
- if not self._paused:
- # reschedule a new read
- self._read_fut = self._loop._proactor.recv_into(self._sock, self._data)
- except ConnectionAbortedError as exc:
- if not self._closing:
- self._fatal_error(exc, 'Fatal read error on pipe transport')
- elif self._loop.get_debug():
- logger.debug("Read error on pipe transport while closing",
- exc_info=True)
- except ConnectionResetError as exc:
- self._force_close(exc)
- except OSError as exc:
- self._fatal_error(exc, 'Fatal read error on pipe transport')
- except exceptions.CancelledError:
- if not self._closing:
- raise
- else:
- if not self._paused:
- self._read_fut.add_done_callback(self._loop_reading)
- finally:
- if length > -1:
- self._data_received(data, length)
-
-
-class _ProactorBaseWritePipeTransport(_ProactorBasePipeTransport,
- transports.WriteTransport):
- """Transport for write pipes."""
-
- _start_tls_compatible = True
-
- def __init__(self, *args, **kw):
- super().__init__(*args, **kw)
- self._empty_waiter = None
-
- def write(self, data):
- if not isinstance(data, (bytes, bytearray, memoryview)):
- raise TypeError(
- f"data argument must be a bytes-like object, "
- f"not {type(data).__name__}")
- if self._eof_written:
- raise RuntimeError('write_eof() already called')
- if self._empty_waiter is not None:
- raise RuntimeError('unable to write; sendfile is in progress')
-
- if not data:
- return
-
- if self._conn_lost:
- if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
- logger.warning('socket.send() raised exception.')
- self._conn_lost += 1
- return
-
- # Observable states:
- # 1. IDLE: _write_fut and _buffer both None
- # 2. WRITING: _write_fut set; _buffer None
- # 3. BACKED UP: _write_fut set; _buffer a bytearray
- # We always copy the data, so the caller can't modify it
- # while we're still waiting for the I/O to happen.
- if self._write_fut is None: # IDLE -> WRITING
- assert self._buffer is None
- # Pass a copy, except if it's already immutable.
- self._loop_writing(data=bytes(data))
- elif not self._buffer: # WRITING -> BACKED UP
- # Make a mutable copy which we can extend.
- self._buffer = bytearray(data)
- self._maybe_pause_protocol()
- else: # BACKED UP
- # Append to buffer (also copies).
- self._buffer.extend(data)
- self._maybe_pause_protocol()
-
- def _loop_writing(self, f=None, data=None):
- try:
- if f is not None and self._write_fut is None and self._closing:
- # XXX most likely self._force_close() has been called, and
- # it has set self._write_fut to None.
- return
- assert f is self._write_fut
- self._write_fut = None
- self._pending_write = 0
- if f:
- f.result()
- if data is None:
- data = self._buffer
- self._buffer = None
- if not data:
- if self._closing:
- self._loop.call_soon(self._call_connection_lost, None)
- if self._eof_written:
- self._sock.shutdown(socket.SHUT_WR)
- # Now that we've reduced the buffer size, tell the
- # protocol to resume writing if it was paused. Note that
- # we do this last since the callback is called immediately
- # and it may add more data to the buffer (even causing the
- # protocol to be paused again).
- self._maybe_resume_protocol()
- else:
- self._write_fut = self._loop._proactor.send(self._sock, data)
- if not self._write_fut.done():
- assert self._pending_write == 0
- self._pending_write = len(data)
- self._write_fut.add_done_callback(self._loop_writing)
- self._maybe_pause_protocol()
- else:
- self._write_fut.add_done_callback(self._loop_writing)
- if self._empty_waiter is not None and self._write_fut is None:
- self._empty_waiter.set_result(None)
- except ConnectionResetError as exc:
- self._force_close(exc)
- except OSError as exc:
- self._fatal_error(exc, 'Fatal write error on pipe transport')
-
- def can_write_eof(self):
- return True
-
- def write_eof(self):
- self.close()
-
- def abort(self):
- self._force_close(None)
-
- def _make_empty_waiter(self):
- if self._empty_waiter is not None:
- raise RuntimeError("Empty waiter is already set")
- self._empty_waiter = self._loop.create_future()
- if self._write_fut is None:
- self._empty_waiter.set_result(None)
- return self._empty_waiter
-
- def _reset_empty_waiter(self):
- self._empty_waiter = None
-
-
-class _ProactorWritePipeTransport(_ProactorBaseWritePipeTransport):
- def __init__(self, *args, **kw):
- super().__init__(*args, **kw)
- self._read_fut = self._loop._proactor.recv(self._sock, 16)
- self._read_fut.add_done_callback(self._pipe_closed)
-
- def _pipe_closed(self, fut):
- if fut.cancelled():
- # the transport has been closed
- return
- assert fut.result() == b''
- if self._closing:
- assert self._read_fut is None
- return
- assert fut is self._read_fut, (fut, self._read_fut)
- self._read_fut = None
- if self._write_fut is not None:
- self._force_close(BrokenPipeError())
- else:
- self.close()
-
-
-class _ProactorDatagramTransport(_ProactorBasePipeTransport,
- transports.DatagramTransport):
- max_size = 256 * 1024
- def __init__(self, loop, sock, protocol, address=None,
- waiter=None, extra=None):
- self._address = address
- self._empty_waiter = None
- # We don't need to call _protocol.connection_made() since our base
- # constructor does it for us.
- super().__init__(loop, sock, protocol, waiter=waiter, extra=extra)
-
- # The base constructor sets _buffer = None, so we set it here
- self._buffer = collections.deque()
- self._loop.call_soon(self._loop_reading)
-
- def _set_extra(self, sock):
- _set_socket_extra(self, sock)
-
- def get_write_buffer_size(self):
- return sum(len(data) for data, _ in self._buffer)
-
- def abort(self):
- self._force_close(None)
-
- def sendto(self, data, addr=None):
- if not isinstance(data, (bytes, bytearray, memoryview)):
- raise TypeError('data argument must be bytes-like object (%r)',
- type(data))
-
- if not data:
- return
-
- if self._address is not None and addr not in (None, self._address):
- raise ValueError(
- f'Invalid address: must be None or {self._address}')
-
- if self._conn_lost and self._address:
- if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
- logger.warning('socket.sendto() raised exception.')
- self._conn_lost += 1
- return
-
- # Ensure that what we buffer is immutable.
- self._buffer.append((bytes(data), addr))
-
- if self._write_fut is None:
- # No current write operations are active, kick one off
- self._loop_writing()
- # else: A write operation is already kicked off
-
- self._maybe_pause_protocol()
-
- def _loop_writing(self, fut=None):
- try:
- if self._conn_lost:
- return
-
- assert fut is self._write_fut
- self._write_fut = None
- if fut:
- # We are in a _loop_writing() done callback, get the result
- fut.result()
-
- if not self._buffer or (self._conn_lost and self._address):
- # The connection has been closed
- if self._closing:
- self._loop.call_soon(self._call_connection_lost, None)
- return
-
- data, addr = self._buffer.popleft()
- if self._address is not None:
- self._write_fut = self._loop._proactor.send(self._sock,
- data)
- else:
- self._write_fut = self._loop._proactor.sendto(self._sock,
- data,
- addr=addr)
- except OSError as exc:
- self._protocol.error_received(exc)
- except Exception as exc:
- self._fatal_error(exc, 'Fatal write error on datagram transport')
- else:
- self._write_fut.add_done_callback(self._loop_writing)
- self._maybe_resume_protocol()
-
- def _loop_reading(self, fut=None):
- data = None
- try:
- if self._conn_lost:
- return
-
- assert self._read_fut is fut or (self._read_fut is None and
- self._closing)
-
- self._read_fut = None
- if fut is not None:
- res = fut.result()
-
- if self._closing:
- # since close() has been called we ignore any read data
- data = None
- return
-
- if self._address is not None:
- data, addr = res, self._address
- else:
- data, addr = res
-
- if self._conn_lost:
- return
- if self._address is not None:
- self._read_fut = self._loop._proactor.recv(self._sock,
- self.max_size)
- else:
- self._read_fut = self._loop._proactor.recvfrom(self._sock,
- self.max_size)
- except OSError as exc:
- self._protocol.error_received(exc)
- except exceptions.CancelledError:
- if not self._closing:
- raise
- else:
- if self._read_fut is not None:
- self._read_fut.add_done_callback(self._loop_reading)
- finally:
- if data:
- self._protocol.datagram_received(data, addr)
-
-
-class _ProactorDuplexPipeTransport(_ProactorReadPipeTransport,
- _ProactorBaseWritePipeTransport,
- transports.Transport):
- """Transport for duplex pipes."""
-
- def can_write_eof(self):
- return False
-
- def write_eof(self):
- raise NotImplementedError
-
-
-class _ProactorSocketTransport(_ProactorReadPipeTransport,
- _ProactorBaseWritePipeTransport,
- transports.Transport):
- """Transport for connected sockets."""
-
- _sendfile_compatible = constants._SendfileMode.TRY_NATIVE
-
- def __init__(self, loop, sock, protocol, waiter=None,
- extra=None, server=None):
- super().__init__(loop, sock, protocol, waiter, extra, server)
- base_events._set_nodelay(sock)
-
- def _set_extra(self, sock):
- _set_socket_extra(self, sock)
-
- def can_write_eof(self):
- return True
-
- def write_eof(self):
- if self._closing or self._eof_written:
- return
- self._eof_written = True
- if self._write_fut is None:
- self._sock.shutdown(socket.SHUT_WR)
-
-
-class BaseProactorEventLoop(base_events.BaseEventLoop):
-
- def __init__(self, proactor):
- super().__init__()
- logger.debug('Using proactor: %s', proactor.__class__.__name__)
- self._proactor = proactor
- self._selector = proactor # convenient alias
- self._self_reading_future = None
- self._accept_futures = {} # socket file descriptor => Future
- proactor.set_loop(self)
- self._make_self_pipe()
- if threading.current_thread() is threading.main_thread():
- # wakeup fd can only be installed to a file descriptor from the main thread
- signal.set_wakeup_fd(self._csock.fileno())
-
- def _make_socket_transport(self, sock, protocol, waiter=None,
- extra=None, server=None):
- return _ProactorSocketTransport(self, sock, protocol, waiter,
- extra, server)
-
- def _make_ssl_transport(
- self, rawsock, protocol, sslcontext, waiter=None,
- *, server_side=False, server_hostname=None,
- extra=None, server=None,
- ssl_handshake_timeout=None):
- ssl_protocol = sslproto.SSLProtocol(
- self, protocol, sslcontext, waiter,
- server_side, server_hostname,
- ssl_handshake_timeout=ssl_handshake_timeout)
- _ProactorSocketTransport(self, rawsock, ssl_protocol,
- extra=extra, server=server)
- return ssl_protocol._app_transport
-
- def _make_datagram_transport(self, sock, protocol,
- address=None, waiter=None, extra=None):
- return _ProactorDatagramTransport(self, sock, protocol, address,
- waiter, extra)
-
- def _make_duplex_pipe_transport(self, sock, protocol, waiter=None,
- extra=None):
- return _ProactorDuplexPipeTransport(self,
- sock, protocol, waiter, extra)
-
- def _make_read_pipe_transport(self, sock, protocol, waiter=None,
- extra=None):
- return _ProactorReadPipeTransport(self, sock, protocol, waiter, extra)
-
- def _make_write_pipe_transport(self, sock, protocol, waiter=None,
- extra=None):
- # We want connection_lost() to be called when other end closes
- return _ProactorWritePipeTransport(self,
- sock, protocol, waiter, extra)
-
- def close(self):
- if self.is_running():
- raise RuntimeError("Cannot close a running event loop")
- if self.is_closed():
- return
-
- if threading.current_thread() is threading.main_thread():
- signal.set_wakeup_fd(-1)
- # Call these methods before closing the event loop (before calling
- # BaseEventLoop.close), because they can schedule callbacks with
- # call_soon(), which is forbidden when the event loop is closed.
- self._stop_accept_futures()
- self._close_self_pipe()
- self._proactor.close()
- self._proactor = None
- self._selector = None
-
- # Close the event loop
- super().close()
-
- async def sock_recv(self, sock, n):
- return await self._proactor.recv(sock, n)
-
- async def sock_recv_into(self, sock, buf):
- return await self._proactor.recv_into(sock, buf)
-
- async def sock_sendall(self, sock, data):
- return await self._proactor.send(sock, data)
-
- async def sock_connect(self, sock, address):
- return await self._proactor.connect(sock, address)
-
- async def sock_accept(self, sock):
- return await self._proactor.accept(sock)
-
- async def _sock_sendfile_native(self, sock, file, offset, count):
- try:
- fileno = file.fileno()
- except (AttributeError, io.UnsupportedOperation) as err:
- raise exceptions.SendfileNotAvailableError("not a regular file")
- try:
- fsize = os.fstat(fileno).st_size
- except OSError:
- raise exceptions.SendfileNotAvailableError("not a regular file")
- blocksize = count if count else fsize
- if not blocksize:
- return 0 # empty file
-
- blocksize = min(blocksize, 0xffff_ffff)
- end_pos = min(offset + count, fsize) if count else fsize
- offset = min(offset, fsize)
- total_sent = 0
- try:
- while True:
- blocksize = min(end_pos - offset, blocksize)
- if blocksize <= 0:
- return total_sent
- await self._proactor.sendfile(sock, file, offset, blocksize)
- offset += blocksize
- total_sent += blocksize
- finally:
- if total_sent > 0:
- file.seek(offset)
-
- async def _sendfile_native(self, transp, file, offset, count):
- resume_reading = transp.is_reading()
- transp.pause_reading()
- await transp._make_empty_waiter()
- try:
- return await self.sock_sendfile(transp._sock, file, offset, count,
- fallback=False)
- finally:
- transp._reset_empty_waiter()
- if resume_reading:
- transp.resume_reading()
-
- def _close_self_pipe(self):
- if self._self_reading_future is not None:
- self._self_reading_future.cancel()
- self._self_reading_future = None
- self._ssock.close()
- self._ssock = None
- self._csock.close()
- self._csock = None
- self._internal_fds -= 1
-
- def _make_self_pipe(self):
- # A self-socket, really. :-)
- self._ssock, self._csock = socket.socketpair()
- self._ssock.setblocking(False)
- self._csock.setblocking(False)
- self._internal_fds += 1
-
- def _loop_self_reading(self, f=None):
- try:
- if f is not None:
- f.result() # may raise
- if self._self_reading_future is not f:
- # When we scheduled this Future, we assigned it to
- # _self_reading_future. If it's not there now, something has
- # tried to cancel the loop while this callback was still in the
- # queue (see windows_events.ProactorEventLoop.run_forever). In
- # that case stop here instead of continuing to schedule a new
- # iteration.
- return
- f = self._proactor.recv(self._ssock, 4096)
- except exceptions.CancelledError:
- # _close_self_pipe() has been called, stop waiting for data
- return
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- self.call_exception_handler({
- 'message': 'Error on reading from the event loop self pipe',
- 'exception': exc,
- 'loop': self,
- })
- else:
- self._self_reading_future = f
- f.add_done_callback(self._loop_self_reading)
-
- def _write_to_self(self):
- # This may be called from a different thread, possibly after
- # _close_self_pipe() has been called or even while it is
- # running. Guard for self._csock being None or closed. When
- # a socket is closed, send() raises OSError (with errno set to
- # EBADF, but let's not rely on the exact error code).
- csock = self._csock
- if csock is None:
- return
-
- try:
- csock.send(b'\0')
- except OSError:
- if self._debug:
- logger.debug("Fail to write a null byte into the "
- "self-pipe socket",
- exc_info=True)
-
- def _start_serving(self, protocol_factory, sock,
- sslcontext=None, server=None, backlog=100,
- ssl_handshake_timeout=None):
-
- def loop(f=None):
- try:
- if f is not None:
- conn, addr = f.result()
- if self._debug:
- logger.debug("%r got a new connection from %r: %r",
- server, addr, conn)
- protocol = protocol_factory()
- if sslcontext is not None:
- self._make_ssl_transport(
- conn, protocol, sslcontext, server_side=True,
- extra={'peername': addr}, server=server,
- ssl_handshake_timeout=ssl_handshake_timeout)
- else:
- self._make_socket_transport(
- conn, protocol,
- extra={'peername': addr}, server=server)
- if self.is_closed():
- return
- f = self._proactor.accept(sock)
- except OSError as exc:
- if sock.fileno() != -1:
- self.call_exception_handler({
- 'message': 'Accept failed on a socket',
- 'exception': exc,
- 'socket': trsock.TransportSocket(sock),
- })
- sock.close()
- elif self._debug:
- logger.debug("Accept failed on socket %r",
- sock, exc_info=True)
- except exceptions.CancelledError:
- sock.close()
- else:
- self._accept_futures[sock.fileno()] = f
- f.add_done_callback(loop)
-
- self.call_soon(loop)
-
- def _process_events(self, event_list):
- # Events are processed in the IocpProactor._poll() method
- pass
-
- def _stop_accept_futures(self):
- for future in self._accept_futures.values():
- future.cancel()
- self._accept_futures.clear()
-
- def _stop_serving(self, sock):
- future = self._accept_futures.pop(sock.fileno(), None)
- if future:
- future.cancel()
- self._proactor._stop_serving(sock)
- sock.close()
diff --git a/lib/python3.10/asyncio/queues.py b/lib/python3.10/asyncio/queues.py
deleted file mode 100644
index 10dd689..0000000
--- a/lib/python3.10/asyncio/queues.py
+++ /dev/null
@@ -1,245 +0,0 @@
-__all__ = ('Queue', 'PriorityQueue', 'LifoQueue', 'QueueFull', 'QueueEmpty')
-
-import collections
-import heapq
-from types import GenericAlias
-
-from . import locks
-from . import mixins
-
-
-class QueueEmpty(Exception):
- """Raised when Queue.get_nowait() is called on an empty Queue."""
- pass
-
-
-class QueueFull(Exception):
- """Raised when the Queue.put_nowait() method is called on a full Queue."""
- pass
-
-
-class Queue(mixins._LoopBoundMixin):
- """A queue, useful for coordinating producer and consumer coroutines.
-
- If maxsize is less than or equal to zero, the queue size is infinite. If it
- is an integer greater than 0, then "await put()" will block when the
- queue reaches maxsize, until an item is removed by get().
-
- Unlike the standard library Queue, you can reliably know this Queue's size
- with qsize(), since your single-threaded asyncio application won't be
- interrupted between calling qsize() and doing an operation on the Queue.
- """
-
- def __init__(self, maxsize=0, *, loop=mixins._marker):
- super().__init__(loop=loop)
- self._maxsize = maxsize
-
- # Futures.
- self._getters = collections.deque()
- # Futures.
- self._putters = collections.deque()
- self._unfinished_tasks = 0
- self._finished = locks.Event()
- self._finished.set()
- self._init(maxsize)
-
- # These three are overridable in subclasses.
-
- def _init(self, maxsize):
- self._queue = collections.deque()
-
- def _get(self):
- return self._queue.popleft()
-
- def _put(self, item):
- self._queue.append(item)
-
- # End of the overridable methods.
-
- def _wakeup_next(self, waiters):
- # Wake up the next waiter (if any) that isn't cancelled.
- while waiters:
- waiter = waiters.popleft()
- if not waiter.done():
- waiter.set_result(None)
- break
-
- def __repr__(self):
- return f'<{type(self).__name__} at {id(self):#x} {self._format()}>'
-
- def __str__(self):
- return f'<{type(self).__name__} {self._format()}>'
-
- __class_getitem__ = classmethod(GenericAlias)
-
- def _format(self):
- result = f'maxsize={self._maxsize!r}'
- if getattr(self, '_queue', None):
- result += f' _queue={list(self._queue)!r}'
- if self._getters:
- result += f' _getters[{len(self._getters)}]'
- if self._putters:
- result += f' _putters[{len(self._putters)}]'
- if self._unfinished_tasks:
- result += f' tasks={self._unfinished_tasks}'
- return result
-
- def qsize(self):
- """Number of items in the queue."""
- return len(self._queue)
-
- @property
- def maxsize(self):
- """Number of items allowed in the queue."""
- return self._maxsize
-
- def empty(self):
- """Return True if the queue is empty, False otherwise."""
- return not self._queue
-
- def full(self):
- """Return True if there are maxsize items in the queue.
-
- Note: if the Queue was initialized with maxsize=0 (the default),
- then full() is never True.
- """
- if self._maxsize <= 0:
- return False
- else:
- return self.qsize() >= self._maxsize
-
- async def put(self, item):
- """Put an item into the queue.
-
- Put an item into the queue. If the queue is full, wait until a free
- slot is available before adding item.
- """
- while self.full():
- putter = self._get_loop().create_future()
- self._putters.append(putter)
- try:
- await putter
- except:
- putter.cancel() # Just in case putter is not done yet.
- try:
- # Clean self._putters from canceled putters.
- self._putters.remove(putter)
- except ValueError:
- # The putter could be removed from self._putters by a
- # previous get_nowait call.
- pass
- if not self.full() and not putter.cancelled():
- # We were woken up by get_nowait(), but can't take
- # the call. Wake up the next in line.
- self._wakeup_next(self._putters)
- raise
- return self.put_nowait(item)
-
- def put_nowait(self, item):
- """Put an item into the queue without blocking.
-
- If no free slot is immediately available, raise QueueFull.
- """
- if self.full():
- raise QueueFull
- self._put(item)
- self._unfinished_tasks += 1
- self._finished.clear()
- self._wakeup_next(self._getters)
-
- async def get(self):
- """Remove and return an item from the queue.
-
- If queue is empty, wait until an item is available.
- """
- while self.empty():
- getter = self._get_loop().create_future()
- self._getters.append(getter)
- try:
- await getter
- except:
- getter.cancel() # Just in case getter is not done yet.
- try:
- # Clean self._getters from canceled getters.
- self._getters.remove(getter)
- except ValueError:
- # The getter could be removed from self._getters by a
- # previous put_nowait call.
- pass
- if not self.empty() and not getter.cancelled():
- # We were woken up by put_nowait(), but can't take
- # the call. Wake up the next in line.
- self._wakeup_next(self._getters)
- raise
- return self.get_nowait()
-
- def get_nowait(self):
- """Remove and return an item from the queue.
-
- Return an item if one is immediately available, else raise QueueEmpty.
- """
- if self.empty():
- raise QueueEmpty
- item = self._get()
- self._wakeup_next(self._putters)
- return item
-
- def task_done(self):
- """Indicate that a formerly enqueued task is complete.
-
- Used by queue consumers. For each get() used to fetch a task,
- a subsequent call to task_done() tells the queue that the processing
- on the task is complete.
-
- If a join() is currently blocking, it will resume when all items have
- been processed (meaning that a task_done() call was received for every
- item that had been put() into the queue).
-
- Raises ValueError if called more times than there were items placed in
- the queue.
- """
- if self._unfinished_tasks <= 0:
- raise ValueError('task_done() called too many times')
- self._unfinished_tasks -= 1
- if self._unfinished_tasks == 0:
- self._finished.set()
-
- async def join(self):
- """Block until all items in the queue have been gotten and processed.
-
- The count of unfinished tasks goes up whenever an item is added to the
- queue. The count goes down whenever a consumer calls task_done() to
- indicate that the item was retrieved and all work on it is complete.
- When the count of unfinished tasks drops to zero, join() unblocks.
- """
- if self._unfinished_tasks > 0:
- await self._finished.wait()
-
-
-class PriorityQueue(Queue):
- """A subclass of Queue; retrieves entries in priority order (lowest first).
-
- Entries are typically tuples of the form: (priority number, data).
- """
-
- def _init(self, maxsize):
- self._queue = []
-
- def _put(self, item, heappush=heapq.heappush):
- heappush(self._queue, item)
-
- def _get(self, heappop=heapq.heappop):
- return heappop(self._queue)
-
-
-class LifoQueue(Queue):
- """A subclass of Queue that retrieves most recently added entries first."""
-
- def _init(self, maxsize):
- self._queue = []
-
- def _put(self, item):
- self._queue.append(item)
-
- def _get(self):
- return self._queue.pop()
diff --git a/lib/python3.10/asyncio/runners.py b/lib/python3.10/asyncio/runners.py
deleted file mode 100644
index 9a5e9a4..0000000
--- a/lib/python3.10/asyncio/runners.py
+++ /dev/null
@@ -1,73 +0,0 @@
-__all__ = 'run',
-
-from . import coroutines
-from . import events
-from . import tasks
-
-
-def run(main, *, debug=None):
- """Execute the coroutine and return the result.
-
- This function runs the passed coroutine, taking care of
- managing the asyncio event loop and finalizing asynchronous
- generators.
-
- This function cannot be called when another asyncio event loop is
- running in the same thread.
-
- If debug is True, the event loop will be run in debug mode.
-
- This function always creates a new event loop and closes it at the end.
- It should be used as a main entry point for asyncio programs, and should
- ideally only be called once.
-
- Example:
-
- async def main():
- await asyncio.sleep(1)
- print('hello')
-
- asyncio.run(main())
- """
- if events._get_running_loop() is not None:
- raise RuntimeError(
- "asyncio.run() cannot be called from a running event loop")
-
- if not coroutines.iscoroutine(main):
- raise ValueError("a coroutine was expected, got {!r}".format(main))
-
- loop = events.new_event_loop()
- try:
- events.set_event_loop(loop)
- if debug is not None:
- loop.set_debug(debug)
- return loop.run_until_complete(main)
- finally:
- try:
- _cancel_all_tasks(loop)
- loop.run_until_complete(loop.shutdown_asyncgens())
- loop.run_until_complete(loop.shutdown_default_executor())
- finally:
- events.set_event_loop(None)
- loop.close()
-
-
-def _cancel_all_tasks(loop):
- to_cancel = tasks.all_tasks(loop)
- if not to_cancel:
- return
-
- for task in to_cancel:
- task.cancel()
-
- loop.run_until_complete(tasks.gather(*to_cancel, return_exceptions=True))
-
- for task in to_cancel:
- if task.cancelled():
- continue
- if task.exception() is not None:
- loop.call_exception_handler({
- 'message': 'unhandled exception during asyncio.run() shutdown',
- 'exception': task.exception(),
- 'task': task,
- })
diff --git a/lib/python3.10/asyncio/selector_events.py b/lib/python3.10/asyncio/selector_events.py
deleted file mode 100644
index 71080b8..0000000
--- a/lib/python3.10/asyncio/selector_events.py
+++ /dev/null
@@ -1,1096 +0,0 @@
-"""Event loop using a selector and related classes.
-
-A selector is a "notify-when-ready" multiplexer. For a subclass which
-also includes support for signal handling, see the unix_events sub-module.
-"""
-
-__all__ = 'BaseSelectorEventLoop',
-
-import collections
-import errno
-import functools
-import selectors
-import socket
-import warnings
-import weakref
-try:
- import ssl
-except ImportError: # pragma: no cover
- ssl = None
-
-from . import base_events
-from . import constants
-from . import events
-from . import futures
-from . import protocols
-from . import sslproto
-from . import transports
-from . import trsock
-from .log import logger
-
-
-def _test_selector_event(selector, fd, event):
- # Test if the selector is monitoring 'event' events
- # for the file descriptor 'fd'.
- try:
- key = selector.get_key(fd)
- except KeyError:
- return False
- else:
- return bool(key.events & event)
-
-
-class BaseSelectorEventLoop(base_events.BaseEventLoop):
- """Selector event loop.
-
- See events.EventLoop for API specification.
- """
-
- def __init__(self, selector=None):
- super().__init__()
-
- if selector is None:
- selector = selectors.DefaultSelector()
- logger.debug('Using selector: %s', selector.__class__.__name__)
- self._selector = selector
- self._make_self_pipe()
- self._transports = weakref.WeakValueDictionary()
-
- def _make_socket_transport(self, sock, protocol, waiter=None, *,
- extra=None, server=None):
- return _SelectorSocketTransport(self, sock, protocol, waiter,
- extra, server)
-
- def _make_ssl_transport(
- self, rawsock, protocol, sslcontext, waiter=None,
- *, server_side=False, server_hostname=None,
- extra=None, server=None,
- ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT):
- ssl_protocol = sslproto.SSLProtocol(
- self, protocol, sslcontext, waiter,
- server_side, server_hostname,
- ssl_handshake_timeout=ssl_handshake_timeout)
- _SelectorSocketTransport(self, rawsock, ssl_protocol,
- extra=extra, server=server)
- return ssl_protocol._app_transport
-
- def _make_datagram_transport(self, sock, protocol,
- address=None, waiter=None, extra=None):
- return _SelectorDatagramTransport(self, sock, protocol,
- address, waiter, extra)
-
- def close(self):
- if self.is_running():
- raise RuntimeError("Cannot close a running event loop")
- if self.is_closed():
- return
- self._close_self_pipe()
- super().close()
- if self._selector is not None:
- self._selector.close()
- self._selector = None
-
- def _close_self_pipe(self):
- self._remove_reader(self._ssock.fileno())
- self._ssock.close()
- self._ssock = None
- self._csock.close()
- self._csock = None
- self._internal_fds -= 1
-
- def _make_self_pipe(self):
- # A self-socket, really. :-)
- self._ssock, self._csock = socket.socketpair()
- self._ssock.setblocking(False)
- self._csock.setblocking(False)
- self._internal_fds += 1
- self._add_reader(self._ssock.fileno(), self._read_from_self)
-
- def _process_self_data(self, data):
- pass
-
- def _read_from_self(self):
- while True:
- try:
- data = self._ssock.recv(4096)
- if not data:
- break
- self._process_self_data(data)
- except InterruptedError:
- continue
- except BlockingIOError:
- break
-
- def _write_to_self(self):
- # This may be called from a different thread, possibly after
- # _close_self_pipe() has been called or even while it is
- # running. Guard for self._csock being None or closed. When
- # a socket is closed, send() raises OSError (with errno set to
- # EBADF, but let's not rely on the exact error code).
- csock = self._csock
- if csock is None:
- return
-
- try:
- csock.send(b'\0')
- except OSError:
- if self._debug:
- logger.debug("Fail to write a null byte into the "
- "self-pipe socket",
- exc_info=True)
-
- def _start_serving(self, protocol_factory, sock,
- sslcontext=None, server=None, backlog=100,
- ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT):
- self._add_reader(sock.fileno(), self._accept_connection,
- protocol_factory, sock, sslcontext, server, backlog,
- ssl_handshake_timeout)
-
- def _accept_connection(
- self, protocol_factory, sock,
- sslcontext=None, server=None, backlog=100,
- ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT):
- # This method is only called once for each event loop tick where the
- # listening socket has triggered an EVENT_READ. There may be multiple
- # connections waiting for an .accept() so it is called in a loop.
- # See https://bugs.python.org/issue27906 for more details.
- for _ in range(backlog):
- try:
- conn, addr = sock.accept()
- if self._debug:
- logger.debug("%r got a new connection from %r: %r",
- server, addr, conn)
- conn.setblocking(False)
- except (BlockingIOError, InterruptedError, ConnectionAbortedError):
- # Early exit because the socket accept buffer is empty.
- return None
- except OSError as exc:
- # There's nowhere to send the error, so just log it.
- if exc.errno in (errno.EMFILE, errno.ENFILE,
- errno.ENOBUFS, errno.ENOMEM):
- # Some platforms (e.g. Linux keep reporting the FD as
- # ready, so we remove the read handler temporarily.
- # We'll try again in a while.
- self.call_exception_handler({
- 'message': 'socket.accept() out of system resource',
- 'exception': exc,
- 'socket': trsock.TransportSocket(sock),
- })
- self._remove_reader(sock.fileno())
- self.call_later(constants.ACCEPT_RETRY_DELAY,
- self._start_serving,
- protocol_factory, sock, sslcontext, server,
- backlog, ssl_handshake_timeout)
- else:
- raise # The event loop will catch, log and ignore it.
- else:
- extra = {'peername': addr}
- accept = self._accept_connection2(
- protocol_factory, conn, extra, sslcontext, server,
- ssl_handshake_timeout)
- self.create_task(accept)
-
- async def _accept_connection2(
- self, protocol_factory, conn, extra,
- sslcontext=None, server=None,
- ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT):
- protocol = None
- transport = None
- try:
- protocol = protocol_factory()
- waiter = self.create_future()
- if sslcontext:
- transport = self._make_ssl_transport(
- conn, protocol, sslcontext, waiter=waiter,
- server_side=True, extra=extra, server=server,
- ssl_handshake_timeout=ssl_handshake_timeout)
- else:
- transport = self._make_socket_transport(
- conn, protocol, waiter=waiter, extra=extra,
- server=server)
-
- try:
- await waiter
- except BaseException:
- transport.close()
- raise
- # It's now up to the protocol to handle the connection.
-
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- if self._debug:
- context = {
- 'message':
- 'Error on transport creation for incoming connection',
- 'exception': exc,
- }
- if protocol is not None:
- context['protocol'] = protocol
- if transport is not None:
- context['transport'] = transport
- self.call_exception_handler(context)
-
- def _ensure_fd_no_transport(self, fd):
- fileno = fd
- if not isinstance(fileno, int):
- try:
- fileno = int(fileno.fileno())
- except (AttributeError, TypeError, ValueError):
- # This code matches selectors._fileobj_to_fd function.
- raise ValueError(f"Invalid file object: {fd!r}") from None
- try:
- transport = self._transports[fileno]
- except KeyError:
- pass
- else:
- if not transport.is_closing():
- raise RuntimeError(
- f'File descriptor {fd!r} is used by transport '
- f'{transport!r}')
-
- def _add_reader(self, fd, callback, *args):
- self._check_closed()
- handle = events.Handle(callback, args, self, None)
- try:
- key = self._selector.get_key(fd)
- except KeyError:
- self._selector.register(fd, selectors.EVENT_READ,
- (handle, None))
- else:
- mask, (reader, writer) = key.events, key.data
- self._selector.modify(fd, mask | selectors.EVENT_READ,
- (handle, writer))
- if reader is not None:
- reader.cancel()
- return handle
-
- def _remove_reader(self, fd):
- if self.is_closed():
- return False
- try:
- key = self._selector.get_key(fd)
- except KeyError:
- return False
- else:
- mask, (reader, writer) = key.events, key.data
- mask &= ~selectors.EVENT_READ
- if not mask:
- self._selector.unregister(fd)
- else:
- self._selector.modify(fd, mask, (None, writer))
-
- if reader is not None:
- reader.cancel()
- return True
- else:
- return False
-
- def _add_writer(self, fd, callback, *args):
- self._check_closed()
- handle = events.Handle(callback, args, self, None)
- try:
- key = self._selector.get_key(fd)
- except KeyError:
- self._selector.register(fd, selectors.EVENT_WRITE,
- (None, handle))
- else:
- mask, (reader, writer) = key.events, key.data
- self._selector.modify(fd, mask | selectors.EVENT_WRITE,
- (reader, handle))
- if writer is not None:
- writer.cancel()
- return handle
-
- def _remove_writer(self, fd):
- """Remove a writer callback."""
- if self.is_closed():
- return False
- try:
- key = self._selector.get_key(fd)
- except KeyError:
- return False
- else:
- mask, (reader, writer) = key.events, key.data
- # Remove both writer and connector.
- mask &= ~selectors.EVENT_WRITE
- if not mask:
- self._selector.unregister(fd)
- else:
- self._selector.modify(fd, mask, (reader, None))
-
- if writer is not None:
- writer.cancel()
- return True
- else:
- return False
-
- def add_reader(self, fd, callback, *args):
- """Add a reader callback."""
- self._ensure_fd_no_transport(fd)
- self._add_reader(fd, callback, *args)
-
- def remove_reader(self, fd):
- """Remove a reader callback."""
- self._ensure_fd_no_transport(fd)
- return self._remove_reader(fd)
-
- def add_writer(self, fd, callback, *args):
- """Add a writer callback.."""
- self._ensure_fd_no_transport(fd)
- self._add_writer(fd, callback, *args)
-
- def remove_writer(self, fd):
- """Remove a writer callback."""
- self._ensure_fd_no_transport(fd)
- return self._remove_writer(fd)
-
- async def sock_recv(self, sock, n):
- """Receive data from the socket.
-
- The return value is a bytes object representing the data received.
- The maximum amount of data to be received at once is specified by
- nbytes.
- """
- base_events._check_ssl_socket(sock)
- if self._debug and sock.gettimeout() != 0:
- raise ValueError("the socket must be non-blocking")
- try:
- return sock.recv(n)
- except (BlockingIOError, InterruptedError):
- pass
- fut = self.create_future()
- fd = sock.fileno()
- self._ensure_fd_no_transport(fd)
- handle = self._add_reader(fd, self._sock_recv, fut, sock, n)
- fut.add_done_callback(
- functools.partial(self._sock_read_done, fd, handle=handle))
- return await fut
-
- def _sock_read_done(self, fd, fut, handle=None):
- if handle is None or not handle.cancelled():
- self.remove_reader(fd)
-
- def _sock_recv(self, fut, sock, n):
- # _sock_recv() can add itself as an I/O callback if the operation can't
- # be done immediately. Don't use it directly, call sock_recv().
- if fut.done():
- return
- try:
- data = sock.recv(n)
- except (BlockingIOError, InterruptedError):
- return # try again next time
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- fut.set_exception(exc)
- else:
- fut.set_result(data)
-
- async def sock_recv_into(self, sock, buf):
- """Receive data from the socket.
-
- The received data is written into *buf* (a writable buffer).
- The return value is the number of bytes written.
- """
- base_events._check_ssl_socket(sock)
- if self._debug and sock.gettimeout() != 0:
- raise ValueError("the socket must be non-blocking")
- try:
- return sock.recv_into(buf)
- except (BlockingIOError, InterruptedError):
- pass
- fut = self.create_future()
- fd = sock.fileno()
- self._ensure_fd_no_transport(fd)
- handle = self._add_reader(fd, self._sock_recv_into, fut, sock, buf)
- fut.add_done_callback(
- functools.partial(self._sock_read_done, fd, handle=handle))
- return await fut
-
- def _sock_recv_into(self, fut, sock, buf):
- # _sock_recv_into() can add itself as an I/O callback if the operation
- # can't be done immediately. Don't use it directly, call
- # sock_recv_into().
- if fut.done():
- return
- try:
- nbytes = sock.recv_into(buf)
- except (BlockingIOError, InterruptedError):
- return # try again next time
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- fut.set_exception(exc)
- else:
- fut.set_result(nbytes)
-
- async def sock_sendall(self, sock, data):
- """Send data to the socket.
-
- The socket must be connected to a remote socket. This method continues
- to send data from data until either all data has been sent or an
- error occurs. None is returned on success. On error, an exception is
- raised, and there is no way to determine how much data, if any, was
- successfully processed by the receiving end of the connection.
- """
- base_events._check_ssl_socket(sock)
- if self._debug and sock.gettimeout() != 0:
- raise ValueError("the socket must be non-blocking")
- try:
- n = sock.send(data)
- except (BlockingIOError, InterruptedError):
- n = 0
-
- if n == len(data):
- # all data sent
- return
-
- fut = self.create_future()
- fd = sock.fileno()
- self._ensure_fd_no_transport(fd)
- # use a trick with a list in closure to store a mutable state
- handle = self._add_writer(fd, self._sock_sendall, fut, sock,
- memoryview(data), [n])
- fut.add_done_callback(
- functools.partial(self._sock_write_done, fd, handle=handle))
- return await fut
-
- def _sock_sendall(self, fut, sock, view, pos):
- if fut.done():
- # Future cancellation can be scheduled on previous loop iteration
- return
- start = pos[0]
- try:
- n = sock.send(view[start:])
- except (BlockingIOError, InterruptedError):
- return
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- fut.set_exception(exc)
- return
-
- start += n
-
- if start == len(view):
- fut.set_result(None)
- else:
- pos[0] = start
-
- async def sock_connect(self, sock, address):
- """Connect to a remote socket at address.
-
- This method is a coroutine.
- """
- base_events._check_ssl_socket(sock)
- if self._debug and sock.gettimeout() != 0:
- raise ValueError("the socket must be non-blocking")
-
- if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX:
- resolved = await self._ensure_resolved(
- address, family=sock.family, type=sock.type, proto=sock.proto,
- loop=self,
- )
- _, _, _, _, address = resolved[0]
-
- fut = self.create_future()
- self._sock_connect(fut, sock, address)
- return await fut
-
- def _sock_connect(self, fut, sock, address):
- fd = sock.fileno()
- try:
- sock.connect(address)
- except (BlockingIOError, InterruptedError):
- # Issue #23618: When the C function connect() fails with EINTR, the
- # connection runs in background. We have to wait until the socket
- # becomes writable to be notified when the connection succeed or
- # fails.
- self._ensure_fd_no_transport(fd)
- handle = self._add_writer(
- fd, self._sock_connect_cb, fut, sock, address)
- fut.add_done_callback(
- functools.partial(self._sock_write_done, fd, handle=handle))
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- fut.set_exception(exc)
- else:
- fut.set_result(None)
-
- def _sock_write_done(self, fd, fut, handle=None):
- if handle is None or not handle.cancelled():
- self.remove_writer(fd)
-
- def _sock_connect_cb(self, fut, sock, address):
- if fut.done():
- return
-
- try:
- err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
- if err != 0:
- # Jump to any except clause below.
- raise OSError(err, f'Connect call failed {address}')
- except (BlockingIOError, InterruptedError):
- # socket is still registered, the callback will be retried later
- pass
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- fut.set_exception(exc)
- else:
- fut.set_result(None)
-
- async def sock_accept(self, sock):
- """Accept a connection.
-
- The socket must be bound to an address and listening for connections.
- The return value is a pair (conn, address) where conn is a new socket
- object usable to send and receive data on the connection, and address
- is the address bound to the socket on the other end of the connection.
- """
- base_events._check_ssl_socket(sock)
- if self._debug and sock.gettimeout() != 0:
- raise ValueError("the socket must be non-blocking")
- fut = self.create_future()
- self._sock_accept(fut, sock)
- return await fut
-
- def _sock_accept(self, fut, sock):
- fd = sock.fileno()
- try:
- conn, address = sock.accept()
- conn.setblocking(False)
- except (BlockingIOError, InterruptedError):
- self._ensure_fd_no_transport(fd)
- handle = self._add_reader(fd, self._sock_accept, fut, sock)
- fut.add_done_callback(
- functools.partial(self._sock_read_done, fd, handle=handle))
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- fut.set_exception(exc)
- else:
- fut.set_result((conn, address))
-
- async def _sendfile_native(self, transp, file, offset, count):
- del self._transports[transp._sock_fd]
- resume_reading = transp.is_reading()
- transp.pause_reading()
- await transp._make_empty_waiter()
- try:
- return await self.sock_sendfile(transp._sock, file, offset, count,
- fallback=False)
- finally:
- transp._reset_empty_waiter()
- if resume_reading:
- transp.resume_reading()
- self._transports[transp._sock_fd] = transp
-
- def _process_events(self, event_list):
- for key, mask in event_list:
- fileobj, (reader, writer) = key.fileobj, key.data
- if mask & selectors.EVENT_READ and reader is not None:
- if reader._cancelled:
- self._remove_reader(fileobj)
- else:
- self._add_callback(reader)
- if mask & selectors.EVENT_WRITE and writer is not None:
- if writer._cancelled:
- self._remove_writer(fileobj)
- else:
- self._add_callback(writer)
-
- def _stop_serving(self, sock):
- self._remove_reader(sock.fileno())
- sock.close()
-
-
-class _SelectorTransport(transports._FlowControlMixin,
- transports.Transport):
-
- max_size = 256 * 1024 # Buffer size passed to recv().
-
- _buffer_factory = bytearray # Constructs initial value for self._buffer.
-
- # Attribute used in the destructor: it must be set even if the constructor
- # is not called (see _SelectorSslTransport which may start by raising an
- # exception)
- _sock = None
-
- def __init__(self, loop, sock, protocol, extra=None, server=None):
- super().__init__(extra, loop)
- self._extra['socket'] = trsock.TransportSocket(sock)
- try:
- self._extra['sockname'] = sock.getsockname()
- except OSError:
- self._extra['sockname'] = None
- if 'peername' not in self._extra:
- try:
- self._extra['peername'] = sock.getpeername()
- except socket.error:
- self._extra['peername'] = None
- self._sock = sock
- self._sock_fd = sock.fileno()
-
- self._protocol_connected = False
- self.set_protocol(protocol)
-
- self._server = server
- self._buffer = self._buffer_factory()
- self._conn_lost = 0 # Set when call to connection_lost scheduled.
- self._closing = False # Set when close() called.
- if self._server is not None:
- self._server._attach()
- loop._transports[self._sock_fd] = self
-
- def __repr__(self):
- info = [self.__class__.__name__]
- if self._sock is None:
- info.append('closed')
- elif self._closing:
- info.append('closing')
- info.append(f'fd={self._sock_fd}')
- # test if the transport was closed
- if self._loop is not None and not self._loop.is_closed():
- polling = _test_selector_event(self._loop._selector,
- self._sock_fd, selectors.EVENT_READ)
- if polling:
- info.append('read=polling')
- else:
- info.append('read=idle')
-
- polling = _test_selector_event(self._loop._selector,
- self._sock_fd,
- selectors.EVENT_WRITE)
- if polling:
- state = 'polling'
- else:
- state = 'idle'
-
- bufsize = self.get_write_buffer_size()
- info.append(f'write=<{state}, bufsize={bufsize}>')
- return '<{}>'.format(' '.join(info))
-
- def abort(self):
- self._force_close(None)
-
- def set_protocol(self, protocol):
- self._protocol = protocol
- self._protocol_connected = True
-
- def get_protocol(self):
- return self._protocol
-
- def is_closing(self):
- return self._closing
-
- def close(self):
- if self._closing:
- return
- self._closing = True
- self._loop._remove_reader(self._sock_fd)
- if not self._buffer:
- self._conn_lost += 1
- self._loop._remove_writer(self._sock_fd)
- self._loop.call_soon(self._call_connection_lost, None)
-
- def __del__(self, _warn=warnings.warn):
- if self._sock is not None:
- _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
- self._sock.close()
-
- def _fatal_error(self, exc, message='Fatal error on transport'):
- # Should be called from exception handler only.
- if isinstance(exc, OSError):
- if self._loop.get_debug():
- logger.debug("%r: %s", self, message, exc_info=True)
- else:
- self._loop.call_exception_handler({
- 'message': message,
- 'exception': exc,
- 'transport': self,
- 'protocol': self._protocol,
- })
- self._force_close(exc)
-
- def _force_close(self, exc):
- if self._conn_lost:
- return
- if self._buffer:
- self._buffer.clear()
- self._loop._remove_writer(self._sock_fd)
- if not self._closing:
- self._closing = True
- self._loop._remove_reader(self._sock_fd)
- self._conn_lost += 1
- self._loop.call_soon(self._call_connection_lost, exc)
-
- def _call_connection_lost(self, exc):
- try:
- if self._protocol_connected:
- self._protocol.connection_lost(exc)
- finally:
- self._sock.close()
- self._sock = None
- self._protocol = None
- self._loop = None
- server = self._server
- if server is not None:
- server._detach()
- self._server = None
-
- def get_write_buffer_size(self):
- return len(self._buffer)
-
- def _add_reader(self, fd, callback, *args):
- if self._closing:
- return
-
- self._loop._add_reader(fd, callback, *args)
-
-
-class _SelectorSocketTransport(_SelectorTransport):
-
- _start_tls_compatible = True
- _sendfile_compatible = constants._SendfileMode.TRY_NATIVE
-
- def __init__(self, loop, sock, protocol, waiter=None,
- extra=None, server=None):
-
- self._read_ready_cb = None
- super().__init__(loop, sock, protocol, extra, server)
- self._eof = False
- self._paused = False
- self._empty_waiter = None
-
- # Disable the Nagle algorithm -- small writes will be
- # sent without waiting for the TCP ACK. This generally
- # decreases the latency (in some cases significantly.)
- base_events._set_nodelay(self._sock)
-
- self._loop.call_soon(self._protocol.connection_made, self)
- # only start reading when connection_made() has been called
- self._loop.call_soon(self._add_reader,
- self._sock_fd, self._read_ready)
- if waiter is not None:
- # only wake up the waiter when connection_made() has been called
- self._loop.call_soon(futures._set_result_unless_cancelled,
- waiter, None)
-
- def set_protocol(self, protocol):
- if isinstance(protocol, protocols.BufferedProtocol):
- self._read_ready_cb = self._read_ready__get_buffer
- else:
- self._read_ready_cb = self._read_ready__data_received
-
- super().set_protocol(protocol)
-
- def is_reading(self):
- return not self._paused and not self._closing
-
- def pause_reading(self):
- if self._closing or self._paused:
- return
- self._paused = True
- self._loop._remove_reader(self._sock_fd)
- if self._loop.get_debug():
- logger.debug("%r pauses reading", self)
-
- def resume_reading(self):
- if self._closing or not self._paused:
- return
- self._paused = False
- self._add_reader(self._sock_fd, self._read_ready)
- if self._loop.get_debug():
- logger.debug("%r resumes reading", self)
-
- def _read_ready(self):
- self._read_ready_cb()
-
- def _read_ready__get_buffer(self):
- if self._conn_lost:
- return
-
- try:
- buf = self._protocol.get_buffer(-1)
- if not len(buf):
- raise RuntimeError('get_buffer() returned an empty buffer')
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- self._fatal_error(
- exc, 'Fatal error: protocol.get_buffer() call failed.')
- return
-
- try:
- nbytes = self._sock.recv_into(buf)
- except (BlockingIOError, InterruptedError):
- return
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- self._fatal_error(exc, 'Fatal read error on socket transport')
- return
-
- if not nbytes:
- self._read_ready__on_eof()
- return
-
- try:
- self._protocol.buffer_updated(nbytes)
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- self._fatal_error(
- exc, 'Fatal error: protocol.buffer_updated() call failed.')
-
- def _read_ready__data_received(self):
- if self._conn_lost:
- return
- try:
- data = self._sock.recv(self.max_size)
- except (BlockingIOError, InterruptedError):
- return
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- self._fatal_error(exc, 'Fatal read error on socket transport')
- return
-
- if not data:
- self._read_ready__on_eof()
- return
-
- try:
- self._protocol.data_received(data)
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- self._fatal_error(
- exc, 'Fatal error: protocol.data_received() call failed.')
-
- def _read_ready__on_eof(self):
- if self._loop.get_debug():
- logger.debug("%r received EOF", self)
-
- try:
- keep_open = self._protocol.eof_received()
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- self._fatal_error(
- exc, 'Fatal error: protocol.eof_received() call failed.')
- return
-
- if keep_open:
- # We're keeping the connection open so the
- # protocol can write more, but we still can't
- # receive more, so remove the reader callback.
- self._loop._remove_reader(self._sock_fd)
- else:
- self.close()
-
- def write(self, data):
- if not isinstance(data, (bytes, bytearray, memoryview)):
- raise TypeError(f'data argument must be a bytes-like object, '
- f'not {type(data).__name__!r}')
- if self._eof:
- raise RuntimeError('Cannot call write() after write_eof()')
- if self._empty_waiter is not None:
- raise RuntimeError('unable to write; sendfile is in progress')
- if not data:
- return
-
- if self._conn_lost:
- if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
- logger.warning('socket.send() raised exception.')
- self._conn_lost += 1
- return
-
- if not self._buffer:
- # Optimization: try to send now.
- try:
- n = self._sock.send(data)
- except (BlockingIOError, InterruptedError):
- pass
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- self._fatal_error(exc, 'Fatal write error on socket transport')
- return
- else:
- data = data[n:]
- if not data:
- return
- # Not all was written; register write handler.
- self._loop._add_writer(self._sock_fd, self._write_ready)
-
- # Add it to the buffer.
- self._buffer.extend(data)
- self._maybe_pause_protocol()
-
- def _write_ready(self):
- assert self._buffer, 'Data should not be empty'
-
- if self._conn_lost:
- return
- try:
- n = self._sock.send(self._buffer)
- except (BlockingIOError, InterruptedError):
- pass
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- self._loop._remove_writer(self._sock_fd)
- self._buffer.clear()
- self._fatal_error(exc, 'Fatal write error on socket transport')
- if self._empty_waiter is not None:
- self._empty_waiter.set_exception(exc)
- else:
- if n:
- del self._buffer[:n]
- self._maybe_resume_protocol() # May append to buffer.
- if not self._buffer:
- self._loop._remove_writer(self._sock_fd)
- if self._empty_waiter is not None:
- self._empty_waiter.set_result(None)
- if self._closing:
- self._call_connection_lost(None)
- elif self._eof:
- self._sock.shutdown(socket.SHUT_WR)
-
- def write_eof(self):
- if self._closing or self._eof:
- return
- self._eof = True
- if not self._buffer:
- self._sock.shutdown(socket.SHUT_WR)
-
- def can_write_eof(self):
- return True
-
- def _call_connection_lost(self, exc):
- super()._call_connection_lost(exc)
- if self._empty_waiter is not None:
- self._empty_waiter.set_exception(
- ConnectionError("Connection is closed by peer"))
-
- def _make_empty_waiter(self):
- if self._empty_waiter is not None:
- raise RuntimeError("Empty waiter is already set")
- self._empty_waiter = self._loop.create_future()
- if not self._buffer:
- self._empty_waiter.set_result(None)
- return self._empty_waiter
-
- def _reset_empty_waiter(self):
- self._empty_waiter = None
-
-
-class _SelectorDatagramTransport(_SelectorTransport):
-
- _buffer_factory = collections.deque
-
- def __init__(self, loop, sock, protocol, address=None,
- waiter=None, extra=None):
- super().__init__(loop, sock, protocol, extra)
- self._address = address
- self._loop.call_soon(self._protocol.connection_made, self)
- # only start reading when connection_made() has been called
- self._loop.call_soon(self._add_reader,
- self._sock_fd, self._read_ready)
- if waiter is not None:
- # only wake up the waiter when connection_made() has been called
- self._loop.call_soon(futures._set_result_unless_cancelled,
- waiter, None)
-
- def get_write_buffer_size(self):
- return sum(len(data) for data, _ in self._buffer)
-
- def _read_ready(self):
- if self._conn_lost:
- return
- try:
- data, addr = self._sock.recvfrom(self.max_size)
- except (BlockingIOError, InterruptedError):
- pass
- except OSError as exc:
- self._protocol.error_received(exc)
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- self._fatal_error(exc, 'Fatal read error on datagram transport')
- else:
- self._protocol.datagram_received(data, addr)
-
- def sendto(self, data, addr=None):
- if not isinstance(data, (bytes, bytearray, memoryview)):
- raise TypeError(f'data argument must be a bytes-like object, '
- f'not {type(data).__name__!r}')
- if not data:
- return
-
- if self._address:
- if addr not in (None, self._address):
- raise ValueError(
- f'Invalid address: must be None or {self._address}')
- addr = self._address
-
- if self._conn_lost and self._address:
- if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
- logger.warning('socket.send() raised exception.')
- self._conn_lost += 1
- return
-
- if not self._buffer:
- # Attempt to send it right away first.
- try:
- if self._extra['peername']:
- self._sock.send(data)
- else:
- self._sock.sendto(data, addr)
- return
- except (BlockingIOError, InterruptedError):
- self._loop._add_writer(self._sock_fd, self._sendto_ready)
- except OSError as exc:
- self._protocol.error_received(exc)
- return
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- self._fatal_error(
- exc, 'Fatal write error on datagram transport')
- return
-
- # Ensure that what we buffer is immutable.
- self._buffer.append((bytes(data), addr))
- self._maybe_pause_protocol()
-
- def _sendto_ready(self):
- while self._buffer:
- data, addr = self._buffer.popleft()
- try:
- if self._extra['peername']:
- self._sock.send(data)
- else:
- self._sock.sendto(data, addr)
- except (BlockingIOError, InterruptedError):
- self._buffer.appendleft((data, addr)) # Try again later.
- break
- except OSError as exc:
- self._protocol.error_received(exc)
- return
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- self._fatal_error(
- exc, 'Fatal write error on datagram transport')
- return
-
- self._maybe_resume_protocol() # May append to buffer.
- if not self._buffer:
- self._loop._remove_writer(self._sock_fd)
- if self._closing:
- self._call_connection_lost(None)
diff --git a/lib/python3.10/asyncio/sslproto.py b/lib/python3.10/asyncio/sslproto.py
deleted file mode 100644
index 00fc16c..0000000
--- a/lib/python3.10/asyncio/sslproto.py
+++ /dev/null
@@ -1,739 +0,0 @@
-import collections
-import warnings
-try:
- import ssl
-except ImportError: # pragma: no cover
- ssl = None
-
-from . import constants
-from . import protocols
-from . import transports
-from .log import logger
-
-
-def _create_transport_context(server_side, server_hostname):
- if server_side:
- raise ValueError('Server side SSL needs a valid SSLContext')
-
- # Client side may pass ssl=True to use a default
- # context; in that case the sslcontext passed is None.
- # The default is secure for client connections.
- # Python 3.4+: use up-to-date strong settings.
- sslcontext = ssl.create_default_context()
- if not server_hostname:
- sslcontext.check_hostname = False
- return sslcontext
-
-
-# States of an _SSLPipe.
-_UNWRAPPED = "UNWRAPPED"
-_DO_HANDSHAKE = "DO_HANDSHAKE"
-_WRAPPED = "WRAPPED"
-_SHUTDOWN = "SHUTDOWN"
-
-
-class _SSLPipe(object):
- """An SSL "Pipe".
-
- An SSL pipe allows you to communicate with an SSL/TLS protocol instance
- through memory buffers. It can be used to implement a security layer for an
- existing connection where you don't have access to the connection's file
- descriptor, or for some reason you don't want to use it.
-
- An SSL pipe can be in "wrapped" and "unwrapped" mode. In unwrapped mode,
- data is passed through untransformed. In wrapped mode, application level
- data is encrypted to SSL record level data and vice versa. The SSL record
- level is the lowest level in the SSL protocol suite and is what travels
- as-is over the wire.
-
- An SslPipe initially is in "unwrapped" mode. To start SSL, call
- do_handshake(). To shutdown SSL again, call unwrap().
- """
-
- max_size = 256 * 1024 # Buffer size passed to read()
-
- def __init__(self, context, server_side, server_hostname=None):
- """
- The *context* argument specifies the ssl.SSLContext to use.
-
- The *server_side* argument indicates whether this is a server side or
- client side transport.
-
- The optional *server_hostname* argument can be used to specify the
- hostname you are connecting to. You may only specify this parameter if
- the _ssl module supports Server Name Indication (SNI).
- """
- self._context = context
- self._server_side = server_side
- self._server_hostname = server_hostname
- self._state = _UNWRAPPED
- self._incoming = ssl.MemoryBIO()
- self._outgoing = ssl.MemoryBIO()
- self._sslobj = None
- self._need_ssldata = False
- self._handshake_cb = None
- self._shutdown_cb = None
-
- @property
- def context(self):
- """The SSL context passed to the constructor."""
- return self._context
-
- @property
- def ssl_object(self):
- """The internal ssl.SSLObject instance.
-
- Return None if the pipe is not wrapped.
- """
- return self._sslobj
-
- @property
- def need_ssldata(self):
- """Whether more record level data is needed to complete a handshake
- that is currently in progress."""
- return self._need_ssldata
-
- @property
- def wrapped(self):
- """
- Whether a security layer is currently in effect.
-
- Return False during handshake.
- """
- return self._state == _WRAPPED
-
- def do_handshake(self, callback=None):
- """Start the SSL handshake.
-
- Return a list of ssldata. A ssldata element is a list of buffers
-
- The optional *callback* argument can be used to install a callback that
- will be called when the handshake is complete. The callback will be
- called with None if successful, else an exception instance.
- """
- if self._state != _UNWRAPPED:
- raise RuntimeError('handshake in progress or completed')
- self._sslobj = self._context.wrap_bio(
- self._incoming, self._outgoing,
- server_side=self._server_side,
- server_hostname=self._server_hostname)
- self._state = _DO_HANDSHAKE
- self._handshake_cb = callback
- ssldata, appdata = self.feed_ssldata(b'', only_handshake=True)
- assert len(appdata) == 0
- return ssldata
-
- def shutdown(self, callback=None):
- """Start the SSL shutdown sequence.
-
- Return a list of ssldata. A ssldata element is a list of buffers
-
- The optional *callback* argument can be used to install a callback that
- will be called when the shutdown is complete. The callback will be
- called without arguments.
- """
- if self._state == _UNWRAPPED:
- raise RuntimeError('no security layer present')
- if self._state == _SHUTDOWN:
- raise RuntimeError('shutdown in progress')
- assert self._state in (_WRAPPED, _DO_HANDSHAKE)
- self._state = _SHUTDOWN
- self._shutdown_cb = callback
- ssldata, appdata = self.feed_ssldata(b'')
- assert appdata == [] or appdata == [b'']
- return ssldata
-
- def feed_eof(self):
- """Send a potentially "ragged" EOF.
-
- This method will raise an SSL_ERROR_EOF exception if the EOF is
- unexpected.
- """
- self._incoming.write_eof()
- ssldata, appdata = self.feed_ssldata(b'')
- assert appdata == [] or appdata == [b'']
-
- def feed_ssldata(self, data, only_handshake=False):
- """Feed SSL record level data into the pipe.
-
- The data must be a bytes instance. It is OK to send an empty bytes
- instance. This can be used to get ssldata for a handshake initiated by
- this endpoint.
-
- Return a (ssldata, appdata) tuple. The ssldata element is a list of
- buffers containing SSL data that needs to be sent to the remote SSL.
-
- The appdata element is a list of buffers containing plaintext data that
- needs to be forwarded to the application. The appdata list may contain
- an empty buffer indicating an SSL "close_notify" alert. This alert must
- be acknowledged by calling shutdown().
- """
- if self._state == _UNWRAPPED:
- # If unwrapped, pass plaintext data straight through.
- if data:
- appdata = [data]
- else:
- appdata = []
- return ([], appdata)
-
- self._need_ssldata = False
- if data:
- self._incoming.write(data)
-
- ssldata = []
- appdata = []
- try:
- if self._state == _DO_HANDSHAKE:
- # Call do_handshake() until it doesn't raise anymore.
- self._sslobj.do_handshake()
- self._state = _WRAPPED
- if self._handshake_cb:
- self._handshake_cb(None)
- if only_handshake:
- return (ssldata, appdata)
- # Handshake done: execute the wrapped block
-
- if self._state == _WRAPPED:
- # Main state: read data from SSL until close_notify
- while True:
- chunk = self._sslobj.read(self.max_size)
- appdata.append(chunk)
- if not chunk: # close_notify
- break
-
- elif self._state == _SHUTDOWN:
- # Call shutdown() until it doesn't raise anymore.
- self._sslobj.unwrap()
- self._sslobj = None
- self._state = _UNWRAPPED
- if self._shutdown_cb:
- self._shutdown_cb()
-
- elif self._state == _UNWRAPPED:
- # Drain possible plaintext data after close_notify.
- appdata.append(self._incoming.read())
- except (ssl.SSLError, ssl.CertificateError) as exc:
- exc_errno = getattr(exc, 'errno', None)
- if exc_errno not in (
- ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE,
- ssl.SSL_ERROR_SYSCALL):
- if self._state == _DO_HANDSHAKE and self._handshake_cb:
- self._handshake_cb(exc)
- raise
- self._need_ssldata = (exc_errno == ssl.SSL_ERROR_WANT_READ)
-
- # Check for record level data that needs to be sent back.
- # Happens for the initial handshake and renegotiations.
- if self._outgoing.pending:
- ssldata.append(self._outgoing.read())
- return (ssldata, appdata)
-
- def feed_appdata(self, data, offset=0):
- """Feed plaintext data into the pipe.
-
- Return an (ssldata, offset) tuple. The ssldata element is a list of
- buffers containing record level data that needs to be sent to the
- remote SSL instance. The offset is the number of plaintext bytes that
- were processed, which may be less than the length of data.
-
- NOTE: In case of short writes, this call MUST be retried with the SAME
- buffer passed into the *data* argument (i.e. the id() must be the
- same). This is an OpenSSL requirement. A further particularity is that
- a short write will always have offset == 0, because the _ssl module
- does not enable partial writes. And even though the offset is zero,
- there will still be encrypted data in ssldata.
- """
- assert 0 <= offset <= len(data)
- if self._state == _UNWRAPPED:
- # pass through data in unwrapped mode
- if offset < len(data):
- ssldata = [data[offset:]]
- else:
- ssldata = []
- return (ssldata, len(data))
-
- ssldata = []
- view = memoryview(data)
- while True:
- self._need_ssldata = False
- try:
- if offset < len(view):
- offset += self._sslobj.write(view[offset:])
- except ssl.SSLError as exc:
- # It is not allowed to call write() after unwrap() until the
- # close_notify is acknowledged. We return the condition to the
- # caller as a short write.
- exc_errno = getattr(exc, 'errno', None)
- if exc.reason == 'PROTOCOL_IS_SHUTDOWN':
- exc_errno = exc.errno = ssl.SSL_ERROR_WANT_READ
- if exc_errno not in (ssl.SSL_ERROR_WANT_READ,
- ssl.SSL_ERROR_WANT_WRITE,
- ssl.SSL_ERROR_SYSCALL):
- raise
- self._need_ssldata = (exc_errno == ssl.SSL_ERROR_WANT_READ)
-
- # See if there's any record level data back for us.
- if self._outgoing.pending:
- ssldata.append(self._outgoing.read())
- if offset == len(view) or self._need_ssldata:
- break
- return (ssldata, offset)
-
-
-class _SSLProtocolTransport(transports._FlowControlMixin,
- transports.Transport):
-
- _sendfile_compatible = constants._SendfileMode.FALLBACK
-
- def __init__(self, loop, ssl_protocol):
- self._loop = loop
- # SSLProtocol instance
- self._ssl_protocol = ssl_protocol
- self._closed = False
-
- def get_extra_info(self, name, default=None):
- """Get optional transport information."""
- return self._ssl_protocol._get_extra_info(name, default)
-
- def set_protocol(self, protocol):
- self._ssl_protocol._set_app_protocol(protocol)
-
- def get_protocol(self):
- return self._ssl_protocol._app_protocol
-
- def is_closing(self):
- return self._closed
-
- def close(self):
- """Close the transport.
-
- Buffered data will be flushed asynchronously. No more data
- will be received. After all buffered data is flushed, the
- protocol's connection_lost() method will (eventually) called
- with None as its argument.
- """
- self._closed = True
- self._ssl_protocol._start_shutdown()
-
- def __del__(self, _warn=warnings.warn):
- if not self._closed:
- _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
- self.close()
-
- def is_reading(self):
- tr = self._ssl_protocol._transport
- if tr is None:
- raise RuntimeError('SSL transport has not been initialized yet')
- return tr.is_reading()
-
- def pause_reading(self):
- """Pause the receiving end.
-
- No data will be passed to the protocol's data_received()
- method until resume_reading() is called.
- """
- self._ssl_protocol._transport.pause_reading()
-
- def resume_reading(self):
- """Resume the receiving end.
-
- Data received will once again be passed to the protocol's
- data_received() method.
- """
- self._ssl_protocol._transport.resume_reading()
-
- def set_write_buffer_limits(self, high=None, low=None):
- """Set the high- and low-water limits for write flow control.
-
- These two values control when to call the protocol's
- pause_writing() and resume_writing() methods. If specified,
- the low-water limit must be less than or equal to the
- high-water limit. Neither value can be negative.
-
- The defaults are implementation-specific. If only the
- high-water limit is given, the low-water limit defaults to an
- implementation-specific value less than or equal to the
- high-water limit. Setting high to zero forces low to zero as
- well, and causes pause_writing() to be called whenever the
- buffer becomes non-empty. Setting low to zero causes
- resume_writing() to be called only once the buffer is empty.
- Use of zero for either limit is generally sub-optimal as it
- reduces opportunities for doing I/O and computation
- concurrently.
- """
- self._ssl_protocol._transport.set_write_buffer_limits(high, low)
-
- def get_write_buffer_size(self):
- """Return the current size of the write buffer."""
- return self._ssl_protocol._transport.get_write_buffer_size()
-
- def get_write_buffer_limits(self):
- """Get the high and low watermarks for write flow control.
- Return a tuple (low, high) where low and high are
- positive number of bytes."""
- return self._ssl_protocol._transport.get_write_buffer_limits()
-
- @property
- def _protocol_paused(self):
- # Required for sendfile fallback pause_writing/resume_writing logic
- return self._ssl_protocol._transport._protocol_paused
-
- def write(self, data):
- """Write some data bytes to the transport.
-
- This does not block; it buffers the data and arranges for it
- to be sent out asynchronously.
- """
- if not isinstance(data, (bytes, bytearray, memoryview)):
- raise TypeError(f"data: expecting a bytes-like instance, "
- f"got {type(data).__name__}")
- if not data:
- return
- self._ssl_protocol._write_appdata(data)
-
- def can_write_eof(self):
- """Return True if this transport supports write_eof(), False if not."""
- return False
-
- def abort(self):
- """Close the transport immediately.
-
- Buffered data will be lost. No more data will be received.
- The protocol's connection_lost() method will (eventually) be
- called with None as its argument.
- """
- self._ssl_protocol._abort()
- self._closed = True
-
-
-class SSLProtocol(protocols.Protocol):
- """SSL protocol.
-
- Implementation of SSL on top of a socket using incoming and outgoing
- buffers which are ssl.MemoryBIO objects.
- """
-
- def __init__(self, loop, app_protocol, sslcontext, waiter,
- server_side=False, server_hostname=None,
- call_connection_made=True,
- ssl_handshake_timeout=None):
- if ssl is None:
- raise RuntimeError('stdlib ssl module not available')
-
- if ssl_handshake_timeout is None:
- ssl_handshake_timeout = constants.SSL_HANDSHAKE_TIMEOUT
- elif ssl_handshake_timeout <= 0:
- raise ValueError(
- f"ssl_handshake_timeout should be a positive number, "
- f"got {ssl_handshake_timeout}")
-
- if not sslcontext:
- sslcontext = _create_transport_context(
- server_side, server_hostname)
-
- self._server_side = server_side
- if server_hostname and not server_side:
- self._server_hostname = server_hostname
- else:
- self._server_hostname = None
- self._sslcontext = sslcontext
- # SSL-specific extra info. More info are set when the handshake
- # completes.
- self._extra = dict(sslcontext=sslcontext)
-
- # App data write buffering
- self._write_backlog = collections.deque()
- self._write_buffer_size = 0
-
- self._waiter = waiter
- self._loop = loop
- self._set_app_protocol(app_protocol)
- self._app_transport = _SSLProtocolTransport(self._loop, self)
- # _SSLPipe instance (None until the connection is made)
- self._sslpipe = None
- self._session_established = False
- self._in_handshake = False
- self._in_shutdown = False
- # transport, ex: SelectorSocketTransport
- self._transport = None
- self._call_connection_made = call_connection_made
- self._ssl_handshake_timeout = ssl_handshake_timeout
-
- def _set_app_protocol(self, app_protocol):
- self._app_protocol = app_protocol
- self._app_protocol_is_buffer = \
- isinstance(app_protocol, protocols.BufferedProtocol)
-
- def _wakeup_waiter(self, exc=None):
- if self._waiter is None:
- return
- if not self._waiter.cancelled():
- if exc is not None:
- self._waiter.set_exception(exc)
- else:
- self._waiter.set_result(None)
- self._waiter = None
-
- def connection_made(self, transport):
- """Called when the low-level connection is made.
-
- Start the SSL handshake.
- """
- self._transport = transport
- self._sslpipe = _SSLPipe(self._sslcontext,
- self._server_side,
- self._server_hostname)
- self._start_handshake()
-
- def connection_lost(self, exc):
- """Called when the low-level connection is lost or closed.
-
- The argument is an exception object or None (the latter
- meaning a regular EOF is received or the connection was
- aborted or closed).
- """
- if self._session_established:
- self._session_established = False
- self._loop.call_soon(self._app_protocol.connection_lost, exc)
- else:
- # Most likely an exception occurred while in SSL handshake.
- # Just mark the app transport as closed so that its __del__
- # doesn't complain.
- if self._app_transport is not None:
- self._app_transport._closed = True
- self._transport = None
- self._app_transport = None
- if getattr(self, '_handshake_timeout_handle', None):
- self._handshake_timeout_handle.cancel()
- self._wakeup_waiter(exc)
- self._app_protocol = None
- self._sslpipe = None
-
- def pause_writing(self):
- """Called when the low-level transport's buffer goes over
- the high-water mark.
- """
- self._app_protocol.pause_writing()
-
- def resume_writing(self):
- """Called when the low-level transport's buffer drains below
- the low-water mark.
- """
- self._app_protocol.resume_writing()
-
- def data_received(self, data):
- """Called when some SSL data is received.
-
- The argument is a bytes object.
- """
- if self._sslpipe is None:
- # transport closing, sslpipe is destroyed
- return
-
- try:
- ssldata, appdata = self._sslpipe.feed_ssldata(data)
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as e:
- self._fatal_error(e, 'SSL error in data received')
- return
-
- for chunk in ssldata:
- self._transport.write(chunk)
-
- for chunk in appdata:
- if chunk:
- try:
- if self._app_protocol_is_buffer:
- protocols._feed_data_to_buffered_proto(
- self._app_protocol, chunk)
- else:
- self._app_protocol.data_received(chunk)
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as ex:
- self._fatal_error(
- ex, 'application protocol failed to receive SSL data')
- return
- else:
- self._start_shutdown()
- break
-
- def eof_received(self):
- """Called when the other end of the low-level stream
- is half-closed.
-
- If this returns a false value (including None), the transport
- will close itself. If it returns a true value, closing the
- transport is up to the protocol.
- """
- try:
- if self._loop.get_debug():
- logger.debug("%r received EOF", self)
-
- self._wakeup_waiter(ConnectionResetError)
-
- if not self._in_handshake:
- keep_open = self._app_protocol.eof_received()
- if keep_open:
- logger.warning('returning true from eof_received() '
- 'has no effect when using ssl')
- finally:
- self._transport.close()
-
- def _get_extra_info(self, name, default=None):
- if name in self._extra:
- return self._extra[name]
- elif self._transport is not None:
- return self._transport.get_extra_info(name, default)
- else:
- return default
-
- def _start_shutdown(self):
- if self._in_shutdown:
- return
- if self._in_handshake:
- self._abort()
- else:
- self._in_shutdown = True
- self._write_appdata(b'')
-
- def _write_appdata(self, data):
- self._write_backlog.append((data, 0))
- self._write_buffer_size += len(data)
- self._process_write_backlog()
-
- def _start_handshake(self):
- if self._loop.get_debug():
- logger.debug("%r starts SSL handshake", self)
- self._handshake_start_time = self._loop.time()
- else:
- self._handshake_start_time = None
- self._in_handshake = True
- # (b'', 1) is a special value in _process_write_backlog() to do
- # the SSL handshake
- self._write_backlog.append((b'', 1))
- self._handshake_timeout_handle = \
- self._loop.call_later(self._ssl_handshake_timeout,
- self._check_handshake_timeout)
- self._process_write_backlog()
-
- def _check_handshake_timeout(self):
- if self._in_handshake is True:
- msg = (
- f"SSL handshake is taking longer than "
- f"{self._ssl_handshake_timeout} seconds: "
- f"aborting the connection"
- )
- self._fatal_error(ConnectionAbortedError(msg))
-
- def _on_handshake_complete(self, handshake_exc):
- self._in_handshake = False
- self._handshake_timeout_handle.cancel()
-
- sslobj = self._sslpipe.ssl_object
- try:
- if handshake_exc is not None:
- raise handshake_exc
-
- peercert = sslobj.getpeercert()
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- if isinstance(exc, ssl.CertificateError):
- msg = 'SSL handshake failed on verifying the certificate'
- else:
- msg = 'SSL handshake failed'
- self._fatal_error(exc, msg)
- return
-
- if self._loop.get_debug():
- dt = self._loop.time() - self._handshake_start_time
- logger.debug("%r: SSL handshake took %.1f ms", self, dt * 1e3)
-
- # Add extra info that becomes available after handshake.
- self._extra.update(peercert=peercert,
- cipher=sslobj.cipher(),
- compression=sslobj.compression(),
- ssl_object=sslobj,
- )
- if self._call_connection_made:
- self._app_protocol.connection_made(self._app_transport)
- self._wakeup_waiter()
- self._session_established = True
- # In case transport.write() was already called. Don't call
- # immediately _process_write_backlog(), but schedule it:
- # _on_handshake_complete() can be called indirectly from
- # _process_write_backlog(), and _process_write_backlog() is not
- # reentrant.
- self._loop.call_soon(self._process_write_backlog)
-
- def _process_write_backlog(self):
- # Try to make progress on the write backlog.
- if self._transport is None or self._sslpipe is None:
- return
-
- try:
- for i in range(len(self._write_backlog)):
- data, offset = self._write_backlog[0]
- if data:
- ssldata, offset = self._sslpipe.feed_appdata(data, offset)
- elif offset:
- ssldata = self._sslpipe.do_handshake(
- self._on_handshake_complete)
- offset = 1
- else:
- ssldata = self._sslpipe.shutdown(self._finalize)
- offset = 1
-
- for chunk in ssldata:
- self._transport.write(chunk)
-
- if offset < len(data):
- self._write_backlog[0] = (data, offset)
- # A short write means that a write is blocked on a read
- # We need to enable reading if it is paused!
- assert self._sslpipe.need_ssldata
- if self._transport._paused:
- self._transport.resume_reading()
- break
-
- # An entire chunk from the backlog was processed. We can
- # delete it and reduce the outstanding buffer size.
- del self._write_backlog[0]
- self._write_buffer_size -= len(data)
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- if self._in_handshake:
- # Exceptions will be re-raised in _on_handshake_complete.
- self._on_handshake_complete(exc)
- else:
- self._fatal_error(exc, 'Fatal error on SSL transport')
-
- def _fatal_error(self, exc, message='Fatal error on transport'):
- if isinstance(exc, OSError):
- if self._loop.get_debug():
- logger.debug("%r: %s", self, message, exc_info=True)
- else:
- self._loop.call_exception_handler({
- 'message': message,
- 'exception': exc,
- 'transport': self._transport,
- 'protocol': self,
- })
- if self._transport:
- self._transport._force_close(exc)
-
- def _finalize(self):
- self._sslpipe = None
-
- if self._transport is not None:
- self._transport.close()
-
- def _abort(self):
- try:
- if self._transport is not None:
- self._transport.abort()
- finally:
- self._finalize()
diff --git a/lib/python3.10/asyncio/streams.py b/lib/python3.10/asyncio/streams.py
deleted file mode 100644
index 080d8a6..0000000
--- a/lib/python3.10/asyncio/streams.py
+++ /dev/null
@@ -1,726 +0,0 @@
-__all__ = (
- 'StreamReader', 'StreamWriter', 'StreamReaderProtocol',
- 'open_connection', 'start_server')
-
-import socket
-import sys
-import warnings
-import weakref
-
-if hasattr(socket, 'AF_UNIX'):
- __all__ += ('open_unix_connection', 'start_unix_server')
-
-from . import coroutines
-from . import events
-from . import exceptions
-from . import format_helpers
-from . import protocols
-from .log import logger
-from .tasks import sleep
-
-
-_DEFAULT_LIMIT = 2 ** 16 # 64 KiB
-
-
-async def open_connection(host=None, port=None, *,
- limit=_DEFAULT_LIMIT, **kwds):
- """A wrapper for create_connection() returning a (reader, writer) pair.
-
- The reader returned is a StreamReader instance; the writer is a
- StreamWriter instance.
-
- The arguments are all the usual arguments to create_connection()
- except protocol_factory; most common are positional host and port,
- with various optional keyword arguments following.
-
- Additional optional keyword arguments are loop (to set the event loop
- instance to use) and limit (to set the buffer limit passed to the
- StreamReader).
-
- (If you want to customize the StreamReader and/or
- StreamReaderProtocol classes, just copy the code -- there's
- really nothing special here except some convenience.)
- """
- loop = events.get_running_loop()
- reader = StreamReader(limit=limit, loop=loop)
- protocol = StreamReaderProtocol(reader, loop=loop)
- transport, _ = await loop.create_connection(
- lambda: protocol, host, port, **kwds)
- writer = StreamWriter(transport, protocol, reader, loop)
- return reader, writer
-
-
-async def start_server(client_connected_cb, host=None, port=None, *,
- limit=_DEFAULT_LIMIT, **kwds):
- """Start a socket server, call back for each client connected.
-
- The first parameter, `client_connected_cb`, takes two parameters:
- client_reader, client_writer. client_reader is a StreamReader
- object, while client_writer is a StreamWriter object. This
- parameter can either be a plain callback function or a coroutine;
- if it is a coroutine, it will be automatically converted into a
- Task.
-
- The rest of the arguments are all the usual arguments to
- loop.create_server() except protocol_factory; most common are
- positional host and port, with various optional keyword arguments
- following. The return value is the same as loop.create_server().
-
- Additional optional keyword arguments are loop (to set the event loop
- instance to use) and limit (to set the buffer limit passed to the
- StreamReader).
-
- The return value is the same as loop.create_server(), i.e. a
- Server object which can be used to stop the service.
- """
- loop = events.get_running_loop()
-
- def factory():
- reader = StreamReader(limit=limit, loop=loop)
- protocol = StreamReaderProtocol(reader, client_connected_cb,
- loop=loop)
- return protocol
-
- return await loop.create_server(factory, host, port, **kwds)
-
-
-if hasattr(socket, 'AF_UNIX'):
- # UNIX Domain Sockets are supported on this platform
-
- async def open_unix_connection(path=None, *,
- limit=_DEFAULT_LIMIT, **kwds):
- """Similar to `open_connection` but works with UNIX Domain Sockets."""
- loop = events.get_running_loop()
-
- reader = StreamReader(limit=limit, loop=loop)
- protocol = StreamReaderProtocol(reader, loop=loop)
- transport, _ = await loop.create_unix_connection(
- lambda: protocol, path, **kwds)
- writer = StreamWriter(transport, protocol, reader, loop)
- return reader, writer
-
- async def start_unix_server(client_connected_cb, path=None, *,
- limit=_DEFAULT_LIMIT, **kwds):
- """Similar to `start_server` but works with UNIX Domain Sockets."""
- loop = events.get_running_loop()
-
- def factory():
- reader = StreamReader(limit=limit, loop=loop)
- protocol = StreamReaderProtocol(reader, client_connected_cb,
- loop=loop)
- return protocol
-
- return await loop.create_unix_server(factory, path, **kwds)
-
-
-class FlowControlMixin(protocols.Protocol):
- """Reusable flow control logic for StreamWriter.drain().
-
- This implements the protocol methods pause_writing(),
- resume_writing() and connection_lost(). If the subclass overrides
- these it must call the super methods.
-
- StreamWriter.drain() must wait for _drain_helper() coroutine.
- """
-
- def __init__(self, loop=None):
- if loop is None:
- self._loop = events._get_event_loop(stacklevel=4)
- else:
- self._loop = loop
- self._paused = False
- self._drain_waiter = None
- self._connection_lost = False
-
- def pause_writing(self):
- assert not self._paused
- self._paused = True
- if self._loop.get_debug():
- logger.debug("%r pauses writing", self)
-
- def resume_writing(self):
- assert self._paused
- self._paused = False
- if self._loop.get_debug():
- logger.debug("%r resumes writing", self)
-
- waiter = self._drain_waiter
- if waiter is not None:
- self._drain_waiter = None
- if not waiter.done():
- waiter.set_result(None)
-
- def connection_lost(self, exc):
- self._connection_lost = True
- # Wake up the writer if currently paused.
- if not self._paused:
- return
- waiter = self._drain_waiter
- if waiter is None:
- return
- self._drain_waiter = None
- if waiter.done():
- return
- if exc is None:
- waiter.set_result(None)
- else:
- waiter.set_exception(exc)
-
- async def _drain_helper(self):
- if self._connection_lost:
- raise ConnectionResetError('Connection lost')
- if not self._paused:
- return
- waiter = self._drain_waiter
- assert waiter is None or waiter.cancelled()
- waiter = self._loop.create_future()
- self._drain_waiter = waiter
- await waiter
-
- def _get_close_waiter(self, stream):
- raise NotImplementedError
-
-
-class StreamReaderProtocol(FlowControlMixin, protocols.Protocol):
- """Helper class to adapt between Protocol and StreamReader.
-
- (This is a helper class instead of making StreamReader itself a
- Protocol subclass, because the StreamReader has other potential
- uses, and to prevent the user of the StreamReader to accidentally
- call inappropriate methods of the protocol.)
- """
-
- _source_traceback = None
-
- def __init__(self, stream_reader, client_connected_cb=None, loop=None):
- super().__init__(loop=loop)
- if stream_reader is not None:
- self._stream_reader_wr = weakref.ref(stream_reader)
- self._source_traceback = stream_reader._source_traceback
- else:
- self._stream_reader_wr = None
- if client_connected_cb is not None:
- # This is a stream created by the `create_server()` function.
- # Keep a strong reference to the reader until a connection
- # is established.
- self._strong_reader = stream_reader
- self._reject_connection = False
- self._stream_writer = None
- self._transport = None
- self._client_connected_cb = client_connected_cb
- self._over_ssl = False
- self._closed = self._loop.create_future()
-
- @property
- def _stream_reader(self):
- if self._stream_reader_wr is None:
- return None
- return self._stream_reader_wr()
-
- def connection_made(self, transport):
- if self._reject_connection:
- context = {
- 'message': ('An open stream was garbage collected prior to '
- 'establishing network connection; '
- 'call "stream.close()" explicitly.')
- }
- if self._source_traceback:
- context['source_traceback'] = self._source_traceback
- self._loop.call_exception_handler(context)
- transport.abort()
- return
- self._transport = transport
- reader = self._stream_reader
- if reader is not None:
- reader.set_transport(transport)
- self._over_ssl = transport.get_extra_info('sslcontext') is not None
- if self._client_connected_cb is not None:
- self._stream_writer = StreamWriter(transport, self,
- reader,
- self._loop)
- res = self._client_connected_cb(reader,
- self._stream_writer)
- if coroutines.iscoroutine(res):
- self._loop.create_task(res)
- self._strong_reader = None
-
- def connection_lost(self, exc):
- reader = self._stream_reader
- if reader is not None:
- if exc is None:
- reader.feed_eof()
- else:
- reader.set_exception(exc)
- if not self._closed.done():
- if exc is None:
- self._closed.set_result(None)
- else:
- self._closed.set_exception(exc)
- super().connection_lost(exc)
- self._stream_reader_wr = None
- self._stream_writer = None
- self._transport = None
-
- def data_received(self, data):
- reader = self._stream_reader
- if reader is not None:
- reader.feed_data(data)
-
- def eof_received(self):
- reader = self._stream_reader
- if reader is not None:
- reader.feed_eof()
- if self._over_ssl:
- # Prevent a warning in SSLProtocol.eof_received:
- # "returning true from eof_received()
- # has no effect when using ssl"
- return False
- return True
-
- def _get_close_waiter(self, stream):
- return self._closed
-
- def __del__(self):
- # Prevent reports about unhandled exceptions.
- # Better than self._closed._log_traceback = False hack
- try:
- closed = self._closed
- except AttributeError:
- pass # failed constructor
- else:
- if closed.done() and not closed.cancelled():
- closed.exception()
-
-
-class StreamWriter:
- """Wraps a Transport.
-
- This exposes write(), writelines(), [can_]write_eof(),
- get_extra_info() and close(). It adds drain() which returns an
- optional Future on which you can wait for flow control. It also
- adds a transport property which references the Transport
- directly.
- """
-
- def __init__(self, transport, protocol, reader, loop):
- self._transport = transport
- self._protocol = protocol
- # drain() expects that the reader has an exception() method
- assert reader is None or isinstance(reader, StreamReader)
- self._reader = reader
- self._loop = loop
- self._complete_fut = self._loop.create_future()
- self._complete_fut.set_result(None)
-
- def __repr__(self):
- info = [self.__class__.__name__, f'transport={self._transport!r}']
- if self._reader is not None:
- info.append(f'reader={self._reader!r}')
- return '<{}>'.format(' '.join(info))
-
- @property
- def transport(self):
- return self._transport
-
- def write(self, data):
- self._transport.write(data)
-
- def writelines(self, data):
- self._transport.writelines(data)
-
- def write_eof(self):
- return self._transport.write_eof()
-
- def can_write_eof(self):
- return self._transport.can_write_eof()
-
- def close(self):
- return self._transport.close()
-
- def is_closing(self):
- return self._transport.is_closing()
-
- async def wait_closed(self):
- await self._protocol._get_close_waiter(self)
-
- def get_extra_info(self, name, default=None):
- return self._transport.get_extra_info(name, default)
-
- async def drain(self):
- """Flush the write buffer.
-
- The intended use is to write
-
- w.write(data)
- await w.drain()
- """
- if self._reader is not None:
- exc = self._reader.exception()
- if exc is not None:
- raise exc
- if self._transport.is_closing():
- # Wait for protocol.connection_lost() call
- # Raise connection closing error if any,
- # ConnectionResetError otherwise
- # Yield to the event loop so connection_lost() may be
- # called. Without this, _drain_helper() would return
- # immediately, and code that calls
- # write(...); await drain()
- # in a loop would never call connection_lost(), so it
- # would not see an error when the socket is closed.
- await sleep(0)
- await self._protocol._drain_helper()
-
-
-class StreamReader:
-
- _source_traceback = None
-
- def __init__(self, limit=_DEFAULT_LIMIT, loop=None):
- # The line length limit is a security feature;
- # it also doubles as half the buffer limit.
-
- if limit <= 0:
- raise ValueError('Limit cannot be <= 0')
-
- self._limit = limit
- if loop is None:
- self._loop = events._get_event_loop()
- else:
- self._loop = loop
- self._buffer = bytearray()
- self._eof = False # Whether we're done.
- self._waiter = None # A future used by _wait_for_data()
- self._exception = None
- self._transport = None
- self._paused = False
- if self._loop.get_debug():
- self._source_traceback = format_helpers.extract_stack(
- sys._getframe(1))
-
- def __repr__(self):
- info = ['StreamReader']
- if self._buffer:
- info.append(f'{len(self._buffer)} bytes')
- if self._eof:
- info.append('eof')
- if self._limit != _DEFAULT_LIMIT:
- info.append(f'limit={self._limit}')
- if self._waiter:
- info.append(f'waiter={self._waiter!r}')
- if self._exception:
- info.append(f'exception={self._exception!r}')
- if self._transport:
- info.append(f'transport={self._transport!r}')
- if self._paused:
- info.append('paused')
- return '<{}>'.format(' '.join(info))
-
- def exception(self):
- return self._exception
-
- def set_exception(self, exc):
- self._exception = exc
-
- waiter = self._waiter
- if waiter is not None:
- self._waiter = None
- if not waiter.cancelled():
- waiter.set_exception(exc)
-
- def _wakeup_waiter(self):
- """Wakeup read*() functions waiting for data or EOF."""
- waiter = self._waiter
- if waiter is not None:
- self._waiter = None
- if not waiter.cancelled():
- waiter.set_result(None)
-
- def set_transport(self, transport):
- assert self._transport is None, 'Transport already set'
- self._transport = transport
-
- def _maybe_resume_transport(self):
- if self._paused and len(self._buffer) <= self._limit:
- self._paused = False
- self._transport.resume_reading()
-
- def feed_eof(self):
- self._eof = True
- self._wakeup_waiter()
-
- def at_eof(self):
- """Return True if the buffer is empty and 'feed_eof' was called."""
- return self._eof and not self._buffer
-
- def feed_data(self, data):
- assert not self._eof, 'feed_data after feed_eof'
-
- if not data:
- return
-
- self._buffer.extend(data)
- self._wakeup_waiter()
-
- if (self._transport is not None and
- not self._paused and
- len(self._buffer) > 2 * self._limit):
- try:
- self._transport.pause_reading()
- except NotImplementedError:
- # The transport can't be paused.
- # We'll just have to buffer all data.
- # Forget the transport so we don't keep trying.
- self._transport = None
- else:
- self._paused = True
-
- async def _wait_for_data(self, func_name):
- """Wait until feed_data() or feed_eof() is called.
-
- If stream was paused, automatically resume it.
- """
- # StreamReader uses a future to link the protocol feed_data() method
- # to a read coroutine. Running two read coroutines at the same time
- # would have an unexpected behaviour. It would not possible to know
- # which coroutine would get the next data.
- if self._waiter is not None:
- raise RuntimeError(
- f'{func_name}() called while another coroutine is '
- f'already waiting for incoming data')
-
- assert not self._eof, '_wait_for_data after EOF'
-
- # Waiting for data while paused will make deadlock, so prevent it.
- # This is essential for readexactly(n) for case when n > self._limit.
- if self._paused:
- self._paused = False
- self._transport.resume_reading()
-
- self._waiter = self._loop.create_future()
- try:
- await self._waiter
- finally:
- self._waiter = None
-
- async def readline(self):
- """Read chunk of data from the stream until newline (b'\n') is found.
-
- On success, return chunk that ends with newline. If only partial
- line can be read due to EOF, return incomplete line without
- terminating newline. When EOF was reached while no bytes read, empty
- bytes object is returned.
-
- If limit is reached, ValueError will be raised. In that case, if
- newline was found, complete line including newline will be removed
- from internal buffer. Else, internal buffer will be cleared. Limit is
- compared against part of the line without newline.
-
- If stream was paused, this function will automatically resume it if
- needed.
- """
- sep = b'\n'
- seplen = len(sep)
- try:
- line = await self.readuntil(sep)
- except exceptions.IncompleteReadError as e:
- return e.partial
- except exceptions.LimitOverrunError as e:
- if self._buffer.startswith(sep, e.consumed):
- del self._buffer[:e.consumed + seplen]
- else:
- self._buffer.clear()
- self._maybe_resume_transport()
- raise ValueError(e.args[0])
- return line
-
- async def readuntil(self, separator=b'\n'):
- """Read data from the stream until ``separator`` is found.
-
- On success, the data and separator will be removed from the
- internal buffer (consumed). Returned data will include the
- separator at the end.
-
- Configured stream limit is used to check result. Limit sets the
- maximal length of data that can be returned, not counting the
- separator.
-
- If an EOF occurs and the complete separator is still not found,
- an IncompleteReadError exception will be raised, and the internal
- buffer will be reset. The IncompleteReadError.partial attribute
- may contain the separator partially.
-
- If the data cannot be read because of over limit, a
- LimitOverrunError exception will be raised, and the data
- will be left in the internal buffer, so it can be read again.
- """
- seplen = len(separator)
- if seplen == 0:
- raise ValueError('Separator should be at least one-byte string')
-
- if self._exception is not None:
- raise self._exception
-
- # Consume whole buffer except last bytes, which length is
- # one less than seplen. Let's check corner cases with
- # separator='SEPARATOR':
- # * we have received almost complete separator (without last
- # byte). i.e buffer='some textSEPARATO'. In this case we
- # can safely consume len(separator) - 1 bytes.
- # * last byte of buffer is first byte of separator, i.e.
- # buffer='abcdefghijklmnopqrS'. We may safely consume
- # everything except that last byte, but this require to
- # analyze bytes of buffer that match partial separator.
- # This is slow and/or require FSM. For this case our
- # implementation is not optimal, since require rescanning
- # of data that is known to not belong to separator. In
- # real world, separator will not be so long to notice
- # performance problems. Even when reading MIME-encoded
- # messages :)
-
- # `offset` is the number of bytes from the beginning of the buffer
- # where there is no occurrence of `separator`.
- offset = 0
-
- # Loop until we find `separator` in the buffer, exceed the buffer size,
- # or an EOF has happened.
- while True:
- buflen = len(self._buffer)
-
- # Check if we now have enough data in the buffer for `separator` to
- # fit.
- if buflen - offset >= seplen:
- isep = self._buffer.find(separator, offset)
-
- if isep != -1:
- # `separator` is in the buffer. `isep` will be used later
- # to retrieve the data.
- break
-
- # see upper comment for explanation.
- offset = buflen + 1 - seplen
- if offset > self._limit:
- raise exceptions.LimitOverrunError(
- 'Separator is not found, and chunk exceed the limit',
- offset)
-
- # Complete message (with full separator) may be present in buffer
- # even when EOF flag is set. This may happen when the last chunk
- # adds data which makes separator be found. That's why we check for
- # EOF *ater* inspecting the buffer.
- if self._eof:
- chunk = bytes(self._buffer)
- self._buffer.clear()
- raise exceptions.IncompleteReadError(chunk, None)
-
- # _wait_for_data() will resume reading if stream was paused.
- await self._wait_for_data('readuntil')
-
- if isep > self._limit:
- raise exceptions.LimitOverrunError(
- 'Separator is found, but chunk is longer than limit', isep)
-
- chunk = self._buffer[:isep + seplen]
- del self._buffer[:isep + seplen]
- self._maybe_resume_transport()
- return bytes(chunk)
-
- async def read(self, n=-1):
- """Read up to `n` bytes from the stream.
-
- If n is not provided, or set to -1, read until EOF and return all read
- bytes. If the EOF was received and the internal buffer is empty, return
- an empty bytes object.
-
- If n is zero, return empty bytes object immediately.
-
- If n is positive, this function try to read `n` bytes, and may return
- less or equal bytes than requested, but at least one byte. If EOF was
- received before any byte is read, this function returns empty byte
- object.
-
- Returned value is not limited with limit, configured at stream
- creation.
-
- If stream was paused, this function will automatically resume it if
- needed.
- """
-
- if self._exception is not None:
- raise self._exception
-
- if n == 0:
- return b''
-
- if n < 0:
- # This used to just loop creating a new waiter hoping to
- # collect everything in self._buffer, but that would
- # deadlock if the subprocess sends more than self.limit
- # bytes. So just call self.read(self._limit) until EOF.
- blocks = []
- while True:
- block = await self.read(self._limit)
- if not block:
- break
- blocks.append(block)
- return b''.join(blocks)
-
- if not self._buffer and not self._eof:
- await self._wait_for_data('read')
-
- # This will work right even if buffer is less than n bytes
- data = bytes(self._buffer[:n])
- del self._buffer[:n]
-
- self._maybe_resume_transport()
- return data
-
- async def readexactly(self, n):
- """Read exactly `n` bytes.
-
- Raise an IncompleteReadError if EOF is reached before `n` bytes can be
- read. The IncompleteReadError.partial attribute of the exception will
- contain the partial read bytes.
-
- if n is zero, return empty bytes object.
-
- Returned value is not limited with limit, configured at stream
- creation.
-
- If stream was paused, this function will automatically resume it if
- needed.
- """
- if n < 0:
- raise ValueError('readexactly size can not be less than zero')
-
- if self._exception is not None:
- raise self._exception
-
- if n == 0:
- return b''
-
- while len(self._buffer) < n:
- if self._eof:
- incomplete = bytes(self._buffer)
- self._buffer.clear()
- raise exceptions.IncompleteReadError(incomplete, n)
-
- await self._wait_for_data('readexactly')
-
- if len(self._buffer) == n:
- data = bytes(self._buffer)
- self._buffer.clear()
- else:
- data = bytes(self._buffer[:n])
- del self._buffer[:n]
- self._maybe_resume_transport()
- return data
-
- def __aiter__(self):
- return self
-
- async def __anext__(self):
- val = await self.readline()
- if val == b'':
- raise StopAsyncIteration
- return val
diff --git a/lib/python3.10/asyncio/subprocess.py b/lib/python3.10/asyncio/subprocess.py
deleted file mode 100644
index cd10231..0000000
--- a/lib/python3.10/asyncio/subprocess.py
+++ /dev/null
@@ -1,223 +0,0 @@
-__all__ = 'create_subprocess_exec', 'create_subprocess_shell'
-
-import subprocess
-
-from . import events
-from . import protocols
-from . import streams
-from . import tasks
-from .log import logger
-
-
-PIPE = subprocess.PIPE
-STDOUT = subprocess.STDOUT
-DEVNULL = subprocess.DEVNULL
-
-
-class SubprocessStreamProtocol(streams.FlowControlMixin,
- protocols.SubprocessProtocol):
- """Like StreamReaderProtocol, but for a subprocess."""
-
- def __init__(self, limit, loop):
- super().__init__(loop=loop)
- self._limit = limit
- self.stdin = self.stdout = self.stderr = None
- self._transport = None
- self._process_exited = False
- self._pipe_fds = []
- self._stdin_closed = self._loop.create_future()
-
- def __repr__(self):
- info = [self.__class__.__name__]
- if self.stdin is not None:
- info.append(f'stdin={self.stdin!r}')
- if self.stdout is not None:
- info.append(f'stdout={self.stdout!r}')
- if self.stderr is not None:
- info.append(f'stderr={self.stderr!r}')
- return '<{}>'.format(' '.join(info))
-
- def connection_made(self, transport):
- self._transport = transport
-
- stdout_transport = transport.get_pipe_transport(1)
- if stdout_transport is not None:
- self.stdout = streams.StreamReader(limit=self._limit,
- loop=self._loop)
- self.stdout.set_transport(stdout_transport)
- self._pipe_fds.append(1)
-
- stderr_transport = transport.get_pipe_transport(2)
- if stderr_transport is not None:
- self.stderr = streams.StreamReader(limit=self._limit,
- loop=self._loop)
- self.stderr.set_transport(stderr_transport)
- self._pipe_fds.append(2)
-
- stdin_transport = transport.get_pipe_transport(0)
- if stdin_transport is not None:
- self.stdin = streams.StreamWriter(stdin_transport,
- protocol=self,
- reader=None,
- loop=self._loop)
-
- def pipe_data_received(self, fd, data):
- if fd == 1:
- reader = self.stdout
- elif fd == 2:
- reader = self.stderr
- else:
- reader = None
- if reader is not None:
- reader.feed_data(data)
-
- def pipe_connection_lost(self, fd, exc):
- if fd == 0:
- pipe = self.stdin
- if pipe is not None:
- pipe.close()
- self.connection_lost(exc)
- if exc is None:
- self._stdin_closed.set_result(None)
- else:
- self._stdin_closed.set_exception(exc)
- return
- if fd == 1:
- reader = self.stdout
- elif fd == 2:
- reader = self.stderr
- else:
- reader = None
- if reader is not None:
- if exc is None:
- reader.feed_eof()
- else:
- reader.set_exception(exc)
-
- if fd in self._pipe_fds:
- self._pipe_fds.remove(fd)
- self._maybe_close_transport()
-
- def process_exited(self):
- self._process_exited = True
- self._maybe_close_transport()
-
- def _maybe_close_transport(self):
- if len(self._pipe_fds) == 0 and self._process_exited:
- self._transport.close()
- self._transport = None
-
- def _get_close_waiter(self, stream):
- if stream is self.stdin:
- return self._stdin_closed
-
-
-class Process:
- def __init__(self, transport, protocol, loop):
- self._transport = transport
- self._protocol = protocol
- self._loop = loop
- self.stdin = protocol.stdin
- self.stdout = protocol.stdout
- self.stderr = protocol.stderr
- self.pid = transport.get_pid()
-
- def __repr__(self):
- return f'<{self.__class__.__name__} {self.pid}>'
-
- @property
- def returncode(self):
- return self._transport.get_returncode()
-
- async def wait(self):
- """Wait until the process exit and return the process return code."""
- return await self._transport._wait()
-
- def send_signal(self, signal):
- self._transport.send_signal(signal)
-
- def terminate(self):
- self._transport.terminate()
-
- def kill(self):
- self._transport.kill()
-
- async def _feed_stdin(self, input):
- debug = self._loop.get_debug()
- self.stdin.write(input)
- if debug:
- logger.debug(
- '%r communicate: feed stdin (%s bytes)', self, len(input))
- try:
- await self.stdin.drain()
- except (BrokenPipeError, ConnectionResetError) as exc:
- # communicate() ignores BrokenPipeError and ConnectionResetError
- if debug:
- logger.debug('%r communicate: stdin got %r', self, exc)
-
- if debug:
- logger.debug('%r communicate: close stdin', self)
- self.stdin.close()
-
- async def _noop(self):
- return None
-
- async def _read_stream(self, fd):
- transport = self._transport.get_pipe_transport(fd)
- if fd == 2:
- stream = self.stderr
- else:
- assert fd == 1
- stream = self.stdout
- if self._loop.get_debug():
- name = 'stdout' if fd == 1 else 'stderr'
- logger.debug('%r communicate: read %s', self, name)
- output = await stream.read()
- if self._loop.get_debug():
- name = 'stdout' if fd == 1 else 'stderr'
- logger.debug('%r communicate: close %s', self, name)
- transport.close()
- return output
-
- async def communicate(self, input=None):
- if input is not None:
- stdin = self._feed_stdin(input)
- else:
- stdin = self._noop()
- if self.stdout is not None:
- stdout = self._read_stream(1)
- else:
- stdout = self._noop()
- if self.stderr is not None:
- stderr = self._read_stream(2)
- else:
- stderr = self._noop()
- stdin, stdout, stderr = await tasks.gather(stdin, stdout, stderr)
- await self.wait()
- return (stdout, stderr)
-
-
-async def create_subprocess_shell(cmd, stdin=None, stdout=None, stderr=None,
- limit=streams._DEFAULT_LIMIT, **kwds):
- loop = events.get_running_loop()
- protocol_factory = lambda: SubprocessStreamProtocol(limit=limit,
- loop=loop)
- transport, protocol = await loop.subprocess_shell(
- protocol_factory,
- cmd, stdin=stdin, stdout=stdout,
- stderr=stderr, **kwds)
- return Process(transport, protocol, loop)
-
-
-async def create_subprocess_exec(program, *args, stdin=None, stdout=None,
- stderr=None, limit=streams._DEFAULT_LIMIT,
- **kwds):
- loop = events.get_running_loop()
- protocol_factory = lambda: SubprocessStreamProtocol(limit=limit,
- loop=loop)
- transport, protocol = await loop.subprocess_exec(
- protocol_factory,
- program, *args,
- stdin=stdin, stdout=stdout,
- stderr=stderr, **kwds)
- return Process(transport, protocol, loop)
diff --git a/lib/python3.10/asyncio/tasks.py b/lib/python3.10/asyncio/tasks.py
deleted file mode 100644
index c4bedb5..0000000
--- a/lib/python3.10/asyncio/tasks.py
+++ /dev/null
@@ -1,939 +0,0 @@
-"""Support for tasks, coroutines and the scheduler."""
-
-__all__ = (
- 'Task', 'create_task',
- 'FIRST_COMPLETED', 'FIRST_EXCEPTION', 'ALL_COMPLETED',
- 'wait', 'wait_for', 'as_completed', 'sleep',
- 'gather', 'shield', 'ensure_future', 'run_coroutine_threadsafe',
- 'current_task', 'all_tasks',
- '_register_task', '_unregister_task', '_enter_task', '_leave_task',
-)
-
-import concurrent.futures
-import contextvars
-import functools
-import inspect
-import itertools
-import types
-import warnings
-import weakref
-from types import GenericAlias
-
-from . import base_tasks
-from . import coroutines
-from . import events
-from . import exceptions
-from . import futures
-from .coroutines import _is_coroutine
-
-# Helper to generate new task names
-# This uses itertools.count() instead of a "+= 1" operation because the latter
-# is not thread safe. See bpo-11866 for a longer explanation.
-_task_name_counter = itertools.count(1).__next__
-
-
-def current_task(loop=None):
- """Return a currently executed task."""
- if loop is None:
- loop = events.get_running_loop()
- return _current_tasks.get(loop)
-
-
-def all_tasks(loop=None):
- """Return a set of all tasks for the loop."""
- if loop is None:
- loop = events.get_running_loop()
- # Looping over a WeakSet (_all_tasks) isn't safe as it can be updated from another
- # thread while we do so. Therefore we cast it to list prior to filtering. The list
- # cast itself requires iteration, so we repeat it several times ignoring
- # RuntimeErrors (which are not very likely to occur). See issues 34970 and 36607 for
- # details.
- i = 0
- while True:
- try:
- tasks = list(_all_tasks)
- except RuntimeError:
- i += 1
- if i >= 1000:
- raise
- else:
- break
- return {t for t in tasks
- if futures._get_loop(t) is loop and not t.done()}
-
-
-def _set_task_name(task, name):
- if name is not None:
- try:
- set_name = task.set_name
- except AttributeError:
- pass
- else:
- set_name(name)
-
-
-class Task(futures._PyFuture): # Inherit Python Task implementation
- # from a Python Future implementation.
-
- """A coroutine wrapped in a Future."""
-
- # An important invariant maintained while a Task not done:
- #
- # - Either _fut_waiter is None, and _step() is scheduled;
- # - or _fut_waiter is some Future, and _step() is *not* scheduled.
- #
- # The only transition from the latter to the former is through
- # _wakeup(). When _fut_waiter is not None, one of its callbacks
- # must be _wakeup().
-
- # If False, don't log a message if the task is destroyed whereas its
- # status is still pending
- _log_destroy_pending = True
-
- def __init__(self, coro, *, loop=None, name=None):
- super().__init__(loop=loop)
- if self._source_traceback:
- del self._source_traceback[-1]
- if not coroutines.iscoroutine(coro):
- # raise after Future.__init__(), attrs are required for __del__
- # prevent logging for pending task in __del__
- self._log_destroy_pending = False
- raise TypeError(f"a coroutine was expected, got {coro!r}")
-
- if name is None:
- self._name = f'Task-{_task_name_counter()}'
- else:
- self._name = str(name)
-
- self._must_cancel = False
- self._fut_waiter = None
- self._coro = coro
- self._context = contextvars.copy_context()
-
- self._loop.call_soon(self.__step, context=self._context)
- _register_task(self)
-
- def __del__(self):
- if self._state == futures._PENDING and self._log_destroy_pending:
- context = {
- 'task': self,
- 'message': 'Task was destroyed but it is pending!',
- }
- if self._source_traceback:
- context['source_traceback'] = self._source_traceback
- self._loop.call_exception_handler(context)
- super().__del__()
-
- __class_getitem__ = classmethod(GenericAlias)
-
- def _repr_info(self):
- return base_tasks._task_repr_info(self)
-
- def get_coro(self):
- return self._coro
-
- def get_name(self):
- return self._name
-
- def set_name(self, value):
- self._name = str(value)
-
- def set_result(self, result):
- raise RuntimeError('Task does not support set_result operation')
-
- def set_exception(self, exception):
- raise RuntimeError('Task does not support set_exception operation')
-
- def get_stack(self, *, limit=None):
- """Return the list of stack frames for this task's coroutine.
-
- If the coroutine is not done, this returns the stack where it is
- suspended. If the coroutine has completed successfully or was
- cancelled, this returns an empty list. If the coroutine was
- terminated by an exception, this returns the list of traceback
- frames.
-
- The frames are always ordered from oldest to newest.
-
- The optional limit gives the maximum number of frames to
- return; by default all available frames are returned. Its
- meaning differs depending on whether a stack or a traceback is
- returned: the newest frames of a stack are returned, but the
- oldest frames of a traceback are returned. (This matches the
- behavior of the traceback module.)
-
- For reasons beyond our control, only one stack frame is
- returned for a suspended coroutine.
- """
- return base_tasks._task_get_stack(self, limit)
-
- def print_stack(self, *, limit=None, file=None):
- """Print the stack or traceback for this task's coroutine.
-
- This produces output similar to that of the traceback module,
- for the frames retrieved by get_stack(). The limit argument
- is passed to get_stack(). The file argument is an I/O stream
- to which the output is written; by default output is written
- to sys.stderr.
- """
- return base_tasks._task_print_stack(self, limit, file)
-
- def cancel(self, msg=None):
- """Request that this task cancel itself.
-
- This arranges for a CancelledError to be thrown into the
- wrapped coroutine on the next cycle through the event loop.
- The coroutine then has a chance to clean up or even deny
- the request using try/except/finally.
-
- Unlike Future.cancel, this does not guarantee that the
- task will be cancelled: the exception might be caught and
- acted upon, delaying cancellation of the task or preventing
- cancellation completely. The task may also return a value or
- raise a different exception.
-
- Immediately after this method is called, Task.cancelled() will
- not return True (unless the task was already cancelled). A
- task will be marked as cancelled when the wrapped coroutine
- terminates with a CancelledError exception (even if cancel()
- was not called).
- """
- self._log_traceback = False
- if self.done():
- return False
- if self._fut_waiter is not None:
- if self._fut_waiter.cancel(msg=msg):
- # Leave self._fut_waiter; it may be a Task that
- # catches and ignores the cancellation so we may have
- # to cancel it again later.
- return True
- # It must be the case that self.__step is already scheduled.
- self._must_cancel = True
- self._cancel_message = msg
- return True
-
- def __step(self, exc=None):
- if self.done():
- raise exceptions.InvalidStateError(
- f'_step(): already done: {self!r}, {exc!r}')
- if self._must_cancel:
- if not isinstance(exc, exceptions.CancelledError):
- exc = self._make_cancelled_error()
- self._must_cancel = False
- coro = self._coro
- self._fut_waiter = None
-
- _enter_task(self._loop, self)
- # Call either coro.throw(exc) or coro.send(None).
- try:
- if exc is None:
- # We use the `send` method directly, because coroutines
- # don't have `__iter__` and `__next__` methods.
- result = coro.send(None)
- else:
- result = coro.throw(exc)
- except StopIteration as exc:
- if self._must_cancel:
- # Task is cancelled right before coro stops.
- self._must_cancel = False
- super().cancel(msg=self._cancel_message)
- else:
- super().set_result(exc.value)
- except exceptions.CancelledError as exc:
- # Save the original exception so we can chain it later.
- self._cancelled_exc = exc
- super().cancel() # I.e., Future.cancel(self).
- except (KeyboardInterrupt, SystemExit) as exc:
- super().set_exception(exc)
- raise
- except BaseException as exc:
- super().set_exception(exc)
- else:
- blocking = getattr(result, '_asyncio_future_blocking', None)
- if blocking is not None:
- # Yielded Future must come from Future.__iter__().
- if futures._get_loop(result) is not self._loop:
- new_exc = RuntimeError(
- f'Task {self!r} got Future '
- f'{result!r} attached to a different loop')
- self._loop.call_soon(
- self.__step, new_exc, context=self._context)
- elif blocking:
- if result is self:
- new_exc = RuntimeError(
- f'Task cannot await on itself: {self!r}')
- self._loop.call_soon(
- self.__step, new_exc, context=self._context)
- else:
- result._asyncio_future_blocking = False
- result.add_done_callback(
- self.__wakeup, context=self._context)
- self._fut_waiter = result
- if self._must_cancel:
- if self._fut_waiter.cancel(
- msg=self._cancel_message):
- self._must_cancel = False
- else:
- new_exc = RuntimeError(
- f'yield was used instead of yield from '
- f'in task {self!r} with {result!r}')
- self._loop.call_soon(
- self.__step, new_exc, context=self._context)
-
- elif result is None:
- # Bare yield relinquishes control for one event loop iteration.
- self._loop.call_soon(self.__step, context=self._context)
- elif inspect.isgenerator(result):
- # Yielding a generator is just wrong.
- new_exc = RuntimeError(
- f'yield was used instead of yield from for '
- f'generator in task {self!r} with {result!r}')
- self._loop.call_soon(
- self.__step, new_exc, context=self._context)
- else:
- # Yielding something else is an error.
- new_exc = RuntimeError(f'Task got bad yield: {result!r}')
- self._loop.call_soon(
- self.__step, new_exc, context=self._context)
- finally:
- _leave_task(self._loop, self)
- self = None # Needed to break cycles when an exception occurs.
-
- def __wakeup(self, future):
- try:
- future.result()
- except BaseException as exc:
- # This may also be a cancellation.
- self.__step(exc)
- else:
- # Don't pass the value of `future.result()` explicitly,
- # as `Future.__iter__` and `Future.__await__` don't need it.
- # If we call `_step(value, None)` instead of `_step()`,
- # Python eval loop would use `.send(value)` method call,
- # instead of `__next__()`, which is slower for futures
- # that return non-generator iterators from their `__iter__`.
- self.__step()
- self = None # Needed to break cycles when an exception occurs.
-
-
-_PyTask = Task
-
-
-try:
- import _asyncio
-except ImportError:
- pass
-else:
- # _CTask is needed for tests.
- Task = _CTask = _asyncio.Task
-
-
-def create_task(coro, *, name=None):
- """Schedule the execution of a coroutine object in a spawn task.
-
- Return a Task object.
- """
- loop = events.get_running_loop()
- task = loop.create_task(coro)
- _set_task_name(task, name)
- return task
-
-
-# wait() and as_completed() similar to those in PEP 3148.
-
-FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED
-FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION
-ALL_COMPLETED = concurrent.futures.ALL_COMPLETED
-
-
-async def wait(fs, *, timeout=None, return_when=ALL_COMPLETED):
- """Wait for the Futures and coroutines given by fs to complete.
-
- The fs iterable must not be empty.
-
- Coroutines will be wrapped in Tasks.
-
- Returns two sets of Future: (done, pending).
-
- Usage:
-
- done, pending = await asyncio.wait(fs)
-
- Note: This does not raise TimeoutError! Futures that aren't done
- when the timeout occurs are returned in the second set.
- """
- if futures.isfuture(fs) or coroutines.iscoroutine(fs):
- raise TypeError(f"expect a list of futures, not {type(fs).__name__}")
- if not fs:
- raise ValueError('Set of coroutines/Futures is empty.')
- if return_when not in (FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED):
- raise ValueError(f'Invalid return_when value: {return_when}')
-
- loop = events.get_running_loop()
-
- fs = set(fs)
-
- if any(coroutines.iscoroutine(f) for f in fs):
- warnings.warn("The explicit passing of coroutine objects to "
- "asyncio.wait() is deprecated since Python 3.8, and "
- "scheduled for removal in Python 3.11.",
- DeprecationWarning, stacklevel=2)
-
- fs = {ensure_future(f, loop=loop) for f in fs}
-
- return await _wait(fs, timeout, return_when, loop)
-
-
-def _release_waiter(waiter, *args):
- if not waiter.done():
- waiter.set_result(None)
-
-
-async def wait_for(fut, timeout):
- """Wait for the single Future or coroutine to complete, with timeout.
-
- Coroutine will be wrapped in Task.
-
- Returns result of the Future or coroutine. When a timeout occurs,
- it cancels the task and raises TimeoutError. To avoid the task
- cancellation, wrap it in shield().
-
- If the wait is cancelled, the task is also cancelled.
-
- This function is a coroutine.
- """
- loop = events.get_running_loop()
-
- if timeout is None:
- return await fut
-
- if timeout <= 0:
- fut = ensure_future(fut, loop=loop)
-
- if fut.done():
- return fut.result()
-
- await _cancel_and_wait(fut, loop=loop)
- try:
- return fut.result()
- except exceptions.CancelledError as exc:
- raise exceptions.TimeoutError() from exc
-
- waiter = loop.create_future()
- timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
- cb = functools.partial(_release_waiter, waiter)
-
- fut = ensure_future(fut, loop=loop)
- fut.add_done_callback(cb)
-
- try:
- # wait until the future completes or the timeout
- try:
- await waiter
- except exceptions.CancelledError:
- if fut.done():
- return fut.result()
- else:
- fut.remove_done_callback(cb)
- # We must ensure that the task is not running
- # after wait_for() returns.
- # See https://bugs.python.org/issue32751
- await _cancel_and_wait(fut, loop=loop)
- raise
-
- if fut.done():
- return fut.result()
- else:
- fut.remove_done_callback(cb)
- # We must ensure that the task is not running
- # after wait_for() returns.
- # See https://bugs.python.org/issue32751
- await _cancel_and_wait(fut, loop=loop)
- # In case task cancellation failed with some
- # exception, we should re-raise it
- # See https://bugs.python.org/issue40607
- try:
- return fut.result()
- except exceptions.CancelledError as exc:
- raise exceptions.TimeoutError() from exc
- finally:
- timeout_handle.cancel()
-
-
-async def _wait(fs, timeout, return_when, loop):
- """Internal helper for wait().
-
- The fs argument must be a collection of Futures.
- """
- assert fs, 'Set of Futures is empty.'
- waiter = loop.create_future()
- timeout_handle = None
- if timeout is not None:
- timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
- counter = len(fs)
-
- def _on_completion(f):
- nonlocal counter
- counter -= 1
- if (counter <= 0 or
- return_when == FIRST_COMPLETED or
- return_when == FIRST_EXCEPTION and (not f.cancelled() and
- f.exception() is not None)):
- if timeout_handle is not None:
- timeout_handle.cancel()
- if not waiter.done():
- waiter.set_result(None)
-
- for f in fs:
- f.add_done_callback(_on_completion)
-
- try:
- await waiter
- finally:
- if timeout_handle is not None:
- timeout_handle.cancel()
- for f in fs:
- f.remove_done_callback(_on_completion)
-
- done, pending = set(), set()
- for f in fs:
- if f.done():
- done.add(f)
- else:
- pending.add(f)
- return done, pending
-
-
-async def _cancel_and_wait(fut, loop):
- """Cancel the *fut* future or task and wait until it completes."""
-
- waiter = loop.create_future()
- cb = functools.partial(_release_waiter, waiter)
- fut.add_done_callback(cb)
-
- try:
- fut.cancel()
- # We cannot wait on *fut* directly to make
- # sure _cancel_and_wait itself is reliably cancellable.
- await waiter
- finally:
- fut.remove_done_callback(cb)
-
-
-# This is *not* a @coroutine! It is just an iterator (yielding Futures).
-def as_completed(fs, *, timeout=None):
- """Return an iterator whose values are coroutines.
-
- When waiting for the yielded coroutines you'll get the results (or
- exceptions!) of the original Futures (or coroutines), in the order
- in which and as soon as they complete.
-
- This differs from PEP 3148; the proper way to use this is:
-
- for f in as_completed(fs):
- result = await f # The 'await' may raise.
- # Use result.
-
- If a timeout is specified, the 'await' will raise
- TimeoutError when the timeout occurs before all Futures are done.
-
- Note: The futures 'f' are not necessarily members of fs.
- """
- if futures.isfuture(fs) or coroutines.iscoroutine(fs):
- raise TypeError(f"expect an iterable of futures, not {type(fs).__name__}")
-
- from .queues import Queue # Import here to avoid circular import problem.
- done = Queue()
-
- loop = events._get_event_loop()
- todo = {ensure_future(f, loop=loop) for f in set(fs)}
- timeout_handle = None
-
- def _on_timeout():
- for f in todo:
- f.remove_done_callback(_on_completion)
- done.put_nowait(None) # Queue a dummy value for _wait_for_one().
- todo.clear() # Can't do todo.remove(f) in the loop.
-
- def _on_completion(f):
- if not todo:
- return # _on_timeout() was here first.
- todo.remove(f)
- done.put_nowait(f)
- if not todo and timeout_handle is not None:
- timeout_handle.cancel()
-
- async def _wait_for_one():
- f = await done.get()
- if f is None:
- # Dummy value from _on_timeout().
- raise exceptions.TimeoutError
- return f.result() # May raise f.exception().
-
- for f in todo:
- f.add_done_callback(_on_completion)
- if todo and timeout is not None:
- timeout_handle = loop.call_later(timeout, _on_timeout)
- for _ in range(len(todo)):
- yield _wait_for_one()
-
-
-@types.coroutine
-def __sleep0():
- """Skip one event loop run cycle.
-
- This is a private helper for 'asyncio.sleep()', used
- when the 'delay' is set to 0. It uses a bare 'yield'
- expression (which Task.__step knows how to handle)
- instead of creating a Future object.
- """
- yield
-
-
-async def sleep(delay, result=None):
- """Coroutine that completes after a given time (in seconds)."""
- if delay <= 0:
- await __sleep0()
- return result
-
- loop = events.get_running_loop()
- future = loop.create_future()
- h = loop.call_later(delay,
- futures._set_result_unless_cancelled,
- future, result)
- try:
- return await future
- finally:
- h.cancel()
-
-
-def ensure_future(coro_or_future, *, loop=None):
- """Wrap a coroutine or an awaitable in a future.
-
- If the argument is a Future, it is returned directly.
- """
- return _ensure_future(coro_or_future, loop=loop)
-
-
-def _ensure_future(coro_or_future, *, loop=None):
- if futures.isfuture(coro_or_future):
- if loop is not None and loop is not futures._get_loop(coro_or_future):
- raise ValueError('The future belongs to a different loop than '
- 'the one specified as the loop argument')
- return coro_or_future
- called_wrap_awaitable = False
- if not coroutines.iscoroutine(coro_or_future):
- if inspect.isawaitable(coro_or_future):
- coro_or_future = _wrap_awaitable(coro_or_future)
- called_wrap_awaitable = True
- else:
- raise TypeError('An asyncio.Future, a coroutine or an awaitable '
- 'is required')
-
- if loop is None:
- loop = events._get_event_loop(stacklevel=4)
- try:
- return loop.create_task(coro_or_future)
- except RuntimeError:
- if not called_wrap_awaitable:
- coro_or_future.close()
- raise
-
-
-@types.coroutine
-def _wrap_awaitable(awaitable):
- """Helper for asyncio.ensure_future().
-
- Wraps awaitable (an object with __await__) into a coroutine
- that will later be wrapped in a Task by ensure_future().
- """
- return (yield from awaitable.__await__())
-
-_wrap_awaitable._is_coroutine = _is_coroutine
-
-
-class _GatheringFuture(futures.Future):
- """Helper for gather().
-
- This overrides cancel() to cancel all the children and act more
- like Task.cancel(), which doesn't immediately mark itself as
- cancelled.
- """
-
- def __init__(self, children, *, loop):
- assert loop is not None
- super().__init__(loop=loop)
- self._children = children
- self._cancel_requested = False
-
- def cancel(self, msg=None):
- if self.done():
- return False
- ret = False
- for child in self._children:
- if child.cancel(msg=msg):
- ret = True
- if ret:
- # If any child tasks were actually cancelled, we should
- # propagate the cancellation request regardless of
- # *return_exceptions* argument. See issue 32684.
- self._cancel_requested = True
- return ret
-
-
-def gather(*coros_or_futures, return_exceptions=False):
- """Return a future aggregating results from the given coroutines/futures.
-
- Coroutines will be wrapped in a future and scheduled in the event
- loop. They will not necessarily be scheduled in the same order as
- passed in.
-
- All futures must share the same event loop. If all the tasks are
- done successfully, the returned future's result is the list of
- results (in the order of the original sequence, not necessarily
- the order of results arrival). If *return_exceptions* is True,
- exceptions in the tasks are treated the same as successful
- results, and gathered in the result list; otherwise, the first
- raised exception will be immediately propagated to the returned
- future.
-
- Cancellation: if the outer Future is cancelled, all children (that
- have not completed yet) are also cancelled. If any child is
- cancelled, this is treated as if it raised CancelledError --
- the outer Future is *not* cancelled in this case. (This is to
- prevent the cancellation of one child to cause other children to
- be cancelled.)
-
- If *return_exceptions* is False, cancelling gather() after it
- has been marked done won't cancel any submitted awaitables.
- For instance, gather can be marked done after propagating an
- exception to the caller, therefore, calling ``gather.cancel()``
- after catching an exception (raised by one of the awaitables) from
- gather won't cancel any other awaitables.
- """
- if not coros_or_futures:
- loop = events._get_event_loop()
- outer = loop.create_future()
- outer.set_result([])
- return outer
-
- def _done_callback(fut):
- nonlocal nfinished
- nfinished += 1
-
- if outer is None or outer.done():
- if not fut.cancelled():
- # Mark exception retrieved.
- fut.exception()
- return
-
- if not return_exceptions:
- if fut.cancelled():
- # Check if 'fut' is cancelled first, as
- # 'fut.exception()' will *raise* a CancelledError
- # instead of returning it.
- exc = fut._make_cancelled_error()
- outer.set_exception(exc)
- return
- else:
- exc = fut.exception()
- if exc is not None:
- outer.set_exception(exc)
- return
-
- if nfinished == nfuts:
- # All futures are done; create a list of results
- # and set it to the 'outer' future.
- results = []
-
- for fut in children:
- if fut.cancelled():
- # Check if 'fut' is cancelled first, as 'fut.exception()'
- # will *raise* a CancelledError instead of returning it.
- # Also, since we're adding the exception return value
- # to 'results' instead of raising it, don't bother
- # setting __context__. This also lets us preserve
- # calling '_make_cancelled_error()' at most once.
- res = exceptions.CancelledError(
- '' if fut._cancel_message is None else
- fut._cancel_message)
- else:
- res = fut.exception()
- if res is None:
- res = fut.result()
- results.append(res)
-
- if outer._cancel_requested:
- # If gather is being cancelled we must propagate the
- # cancellation regardless of *return_exceptions* argument.
- # See issue 32684.
- exc = fut._make_cancelled_error()
- outer.set_exception(exc)
- else:
- outer.set_result(results)
-
- arg_to_fut = {}
- children = []
- nfuts = 0
- nfinished = 0
- loop = None
- outer = None # bpo-46672
- for arg in coros_or_futures:
- if arg not in arg_to_fut:
- fut = _ensure_future(arg, loop=loop)
- if loop is None:
- loop = futures._get_loop(fut)
- if fut is not arg:
- # 'arg' was not a Future, therefore, 'fut' is a new
- # Future created specifically for 'arg'. Since the caller
- # can't control it, disable the "destroy pending task"
- # warning.
- fut._log_destroy_pending = False
-
- nfuts += 1
- arg_to_fut[arg] = fut
- fut.add_done_callback(_done_callback)
-
- else:
- # There's a duplicate Future object in coros_or_futures.
- fut = arg_to_fut[arg]
-
- children.append(fut)
-
- outer = _GatheringFuture(children, loop=loop)
- return outer
-
-
-def shield(arg):
- """Wait for a future, shielding it from cancellation.
-
- The statement
-
- res = await shield(something())
-
- is exactly equivalent to the statement
-
- res = await something()
-
- *except* that if the coroutine containing it is cancelled, the
- task running in something() is not cancelled. From the POV of
- something(), the cancellation did not happen. But its caller is
- still cancelled, so the yield-from expression still raises
- CancelledError. Note: If something() is cancelled by other means
- this will still cancel shield().
-
- If you want to completely ignore cancellation (not recommended)
- you can combine shield() with a try/except clause, as follows:
-
- try:
- res = await shield(something())
- except CancelledError:
- res = None
- """
- inner = _ensure_future(arg)
- if inner.done():
- # Shortcut.
- return inner
- loop = futures._get_loop(inner)
- outer = loop.create_future()
-
- def _inner_done_callback(inner):
- if outer.cancelled():
- if not inner.cancelled():
- # Mark inner's result as retrieved.
- inner.exception()
- return
-
- if inner.cancelled():
- outer.cancel()
- else:
- exc = inner.exception()
- if exc is not None:
- outer.set_exception(exc)
- else:
- outer.set_result(inner.result())
-
-
- def _outer_done_callback(outer):
- if not inner.done():
- inner.remove_done_callback(_inner_done_callback)
-
- inner.add_done_callback(_inner_done_callback)
- outer.add_done_callback(_outer_done_callback)
- return outer
-
-
-def run_coroutine_threadsafe(coro, loop):
- """Submit a coroutine object to a given event loop.
-
- Return a concurrent.futures.Future to access the result.
- """
- if not coroutines.iscoroutine(coro):
- raise TypeError('A coroutine object is required')
- future = concurrent.futures.Future()
-
- def callback():
- try:
- futures._chain_future(ensure_future(coro, loop=loop), future)
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- if future.set_running_or_notify_cancel():
- future.set_exception(exc)
- raise
-
- loop.call_soon_threadsafe(callback)
- return future
-
-
-# WeakSet containing all alive tasks.
-_all_tasks = weakref.WeakSet()
-
-# Dictionary containing tasks that are currently active in
-# all running event loops. {EventLoop: Task}
-_current_tasks = {}
-
-
-def _register_task(task):
- """Register a new task in asyncio as executed by loop."""
- _all_tasks.add(task)
-
-
-def _enter_task(loop, task):
- current_task = _current_tasks.get(loop)
- if current_task is not None:
- raise RuntimeError(f"Cannot enter into task {task!r} while another "
- f"task {current_task!r} is being executed.")
- _current_tasks[loop] = task
-
-
-def _leave_task(loop, task):
- current_task = _current_tasks.get(loop)
- if current_task is not task:
- raise RuntimeError(f"Leaving task {task!r} does not match "
- f"the current task {current_task!r}.")
- del _current_tasks[loop]
-
-
-def _unregister_task(task):
- """Unregister a task."""
- _all_tasks.discard(task)
-
-
-_py_register_task = _register_task
-_py_unregister_task = _unregister_task
-_py_enter_task = _enter_task
-_py_leave_task = _leave_task
-
-
-try:
- from _asyncio import (_register_task, _unregister_task,
- _enter_task, _leave_task,
- _all_tasks, _current_tasks)
-except ImportError:
- pass
-else:
- _c_register_task = _register_task
- _c_unregister_task = _unregister_task
- _c_enter_task = _enter_task
- _c_leave_task = _leave_task
diff --git a/lib/python3.10/asyncio/transports.py b/lib/python3.10/asyncio/transports.py
deleted file mode 100644
index 73b1fa2..0000000
--- a/lib/python3.10/asyncio/transports.py
+++ /dev/null
@@ -1,335 +0,0 @@
-"""Abstract Transport class."""
-
-__all__ = (
- 'BaseTransport', 'ReadTransport', 'WriteTransport',
- 'Transport', 'DatagramTransport', 'SubprocessTransport',
-)
-
-
-class BaseTransport:
- """Base class for transports."""
-
- __slots__ = ('_extra',)
-
- def __init__(self, extra=None):
- if extra is None:
- extra = {}
- self._extra = extra
-
- def get_extra_info(self, name, default=None):
- """Get optional transport information."""
- return self._extra.get(name, default)
-
- def is_closing(self):
- """Return True if the transport is closing or closed."""
- raise NotImplementedError
-
- def close(self):
- """Close the transport.
-
- Buffered data will be flushed asynchronously. No more data
- will be received. After all buffered data is flushed, the
- protocol's connection_lost() method will (eventually) be
- called with None as its argument.
- """
- raise NotImplementedError
-
- def set_protocol(self, protocol):
- """Set a new protocol."""
- raise NotImplementedError
-
- def get_protocol(self):
- """Return the current protocol."""
- raise NotImplementedError
-
-
-class ReadTransport(BaseTransport):
- """Interface for read-only transports."""
-
- __slots__ = ()
-
- def is_reading(self):
- """Return True if the transport is receiving."""
- raise NotImplementedError
-
- def pause_reading(self):
- """Pause the receiving end.
-
- No data will be passed to the protocol's data_received()
- method until resume_reading() is called.
- """
- raise NotImplementedError
-
- def resume_reading(self):
- """Resume the receiving end.
-
- Data received will once again be passed to the protocol's
- data_received() method.
- """
- raise NotImplementedError
-
-
-class WriteTransport(BaseTransport):
- """Interface for write-only transports."""
-
- __slots__ = ()
-
- def set_write_buffer_limits(self, high=None, low=None):
- """Set the high- and low-water limits for write flow control.
-
- These two values control when to call the protocol's
- pause_writing() and resume_writing() methods. If specified,
- the low-water limit must be less than or equal to the
- high-water limit. Neither value can be negative.
-
- The defaults are implementation-specific. If only the
- high-water limit is given, the low-water limit defaults to an
- implementation-specific value less than or equal to the
- high-water limit. Setting high to zero forces low to zero as
- well, and causes pause_writing() to be called whenever the
- buffer becomes non-empty. Setting low to zero causes
- resume_writing() to be called only once the buffer is empty.
- Use of zero for either limit is generally sub-optimal as it
- reduces opportunities for doing I/O and computation
- concurrently.
- """
- raise NotImplementedError
-
- def get_write_buffer_size(self):
- """Return the current size of the write buffer."""
- raise NotImplementedError
-
- def get_write_buffer_limits(self):
- """Get the high and low watermarks for write flow control.
- Return a tuple (low, high) where low and high are
- positive number of bytes."""
- raise NotImplementedError
-
- def write(self, data):
- """Write some data bytes to the transport.
-
- This does not block; it buffers the data and arranges for it
- to be sent out asynchronously.
- """
- raise NotImplementedError
-
- def writelines(self, list_of_data):
- """Write a list (or any iterable) of data bytes to the transport.
-
- The default implementation concatenates the arguments and
- calls write() on the result.
- """
- data = b''.join(list_of_data)
- self.write(data)
-
- def write_eof(self):
- """Close the write end after flushing buffered data.
-
- (This is like typing ^D into a UNIX program reading from stdin.)
-
- Data may still be received.
- """
- raise NotImplementedError
-
- def can_write_eof(self):
- """Return True if this transport supports write_eof(), False if not."""
- raise NotImplementedError
-
- def abort(self):
- """Close the transport immediately.
-
- Buffered data will be lost. No more data will be received.
- The protocol's connection_lost() method will (eventually) be
- called with None as its argument.
- """
- raise NotImplementedError
-
-
-class Transport(ReadTransport, WriteTransport):
- """Interface representing a bidirectional transport.
-
- There may be several implementations, but typically, the user does
- not implement new transports; rather, the platform provides some
- useful transports that are implemented using the platform's best
- practices.
-
- The user never instantiates a transport directly; they call a
- utility function, passing it a protocol factory and other
- information necessary to create the transport and protocol. (E.g.
- EventLoop.create_connection() or EventLoop.create_server().)
-
- The utility function will asynchronously create a transport and a
- protocol and hook them up by calling the protocol's
- connection_made() method, passing it the transport.
-
- The implementation here raises NotImplemented for every method
- except writelines(), which calls write() in a loop.
- """
-
- __slots__ = ()
-
-
-class DatagramTransport(BaseTransport):
- """Interface for datagram (UDP) transports."""
-
- __slots__ = ()
-
- def sendto(self, data, addr=None):
- """Send data to the transport.
-
- This does not block; it buffers the data and arranges for it
- to be sent out asynchronously.
- addr is target socket address.
- If addr is None use target address pointed on transport creation.
- """
- raise NotImplementedError
-
- def abort(self):
- """Close the transport immediately.
-
- Buffered data will be lost. No more data will be received.
- The protocol's connection_lost() method will (eventually) be
- called with None as its argument.
- """
- raise NotImplementedError
-
-
-class SubprocessTransport(BaseTransport):
-
- __slots__ = ()
-
- def get_pid(self):
- """Get subprocess id."""
- raise NotImplementedError
-
- def get_returncode(self):
- """Get subprocess returncode.
-
- See also
- http://docs.python.org/3/library/subprocess#subprocess.Popen.returncode
- """
- raise NotImplementedError
-
- def get_pipe_transport(self, fd):
- """Get transport for pipe with number fd."""
- raise NotImplementedError
-
- def send_signal(self, signal):
- """Send signal to subprocess.
-
- See also:
- docs.python.org/3/library/subprocess#subprocess.Popen.send_signal
- """
- raise NotImplementedError
-
- def terminate(self):
- """Stop the subprocess.
-
- Alias for close() method.
-
- On Posix OSs the method sends SIGTERM to the subprocess.
- On Windows the Win32 API function TerminateProcess()
- is called to stop the subprocess.
-
- See also:
- http://docs.python.org/3/library/subprocess#subprocess.Popen.terminate
- """
- raise NotImplementedError
-
- def kill(self):
- """Kill the subprocess.
-
- On Posix OSs the function sends SIGKILL to the subprocess.
- On Windows kill() is an alias for terminate().
-
- See also:
- http://docs.python.org/3/library/subprocess#subprocess.Popen.kill
- """
- raise NotImplementedError
-
-
-class _FlowControlMixin(Transport):
- """All the logic for (write) flow control in a mix-in base class.
-
- The subclass must implement get_write_buffer_size(). It must call
- _maybe_pause_protocol() whenever the write buffer size increases,
- and _maybe_resume_protocol() whenever it decreases. It may also
- override set_write_buffer_limits() (e.g. to specify different
- defaults).
-
- The subclass constructor must call super().__init__(extra). This
- will call set_write_buffer_limits().
-
- The user may call set_write_buffer_limits() and
- get_write_buffer_size(), and their protocol's pause_writing() and
- resume_writing() may be called.
- """
-
- __slots__ = ('_loop', '_protocol_paused', '_high_water', '_low_water')
-
- def __init__(self, extra=None, loop=None):
- super().__init__(extra)
- assert loop is not None
- self._loop = loop
- self._protocol_paused = False
- self._set_write_buffer_limits()
-
- def _maybe_pause_protocol(self):
- size = self.get_write_buffer_size()
- if size <= self._high_water:
- return
- if not self._protocol_paused:
- self._protocol_paused = True
- try:
- self._protocol.pause_writing()
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- self._loop.call_exception_handler({
- 'message': 'protocol.pause_writing() failed',
- 'exception': exc,
- 'transport': self,
- 'protocol': self._protocol,
- })
-
- def _maybe_resume_protocol(self):
- if (self._protocol_paused and
- self.get_write_buffer_size() <= self._low_water):
- self._protocol_paused = False
- try:
- self._protocol.resume_writing()
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- self._loop.call_exception_handler({
- 'message': 'protocol.resume_writing() failed',
- 'exception': exc,
- 'transport': self,
- 'protocol': self._protocol,
- })
-
- def get_write_buffer_limits(self):
- return (self._low_water, self._high_water)
-
- def _set_write_buffer_limits(self, high=None, low=None):
- if high is None:
- if low is None:
- high = 64 * 1024
- else:
- high = 4 * low
- if low is None:
- low = high // 4
-
- if not high >= low >= 0:
- raise ValueError(
- f'high ({high!r}) must be >= low ({low!r}) must be >= 0')
-
- self._high_water = high
- self._low_water = low
-
- def set_write_buffer_limits(self, high=None, low=None):
- self._set_write_buffer_limits(high=high, low=low)
- self._maybe_pause_protocol()
-
- def get_write_buffer_size(self):
- raise NotImplementedError
diff --git a/lib/python3.10/asyncio/trsock.py b/lib/python3.10/asyncio/trsock.py
deleted file mode 100644
index e9ebcc3..0000000
--- a/lib/python3.10/asyncio/trsock.py
+++ /dev/null
@@ -1,206 +0,0 @@
-import socket
-import warnings
-
-
-class TransportSocket:
-
- """A socket-like wrapper for exposing real transport sockets.
-
- These objects can be safely returned by APIs like
- `transport.get_extra_info('socket')`. All potentially disruptive
- operations (like "socket.close()") are banned.
- """
-
- __slots__ = ('_sock',)
-
- def __init__(self, sock: socket.socket):
- self._sock = sock
-
- def _na(self, what):
- warnings.warn(
- f"Using {what} on sockets returned from get_extra_info('socket') "
- f"will be prohibited in asyncio 3.9. Please report your use case "
- f"to bugs.python.org.",
- DeprecationWarning, source=self)
-
- @property
- def family(self):
- return self._sock.family
-
- @property
- def type(self):
- return self._sock.type
-
- @property
- def proto(self):
- return self._sock.proto
-
- def __repr__(self):
- s = (
- f"<asyncio.TransportSocket fd={self.fileno()}, "
- f"family={self.family!s}, type={self.type!s}, "
- f"proto={self.proto}"
- )
-
- if self.fileno() != -1:
- try:
- laddr = self.getsockname()
- if laddr:
- s = f"{s}, laddr={laddr}"
- except socket.error:
- pass
- try:
- raddr = self.getpeername()
- if raddr:
- s = f"{s}, raddr={raddr}"
- except socket.error:
- pass
-
- return f"{s}>"
-
- def __getstate__(self):
- raise TypeError("Cannot serialize asyncio.TransportSocket object")
-
- def fileno(self):
- return self._sock.fileno()
-
- def dup(self):
- return self._sock.dup()
-
- def get_inheritable(self):
- return self._sock.get_inheritable()
-
- def shutdown(self, how):
- # asyncio doesn't currently provide a high-level transport API
- # to shutdown the connection.
- self._sock.shutdown(how)
-
- def getsockopt(self, *args, **kwargs):
- return self._sock.getsockopt(*args, **kwargs)
-
- def setsockopt(self, *args, **kwargs):
- self._sock.setsockopt(*args, **kwargs)
-
- def getpeername(self):
- return self._sock.getpeername()
-
- def getsockname(self):
- return self._sock.getsockname()
-
- def getsockbyname(self):
- return self._sock.getsockbyname()
-
- def accept(self):
- self._na('accept() method')
- return self._sock.accept()
-
- def connect(self, *args, **kwargs):
- self._na('connect() method')
- return self._sock.connect(*args, **kwargs)
-
- def connect_ex(self, *args, **kwargs):
- self._na('connect_ex() method')
- return self._sock.connect_ex(*args, **kwargs)
-
- def bind(self, *args, **kwargs):
- self._na('bind() method')
- return self._sock.bind(*args, **kwargs)
-
- def ioctl(self, *args, **kwargs):
- self._na('ioctl() method')
- return self._sock.ioctl(*args, **kwargs)
-
- def listen(self, *args, **kwargs):
- self._na('listen() method')
- return self._sock.listen(*args, **kwargs)
-
- def makefile(self):
- self._na('makefile() method')
- return self._sock.makefile()
-
- def sendfile(self, *args, **kwargs):
- self._na('sendfile() method')
- return self._sock.sendfile(*args, **kwargs)
-
- def close(self):
- self._na('close() method')
- return self._sock.close()
-
- def detach(self):
- self._na('detach() method')
- return self._sock.detach()
-
- def sendmsg_afalg(self, *args, **kwargs):
- self._na('sendmsg_afalg() method')
- return self._sock.sendmsg_afalg(*args, **kwargs)
-
- def sendmsg(self, *args, **kwargs):
- self._na('sendmsg() method')
- return self._sock.sendmsg(*args, **kwargs)
-
- def sendto(self, *args, **kwargs):
- self._na('sendto() method')
- return self._sock.sendto(*args, **kwargs)
-
- def send(self, *args, **kwargs):
- self._na('send() method')
- return self._sock.send(*args, **kwargs)
-
- def sendall(self, *args, **kwargs):
- self._na('sendall() method')
- return self._sock.sendall(*args, **kwargs)
-
- def set_inheritable(self, *args, **kwargs):
- self._na('set_inheritable() method')
- return self._sock.set_inheritable(*args, **kwargs)
-
- def share(self, process_id):
- self._na('share() method')
- return self._sock.share(process_id)
-
- def recv_into(self, *args, **kwargs):
- self._na('recv_into() method')
- return self._sock.recv_into(*args, **kwargs)
-
- def recvfrom_into(self, *args, **kwargs):
- self._na('recvfrom_into() method')
- return self._sock.recvfrom_into(*args, **kwargs)
-
- def recvmsg_into(self, *args, **kwargs):
- self._na('recvmsg_into() method')
- return self._sock.recvmsg_into(*args, **kwargs)
-
- def recvmsg(self, *args, **kwargs):
- self._na('recvmsg() method')
- return self._sock.recvmsg(*args, **kwargs)
-
- def recvfrom(self, *args, **kwargs):
- self._na('recvfrom() method')
- return self._sock.recvfrom(*args, **kwargs)
-
- def recv(self, *args, **kwargs):
- self._na('recv() method')
- return self._sock.recv(*args, **kwargs)
-
- def settimeout(self, value):
- if value == 0:
- return
- raise ValueError(
- 'settimeout(): only 0 timeout is allowed on transport sockets')
-
- def gettimeout(self):
- return 0
-
- def setblocking(self, flag):
- if not flag:
- return
- raise ValueError(
- 'setblocking(): transport sockets cannot be blocking')
-
- def __enter__(self):
- self._na('context manager protocol')
- return self._sock.__enter__()
-
- def __exit__(self, *err):
- self._na('context manager protocol')
- return self._sock.__exit__(*err)
diff --git a/lib/python3.10/asyncio/unix_events.py b/lib/python3.10/asyncio/unix_events.py
deleted file mode 100644
index c88b818..0000000
--- a/lib/python3.10/asyncio/unix_events.py
+++ /dev/null
@@ -1,1466 +0,0 @@
-"""Selector event loop for Unix with signal handling."""
-
-import errno
-import io
-import itertools
-import os
-import selectors
-import signal
-import socket
-import stat
-import subprocess
-import sys
-import threading
-import warnings
-
-from . import base_events
-from . import base_subprocess
-from . import constants
-from . import coroutines
-from . import events
-from . import exceptions
-from . import futures
-from . import selector_events
-from . import tasks
-from . import transports
-from .log import logger
-
-
-__all__ = (
- 'SelectorEventLoop',
- 'AbstractChildWatcher', 'SafeChildWatcher',
- 'FastChildWatcher', 'PidfdChildWatcher',
- 'MultiLoopChildWatcher', 'ThreadedChildWatcher',
- 'DefaultEventLoopPolicy',
-)
-
-
-if sys.platform == 'win32': # pragma: no cover
- raise ImportError('Signals are not really supported on Windows')
-
-
-def _sighandler_noop(signum, frame):
- """Dummy signal handler."""
- pass
-
-
-def waitstatus_to_exitcode(status):
- try:
- return os.waitstatus_to_exitcode(status)
- except ValueError:
- # The child exited, but we don't understand its status.
- # This shouldn't happen, but if it does, let's just
- # return that status; perhaps that helps debug it.
- return status
-
-
-class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
- """Unix event loop.
-
- Adds signal handling and UNIX Domain Socket support to SelectorEventLoop.
- """
-
- def __init__(self, selector=None):
- super().__init__(selector)
- self._signal_handlers = {}
-
- def close(self):
- super().close()
- if not sys.is_finalizing():
- for sig in list(self._signal_handlers):
- self.remove_signal_handler(sig)
- else:
- if self._signal_handlers:
- warnings.warn(f"Closing the loop {self!r} "
- f"on interpreter shutdown "
- f"stage, skipping signal handlers removal",
- ResourceWarning,
- source=self)
- self._signal_handlers.clear()
-
- def _process_self_data(self, data):
- for signum in data:
- if not signum:
- # ignore null bytes written by _write_to_self()
- continue
- self._handle_signal(signum)
-
- def add_signal_handler(self, sig, callback, *args):
- """Add a handler for a signal. UNIX only.
-
- Raise ValueError if the signal number is invalid or uncatchable.
- Raise RuntimeError if there is a problem setting up the handler.
- """
- if (coroutines.iscoroutine(callback) or
- coroutines.iscoroutinefunction(callback)):
- raise TypeError("coroutines cannot be used "
- "with add_signal_handler()")
- self._check_signal(sig)
- self._check_closed()
- try:
- # set_wakeup_fd() raises ValueError if this is not the
- # main thread. By calling it early we ensure that an
- # event loop running in another thread cannot add a signal
- # handler.
- signal.set_wakeup_fd(self._csock.fileno())
- except (ValueError, OSError) as exc:
- raise RuntimeError(str(exc))
-
- handle = events.Handle(callback, args, self, None)
- self._signal_handlers[sig] = handle
-
- try:
- # Register a dummy signal handler to ask Python to write the signal
- # number in the wakeup file descriptor. _process_self_data() will
- # read signal numbers from this file descriptor to handle signals.
- signal.signal(sig, _sighandler_noop)
-
- # Set SA_RESTART to limit EINTR occurrences.
- signal.siginterrupt(sig, False)
- except OSError as exc:
- del self._signal_handlers[sig]
- if not self._signal_handlers:
- try:
- signal.set_wakeup_fd(-1)
- except (ValueError, OSError) as nexc:
- logger.info('set_wakeup_fd(-1) failed: %s', nexc)
-
- if exc.errno == errno.EINVAL:
- raise RuntimeError(f'sig {sig} cannot be caught')
- else:
- raise
-
- def _handle_signal(self, sig):
- """Internal helper that is the actual signal handler."""
- handle = self._signal_handlers.get(sig)
- if handle is None:
- return # Assume it's some race condition.
- if handle._cancelled:
- self.remove_signal_handler(sig) # Remove it properly.
- else:
- self._add_callback_signalsafe(handle)
-
- def remove_signal_handler(self, sig):
- """Remove a handler for a signal. UNIX only.
-
- Return True if a signal handler was removed, False if not.
- """
- self._check_signal(sig)
- try:
- del self._signal_handlers[sig]
- except KeyError:
- return False
-
- if sig == signal.SIGINT:
- handler = signal.default_int_handler
- else:
- handler = signal.SIG_DFL
-
- try:
- signal.signal(sig, handler)
- except OSError as exc:
- if exc.errno == errno.EINVAL:
- raise RuntimeError(f'sig {sig} cannot be caught')
- else:
- raise
-
- if not self._signal_handlers:
- try:
- signal.set_wakeup_fd(-1)
- except (ValueError, OSError) as exc:
- logger.info('set_wakeup_fd(-1) failed: %s', exc)
-
- return True
-
- def _check_signal(self, sig):
- """Internal helper to validate a signal.
-
- Raise ValueError if the signal number is invalid or uncatchable.
- Raise RuntimeError if there is a problem setting up the handler.
- """
- if not isinstance(sig, int):
- raise TypeError(f'sig must be an int, not {sig!r}')
-
- if sig not in signal.valid_signals():
- raise ValueError(f'invalid signal number {sig}')
-
- def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
- extra=None):
- return _UnixReadPipeTransport(self, pipe, protocol, waiter, extra)
-
- def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
- extra=None):
- return _UnixWritePipeTransport(self, pipe, protocol, waiter, extra)
-
- async def _make_subprocess_transport(self, protocol, args, shell,
- stdin, stdout, stderr, bufsize,
- extra=None, **kwargs):
- with events.get_child_watcher() as watcher:
- if not watcher.is_active():
- # Check early.
- # Raising exception before process creation
- # prevents subprocess execution if the watcher
- # is not ready to handle it.
- raise RuntimeError("asyncio.get_child_watcher() is not activated, "
- "subprocess support is not installed.")
- waiter = self.create_future()
- transp = _UnixSubprocessTransport(self, protocol, args, shell,
- stdin, stdout, stderr, bufsize,
- waiter=waiter, extra=extra,
- **kwargs)
-
- watcher.add_child_handler(transp.get_pid(),
- self._child_watcher_callback, transp)
- try:
- await waiter
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException:
- transp.close()
- await transp._wait()
- raise
-
- return transp
-
- def _child_watcher_callback(self, pid, returncode, transp):
- self.call_soon_threadsafe(transp._process_exited, returncode)
-
- async def create_unix_connection(
- self, protocol_factory, path=None, *,
- ssl=None, sock=None,
- server_hostname=None,
- ssl_handshake_timeout=None):
- assert server_hostname is None or isinstance(server_hostname, str)
- if ssl:
- if server_hostname is None:
- raise ValueError(
- 'you have to pass server_hostname when using ssl')
- else:
- if server_hostname is not None:
- raise ValueError('server_hostname is only meaningful with ssl')
- if ssl_handshake_timeout is not None:
- raise ValueError(
- 'ssl_handshake_timeout is only meaningful with ssl')
-
- if path is not None:
- if sock is not None:
- raise ValueError(
- 'path and sock can not be specified at the same time')
-
- path = os.fspath(path)
- sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)
- try:
- sock.setblocking(False)
- await self.sock_connect(sock, path)
- except:
- sock.close()
- raise
-
- else:
- if sock is None:
- raise ValueError('no path and sock were specified')
- if (sock.family != socket.AF_UNIX or
- sock.type != socket.SOCK_STREAM):
- raise ValueError(
- f'A UNIX Domain Stream Socket was expected, got {sock!r}')
- sock.setblocking(False)
-
- transport, protocol = await self._create_connection_transport(
- sock, protocol_factory, ssl, server_hostname,
- ssl_handshake_timeout=ssl_handshake_timeout)
- return transport, protocol
-
- async def create_unix_server(
- self, protocol_factory, path=None, *,
- sock=None, backlog=100, ssl=None,
- ssl_handshake_timeout=None,
- start_serving=True):
- if isinstance(ssl, bool):
- raise TypeError('ssl argument must be an SSLContext or None')
-
- if ssl_handshake_timeout is not None and not ssl:
- raise ValueError(
- 'ssl_handshake_timeout is only meaningful with ssl')
-
- if path is not None:
- if sock is not None:
- raise ValueError(
- 'path and sock can not be specified at the same time')
-
- path = os.fspath(path)
- sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
-
- # Check for abstract socket. `str` and `bytes` paths are supported.
- if path[0] not in (0, '\x00'):
- try:
- if stat.S_ISSOCK(os.stat(path).st_mode):
- os.remove(path)
- except FileNotFoundError:
- pass
- except OSError as err:
- # Directory may have permissions only to create socket.
- logger.error('Unable to check or remove stale UNIX socket '
- '%r: %r', path, err)
-
- try:
- sock.bind(path)
- except OSError as exc:
- sock.close()
- if exc.errno == errno.EADDRINUSE:
- # Let's improve the error message by adding
- # with what exact address it occurs.
- msg = f'Address {path!r} is already in use'
- raise OSError(errno.EADDRINUSE, msg) from None
- else:
- raise
- except:
- sock.close()
- raise
- else:
- if sock is None:
- raise ValueError(
- 'path was not specified, and no sock specified')
-
- if (sock.family != socket.AF_UNIX or
- sock.type != socket.SOCK_STREAM):
- raise ValueError(
- f'A UNIX Domain Stream Socket was expected, got {sock!r}')
-
- sock.setblocking(False)
- server = base_events.Server(self, [sock], protocol_factory,
- ssl, backlog, ssl_handshake_timeout)
- if start_serving:
- server._start_serving()
- # Skip one loop iteration so that all 'loop.add_reader'
- # go through.
- await tasks.sleep(0)
-
- return server
-
- async def _sock_sendfile_native(self, sock, file, offset, count):
- try:
- os.sendfile
- except AttributeError:
- raise exceptions.SendfileNotAvailableError(
- "os.sendfile() is not available")
- try:
- fileno = file.fileno()
- except (AttributeError, io.UnsupportedOperation) as err:
- raise exceptions.SendfileNotAvailableError("not a regular file")
- try:
- fsize = os.fstat(fileno).st_size
- except OSError:
- raise exceptions.SendfileNotAvailableError("not a regular file")
- blocksize = count if count else fsize
- if not blocksize:
- return 0 # empty file
-
- fut = self.create_future()
- self._sock_sendfile_native_impl(fut, None, sock, fileno,
- offset, count, blocksize, 0)
- return await fut
-
- def _sock_sendfile_native_impl(self, fut, registered_fd, sock, fileno,
- offset, count, blocksize, total_sent):
- fd = sock.fileno()
- if registered_fd is not None:
- # Remove the callback early. It should be rare that the
- # selector says the fd is ready but the call still returns
- # EAGAIN, and I am willing to take a hit in that case in
- # order to simplify the common case.
- self.remove_writer(registered_fd)
- if fut.cancelled():
- self._sock_sendfile_update_filepos(fileno, offset, total_sent)
- return
- if count:
- blocksize = count - total_sent
- if blocksize <= 0:
- self._sock_sendfile_update_filepos(fileno, offset, total_sent)
- fut.set_result(total_sent)
- return
-
- try:
- sent = os.sendfile(fd, fileno, offset, blocksize)
- except (BlockingIOError, InterruptedError):
- if registered_fd is None:
- self._sock_add_cancellation_callback(fut, sock)
- self.add_writer(fd, self._sock_sendfile_native_impl, fut,
- fd, sock, fileno,
- offset, count, blocksize, total_sent)
- except OSError as exc:
- if (registered_fd is not None and
- exc.errno == errno.ENOTCONN and
- type(exc) is not ConnectionError):
- # If we have an ENOTCONN and this isn't a first call to
- # sendfile(), i.e. the connection was closed in the middle
- # of the operation, normalize the error to ConnectionError
- # to make it consistent across all Posix systems.
- new_exc = ConnectionError(
- "socket is not connected", errno.ENOTCONN)
- new_exc.__cause__ = exc
- exc = new_exc
- if total_sent == 0:
- # We can get here for different reasons, the main
- # one being 'file' is not a regular mmap(2)-like
- # file, in which case we'll fall back on using
- # plain send().
- err = exceptions.SendfileNotAvailableError(
- "os.sendfile call failed")
- self._sock_sendfile_update_filepos(fileno, offset, total_sent)
- fut.set_exception(err)
- else:
- self._sock_sendfile_update_filepos(fileno, offset, total_sent)
- fut.set_exception(exc)
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- self._sock_sendfile_update_filepos(fileno, offset, total_sent)
- fut.set_exception(exc)
- else:
- if sent == 0:
- # EOF
- self._sock_sendfile_update_filepos(fileno, offset, total_sent)
- fut.set_result(total_sent)
- else:
- offset += sent
- total_sent += sent
- if registered_fd is None:
- self._sock_add_cancellation_callback(fut, sock)
- self.add_writer(fd, self._sock_sendfile_native_impl, fut,
- fd, sock, fileno,
- offset, count, blocksize, total_sent)
-
- def _sock_sendfile_update_filepos(self, fileno, offset, total_sent):
- if total_sent > 0:
- os.lseek(fileno, offset, os.SEEK_SET)
-
- def _sock_add_cancellation_callback(self, fut, sock):
- def cb(fut):
- if fut.cancelled():
- fd = sock.fileno()
- if fd != -1:
- self.remove_writer(fd)
- fut.add_done_callback(cb)
-
-
-class _UnixReadPipeTransport(transports.ReadTransport):
-
- max_size = 256 * 1024 # max bytes we read in one event loop iteration
-
- def __init__(self, loop, pipe, protocol, waiter=None, extra=None):
- super().__init__(extra)
- self._extra['pipe'] = pipe
- self._loop = loop
- self._pipe = pipe
- self._fileno = pipe.fileno()
- self._protocol = protocol
- self._closing = False
- self._paused = False
-
- mode = os.fstat(self._fileno).st_mode
- if not (stat.S_ISFIFO(mode) or
- stat.S_ISSOCK(mode) or
- stat.S_ISCHR(mode)):
- self._pipe = None
- self._fileno = None
- self._protocol = None
- raise ValueError("Pipe transport is for pipes/sockets only.")
-
- os.set_blocking(self._fileno, False)
-
- self._loop.call_soon(self._protocol.connection_made, self)
- # only start reading when connection_made() has been called
- self._loop.call_soon(self._loop._add_reader,
- self._fileno, self._read_ready)
- if waiter is not None:
- # only wake up the waiter when connection_made() has been called
- self._loop.call_soon(futures._set_result_unless_cancelled,
- waiter, None)
-
- def __repr__(self):
- info = [self.__class__.__name__]
- if self._pipe is None:
- info.append('closed')
- elif self._closing:
- info.append('closing')
- info.append(f'fd={self._fileno}')
- selector = getattr(self._loop, '_selector', None)
- if self._pipe is not None and selector is not None:
- polling = selector_events._test_selector_event(
- selector, self._fileno, selectors.EVENT_READ)
- if polling:
- info.append('polling')
- else:
- info.append('idle')
- elif self._pipe is not None:
- info.append('open')
- else:
- info.append('closed')
- return '<{}>'.format(' '.join(info))
-
- def _read_ready(self):
- try:
- data = os.read(self._fileno, self.max_size)
- except (BlockingIOError, InterruptedError):
- pass
- except OSError as exc:
- self._fatal_error(exc, 'Fatal read error on pipe transport')
- else:
- if data:
- self._protocol.data_received(data)
- else:
- if self._loop.get_debug():
- logger.info("%r was closed by peer", self)
- self._closing = True
- self._loop._remove_reader(self._fileno)
- self._loop.call_soon(self._protocol.eof_received)
- self._loop.call_soon(self._call_connection_lost, None)
-
- def pause_reading(self):
- if self._closing or self._paused:
- return
- self._paused = True
- self._loop._remove_reader(self._fileno)
- if self._loop.get_debug():
- logger.debug("%r pauses reading", self)
-
- def resume_reading(self):
- if self._closing or not self._paused:
- return
- self._paused = False
- self._loop._add_reader(self._fileno, self._read_ready)
- if self._loop.get_debug():
- logger.debug("%r resumes reading", self)
-
- def set_protocol(self, protocol):
- self._protocol = protocol
-
- def get_protocol(self):
- return self._protocol
-
- def is_closing(self):
- return self._closing
-
- def close(self):
- if not self._closing:
- self._close(None)
-
- def __del__(self, _warn=warnings.warn):
- if self._pipe is not None:
- _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
- self._pipe.close()
-
- def _fatal_error(self, exc, message='Fatal error on pipe transport'):
- # should be called by exception handler only
- if (isinstance(exc, OSError) and exc.errno == errno.EIO):
- if self._loop.get_debug():
- logger.debug("%r: %s", self, message, exc_info=True)
- else:
- self._loop.call_exception_handler({
- 'message': message,
- 'exception': exc,
- 'transport': self,
- 'protocol': self._protocol,
- })
- self._close(exc)
-
- def _close(self, exc):
- self._closing = True
- self._loop._remove_reader(self._fileno)
- self._loop.call_soon(self._call_connection_lost, exc)
-
- def _call_connection_lost(self, exc):
- try:
- self._protocol.connection_lost(exc)
- finally:
- self._pipe.close()
- self._pipe = None
- self._protocol = None
- self._loop = None
-
-
-class _UnixWritePipeTransport(transports._FlowControlMixin,
- transports.WriteTransport):
-
- def __init__(self, loop, pipe, protocol, waiter=None, extra=None):
- super().__init__(extra, loop)
- self._extra['pipe'] = pipe
- self._pipe = pipe
- self._fileno = pipe.fileno()
- self._protocol = protocol
- self._buffer = bytearray()
- self._conn_lost = 0
- self._closing = False # Set when close() or write_eof() called.
-
- mode = os.fstat(self._fileno).st_mode
- is_char = stat.S_ISCHR(mode)
- is_fifo = stat.S_ISFIFO(mode)
- is_socket = stat.S_ISSOCK(mode)
- if not (is_char or is_fifo or is_socket):
- self._pipe = None
- self._fileno = None
- self._protocol = None
- raise ValueError("Pipe transport is only for "
- "pipes, sockets and character devices")
-
- os.set_blocking(self._fileno, False)
- self._loop.call_soon(self._protocol.connection_made, self)
-
- # On AIX, the reader trick (to be notified when the read end of the
- # socket is closed) only works for sockets. On other platforms it
- # works for pipes and sockets. (Exception: OS X 10.4? Issue #19294.)
- if is_socket or (is_fifo and not sys.platform.startswith("aix")):
- # only start reading when connection_made() has been called
- self._loop.call_soon(self._loop._add_reader,
- self._fileno, self._read_ready)
-
- if waiter is not None:
- # only wake up the waiter when connection_made() has been called
- self._loop.call_soon(futures._set_result_unless_cancelled,
- waiter, None)
-
- def __repr__(self):
- info = [self.__class__.__name__]
- if self._pipe is None:
- info.append('closed')
- elif self._closing:
- info.append('closing')
- info.append(f'fd={self._fileno}')
- selector = getattr(self._loop, '_selector', None)
- if self._pipe is not None and selector is not None:
- polling = selector_events._test_selector_event(
- selector, self._fileno, selectors.EVENT_WRITE)
- if polling:
- info.append('polling')
- else:
- info.append('idle')
-
- bufsize = self.get_write_buffer_size()
- info.append(f'bufsize={bufsize}')
- elif self._pipe is not None:
- info.append('open')
- else:
- info.append('closed')
- return '<{}>'.format(' '.join(info))
-
- def get_write_buffer_size(self):
- return len(self._buffer)
-
- def _read_ready(self):
- # Pipe was closed by peer.
- if self._loop.get_debug():
- logger.info("%r was closed by peer", self)
- if self._buffer:
- self._close(BrokenPipeError())
- else:
- self._close()
-
- def write(self, data):
- assert isinstance(data, (bytes, bytearray, memoryview)), repr(data)
- if isinstance(data, bytearray):
- data = memoryview(data)
- if not data:
- return
-
- if self._conn_lost or self._closing:
- if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
- logger.warning('pipe closed by peer or '
- 'os.write(pipe, data) raised exception.')
- self._conn_lost += 1
- return
-
- if not self._buffer:
- # Attempt to send it right away first.
- try:
- n = os.write(self._fileno, data)
- except (BlockingIOError, InterruptedError):
- n = 0
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- self._conn_lost += 1
- self._fatal_error(exc, 'Fatal write error on pipe transport')
- return
- if n == len(data):
- return
- elif n > 0:
- data = memoryview(data)[n:]
- self._loop._add_writer(self._fileno, self._write_ready)
-
- self._buffer += data
- self._maybe_pause_protocol()
-
- def _write_ready(self):
- assert self._buffer, 'Data should not be empty'
-
- try:
- n = os.write(self._fileno, self._buffer)
- except (BlockingIOError, InterruptedError):
- pass
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- self._buffer.clear()
- self._conn_lost += 1
- # Remove writer here, _fatal_error() doesn't it
- # because _buffer is empty.
- self._loop._remove_writer(self._fileno)
- self._fatal_error(exc, 'Fatal write error on pipe transport')
- else:
- if n == len(self._buffer):
- self._buffer.clear()
- self._loop._remove_writer(self._fileno)
- self._maybe_resume_protocol() # May append to buffer.
- if self._closing:
- self._loop._remove_reader(self._fileno)
- self._call_connection_lost(None)
- return
- elif n > 0:
- del self._buffer[:n]
-
- def can_write_eof(self):
- return True
-
- def write_eof(self):
- if self._closing:
- return
- assert self._pipe
- self._closing = True
- if not self._buffer:
- self._loop._remove_reader(self._fileno)
- self._loop.call_soon(self._call_connection_lost, None)
-
- def set_protocol(self, protocol):
- self._protocol = protocol
-
- def get_protocol(self):
- return self._protocol
-
- def is_closing(self):
- return self._closing
-
- def close(self):
- if self._pipe is not None and not self._closing:
- # write_eof is all what we needed to close the write pipe
- self.write_eof()
-
- def __del__(self, _warn=warnings.warn):
- if self._pipe is not None:
- _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
- self._pipe.close()
-
- def abort(self):
- self._close(None)
-
- def _fatal_error(self, exc, message='Fatal error on pipe transport'):
- # should be called by exception handler only
- if isinstance(exc, OSError):
- if self._loop.get_debug():
- logger.debug("%r: %s", self, message, exc_info=True)
- else:
- self._loop.call_exception_handler({
- 'message': message,
- 'exception': exc,
- 'transport': self,
- 'protocol': self._protocol,
- })
- self._close(exc)
-
- def _close(self, exc=None):
- self._closing = True
- if self._buffer:
- self._loop._remove_writer(self._fileno)
- self._buffer.clear()
- self._loop._remove_reader(self._fileno)
- self._loop.call_soon(self._call_connection_lost, exc)
-
- def _call_connection_lost(self, exc):
- try:
- self._protocol.connection_lost(exc)
- finally:
- self._pipe.close()
- self._pipe = None
- self._protocol = None
- self._loop = None
-
-
-class _UnixSubprocessTransport(base_subprocess.BaseSubprocessTransport):
-
- def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
- stdin_w = None
- if stdin == subprocess.PIPE:
- # Use a socket pair for stdin, since not all platforms
- # support selecting read events on the write end of a
- # socket (which we use in order to detect closing of the
- # other end). Notably this is needed on AIX, and works
- # just fine on other platforms.
- stdin, stdin_w = socket.socketpair()
- try:
- self._proc = subprocess.Popen(
- args, shell=shell, stdin=stdin, stdout=stdout, stderr=stderr,
- universal_newlines=False, bufsize=bufsize, **kwargs)
- if stdin_w is not None:
- stdin.close()
- self._proc.stdin = open(stdin_w.detach(), 'wb', buffering=bufsize)
- stdin_w = None
- finally:
- if stdin_w is not None:
- stdin.close()
- stdin_w.close()
-
-
-class AbstractChildWatcher:
- """Abstract base class for monitoring child processes.
-
- Objects derived from this class monitor a collection of subprocesses and
- report their termination or interruption by a signal.
-
- New callbacks are registered with .add_child_handler(). Starting a new
- process must be done within a 'with' block to allow the watcher to suspend
- its activity until the new process if fully registered (this is needed to
- prevent a race condition in some implementations).
-
- Example:
- with watcher:
- proc = subprocess.Popen("sleep 1")
- watcher.add_child_handler(proc.pid, callback)
-
- Notes:
- Implementations of this class must be thread-safe.
-
- Since child watcher objects may catch the SIGCHLD signal and call
- waitpid(-1), there should be only one active object per process.
- """
-
- def add_child_handler(self, pid, callback, *args):
- """Register a new child handler.
-
- Arrange for callback(pid, returncode, *args) to be called when
- process 'pid' terminates. Specifying another callback for the same
- process replaces the previous handler.
-
- Note: callback() must be thread-safe.
- """
- raise NotImplementedError()
-
- def remove_child_handler(self, pid):
- """Removes the handler for process 'pid'.
-
- The function returns True if the handler was successfully removed,
- False if there was nothing to remove."""
-
- raise NotImplementedError()
-
- def attach_loop(self, loop):
- """Attach the watcher to an event loop.
-
- If the watcher was previously attached to an event loop, then it is
- first detached before attaching to the new loop.
-
- Note: loop may be None.
- """
- raise NotImplementedError()
-
- def close(self):
- """Close the watcher.
-
- This must be called to make sure that any underlying resource is freed.
- """
- raise NotImplementedError()
-
- def is_active(self):
- """Return ``True`` if the watcher is active and is used by the event loop.
-
- Return True if the watcher is installed and ready to handle process exit
- notifications.
-
- """
- raise NotImplementedError()
-
- def __enter__(self):
- """Enter the watcher's context and allow starting new processes
-
- This function must return self"""
- raise NotImplementedError()
-
- def __exit__(self, a, b, c):
- """Exit the watcher's context"""
- raise NotImplementedError()
-
-
-class PidfdChildWatcher(AbstractChildWatcher):
- """Child watcher implementation using Linux's pid file descriptors.
-
- This child watcher polls process file descriptors (pidfds) to await child
- process termination. In some respects, PidfdChildWatcher is a "Goldilocks"
- child watcher implementation. It doesn't require signals or threads, doesn't
- interfere with any processes launched outside the event loop, and scales
- linearly with the number of subprocesses launched by the event loop. The
- main disadvantage is that pidfds are specific to Linux, and only work on
- recent (5.3+) kernels.
- """
-
- def __init__(self):
- self._loop = None
- self._callbacks = {}
-
- def __enter__(self):
- return self
-
- def __exit__(self, exc_type, exc_value, exc_traceback):
- pass
-
- def is_active(self):
- return self._loop is not None and self._loop.is_running()
-
- def close(self):
- self.attach_loop(None)
-
- def attach_loop(self, loop):
- if self._loop is not None and loop is None and self._callbacks:
- warnings.warn(
- 'A loop is being detached '
- 'from a child watcher with pending handlers',
- RuntimeWarning)
- for pidfd, _, _ in self._callbacks.values():
- self._loop._remove_reader(pidfd)
- os.close(pidfd)
- self._callbacks.clear()
- self._loop = loop
-
- def add_child_handler(self, pid, callback, *args):
- existing = self._callbacks.get(pid)
- if existing is not None:
- self._callbacks[pid] = existing[0], callback, args
- else:
- pidfd = os.pidfd_open(pid)
- self._loop._add_reader(pidfd, self._do_wait, pid)
- self._callbacks[pid] = pidfd, callback, args
-
- def _do_wait(self, pid):
- pidfd, callback, args = self._callbacks.pop(pid)
- self._loop._remove_reader(pidfd)
- try:
- _, status = os.waitpid(pid, 0)
- except ChildProcessError:
- # The child process is already reaped
- # (may happen if waitpid() is called elsewhere).
- returncode = 255
- logger.warning(
- "child process pid %d exit status already read: "
- " will report returncode 255",
- pid)
- else:
- returncode = waitstatus_to_exitcode(status)
-
- os.close(pidfd)
- callback(pid, returncode, *args)
-
- def remove_child_handler(self, pid):
- try:
- pidfd, _, _ = self._callbacks.pop(pid)
- except KeyError:
- return False
- self._loop._remove_reader(pidfd)
- os.close(pidfd)
- return True
-
-
-class BaseChildWatcher(AbstractChildWatcher):
-
- def __init__(self):
- self._loop = None
- self._callbacks = {}
-
- def close(self):
- self.attach_loop(None)
-
- def is_active(self):
- return self._loop is not None and self._loop.is_running()
-
- def _do_waitpid(self, expected_pid):
- raise NotImplementedError()
-
- def _do_waitpid_all(self):
- raise NotImplementedError()
-
- def attach_loop(self, loop):
- assert loop is None or isinstance(loop, events.AbstractEventLoop)
-
- if self._loop is not None and loop is None and self._callbacks:
- warnings.warn(
- 'A loop is being detached '
- 'from a child watcher with pending handlers',
- RuntimeWarning)
-
- if self._loop is not None:
- self._loop.remove_signal_handler(signal.SIGCHLD)
-
- self._loop = loop
- if loop is not None:
- loop.add_signal_handler(signal.SIGCHLD, self._sig_chld)
-
- # Prevent a race condition in case a child terminated
- # during the switch.
- self._do_waitpid_all()
-
- def _sig_chld(self):
- try:
- self._do_waitpid_all()
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException as exc:
- # self._loop should always be available here
- # as '_sig_chld' is added as a signal handler
- # in 'attach_loop'
- self._loop.call_exception_handler({
- 'message': 'Unknown exception in SIGCHLD handler',
- 'exception': exc,
- })
-
-
-class SafeChildWatcher(BaseChildWatcher):
- """'Safe' child watcher implementation.
-
- This implementation avoids disrupting other code spawning processes by
- polling explicitly each process in the SIGCHLD handler instead of calling
- os.waitpid(-1).
-
- This is a safe solution but it has a significant overhead when handling a
- big number of children (O(n) each time SIGCHLD is raised)
- """
-
- def close(self):
- self._callbacks.clear()
- super().close()
-
- def __enter__(self):
- return self
-
- def __exit__(self, a, b, c):
- pass
-
- def add_child_handler(self, pid, callback, *args):
- self._callbacks[pid] = (callback, args)
-
- # Prevent a race condition in case the child is already terminated.
- self._do_waitpid(pid)
-
- def remove_child_handler(self, pid):
- try:
- del self._callbacks[pid]
- return True
- except KeyError:
- return False
-
- def _do_waitpid_all(self):
-
- for pid in list(self._callbacks):
- self._do_waitpid(pid)
-
- def _do_waitpid(self, expected_pid):
- assert expected_pid > 0
-
- try:
- pid, status = os.waitpid(expected_pid, os.WNOHANG)
- except ChildProcessError:
- # The child process is already reaped
- # (may happen if waitpid() is called elsewhere).
- pid = expected_pid
- returncode = 255
- logger.warning(
- "Unknown child process pid %d, will report returncode 255",
- pid)
- else:
- if pid == 0:
- # The child process is still alive.
- return
-
- returncode = waitstatus_to_exitcode(status)
- if self._loop.get_debug():
- logger.debug('process %s exited with returncode %s',
- expected_pid, returncode)
-
- try:
- callback, args = self._callbacks.pop(pid)
- except KeyError: # pragma: no cover
- # May happen if .remove_child_handler() is called
- # after os.waitpid() returns.
- if self._loop.get_debug():
- logger.warning("Child watcher got an unexpected pid: %r",
- pid, exc_info=True)
- else:
- callback(pid, returncode, *args)
-
-
-class FastChildWatcher(BaseChildWatcher):
- """'Fast' child watcher implementation.
-
- This implementation reaps every terminated processes by calling
- os.waitpid(-1) directly, possibly breaking other code spawning processes
- and waiting for their termination.
-
- There is no noticeable overhead when handling a big number of children
- (O(1) each time a child terminates).
- """
- def __init__(self):
- super().__init__()
- self._lock = threading.Lock()
- self._zombies = {}
- self._forks = 0
-
- def close(self):
- self._callbacks.clear()
- self._zombies.clear()
- super().close()
-
- def __enter__(self):
- with self._lock:
- self._forks += 1
-
- return self
-
- def __exit__(self, a, b, c):
- with self._lock:
- self._forks -= 1
-
- if self._forks or not self._zombies:
- return
-
- collateral_victims = str(self._zombies)
- self._zombies.clear()
-
- logger.warning(
- "Caught subprocesses termination from unknown pids: %s",
- collateral_victims)
-
- def add_child_handler(self, pid, callback, *args):
- assert self._forks, "Must use the context manager"
-
- with self._lock:
- try:
- returncode = self._zombies.pop(pid)
- except KeyError:
- # The child is running.
- self._callbacks[pid] = callback, args
- return
-
- # The child is dead already. We can fire the callback.
- callback(pid, returncode, *args)
-
- def remove_child_handler(self, pid):
- try:
- del self._callbacks[pid]
- return True
- except KeyError:
- return False
-
- def _do_waitpid_all(self):
- # Because of signal coalescing, we must keep calling waitpid() as
- # long as we're able to reap a child.
- while True:
- try:
- pid, status = os.waitpid(-1, os.WNOHANG)
- except ChildProcessError:
- # No more child processes exist.
- return
- else:
- if pid == 0:
- # A child process is still alive.
- return
-
- returncode = waitstatus_to_exitcode(status)
-
- with self._lock:
- try:
- callback, args = self._callbacks.pop(pid)
- except KeyError:
- # unknown child
- if self._forks:
- # It may not be registered yet.
- self._zombies[pid] = returncode
- if self._loop.get_debug():
- logger.debug('unknown process %s exited '
- 'with returncode %s',
- pid, returncode)
- continue
- callback = None
- else:
- if self._loop.get_debug():
- logger.debug('process %s exited with returncode %s',
- pid, returncode)
-
- if callback is None:
- logger.warning(
- "Caught subprocess termination from unknown pid: "
- "%d -> %d", pid, returncode)
- else:
- callback(pid, returncode, *args)
-
-
-class MultiLoopChildWatcher(AbstractChildWatcher):
- """A watcher that doesn't require running loop in the main thread.
-
- This implementation registers a SIGCHLD signal handler on
- instantiation (which may conflict with other code that
- install own handler for this signal).
-
- The solution is safe but it has a significant overhead when
- handling a big number of processes (*O(n)* each time a
- SIGCHLD is received).
- """
-
- # Implementation note:
- # The class keeps compatibility with AbstractChildWatcher ABC
- # To achieve this it has empty attach_loop() method
- # and doesn't accept explicit loop argument
- # for add_child_handler()/remove_child_handler()
- # but retrieves the current loop by get_running_loop()
-
- def __init__(self):
- self._callbacks = {}
- self._saved_sighandler = None
-
- def is_active(self):
- return self._saved_sighandler is not None
-
- def close(self):
- self._callbacks.clear()
- if self._saved_sighandler is None:
- return
-
- handler = signal.getsignal(signal.SIGCHLD)
- if handler != self._sig_chld:
- logger.warning("SIGCHLD handler was changed by outside code")
- else:
- signal.signal(signal.SIGCHLD, self._saved_sighandler)
- self._saved_sighandler = None
-
- def __enter__(self):
- return self
-
- def __exit__(self, exc_type, exc_val, exc_tb):
- pass
-
- def add_child_handler(self, pid, callback, *args):
- loop = events.get_running_loop()
- self._callbacks[pid] = (loop, callback, args)
-
- # Prevent a race condition in case the child is already terminated.
- self._do_waitpid(pid)
-
- def remove_child_handler(self, pid):
- try:
- del self._callbacks[pid]
- return True
- except KeyError:
- return False<