# Auto-generated from cpython_chunk_0.txt TEXT_DATA = r""" This is Python version 3.15.0 alpha 5 ===================================== .. image:: https://github.com/python/cpython/actions/workflows/build.yml/badge.svg?branch=main&event=push :alt: CPython build status on GitHub Actions :target: https://github.com/python/cpython/actions .. image:: https://dev.azure.com/python/cpython/_apis/build/status/Azure%20Pipelines%20CI?branchName=main :alt: CPython build status on Azure DevOps :target: https://dev.azure.com/python/cpython/_build/latest?definitionId=4&branchName=main .. image:: https://img.shields.io/badge/discourse-join_chat-brightgreen.svg :alt: Python Discourse chat :target: https://discuss.python.org/ Copyright © 2001 Python Software Foundation. All rights reserved. See the end of this file for further copyright and license information. .. contents:: General Information ------------------- - Website: https://www.python.org - Source code: https://github.com/python/cpython - Issue tracker: https://github.com/python/cpython/issues - Documentation: https://docs.python.org - Developer's Guide: https://devguide.python.org/ Contributing to CPython ----------------------- For more complete instructions on contributing to CPython development, see the `Developer Guide`_. .. _Developer Guide: https://devguide.python.org/ Using Python ------------ Installable Python kits, and information about using Python, are available at `python.org`_. .. _python.org: https://www.python.org/ Build Instructions ------------------ On Unix, Linux, BSD, macOS, and Cygwin:: ./configure make make test sudo make install This will install Python as ``python3``. You can pass many options to the configure script; run ``./configure --help`` to find out more. On macOS case-insensitive file systems and on Cygwin, the executable is called ``python.exe``; elsewhere it's just ``python``. Building a complete Python installation requires the use of various additional third-party libraries, depending on your build platform and configure options. Not all standard library modules are buildable or usable on all platforms. Refer to the `Install dependencies `_ section of the `Developer Guide`_ for current detailed information on dependencies for various Linux distributions and macOS. On macOS, there are additional configure and build options related to macOS framework and universal builds. Refer to `Mac/README.rst `_. On Windows, see `PCbuild/readme.txt `_. To build Windows installer, see `Tools/msi/README.txt `_. If you wish, you can create a subdirectory and invoke configure from there. For example:: mkdir debug cd debug ../configure --with-pydebug make make test (This will fail if you *also* built at the top-level directory. You should do a ``make clean`` at the top-level first.) To get an optimized build of Python, ``configure --enable-optimizations`` before you run ``make``. This sets the default make targets up to enable Profile Guided Optimization (PGO) and may be used to auto-enable Link Time Optimization (LTO) on some platforms. For more details, see the sections below. Profile Guided Optimization ^^^^^^^^^^^^^^^^^^^^^^^^^^^ PGO takes advantage of recent versions of the GCC or Clang compilers. If used, either via ``configure --enable-optimizations`` or by manually running ``make profile-opt`` regardless of configure flags, the optimized build process will perform the following steps: The entire Python directory is cleaned of temporary files that may have resulted from a previous compilation. An instrumented version of the interpreter is built, using suitable compiler flags for each flavor. Note that this is just an intermediary step. The binary resulting from this step is not good for real-life workloads as it has profiling instructions embedded inside. After the instrumented interpreter is built, the Makefile will run a training workload. This is necessary in order to profile the interpreter's execution. Note also that any output, both stdout and stderr, that may appear at this step is suppressed. The final step is to build the actual interpreter, using the information collected from the instrumented one. The end result will be a Python binary that is optimized; suitable for distribution or production installation. Link Time Optimization ^^^^^^^^^^^^^^^^^^^^^^ Enabled via configure's ``--with-lto`` flag. LTO takes advantage of the ability of recent compiler toolchains to optimize across the otherwise arbitrary ``.o`` file boundary when building final executables or shared libraries for additional performance gains. What's New ---------- We have a comprehensive overview of the changes in the `What's new in Python 3.15 `_ document. For a more detailed change log, read `Misc/NEWS `_, but a full accounting of changes can only be gleaned from the `commit history `_. If you want to install multiple versions of Python, see the section below entitled "Installing multiple versions". Documentation ------------- `Documentation for Python 3.15 `_ is online, updated daily. It can also be downloaded in many formats for faster access. The documentation is downloadable in HTML, EPUB, and reStructuredText formats; the latter version is primarily for documentation authors, translators, and people with special formatting requirements. For information about building Python's documentation, refer to `Doc/README.rst `_. Testing ------- To test the interpreter, type ``make test`` in the top-level directory. The test set produces some output. You can generally ignore the messages about skipped tests due to optional features which can't be imported. If a message is printed about a failed test or a traceback or core dump is produced, something is wrong. By default, tests are prevented from overusing resources like disk space and memory. To enable these tests, run ``make buildbottest``. If any tests fail, you can re-run the failing test(s) in verbose mode. For example, if ``test_os`` and ``test_gdb`` failed, you can run:: make test TESTOPTS="-v test_os test_gdb" If the failure persists and appears to be a problem with Python rather than your environment, you can `file a bug report `_ and include relevant output from that command to show the issue. See `Running & Writing Tests `_ for more on running tests. Installing multiple versions ---------------------------- On Unix and Mac systems if you intend to install multiple versions of Python using the same installation prefix (``--prefix`` argument to the configure script) you must take care that your primary python executable is not overwritten by the installation of a different version. All files and directories installed using ``make altinstall`` contain the major and minor version and can thus live side-by-side. ``make install`` also creates ``${prefix}/bin/python3`` which refers to ``${prefix}/bin/python3.X``. If you intend to install multiple versions using the same prefix you must decide which version (if any) is your "primary" version. Install that version using ``make install``. Install all other versions using ``make altinstall``. For example, if you want to install Python 2.7, 3.6, and 3.15 with 3.15 being the primary version, you would execute ``make install`` in your 3.15 build directory and ``make altinstall`` in the others. Release Schedule ---------------- See `PEP 790 `__ for Python 3.15 release details. Copyright and License Information --------------------------------- Copyright © 2001 Python Software Foundation. All rights reserved. Copyright © 2000 BeOpen.com. All rights reserved. Copyright © 1995-2001 Corporation for National Research Initiatives. All rights reserved. Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved. See the `LICENSE `_ for information on the history of this software, terms & conditions for usage, and a DISCLAIMER OF ALL WARRANTIES. This Python distribution contains *no* GNU General Public License (GPL) code, so it may be used in proprietary projects. There are interfaces to some GNU code but these are entirely optional. All trademarks referenced herein are property of their respective holders. /* * New exceptions.c written in Iceland by Richard Jones and Georg Brandl. * * Thanks go to Tim Peters and Michael Hudson for debugging. */ #include #include #include "pycore_abstract.h" // _PyObject_RealIsSubclass() #include "pycore_ceval.h" // _Py_EnterRecursiveCall #include "pycore_exceptions.h" // struct _Py_exc_state #include "pycore_initconfig.h" #include "pycore_modsupport.h" // _PyArg_NoKeywords() #include "pycore_object.h" #include "pycore_pyerrors.h" // struct _PyErr_SetRaisedException #include "osdefs.h" // SEP #include "clinic/exceptions.c.h" /*[clinic input] class BaseException "PyBaseExceptionObject *" "&PyExc_BaseException" class BaseExceptionGroup "PyBaseExceptionGroupObject *" "&PyExc_BaseExceptionGroup" [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=b7c45e78cff8edc3]*/ static struct _Py_exc_state* get_exc_state(void) { PyInterpreterState *interp = _PyInterpreterState_GET(); return &interp->exc_state; } /* NOTE: If the exception class hierarchy changes, don't forget to update * Lib/test/exception_hierarchy.txt */ static inline PyBaseExceptionObject * PyBaseExceptionObject_CAST(PyObject *exc) { assert(PyExceptionInstance_Check(exc)); return (PyBaseExceptionObject *)exc; } /* * BaseException */ static PyObject * BaseException_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyBaseExceptionObject *self; self = (PyBaseExceptionObject *)type->tp_alloc(type, 0); if (!self) return NULL; /* the dict is created on the fly in PyObject_GenericSetAttr */ self->dict = NULL; self->notes = NULL; self->traceback = self->cause = self->context = NULL; self->suppress_context = 0; if (args) { self->args = Py_NewRef(args); return (PyObject *)self; } self->args = PyTuple_New(0); if (!self->args) { Py_DECREF(self); return NULL; } return (PyObject *)self; } static int BaseException_init(PyObject *op, PyObject *args, PyObject *kwds) { PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op); if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds)) return -1; Py_XSETREF(self->args, Py_NewRef(args)); return 0; } static PyObject * BaseException_vectorcall(PyObject *type_obj, PyObject * const*args, size_t nargsf, PyObject *kwnames) { PyTypeObject *type = _PyType_CAST(type_obj); if (!_PyArg_NoKwnames(type->tp_name, kwnames)) { return NULL; } PyBaseExceptionObject *self; self = (PyBaseExceptionObject *)type->tp_alloc(type, 0); if (!self) { return NULL; } // The dict is created on the fly in PyObject_GenericSetAttr() self->dict = NULL; self->notes = NULL; self->traceback = NULL; self->cause = NULL; self->context = NULL; self->suppress_context = 0; self->args = PyTuple_FromArray(args, PyVectorcall_NARGS(nargsf)); if (!self->args) { Py_DECREF(self); return NULL; } return (PyObject *)self; } static int BaseException_clear(PyObject *op) { PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op); Py_CLEAR(self->dict); Py_CLEAR(self->args); Py_CLEAR(self->notes); Py_CLEAR(self->traceback); Py_CLEAR(self->cause); Py_CLEAR(self->context); return 0; } static void BaseException_dealloc(PyObject *op) { PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op); PyObject_GC_UnTrack(self); // bpo-44348: The trashcan mechanism prevents stack overflow when deleting // long chains of exceptions. For example, exceptions can be chained // through the __context__ attributes or the __traceback__ attribute. (void)BaseException_clear(op); Py_TYPE(self)->tp_free(self); } static int BaseException_traverse(PyObject *op, visitproc visit, void *arg) { PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op); Py_VISIT(self->dict); Py_VISIT(self->args); Py_VISIT(self->notes); Py_VISIT(self->traceback); Py_VISIT(self->cause); Py_VISIT(self->context); return 0; } static PyObject * BaseException_str(PyObject *op) { PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op); PyObject *res; Py_BEGIN_CRITICAL_SECTION(self); switch (PyTuple_GET_SIZE(self->args)) { case 0: res = Py_GetConstant(Py_CONSTANT_EMPTY_STR); break; case 1: res = PyObject_Str(PyTuple_GET_ITEM(self->args, 0)); break; default: res = PyObject_Str(self->args); break; } Py_END_CRITICAL_SECTION(); return res; } static PyObject * BaseException_repr(PyObject *op) { PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op); PyObject *res; Py_BEGIN_CRITICAL_SECTION(self); const char *name = _PyType_Name(Py_TYPE(self)); if (PyTuple_GET_SIZE(self->args) == 1) { res = PyUnicode_FromFormat("%s(%R)", name, PyTuple_GET_ITEM(self->args, 0)); } else { res = PyUnicode_FromFormat("%s%R", name, self->args); } Py_END_CRITICAL_SECTION(); return res; } /* Pickling support */ /*[clinic input] @critical_section BaseException.__reduce__ [clinic start generated code]*/ static PyObject * BaseException___reduce___impl(PyBaseExceptionObject *self) /*[clinic end generated code: output=af87c1247ef98748 input=283be5a10d9c964f]*/ { if (self->args && self->dict) return PyTuple_Pack(3, Py_TYPE(self), self->args, self->dict); else return PyTuple_Pack(2, Py_TYPE(self), self->args); } /* * Needed for backward compatibility, since exceptions used to store * all their attributes in the __dict__. Code is taken from cPickle's * load_build function. */ /*[clinic input] @critical_section BaseException.__setstate__ state: object / [clinic start generated code]*/ static PyObject * BaseException___setstate___impl(PyBaseExceptionObject *self, PyObject *state) /*[clinic end generated code: output=f3834889950453ab input=5524b61cfe9b9856]*/ { PyObject *d_key, *d_value; Py_ssize_t i = 0; if (state != Py_None) { if (!PyDict_Check(state)) { PyErr_SetString(PyExc_TypeError, "state is not a dictionary"); return NULL; } while (PyDict_Next(state, &i, &d_key, &d_value)) { Py_INCREF(d_key); Py_INCREF(d_value); int res = PyObject_SetAttr((PyObject *)self, d_key, d_value); Py_DECREF(d_value); Py_DECREF(d_key); if (res < 0) { return NULL; } } } Py_RETURN_NONE; } /*[clinic input] @critical_section BaseException.with_traceback tb: object / Set self.__traceback__ to tb and return self. [clinic start generated code]*/ static PyObject * BaseException_with_traceback_impl(PyBaseExceptionObject *self, PyObject *tb) /*[clinic end generated code: output=81e92f2387927f10 input=b5fb64d834717e36]*/ { if (BaseException___traceback___set_impl(self, tb) < 0){ return NULL; } return Py_NewRef(self); } /*[clinic input] @critical_section BaseException.add_note note: object(subclass_of="&PyUnicode_Type") / Add a note to the exception [clinic start generated code]*/ static PyObject * BaseException_add_note_impl(PyBaseExceptionObject *self, PyObject *note) /*[clinic end generated code: output=fb7cbcba611c187b input=e60a6b6e9596acaf]*/ { PyObject *notes; if (PyObject_GetOptionalAttr((PyObject *)self, &_Py_ID(__notes__), ¬es) < 0) { return NULL; } if (notes == NULL) { notes = PyList_New(0); if (notes == NULL) { return NULL; } if (PyObject_SetAttr((PyObject *)self, &_Py_ID(__notes__), notes) < 0) { Py_DECREF(notes); return NULL; } } else if (!PyList_Check(notes)) { Py_DECREF(notes); PyErr_SetString(PyExc_TypeError, "Cannot add note: __notes__ is not a list"); return NULL; } if (PyList_Append(notes, note) < 0) { Py_DECREF(notes); return NULL; } Py_DECREF(notes); Py_RETURN_NONE; } static PyMethodDef BaseException_methods[] = { BASEEXCEPTION___REDUCE___METHODDEF BASEEXCEPTION___SETSTATE___METHODDEF BASEEXCEPTION_WITH_TRACEBACK_METHODDEF BASEEXCEPTION_ADD_NOTE_METHODDEF {NULL, NULL, 0, NULL}, }; /*[clinic input] @critical_section @getter BaseException.args [clinic start generated code]*/ static PyObject * BaseException_args_get_impl(PyBaseExceptionObject *self) /*[clinic end generated code: output=e02e34e35cf4d677 input=64282386e4d7822d]*/ { if (self->args == NULL) { Py_RETURN_NONE; } return Py_NewRef(self->args); } /*[clinic input] @critical_section @setter BaseException.args [clinic start generated code]*/ static int BaseException_args_set_impl(PyBaseExceptionObject *self, PyObject *value) /*[clinic end generated code: output=331137e11d8f9e80 input=2400047ea5970a84]*/ { PyObject *seq; if (value == NULL) { PyErr_SetString(PyExc_TypeError, "args may not be deleted"); return -1; } seq = PySequence_Tuple(value); if (!seq) return -1; Py_XSETREF(self->args, seq); return 0; } /*[clinic input] @critical_section @getter BaseException.__traceback__ [clinic start generated code]*/ static PyObject * BaseException___traceback___get_impl(PyBaseExceptionObject *self) /*[clinic end generated code: output=17cf874a52339398 input=a2277f0de62170cf]*/ { if (self->traceback == NULL) { Py_RETURN_NONE; } return Py_NewRef(self->traceback); } /*[clinic input] @critical_section @setter BaseException.__traceback__ [clinic start generated code]*/ static int BaseException___traceback___set_impl(PyBaseExceptionObject *self, PyObject *value) /*[clinic end generated code: output=a82c86d9f29f48f0 input=12676035676badad]*/ { if (value == NULL) { PyErr_SetString(PyExc_TypeError, "__traceback__ may not be deleted"); return -1; } if (PyTraceBack_Check(value)) { Py_XSETREF(self->traceback, Py_NewRef(value)); } else if (value == Py_None) { Py_CLEAR(self->traceback); } else { PyErr_SetString(PyExc_TypeError, "__traceback__ must be a traceback or None"); return -1; } return 0; } /*[clinic input] @critical_section @getter BaseException.__context__ [clinic start generated code]*/ static PyObject * BaseException___context___get_impl(PyBaseExceptionObject *self) /*[clinic end generated code: output=6ec5d296ce8d1c93 input=b2d22687937e66ab]*/ { if (self->context == NULL) { Py_RETURN_NONE; } return Py_NewRef(self->context); } /*[clinic input] @critical_section @setter BaseException.__context__ [clinic start generated code]*/ static int BaseException___context___set_impl(PyBaseExceptionObject *self, PyObject *value) /*[clinic end generated code: output=b4cb52dcca1da3bd input=c0971adf47fa1858]*/ { if (value == NULL) { PyErr_SetString(PyExc_TypeError, "__context__ may not be deleted"); return -1; } else if (value == Py_None) { value = NULL; } else if (!PyExceptionInstance_Check(value)) { PyErr_SetString(PyExc_TypeError, "exception context must be None " "or derive from BaseException"); return -1; } else { Py_INCREF(value); } Py_XSETREF(self->context, value); return 0; } /*[clinic input] @critical_section @getter BaseException.__cause__ [clinic start generated code]*/ static PyObject * BaseException___cause___get_impl(PyBaseExceptionObject *self) /*[clinic end generated code: output=987f6c4d8a0bdbab input=40e0eac427b6e602]*/ { if (self->cause == NULL) { Py_RETURN_NONE; } return Py_NewRef(self->cause); } /*[clinic input] @critical_section @setter BaseException.__cause__ [clinic start generated code]*/ static int BaseException___cause___set_impl(PyBaseExceptionObject *self, PyObject *value) /*[clinic end generated code: output=6161315398aaf541 input=e1b403c0bde3f62a]*/ { if (value == NULL) { PyErr_SetString(PyExc_TypeError, "__cause__ may not be deleted"); return -1; } else if (value == Py_None) { value = NULL; } else if (!PyExceptionInstance_Check(value)) { PyErr_SetString(PyExc_TypeError, "exception cause must be None " "or derive from BaseException"); return -1; } else { /* PyException_SetCause steals this reference */ Py_INCREF(value); } PyException_SetCause((PyObject *)self, value); return 0; } static PyGetSetDef BaseException_getset[] = { {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict}, BASEEXCEPTION_ARGS_GETSETDEF BASEEXCEPTION___TRACEBACK___GETSETDEF BASEEXCEPTION___CONTEXT___GETSETDEF BASEEXCEPTION___CAUSE___GETSETDEF {NULL}, }; PyObject * PyException_GetTraceback(PyObject *self) { PyObject *traceback; Py_BEGIN_CRITICAL_SECTION(self); traceback = Py_XNewRef(PyBaseExceptionObject_CAST(self)->traceback); Py_END_CRITICAL_SECTION(); return traceback; } int PyException_SetTraceback(PyObject *self, PyObject *tb) { int res; Py_BEGIN_CRITICAL_SECTION(self); res = BaseException___traceback___set_impl(PyBaseExceptionObject_CAST(self), tb); Py_END_CRITICAL_SECTION(); return res; } PyObject * PyException_GetCause(PyObject *self) { PyObject *cause; Py_BEGIN_CRITICAL_SECTION(self); cause = Py_XNewRef(PyBaseExceptionObject_CAST(self)->cause); Py_END_CRITICAL_SECTION(); return cause; } /* Steals a reference to cause */ void PyException_SetCause(PyObject *self, PyObject *cause) { Py_BEGIN_CRITICAL_SECTION(self); PyBaseExceptionObject *base_self = PyBaseExceptionObject_CAST(self); base_self->suppress_context = 1; Py_XSETREF(base_self->cause, cause); Py_END_CRITICAL_SECTION(); } PyObject * PyException_GetContext(PyObject *self) { PyObject *context; Py_BEGIN_CRITICAL_SECTION(self); context = Py_XNewRef(PyBaseExceptionObject_CAST(self)->context); Py_END_CRITICAL_SECTION(); return context; } /* Steals a reference to context */ void PyException_SetContext(PyObject *self, PyObject *context) { Py_BEGIN_CRITICAL_SECTION(self); Py_XSETREF(PyBaseExceptionObject_CAST(self)->context, context); Py_END_CRITICAL_SECTION(); } PyObject * PyException_GetArgs(PyObject *self) { PyObject *args; Py_BEGIN_CRITICAL_SECTION(self); args = Py_NewRef(PyBaseExceptionObject_CAST(self)->args); Py_END_CRITICAL_SECTION(); return args; } void PyException_SetArgs(PyObject *self, PyObject *args) { Py_BEGIN_CRITICAL_SECTION(self); Py_INCREF(args); Py_XSETREF(PyBaseExceptionObject_CAST(self)->args, args); Py_END_CRITICAL_SECTION(); } const char * PyExceptionClass_Name(PyObject *ob) { assert(PyExceptionClass_Check(ob)); return ((PyTypeObject*)ob)->tp_name; } static struct PyMemberDef BaseException_members[] = { {"__suppress_context__", Py_T_BOOL, offsetof(PyBaseExceptionObject, suppress_context)}, {NULL} }; static PyTypeObject _PyExc_BaseException = { PyVarObject_HEAD_INIT(NULL, 0) "BaseException", /*tp_name*/ sizeof(PyBaseExceptionObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ BaseException_dealloc, /*tp_dealloc*/ 0, /*tp_vectorcall_offset*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_as_async*/ BaseException_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ BaseException_str, /*tp_str*/ PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/ PyDoc_STR("Common base class for all exceptions"), /* tp_doc */ BaseException_traverse, /* tp_traverse */ BaseException_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ BaseException_methods, /* tp_methods */ BaseException_members, /* tp_members */ BaseException_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(PyBaseExceptionObject, dict), /* tp_dictoffset */ BaseException_init, /* tp_init */ 0, /* tp_alloc */ BaseException_new, /* tp_new */ .tp_vectorcall = BaseException_vectorcall, }; /* the CPython API expects exceptions to be (PyObject *) - both a hold-over from the previous implementation and also allowing Python objects to be used in the API */ PyObject *PyExc_BaseException = (PyObject *)&_PyExc_BaseException; /* note these macros omit the last semicolon so the macro invocation may * include it and not look strange. */ #define SimpleExtendsException(EXCBASE, EXCNAME, EXCDOC) \ static PyTypeObject _PyExc_ ## EXCNAME = { \ PyVarObject_HEAD_INIT(NULL, 0) \ # EXCNAME, \ sizeof(PyBaseExceptionObject), \ 0, BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \ 0, 0, 0, 0, 0, 0, 0, \ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \ PyDoc_STR(EXCDOC), BaseException_traverse, \ BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \ 0, 0, 0, offsetof(PyBaseExceptionObject, dict), \ BaseException_init, 0, BaseException_new,\ }; \ PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME #define MiddlingExtendsExceptionEx(EXCBASE, EXCNAME, PYEXCNAME, EXCSTORE, EXCDOC) \ PyTypeObject _PyExc_ ## EXCNAME = { \ PyVarObject_HEAD_INIT(NULL, 0) \ # PYEXCNAME, \ sizeof(Py ## EXCSTORE ## Object), \ 0, EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \ 0, 0, 0, 0, 0, \ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \ PyDoc_STR(EXCDOC), EXCSTORE ## _traverse, \ EXCSTORE ## _clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \ 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \ EXCSTORE ## _init, 0, 0, \ }; #define MiddlingExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDOC) \ static MiddlingExtendsExceptionEx( \ EXCBASE, EXCNAME, EXCNAME, EXCSTORE, EXCDOC); \ PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME #define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCNEW, \ EXCMETHODS, EXCMEMBERS, EXCGETSET, \ EXCSTR, EXCREPR, EXCDOC) \ static PyTypeObject _PyExc_ ## EXCNAME = { \ PyVarObject_HEAD_INIT(NULL, 0) \ # EXCNAME, \ sizeof(Py ## EXCSTORE ## Object), 0, \ EXCSTORE ## _dealloc, 0, 0, 0, 0, EXCREPR, 0, 0, 0, 0, 0, \ EXCSTR, 0, 0, 0, \ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \ PyDoc_STR(EXCDOC), EXCSTORE ## _traverse, \ EXCSTORE ## _clear, 0, 0, 0, 0, EXCMETHODS, \ EXCMEMBERS, EXCGETSET, &_ ## EXCBASE, \ 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \ EXCSTORE ## _init, 0, EXCNEW,\ }; \ PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME /* * Exception extends BaseException */ SimpleExtendsException(PyExc_BaseException, Exception, "Common base class for all non-exit exceptions."); /* * TypeError extends Exception */ SimpleExtendsException(PyExc_Exception, TypeError, "Inappropriate argument type."); /* * StopAsyncIteration extends Exception */ SimpleExtendsException(PyExc_Exception, StopAsyncIteration, "Signal the end from iterator.__anext__()."); /* * StopIteration extends Exception */ static PyMemberDef StopIteration_members[] = { {"value", _Py_T_OBJECT, offsetof(PyStopIterationObject, value), 0, PyDoc_STR("generator return value")}, {NULL} /* Sentinel */ }; static inline PyStopIterationObject * PyStopIterationObject_CAST(PyObject *self) { assert(PyObject_TypeCheck(self, (PyTypeObject *)PyExc_StopIteration)); return (PyStopIterationObject *)self; } static int StopIteration_init(PyObject *op, PyObject *args, PyObject *kwds) { Py_ssize_t size = PyTuple_GET_SIZE(args); PyObject *value; if (BaseException_init(op, args, kwds) == -1) return -1; PyStopIterationObject *self = PyStopIterationObject_CAST(op); Py_CLEAR(self->value); if (size > 0) value = PyTuple_GET_ITEM(args, 0); else value = Py_None; self->value = Py_NewRef(value); return 0; } static int StopIteration_clear(PyObject *op) { PyStopIterationObject *self = PyStopIterationObject_CAST(op); Py_CLEAR(self->value); return BaseException_clear(op); } static void StopIteration_dealloc(PyObject *self) { PyObject_GC_UnTrack(self); (void)StopIteration_clear(self); Py_TYPE(self)->tp_free(self); } static int StopIteration_traverse(PyObject *op, visitproc visit, void *arg) { PyStopIterationObject *self = PyStopIterationObject_CAST(op); Py_VISIT(self->value); return BaseException_traverse(op, visit, arg); } ComplexExtendsException(PyExc_Exception, StopIteration, StopIteration, 0, 0, StopIteration_members, 0, 0, 0, "Signal the end from iterator.__next__()."); /* * GeneratorExit extends BaseException */ SimpleExtendsException(PyExc_BaseException, GeneratorExit, "Request that a generator exit."); /* * SystemExit extends BaseException */ static inline PySystemExitObject * PySystemExitObject_CAST(PyObject *self) { assert(PyObject_TypeCheck(self, (PyTypeObject *)PyExc_SystemExit)); return (PySystemExitObject *)self; } static int SystemExit_init(PyObject *op, PyObject *args, PyObject *kwds) { Py_ssize_t size = PyTuple_GET_SIZE(args); if (BaseException_init(op, args, kwds) == -1) return -1; PySystemExitObject *self = PySystemExitObject_CAST(op); if (size == 0) return 0; if (size == 1) { Py_XSETREF(self->code, Py_NewRef(PyTuple_GET_ITEM(args, 0))); } else { /* size > 1 */ Py_XSETREF(self->code, Py_NewRef(args)); } return 0; } static int SystemExit_clear(PyObject *op) { PySystemExitObject *self = PySystemExitObject_CAST(op); Py_CLEAR(self->code); return BaseException_clear(op); } static void SystemExit_dealloc(PyObject *self) { _PyObject_GC_UNTRACK(self); (void)SystemExit_clear(self); Py_TYPE(self)->tp_free(self); } static int SystemExit_traverse(PyObject *op, visitproc visit, void *arg) { PySystemExitObject *self = PySystemExitObject_CAST(op); Py_VISIT(self->code); return BaseException_traverse(op, visit, arg); } static PyMemberDef SystemExit_members[] = { {"code", _Py_T_OBJECT, offsetof(PySystemExitObject, code), 0, PyDoc_STR("exception code")}, {NULL} /* Sentinel */ }; ComplexExtendsException(PyExc_BaseException, SystemExit, SystemExit, 0, 0, SystemExit_members, 0, 0, 0, "Request to exit from the interpreter."); /* * BaseExceptionGroup extends BaseException * ExceptionGroup extends BaseExceptionGroup and Exception */ static inline PyBaseExceptionGroupObject* PyBaseExceptionGroupObject_CAST(PyObject *exc) { assert(_PyBaseExceptionGroup_Check(exc)); return (PyBaseExceptionGroupObject *)exc; } static PyObject * BaseExceptionGroup_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { struct _Py_exc_state *state = get_exc_state(); PyTypeObject *PyExc_ExceptionGroup = (PyTypeObject*)state->PyExc_ExceptionGroup; PyObject *message = NULL; PyObject *exceptions = NULL; PyObject *exceptions_str = NULL; if (!PyArg_ParseTuple(args, "UO:BaseExceptionGroup.__new__", &message, &exceptions)) { return NULL; } if (!PySequence_Check(exceptions)) { PyErr_SetString( PyExc_TypeError, "second argument (exceptions) must be a sequence"); return NULL; } /* Save initial exceptions sequence as a string in case sequence is mutated */ if (!PyList_Check(exceptions) && !PyTuple_Check(exceptions)) { exceptions_str = PyObject_Repr(exceptions); if (exceptions_str == NULL) { /* We don't hold a reference to exceptions, so clear it before * attempting a decref in the cleanup. */ exceptions = NULL; goto error; } } exceptions = PySequence_Tuple(exceptions); if (!exceptions) { return NULL; } /* We are now holding a ref to the exceptions tuple */ Py_ssize_t numexcs = PyTuple_GET_SIZE(exceptions); if (numexcs == 0) { PyErr_SetString( PyExc_ValueError, "second argument (exceptions) must be a non-empty sequence"); goto error; } bool nested_base_exceptions = false; for (Py_ssize_t i = 0; i < numexcs; i++) { PyObject *exc = PyTuple_GET_ITEM(exceptions, i); if (!exc) { goto error; } if (!PyExceptionInstance_Check(exc)) { PyErr_Format( PyExc_ValueError, "Item %d of second argument (exceptions) is not an exception", i); goto error; } int is_nonbase_exception = PyObject_IsInstance(exc, PyExc_Exception); if (is_nonbase_exception < 0) { goto error; } else if (is_nonbase_exception == 0) { nested_base_exceptions = true; } } PyTypeObject *cls = type; if (cls == PyExc_ExceptionGroup) { if (nested_base_exceptions) { PyErr_SetString(PyExc_TypeError, "Cannot nest BaseExceptions in an ExceptionGroup"); goto error; } } else if (cls == (PyTypeObject*)PyExc_BaseExceptionGroup) { if (!nested_base_exceptions) { /* All nested exceptions are Exception subclasses, * wrap them in an ExceptionGroup */ cls = PyExc_ExceptionGroup; } } else { /* user-defined subclass */ if (nested_base_exceptions) { int nonbase = PyObject_IsSubclass((PyObject*)cls, PyExc_Exception); if (nonbase == -1) { goto error; } else if (nonbase == 1) { PyErr_Format(PyExc_TypeError, "Cannot nest BaseExceptions in '%.200s'", cls->tp_name); goto error; } } } if (!cls) { /* Don't crash during interpreter shutdown * (PyExc_ExceptionGroup may have been cleared) */ cls = (PyTypeObject*)PyExc_BaseExceptionGroup; } PyBaseExceptionGroupObject *self = PyBaseExceptionGroupObject_CAST(BaseException_new(cls, args, kwds)); if (!self) { goto error; } self->msg = Py_NewRef(message); self->excs = exceptions; self->excs_str = exceptions_str; return (PyObject*)self; error: Py_XDECREF(exceptions); Py_XDECREF(exceptions_str); return NULL; } PyObject * _PyExc_CreateExceptionGroup(const char *msg_str, PyObject *excs) { PyObject *msg = PyUnicode_FromString(msg_str); if (!msg) { return NULL; } PyObject *args = PyTuple_Pack(2, msg, excs); Py_DECREF(msg); if (!args) { return NULL; } PyObject *result = PyObject_CallObject(PyExc_BaseExceptionGroup, args); Py_DECREF(args); return result; } static int BaseExceptionGroup_init(PyObject *self, PyObject *args, PyObject *kwds) { if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds)) { return -1; } if (BaseException_init(self, args, kwds) == -1) { return -1; } return 0; } static int BaseExceptionGroup_clear(PyObject *op) { PyBaseExceptionGroupObject *self = PyBaseExceptionGroupObject_CAST(op); Py_CLEAR(self->msg); Py_CLEAR(self->excs); Py_CLEAR(self->excs_str); return BaseException_clear(op); } static void BaseExceptionGroup_dealloc(PyObject *self) { _PyObject_GC_UNTRACK(self); (void)BaseExceptionGroup_clear(self); Py_TYPE(self)->tp_free(self); } static int BaseExceptionGroup_traverse(PyObject *op, visitproc visit, void *arg) { PyBaseExceptionGroupObject *self = PyBaseExceptionGroupObject_CAST(op); Py_VISIT(self->msg); Py_VISIT(self->excs); Py_VISIT(self->excs_str); return BaseException_traverse(op, visit, arg); } static PyObject * BaseExceptionGroup_str(PyObject *op) { PyBaseExceptionGroupObject *self = PyBaseExceptionGroupObject_CAST(op); assert(self->msg); assert(PyUnicode_Check(self->msg)); assert(PyTuple_CheckExact(self->excs)); Py_ssize_t num_excs = PyTuple_Size(self->excs); return PyUnicode_FromFormat( "%S (%zd sub-exception%s)", self->msg, num_excs, num_excs > 1 ? "s" : ""); } static PyObject * BaseExceptionGroup_repr(PyObject *op) { PyBaseExceptionGroupObject *self = PyBaseExceptionGroupObject_CAST(op); assert(self->msg); PyObject *exceptions_str = NULL; /* Use the saved exceptions string for custom sequences. */ if (self->excs_str) { exceptions_str = Py_NewRef(self->excs_str); } else { assert(self->excs); /* Older versions delegated to BaseException, inserting the current * value of self.args[1]; but this can be mutable and go out-of-sync * with self.exceptions. Instead, use self.exceptions for accuracy, * making it look like self.args[1] for backwards compatibility. */ if (PyList_Check(PyTuple_GET_ITEM(self->args, 1))) { PyObject *exceptions_list = PySequence_List(self->excs); if (!exceptions_list) { return NULL; } exceptions_str = PyObject_Repr(exceptions_list); Py_DECREF(exceptions_list); } else { exceptions_str = PyObject_Repr(self->excs); } if (!exceptions_str) { return NULL; } } assert(exceptions_str != NULL); const char *name = _PyType_Name(Py_TYPE(self)); PyObject *repr = PyUnicode_FromFormat( "%s(%R, %U)", name, self->msg, exceptions_str); Py_DECREF(exceptions_str); return repr; } /*[clinic input] @critical_section BaseExceptionGroup.derive excs: object / [clinic start generated code]*/ static PyObject * BaseExceptionGroup_derive_impl(PyBaseExceptionGroupObject *self, PyObject *excs) /*[clinic end generated code: output=4307564218dfbf06 input=f72009d38e98cec1]*/ { PyObject *init_args = PyTuple_Pack(2, self->msg, excs); if (!init_args) { return NULL; } PyObject *eg = PyObject_CallObject( PyExc_BaseExceptionGroup, init_args); Py_DECREF(init_args); return eg; } static int exceptiongroup_subset( PyBaseExceptionGroupObject *_orig, PyObject *excs, PyObject **result) { /* Sets *result to an ExceptionGroup wrapping excs with metadata from * _orig. If excs is empty, sets *result to NULL. * Returns 0 on success and -1 on error. * This function is used by split() to construct the match/rest parts, * so excs is the matching or non-matching sub-sequence of orig->excs * (this function does not verify that it is a subsequence). */ PyObject *orig = (PyObject *)_orig; *result = NULL; Py_ssize_t num_excs = PySequence_Size(excs); if (num_excs < 0) { return -1; } else if (num_excs == 0) { return 0; } PyObject *eg = PyObject_CallMethod( orig, "derive", "(O)", excs); if (!eg) { return -1; } if (!_PyBaseExceptionGroup_Check(eg)) { PyErr_SetString(PyExc_TypeError, "derive must return an instance of BaseExceptionGroup"); goto error; } /* Now we hold a reference to the new eg */ PyObject *tb = PyException_GetTraceback(orig); if (tb) { int res = PyException_SetTraceback(eg, tb); Py_DECREF(tb); if (res < 0) { goto error; } } PyException_SetContext(eg, PyException_GetContext(orig)); PyException_SetCause(eg, PyException_GetCause(orig)); PyObject *notes; if (PyObject_GetOptionalAttr(orig, &_Py_ID(__notes__), ¬es) < 0) { goto error; } if (notes) { if (PySequence_Check(notes)) { /* Make a copy so the parts have independent notes lists. */ PyObject *notes_copy = PySequence_List(notes); Py_DECREF(notes); if (notes_copy == NULL) { goto error; } int res = PyObject_SetAttr(eg, &_Py_ID(__notes__), notes_copy); Py_DECREF(notes_copy); if (res < 0) { goto error; } } else { /* __notes__ is supposed to be a list, and split() is not a * good place to report earlier user errors, so we just ignore * notes of non-sequence type. */ Py_DECREF(notes); } } *result = eg; return 0; error: Py_DECREF(eg); return -1; } typedef enum { /* Exception type or tuple of thereof */ EXCEPTION_GROUP_MATCH_BY_TYPE = 0, /* A PyFunction returning True for matching exceptions */ EXCEPTION_GROUP_MATCH_BY_PREDICATE = 1, /* A set of the IDs of leaf exceptions to include in the result. * This matcher type is used internally by the interpreter * to construct reraised exceptions. */ EXCEPTION_GROUP_MATCH_INSTANCE_IDS = 2 } _exceptiongroup_split_matcher_type; static int get_matcher_type(PyObject *value, _exceptiongroup_split_matcher_type *type) { assert(value); if (PyCallable_Check(value) && !PyType_Check(value)) { *type = EXCEPTION_GROUP_MATCH_BY_PREDICATE; return 0; } if (PyExceptionClass_Check(value)) { *type = EXCEPTION_GROUP_MATCH_BY_TYPE; return 0; } if (PyTuple_CheckExact(value)) { Py_ssize_t n = PyTuple_GET_SIZE(value); for (Py_ssize_t i=0; imatch = NULL; result->rest = NULL; int is_match = exceptiongroup_split_check_match( exc, matcher_type, matcher_value); if (is_match < 0) { return -1; } if (is_match) { /* Full match */ result->match = Py_NewRef(exc); return 0; } else if (!_PyBaseExceptionGroup_Check(exc)) { /* Leaf exception and no match */ if (construct_rest) { result->rest = Py_NewRef(exc); } return 0; } /* Partial match */ PyBaseExceptionGroupObject *eg = PyBaseExceptionGroupObject_CAST(exc); assert(PyTuple_CheckExact(eg->excs)); Py_ssize_t num_excs = PyTuple_Size(eg->excs); if (num_excs < 0) { return -1; } assert(num_excs > 0); /* checked in constructor, and excs is read-only */ int retval = -1; PyObject *match_list = PyList_New(0); if (!match_list) { return -1; } PyObject *rest_list = NULL; if (construct_rest) { rest_list = PyList_New(0); if (!rest_list) { goto done; } } /* recursive calls */ for (Py_ssize_t i = 0; i < num_excs; i++) { PyObject *e = PyTuple_GET_ITEM(eg->excs, i); _exceptiongroup_split_result rec_result; if (_Py_EnterRecursiveCall(" in exceptiongroup_split_recursive")) { goto done; } if (exceptiongroup_split_recursive( e, matcher_type, matcher_value, construct_rest, &rec_result) < 0) { assert(!rec_result.match); assert(!rec_result.rest); _Py_LeaveRecursiveCall(); goto done; } _Py_LeaveRecursiveCall(); if (rec_result.match) { assert(PyList_CheckExact(match_list)); if (PyList_Append(match_list, rec_result.match) < 0) { Py_DECREF(rec_result.match); Py_XDECREF(rec_result.rest); goto done; } Py_DECREF(rec_result.match); } if (rec_result.rest) { assert(construct_rest); assert(PyList_CheckExact(rest_list)); if (PyList_Append(rest_list, rec_result.rest) < 0) { Py_DECREF(rec_result.rest); goto done; } Py_DECREF(rec_result.rest); } } /* construct result */ if (exceptiongroup_subset(eg, match_list, &result->match) < 0) { goto done; } if (construct_rest) { assert(PyList_CheckExact(rest_list)); if (exceptiongroup_subset(eg, rest_list, &result->rest) < 0) { Py_CLEAR(result->match); goto done; } } retval = 0; done: Py_DECREF(match_list); Py_XDECREF(rest_list); if (retval < 0) { Py_CLEAR(result->match); Py_CLEAR(result->rest); } return retval; } /*[clinic input] @critical_section BaseExceptionGroup.split matcher_value: object / [clinic start generated code]*/ static PyObject * BaseExceptionGroup_split_impl(PyBaseExceptionGroupObject *self, PyObject *matcher_value) /*[clinic end generated code: output=d74db579da4df6e2 input=0c5cfbfed57e0052]*/ { _exceptiongroup_split_matcher_type matcher_type; if (get_matcher_type(matcher_value, &matcher_type) < 0) { return NULL; } _exceptiongroup_split_result split_result; bool construct_rest = true; if (exceptiongroup_split_recursive( (PyObject *)self, matcher_type, matcher_value, construct_rest, &split_result) < 0) { return NULL; } PyObject *result = PyTuple_Pack( 2, split_result.match ? split_result.match : Py_None, split_result.rest ? split_result.rest : Py_None); Py_XDECREF(split_result.match); Py_XDECREF(split_result.rest); return result; } /*[clinic input] @critical_section BaseExceptionGroup.subgroup matcher_value: object / [clinic start generated code]*/ static PyObject * BaseExceptionGroup_subgroup_impl(PyBaseExceptionGroupObject *self, PyObject *matcher_value) /*[clinic end generated code: output=07dbec8f77d4dd8e input=988ffdd755a151ce]*/ { _exceptiongroup_split_matcher_type matcher_type; if (get_matcher_type(matcher_value, &matcher_type) < 0) { return NULL; } _exceptiongroup_split_result split_result; bool construct_rest = false; if (exceptiongroup_split_recursive( (PyObject *)self, matcher_type, matcher_value, construct_rest, &split_result) < 0) { return NULL; } PyObject *result = Py_NewRef( split_result.match ? split_result.match : Py_None); Py_XDECREF(split_result.match); assert(!split_result.rest); return result; } static int collect_exception_group_leaf_ids(PyObject *exc, PyObject *leaf_ids) { if (Py_IsNone(exc)) { return 0; } assert(PyExceptionInstance_Check(exc)); assert(PySet_Check(leaf_ids)); /* Add IDs of all leaf exceptions in exc to the leaf_ids set */ if (!_PyBaseExceptionGroup_Check(exc)) { PyObject *exc_id = PyLong_FromVoidPtr(exc); if (exc_id == NULL) { return -1; } int res = PySet_Add(leaf_ids, exc_id); Py_DECREF(exc_id); return res; } PyBaseExceptionGroupObject *eg = PyBaseExceptionGroupObject_CAST(exc); Py_ssize_t num_excs = PyTuple_GET_SIZE(eg->excs); /* recursive calls */ for (Py_ssize_t i = 0; i < num_excs; i++) { PyObject *e = PyTuple_GET_ITEM(eg->excs, i); if (_Py_EnterRecursiveCall(" in collect_exception_group_leaf_ids")) { return -1; } int res = collect_exception_group_leaf_ids(e, leaf_ids); _Py_LeaveRecursiveCall(); if (res < 0) { return -1; } } return 0; } /* This function is used by the interpreter to construct reraised * exception groups. It takes an exception group eg and a list * of exception groups keep and returns the sub-exception group * of eg which contains all leaf exceptions that are contained * in any exception group in keep. */ static PyObject * exception_group_projection(PyObject *eg, PyObject *keep) { assert(_PyBaseExceptionGroup_Check(eg)); assert(PyList_CheckExact(keep)); PyObject *leaf_ids = PySet_New(NULL); if (!leaf_ids) { return NULL; } Py_ssize_t n = PyList_GET_SIZE(keep); for (Py_ssize_t i = 0; i < n; i++) { PyObject *e = PyList_GET_ITEM(keep, i); assert(e != NULL); assert(_PyBaseExceptionGroup_Check(e)); if (collect_exception_group_leaf_ids(e, leaf_ids) < 0) { Py_DECREF(leaf_ids); return NULL; } } _exceptiongroup_split_result split_result; bool construct_rest = false; int err = exceptiongroup_split_recursive( eg, EXCEPTION_GROUP_MATCH_INSTANCE_IDS, leaf_ids, construct_rest, &split_result); Py_DECREF(leaf_ids); if (err < 0) { return NULL; } PyObject *result = split_result.match ? split_result.match : Py_NewRef(Py_None); assert(split_result.rest == NULL); return result; } static bool is_same_exception_metadata(PyObject *exc1, PyObject *exc2) { assert(PyExceptionInstance_Check(exc1)); assert(PyExceptionInstance_Check(exc2)); PyBaseExceptionObject *e1 = (PyBaseExceptionObject *)exc1; PyBaseExceptionObject *e2 = (PyBaseExceptionObject *)exc2; return (e1->notes == e2->notes && e1->traceback == e2->traceback && e1->cause == e2->cause && e1->context == e2->context); } /* This function is used by the interpreter to calculate the exception group to be raised at the end of a try-except* construct. orig: the original except that was caught. excs: a list of exceptions that were raised/reraised in the except* clauses. Calculates an exception group to raise. It contains all exceptions in excs, where those that were reraised have same nesting structure as in orig, and those that were raised (if any) are added as siblings in a new EG. Returns NULL and sets an exception on failure. */ PyObject * _PyExc_PrepReraiseStar(PyObject *orig, PyObject *excs) { /* orig must be a raised & caught exception, so it has a traceback */ assert(PyExceptionInstance_Check(orig)); assert(PyBaseExceptionObject_CAST(orig)->traceback != NULL); assert(PyList_Check(excs)); Py_ssize_t numexcs = PyList_GET_SIZE(excs); if (numexcs == 0) { return Py_NewRef(Py_None); } if (!_PyBaseExceptionGroup_Check(orig)) { /* a naked exception was caught and wrapped. Only one except* clause * could have executed,so there is at most one exception to raise. */ assert(numexcs == 1 || (numexcs == 2 && PyList_GET_ITEM(excs, 1) == Py_None)); PyObject *e = PyList_GET_ITEM(excs, 0); assert(e != NULL); return Py_NewRef(e); } PyObject *raised_list = PyList_New(0); if (raised_list == NULL) { return NULL; } PyObject* reraised_list = PyList_New(0); if (reraised_list == NULL) { Py_DECREF(raised_list); return NULL; } /* Now we are holding refs to raised_list and reraised_list */ PyObject *result = NULL; /* Split excs into raised and reraised by comparing metadata with orig */ for (Py_ssize_t i = 0; i < numexcs; i++) { PyObject *e = PyList_GET_ITEM(excs, i); assert(e != NULL); if (Py_IsNone(e)) { continue; } bool is_reraise = is_same_exception_metadata(e, orig); PyObject *append_list = is_reraise ? reraised_list : raised_list; if (PyList_Append(append_list, e) < 0) { goto done; } } PyObject *reraised_eg = exception_group_projection(orig, reraised_list); if (reraised_eg == NULL) { goto done; } if (!Py_IsNone(reraised_eg)) { assert(is_same_exception_metadata(reraised_eg, orig)); } Py_ssize_t num_raised = PyList_GET_SIZE(raised_list); if (num_raised == 0) { result = reraised_eg; } else if (num_raised > 0) { int res = 0; if (!Py_IsNone(reraised_eg)) { res = PyList_Append(raised_list, reraised_eg); } Py_DECREF(reraised_eg); if (res < 0) { goto done; } if (PyList_GET_SIZE(raised_list) > 1) { result = _PyExc_CreateExceptionGroup("", raised_list); } else { result = Py_NewRef(PyList_GetItem(raised_list, 0)); } if (result == NULL) { goto done; } } done: Py_XDECREF(raised_list); Py_XDECREF(reraised_list); return result; } PyObject * PyUnstable_Exc_PrepReraiseStar(PyObject *orig, PyObject *excs) { if (orig == NULL || !PyExceptionInstance_Check(orig)) { PyErr_SetString(PyExc_TypeError, "orig must be an exception instance"); return NULL; } if (excs == NULL || !PyList_Check(excs)) { PyErr_SetString(PyExc_TypeError, "excs must be a list of exception instances"); return NULL; } Py_ssize_t numexcs = PyList_GET_SIZE(excs); for (Py_ssize_t i = 0; i < numexcs; i++) { PyObject *exc = PyList_GET_ITEM(excs, i); if (exc == NULL || !(PyExceptionInstance_Check(exc) || Py_IsNone(exc))) { PyErr_Format(PyExc_TypeError, "item %d of excs is not an exception", i); return NULL; } } /* Make sure that orig has something as traceback, in the interpreter * it always does because it's a raised exception. */ PyObject *tb = PyException_GetTraceback(orig); if (tb == NULL) { PyErr_Format(PyExc_ValueError, "orig must be a raised exception"); return NULL; } Py_DECREF(tb); return _PyExc_PrepReraiseStar(orig, excs); } static PyMemberDef BaseExceptionGroup_members[] = { {"message", _Py_T_OBJECT, offsetof(PyBaseExceptionGroupObject, msg), Py_READONLY, PyDoc_STR("exception message")}, {"exceptions", _Py_T_OBJECT, offsetof(PyBaseExceptionGroupObject, excs), Py_READONLY, PyDoc_STR("nested exceptions")}, {NULL} /* Sentinel */ }; static PyMethodDef BaseExceptionGroup_methods[] = { {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, PyDoc_STR("See PEP 585")}, BASEEXCEPTIONGROUP_DERIVE_METHODDEF BASEEXCEPTIONGROUP_SPLIT_METHODDEF BASEEXCEPTIONGROUP_SUBGROUP_METHODDEF {NULL} }; ComplexExtendsException(PyExc_BaseException, BaseExceptionGroup, BaseExceptionGroup, BaseExceptionGroup_new /* new */, BaseExceptionGroup_methods, BaseExceptionGroup_members, 0 /* getset */, BaseExceptionGroup_str, BaseExceptionGroup_repr, "A combination of multiple unrelated exceptions."); /* * ExceptionGroup extends BaseExceptionGroup, Exception */ static PyObject* create_exception_group_class(void) { struct _Py_exc_state *state = get_exc_state(); PyObject *bases = PyTuple_Pack( 2, PyExc_BaseExceptionGroup, PyExc_Exception); if (bases == NULL) { return NULL; } assert(!state->PyExc_ExceptionGroup); state->PyExc_ExceptionGroup = PyErr_NewException( "builtins.ExceptionGroup", bases, NULL); Py_DECREF(bases); return state->PyExc_ExceptionGroup; } /* * KeyboardInterrupt extends BaseException */ SimpleExtendsException(PyExc_BaseException, KeyboardInterrupt, "Program interrupted by user."); /* * ImportError extends Exception */ static inline PyImportErrorObject * PyImportErrorObject_CAST(PyObject *self) { assert(PyObject_TypeCheck(self, (PyTypeObject *)PyExc_ImportError)); return (PyImportErrorObject *)self; } static int ImportError_init(PyObject *op, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"name", "path", "name_from", 0}; PyObject *empty_tuple; PyObject *msg = NULL; PyObject *name = NULL; PyObject *path = NULL; PyObject *name_from = NULL; if (BaseException_init(op, args, NULL) == -1) return -1; PyImportErrorObject *self = PyImportErrorObject_CAST(op); empty_tuple = PyTuple_New(0); if (!empty_tuple) return -1; if (!PyArg_ParseTupleAndKeywords(empty_tuple, kwds, "|$OOO:ImportError", kwlist, &name, &path, &name_from)) { Py_DECREF(empty_tuple); return -1; } Py_DECREF(empty_tuple); Py_XSETREF(self->name, Py_XNewRef(name)); Py_XSETREF(self->path, Py_XNewRef(path)); Py_XSETREF(self->name_from, Py_XNewRef(name_from)); if (PyTuple_GET_SIZE(args) == 1) { msg = Py_NewRef(PyTuple_GET_ITEM(args, 0)); } Py_XSETREF(self->msg, msg); return 0; } static int ImportError_clear(PyObject *op) { PyImportErrorObject *self = PyImportErrorObject_CAST(op); Py_CLEAR(self->msg); Py_CLEAR(self->name); Py_CLEAR(self->path); Py_CLEAR(self->name_from); return BaseException_clear(op); } static void ImportError_dealloc(PyObject *self) { _PyObject_GC_UNTRACK(self); (void)ImportError_clear(self); Py_TYPE(self)->tp_free(self); } static int ImportError_traverse(PyObject *op, visitproc visit, void *arg) { PyImportErrorObject *self = PyImportErrorObject_CAST(op); Py_VISIT(self->msg); Py_VISIT(self->name); Py_VISIT(self->path); Py_VISIT(self->name_from); return BaseException_traverse(op, visit, arg); } static PyObject * ImportError_str(PyObject *op) { PyImportErrorObject *self = PyImportErrorObject_CAST(op); if (self->msg && PyUnicode_CheckExact(self->msg)) { return Py_NewRef(self->msg); } return BaseException_str(op); } static PyObject * ImportError_getstate(PyObject *op) { PyImportErrorObject *self = PyImportErrorObject_CAST(op); PyObject *dict = self->dict; if (self->name || self->path || self->name_from) { dict = dict ? PyDict_Copy(dict) : PyDict_New(); if (dict == NULL) return NULL; if (self->name && PyDict_SetItem(dict, &_Py_ID(name), self->name) < 0) { Py_DECREF(dict); return NULL; } if (self->path && PyDict_SetItem(dict, &_Py_ID(path), self->path) < 0) { Py_DECREF(dict); return NULL; } if (self->name_from && PyDict_SetItem(dict, &_Py_ID(name_from), self->name_from) < 0) { Py_DECREF(dict); return NULL; } return dict; } else if (dict) { return Py_NewRef(dict); } else { Py_RETURN_NONE; } } /* Pickling support */ static PyObject * ImportError_reduce(PyObject *self, PyObject *Py_UNUSED(ignored)) { PyObject *res; PyObject *state = ImportError_getstate(self); if (state == NULL) return NULL; PyBaseExceptionObject *exc = PyBaseExceptionObject_CAST(self); if (state == Py_None) res = PyTuple_Pack(2, Py_TYPE(self), exc->args); else res = PyTuple_Pack(3, Py_TYPE(self), exc->args, state); Py_DECREF(state); return res; } static PyObject * ImportError_repr(PyObject *self) { int hasargs = PyTuple_GET_SIZE(((PyBaseExceptionObject *)self)->args) != 0; PyImportErrorObject *exc = PyImportErrorObject_CAST(self); if (exc->name == NULL && exc->path == NULL) { return BaseException_repr(self); } PyUnicodeWriter *writer = PyUnicodeWriter_Create(0); if (writer == NULL) { goto error; } PyObject *r = BaseException_repr(self); if (r == NULL) { goto error; } if (PyUnicodeWriter_WriteSubstring( writer, r, 0, PyUnicode_GET_LENGTH(r) - 1) < 0) { Py_DECREF(r); goto error; } Py_DECREF(r); if (exc->name) { if (hasargs) { if (PyUnicodeWriter_WriteASCII(writer, ", ", 2) < 0) { goto error; } } if (PyUnicodeWriter_Format(writer, "name=%R", exc->name) < 0) { goto error; } hasargs = 1; } if (exc->path) { if (hasargs) { if (PyUnicodeWriter_WriteASCII(writer, ", ", 2) < 0) { goto error; } } if (PyUnicodeWriter_Format(writer, "path=%R", exc->path) < 0) { goto error; } } if (PyUnicodeWriter_WriteChar(writer, ')') < 0) { goto error; } return PyUnicodeWriter_Finish(writer); error: PyUnicodeWriter_Discard(writer); return NULL; } static PyMemberDef ImportError_members[] = { {"msg", _Py_T_OBJECT, offsetof(PyImportErrorObject, msg), 0, PyDoc_STR("exception message")}, {"name", _Py_T_OBJECT, offsetof(PyImportErrorObject, name), 0, PyDoc_STR("module name")}, {"path", _Py_T_OBJECT, offsetof(PyImportErrorObject, path), 0, PyDoc_STR("module path")}, {"name_from", _Py_T_OBJECT, offsetof(PyImportErrorObject, name_from), 0, PyDoc_STR("name imported from module")}, {NULL} /* Sentinel */ }; static PyMethodDef ImportError_methods[] = { {"__reduce__", ImportError_reduce, METH_NOARGS}, {NULL} }; static PyTypeObject _PyExc_ImportError = { PyVarObject_HEAD_INIT(NULL, 0) .tp_name = "ImportError", .tp_basicsize = sizeof(PyImportErrorObject), .tp_dealloc = ImportError_dealloc, .tp_repr = ImportError_repr, .tp_str = ImportError_str, .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, .tp_doc = PyDoc_STR( "Import can't find module, " "or can't find name in module."), .tp_traverse = ImportError_traverse, .tp_clear = ImportError_clear, .tp_methods = ImportError_methods, .tp_members = ImportError_members, .tp_base = &_PyExc_Exception, .tp_dictoffset = offsetof(PyImportErrorObject, dict), .tp_init = ImportError_init, }; PyObject *PyExc_ImportError = (PyObject *)&_PyExc_ImportError; /* * ModuleNotFoundError extends ImportError */ MiddlingExtendsException(PyExc_ImportError, ModuleNotFoundError, ImportError, "Module not found."); /* * OSError extends Exception */ static inline PyOSErrorObject * PyOSErrorObject_CAST(PyObject *self) { assert(PyObject_TypeCheck(self, (PyTypeObject *)PyExc_OSError)); return (PyOSErrorObject *)self; } #ifdef MS_WINDOWS #include "errmap.h" #endif /* Where a function has a single filename, such as open() or some * of the os module functions, PyErr_SetFromErrnoWithFilename() is * called, giving a third argument which is the filename. But, so * that old code using in-place unpacking doesn't break, e.g.: * * except OSError, (errno, strerror): * * we hack args so that it only contains two items. This also * means we need our own __str__() which prints out the filename * when it was supplied. * * (If a function has two filenames, such as rename(), symlink(), * or copy(), PyErr_SetFromErrnoWithFilenameObjects() is called, * which allows passing in a second filename.) */ /* This function doesn't cleanup on error, the caller should */ static int oserror_parse_args(PyObject **p_args, PyObject **myerrno, PyObject **strerror, PyObject **filename, PyObject **filename2 #ifdef MS_WINDOWS , PyObject **winerror #endif ) { Py_ssize_t nargs; PyObject *args = *p_args; #ifndef MS_WINDOWS /* * ignored on non-Windows platforms, * but parsed so OSError has a consistent signature */ PyObject *_winerror = NULL; PyObject **winerror = &_winerror; #endif /* MS_WINDOWS */ nargs = PyTuple_GET_SIZE(args); if (nargs >= 2 && nargs <= 5) { if (!PyArg_UnpackTuple(args, "OSError", 2, 5, myerrno, strerror, filename, winerror, filename2)) return -1; #ifdef MS_WINDOWS if (*winerror && PyLong_Check(*winerror)) { long errcode, winerrcode; PyObject *newargs; Py_ssize_t i; winerrcode = PyLong_AsLong(*winerror); if (winerrcode == -1 && PyErr_Occurred()) return -1; errcode = winerror_to_errno(winerrcode); *myerrno = PyLong_FromLong(errcode); if (!*myerrno) return -1; newargs = PyTuple_New(nargs); if (!newargs) return -1; PyTuple_SET_ITEM(newargs, 0, *myerrno); for (i = 1; i < nargs; i++) { PyObject *val = PyTuple_GET_ITEM(args, i); PyTuple_SET_ITEM(newargs, i, Py_NewRef(val)); } Py_DECREF(args); args = *p_args = newargs; } #endif /* MS_WINDOWS */ } return 0; } static int oserror_init(PyOSErrorObject *self, PyObject **p_args, PyObject *myerrno, PyObject *strerror, PyObject *filename, PyObject *filename2 #ifdef MS_WINDOWS , PyObject *winerror #endif ) { PyObject *args = *p_args; Py_ssize_t nargs = PyTuple_GET_SIZE(args); /* self->filename will remain Py_None otherwise */ if (filename && filename != Py_None) { if (Py_IS_TYPE(self, (PyTypeObject *) PyExc_BlockingIOError) && PyNumber_Check(filename)) { /* BlockingIOError's 3rd argument can be the number of * characters written. */ self->written = PyNumber_AsSsize_t(filename, PyExc_ValueError); if (self->written == -1 && PyErr_Occurred()) return -1; } else { self->filename = Py_NewRef(filename); if (filename2 && filename2 != Py_None) { self->filename2 = Py_NewRef(filename2); } if (nargs >= 2 && nargs <= 5) { /* filename, filename2, and winerror are removed from the args tuple (for compatibility purposes, see test_exceptions.py) */ PyObject *subslice = PyTuple_GetSlice(args, 0, 2); if (!subslice) return -1; Py_DECREF(args); /* replacing args */ *p_args = args = subslice; } } } self->myerrno = Py_XNewRef(myerrno); self->strerror = Py_XNewRef(strerror); #ifdef MS_WINDOWS self->winerror = Py_XNewRef(winerror); #endif /* Steals the reference to args */ Py_XSETREF(self->args, args); *p_args = args = NULL; return 0; } static PyObject * OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds); static int OSError_init(PyObject *self, PyObject *args, PyObject *kwds); static int oserror_use_init(PyTypeObject *type) { /* When __init__ is defined in an OSError subclass, we want any extraneous argument to __new__ to be ignored. The only reasonable solution, given __new__ takes a variable number of arguments, is to defer arg parsing and initialization to __init__. But when __new__ is overridden as well, it should call our __new__ with the right arguments. (see http://bugs.python.org/issue12555#msg148829 ) */ if (type->tp_init != OSError_init && type->tp_new == OSError_new) { assert((PyObject *) type != PyExc_OSError); return 1; } return 0; } static PyObject * OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyOSErrorObject *self = NULL; PyObject *myerrno = NULL, *strerror = NULL; PyObject *filename = NULL, *filename2 = NULL; #ifdef MS_WINDOWS PyObject *winerror = NULL; #endif Py_INCREF(args); if (!oserror_use_init(type)) { if (!_PyArg_NoKeywords(type->tp_name, kwds)) goto error; if (oserror_parse_args(&args, &myerrno, &strerror, &filename, &filename2 #ifdef MS_WINDOWS , &winerror #endif )) goto error; struct _Py_exc_state *state = get_exc_state(); if (myerrno && PyLong_Check(myerrno) && state->errnomap && (PyObject *) type == PyExc_OSError) { PyObject *newtype; newtype = PyDict_GetItemWithError(state->errnomap, myerrno); if (newtype) { type = _PyType_CAST(newtype); } else if (PyErr_Occurred()) goto error; } } self = (PyOSErrorObject *) type->tp_alloc(type, 0); if (!self) goto error; self->dict = NULL; self->traceback = self->cause = self->context = NULL; self->written = -1; if (!oserror_use_init(type)) { if (oserror_init(self, &args, myerrno, strerror, filename, filename2 #ifdef MS_WINDOWS , winerror #endif )) goto error; } else { self->args = PyTuple_New(0); if (self->args == NULL) goto error; } Py_XDECREF(args); return (PyObject *) self; error: Py_XDECREF(args); Py_XDECREF(self); return NULL; } static int OSError_init(PyObject *op, PyObject *args, PyObject *kwds) { PyOSErrorObject *self = PyOSErrorObject_CAST(op); PyObject *myerrno = NULL, *strerror = NULL; PyObject *filename = NULL, *filename2 = NULL; #ifdef MS_WINDOWS PyObject *winerror = NULL; #endif if (!oserror_use_init(Py_TYPE(self))) /* Everything already done in OSError_new */ return 0; if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds)) return -1; Py_INCREF(args); if (oserror_parse_args(&args, &myerrno, &strerror, &filename, &filename2 #ifdef MS_WINDOWS , &winerror #endif )) goto error; if (oserror_init(self, &args, myerrno, strerror, filename, filename2 #ifdef MS_WINDOWS , winerror #endif )) goto error; return 0; error: Py_DECREF(args); return -1; } static int OSError_clear(PyObject *op) { PyOSErrorObject *self = PyOSErrorObject_CAST(op); Py_CLEAR(self->myerrno); Py_CLEAR(self->strerror); Py_CLEAR(self->filename); Py_CLEAR(self->filename2); #ifdef MS_WINDOWS Py_CLEAR(self->winerror); #endif return BaseException_clear(op); } static void OSError_dealloc(PyObject *self) { _PyObject_GC_UNTRACK(self); (void)OSError_clear(self); Py_TYPE(self)->tp_free(self); } static int OSError_traverse(PyObject *op, visitproc visit, void *arg) { PyOSErrorObject *self = PyOSErrorObject_CAST(op); Py_VISIT(self->myerrno); Py_VISIT(self->strerror); Py_VISIT(self->filename); Py_VISIT(self->filename2); #ifdef MS_WINDOWS Py_VISIT(self->winerror); #endif return BaseException_traverse(op, visit, arg); } static PyObject * OSError_str(PyObject *op) { PyOSErrorObject *self = PyOSErrorObject_CAST(op); #define OR_NONE(x) ((x)?(x):Py_None) #ifdef MS_WINDOWS /* If available, winerror has the priority over myerrno */ if (self->winerror && self->filename) { if (self->filename2) { return PyUnicode_FromFormat("[WinError %S] %S: %R -> %R", OR_NONE(self->winerror), OR_NONE(self->strerror), self->filename, self->filename2); } else { return PyUnicode_FromFormat("[WinError %S] %S: %R", OR_NONE(self->winerror), OR_NONE(self->strerror), self->filename); } } if (self->winerror && self->strerror) return PyUnicode_FromFormat("[WinError %S] %S", self->winerror ? self->winerror: Py_None, self->strerror ? self->strerror: Py_None); #endif if (self->filename) { if (self->filename2) { return PyUnicode_FromFormat("[Errno %S] %S: %R -> %R", OR_NONE(self->myerrno), OR_NONE(self->strerror), self->filename, self->filename2); } else { return PyUnicode_FromFormat("[Errno %S] %S: %R", OR_NONE(self->myerrno), OR_NONE(self->strerror), self->filename); } } if (self->myerrno && self->strerror) return PyUnicode_FromFormat("[Errno %S] %S", self->myerrno, self->strerror); return BaseException_str(op); } static PyObject * OSError_reduce(PyObject *op, PyObject *Py_UNUSED(ignored)) { PyOSErrorObject *self = PyOSErrorObject_CAST(op); PyObject *args = self->args; PyObject *res = NULL; /* self->args is only the first two real arguments if there was a * file name given to OSError. */ if (PyTuple_GET_SIZE(args) == 2 && self->filename) { Py_ssize_t size = self->filename2 ? 5 : 3; args = PyTuple_New(size); if (!args) return NULL; PyTuple_SET_ITEM(args, 0, Py_NewRef(PyTuple_GET_ITEM(self->args, 0))); PyTuple_SET_ITEM(args, 1, Py_NewRef(PyTuple_GET_ITEM(self->args, 1))); PyTuple_SET_ITEM(args, 2, Py_NewRef(self->filename)); if (self->filename2) { /* * This tuple is essentially used as OSError(*args). * So, to recreate filename2, we need to pass in * winerror as well. */ PyTuple_SET_ITEM(args, 3, Py_NewRef(Py_None)); /* filename2 */ PyTuple_SET_ITEM(args, 4, Py_NewRef(self->filename2)); } } else Py_INCREF(args); if (self->dict) res = PyTuple_Pack(3, Py_TYPE(self), args, self->dict); else res = PyTuple_Pack(2, Py_TYPE(self), args); Py_DECREF(args); return res; } static PyObject * OSError_written_get(PyObject *op, void *context) { PyOSErrorObject *self = PyOSErrorObject_CAST(op); if (self->written == -1) { PyErr_SetString(PyExc_AttributeError, "characters_written"); return NULL; } return PyLong_FromSsize_t(self->written); } static int OSError_written_set(PyObject *op, PyObject *arg, void *context) { PyOSErrorObject *self = PyOSErrorObject_CAST(op); if (arg == NULL) { if (self->written == -1) { PyErr_SetString(PyExc_AttributeError, "characters_written"); return -1; } self->written = -1; return 0; } Py_ssize_t n; n = PyNumber_AsSsize_t(arg, PyExc_ValueError); if (n == -1 && PyErr_Occurred()) return -1; self->written = n; return 0; } static PyMemberDef OSError_members[] = { {"errno", _Py_T_OBJECT, offsetof(PyOSErrorObject, myerrno), 0, PyDoc_STR("POSIX exception code")}, {"strerror", _Py_T_OBJECT, offsetof(PyOSErrorObject, strerror), 0, PyDoc_STR("exception strerror")}, {"filename", _Py_T_OBJECT, offsetof(PyOSErrorObject, filename), 0, PyDoc_STR("exception filename")}, {"filename2", _Py_T_OBJECT, offsetof(PyOSErrorObject, filename2), 0, PyDoc_STR("second exception filename")}, #ifdef MS_WINDOWS {"winerror", _Py_T_OBJECT, offsetof(PyOSErrorObject, winerror), 0, PyDoc_STR("Win32 exception code")}, #endif {NULL} /* Sentinel */ }; static PyMethodDef OSError_methods[] = { {"__reduce__", OSError_reduce, METH_NOARGS}, {NULL} }; static PyGetSetDef OSError_getset[] = { {"characters_written", OSError_written_get, OSError_written_set, NULL}, {NULL} }; ComplexExtendsException(PyExc_Exception, OSError, OSError, OSError_new, OSError_methods, OSError_members, OSError_getset, OSError_str, 0, "Base class for I/O related errors."); /* * Various OSError subclasses */ MiddlingExtendsException(PyExc_OSError, BlockingIOError, OSError, "I/O operation would block."); MiddlingExtendsException(PyExc_OSError, ConnectionError, OSError, "Connection error."); MiddlingExtendsException(PyExc_OSError, ChildProcessError, OSError, "Child process error."); MiddlingExtendsException(PyExc_ConnectionError, BrokenPipeError, OSError, "Broken pipe."); MiddlingExtendsException(PyExc_ConnectionError, ConnectionAbortedError, OSError, "Connection aborted."); MiddlingExtendsException(PyExc_ConnectionError, ConnectionRefusedError, OSError, "Connection refused."); MiddlingExtendsException(PyExc_ConnectionError, ConnectionResetError, OSError, "Connection reset."); MiddlingExtendsException(PyExc_OSError, FileExistsError, OSError, "File already exists."); MiddlingExtendsException(PyExc_OSError, FileNotFoundError, OSError, "File not found."); MiddlingExtendsException(PyExc_OSError, IsADirectoryError, OSError, "Operation doesn't work on directories."); MiddlingExtendsException(PyExc_OSError, NotADirectoryError, OSError, "Operation only works on directories."); MiddlingExtendsException(PyExc_OSError, InterruptedError, OSError, "Interrupted by signal."); MiddlingExtendsException(PyExc_OSError, PermissionError, OSError, "Not enough permissions."); MiddlingExtendsException(PyExc_OSError, ProcessLookupError, OSError, "Process not found."); MiddlingExtendsException(PyExc_OSError, TimeoutError, OSError, "Timeout expired."); /* Compatibility aliases */ PyObject *PyExc_EnvironmentError = (PyObject *)&_PyExc_OSError; // borrowed ref PyObject *PyExc_IOError = (PyObject *)&_PyExc_OSError; // borrowed ref #ifdef MS_WINDOWS PyObject *PyExc_WindowsError = (PyObject *)&_PyExc_OSError; // borrowed ref #endif /* * EOFError extends Exception */ SimpleExtendsException(PyExc_Exception, EOFError, "Read beyond end of file."); /* * RuntimeError extends Exception */ SimpleExtendsException(PyExc_Exception, RuntimeError, "Unspecified run-time error."); /* * RecursionError extends RuntimeError */ SimpleExtendsException(PyExc_RuntimeError, RecursionError, "Recursion limit exceeded."); // PythonFinalizationError extends RuntimeError SimpleExtendsException(PyExc_RuntimeError, PythonFinalizationError, "Operation blocked during Python finalization."); /* * NotImplementedError extends RuntimeError */ SimpleExtendsException(PyExc_RuntimeError, NotImplementedError, "Method or function hasn't been implemented yet."); /* * NameError extends Exception */ static inline PyNameErrorObject * PyNameErrorObject_CAST(PyObject *self) { assert(PyObject_TypeCheck(self, (PyTypeObject *)PyExc_NameError)); return (PyNameErrorObject *)self; } static int NameError_init(PyObject *op, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"name", NULL}; PyObject *name = NULL; if (BaseException_init(op, args, NULL) == -1) { return -1; } PyObject *empty_tuple = PyTuple_New(0); if (!empty_tuple) { return -1; } if (!PyArg_ParseTupleAndKeywords(empty_tuple, kwds, "|$O:NameError", kwlist, &name)) { Py_DECREF(empty_tuple); return -1; } Py_DECREF(empty_tuple); PyNameErrorObject *self = PyNameErrorObject_CAST(op); Py_XSETREF(self->name, Py_XNewRef(name)); return 0; } static int NameError_clear(PyObject *op) { PyNameErrorObject *self = PyNameErrorObject_CAST(op); Py_CLEAR(self->name); return BaseException_clear(op); } static void NameError_dealloc(PyObject *self) { _PyObject_GC_UNTRACK(self); (void)NameError_clear(self); Py_TYPE(self)->tp_free(self); } static int NameError_traverse(PyObject *op, visitproc visit, void *arg) { PyNameErrorObject *self = PyNameErrorObject_CAST(op); Py_VISIT(self->name); return BaseException_traverse(op, visit, arg); } static PyMemberDef NameError_members[] = { {"name", _Py_T_OBJECT, offsetof(PyNameErrorObject, name), 0, PyDoc_STR("name")}, {NULL} /* Sentinel */ }; static PyMethodDef NameError_methods[] = { {NULL} /* Sentinel */ }; ComplexExtendsException(PyExc_Exception, NameError, NameError, 0, NameError_methods, NameError_members, 0, BaseException_str, 0, "Name not found globally."); /* * UnboundLocalError extends NameError */ MiddlingExtendsException(PyExc_NameError, UnboundLocalError, NameError, "Local name referenced but not bound to a value."); /* * AttributeError extends Exception */ static inline PyAttributeErrorObject * PyAttributeErrorObject_CAST(PyObject *self) { assert(PyObject_TypeCheck(self, (PyTypeObject *)PyExc_AttributeError)); return (PyAttributeErrorObject *)self; } static int AttributeError_init(PyObject *op, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"name", "obj", NULL}; PyObject *name = NULL; PyObject *obj = NULL; if (BaseException_init(op, args, NULL) == -1) { return -1; } PyObject *empty_tuple = PyTuple_New(0); if (!empty_tuple) { return -1; } if (!PyArg_ParseTupleAndKeywords(empty_tuple, kwds, "|$OO:AttributeError", kwlist, &name, &obj)) { Py_DECREF(empty_tuple); return -1; } Py_DECREF(empty_tuple); PyAttributeErrorObject *self = PyAttributeErrorObject_CAST(op); Py_XSETREF(self->name, Py_XNewRef(name)); Py_XSETREF(self->obj, Py_XNewRef(obj)); return 0; } static int AttributeError_clear(PyObject *op) { PyAttributeErrorObject *self = PyAttributeErrorObject_CAST(op); Py_CLEAR(self->obj); Py_CLEAR(self->name); return BaseException_clear(op); } static void AttributeError_dealloc(PyObject *self) { _PyObject_GC_UNTRACK(self); (void)AttributeError_clear(self); Py_TYPE(self)->tp_free(self); } static int AttributeError_traverse(PyObject *op, visitproc visit, void *arg) { PyAttributeErrorObject *self = PyAttributeErrorObject_CAST(op); Py_VISIT(self->obj); Py_VISIT(self->name); return BaseException_traverse(op, visit, arg); } /* Pickling support */ static PyObject * AttributeError_getstate(PyObject *op, PyObject *Py_UNUSED(ignored)) { PyAttributeErrorObject *self = PyAttributeErrorObject_CAST(op); PyObject *dict = self->dict; if (self->name || self->args) { dict = dict ? PyDict_Copy(dict) : PyDict_New(); if (dict == NULL) { return NULL; } if (self->name && PyDict_SetItemString(dict, "name", self->name) < 0) { Py_DECREF(dict); return NULL; } /* We specifically are not pickling the obj attribute since there are many cases where it is unlikely to be picklable. See GH-103352. */ if (self->args && PyDict_SetItemString(dict, "args", self->args) < 0) { Py_DECREF(dict); return NULL; } return dict; } else if (dict) { return Py_NewRef(dict); } Py_RETURN_NONE; } static PyObject * AttributeError_reduce(PyObject *op, PyObject *Py_UNUSED(ignored)) { PyObject *state = AttributeError_getstate(op, NULL); if (state == NULL) { return NULL; } PyAttributeErrorObject *self = PyAttributeErrorObject_CAST(op); PyObject *return_value = PyTuple_Pack(3, Py_TYPE(self), self->args, state); Py_DECREF(state); return return_value; } static PyMemberDef AttributeError_members[] = { {"name", _Py_T_OBJECT, offsetof(PyAttributeErrorObject, name), 0, PyDoc_STR("attribute name")}, {"obj", _Py_T_OBJECT, offsetof(PyAttributeErrorObject, obj), 0, PyDoc_STR("object")}, {NULL} /* Sentinel */ }; static PyMethodDef AttributeError_methods[] = { {"__getstate__", AttributeError_getstate, METH_NOARGS}, {"__reduce__", AttributeError_reduce, METH_NOARGS }, {NULL} }; ComplexExtendsException(PyExc_Exception, AttributeError, AttributeError, 0, AttributeError_methods, AttributeError_members, 0, BaseException_str, 0, "Attribute not found."); /* * SyntaxError extends Exception */ static inline PySyntaxErrorObject * PySyntaxErrorObject_CAST(PyObject *self) { assert(PyObject_TypeCheck(self, (PyTypeObject *)PyExc_SyntaxError)); return (PySyntaxErrorObject *)self; } static int SyntaxError_init(PyObject *op, PyObject *args, PyObject *kwds) { PyObject *info = NULL; Py_ssize_t lenargs = PyTuple_GET_SIZE(args); if (BaseException_init(op, args, kwds) == -1) return -1; PySyntaxErrorObject *self = PySyntaxErrorObject_CAST(op); if (lenargs >= 1) { Py_XSETREF(self->msg, Py_NewRef(PyTuple_GET_ITEM(args, 0))); } if (lenargs == 2) { info = PyTuple_GET_ITEM(args, 1); info = PySequence_Tuple(info); if (!info) { return -1; } self->end_lineno = NULL; self->end_offset = NULL; if (!PyArg_ParseTuple(info, "OOOO|OOO", &self->filename, &self->lineno, &self->offset, &self->text, &self->end_lineno, &self->end_offset, &self->metadata)) { Py_DECREF(info); return -1; } Py_INCREF(self->filename); Py_INCREF(self->lineno); Py_INCREF(self->offset); Py_INCREF(self->text); Py_XINCREF(self->end_lineno); Py_XINCREF(self->end_offset); Py_XINCREF(self->metadata); Py_DECREF(info); if (self->end_lineno != NULL && self->end_offset == NULL) { PyErr_SetString(PyExc_TypeError, "end_offset must be provided when end_lineno is provided"); return -1; } } return 0; } static int SyntaxError_clear(PyObject *op) { PySyntaxErrorObject *self = PySyntaxErrorObject_CAST(op); Py_CLEAR(self->msg); Py_CLEAR(self->filename); Py_CLEAR(self->lineno); Py_CLEAR(self->offset); Py_CLEAR(self->end_lineno); Py_CLEAR(self->end_offset); Py_CLEAR(self->text); Py_CLEAR(self->print_file_and_line); Py_CLEAR(self->metadata); return BaseException_clear(op); } static void SyntaxError_dealloc(PyObject *self) { _PyObject_GC_UNTRACK(self); (void)SyntaxError_clear(self); Py_TYPE(self)->tp_free(self); } static int SyntaxError_traverse(PyObject *op, visitproc visit, void *arg) { PySyntaxErrorObject *self = PySyntaxErrorObject_CAST(op); Py_VISIT(self->msg); Py_VISIT(self->filename); Py_VISIT(self->lineno); Py_VISIT(self->offset); Py_VISIT(self->end_lineno); Py_VISIT(self->end_offset); Py_VISIT(self->text); Py_VISIT(self->print_file_and_line); Py_VISIT(self->metadata); return BaseException_traverse(op, visit, arg); } /* This is called "my_basename" instead of just "basename" to avoid name conflicts with glibc; basename is already prototyped if _GNU_SOURCE is defined, and Python does define that. */ static PyObject* my_basename(PyObject *name) { Py_ssize_t i, size, offset; int kind; const void *data; kind = PyUnicode_KIND(name); data = PyUnicode_DATA(name); size = PyUnicode_GET_LENGTH(name); offset = 0; for(i=0; i < size; i++) { if (PyUnicode_READ(kind, data, i) == SEP) { offset = i + 1; } } if (offset != 0) { return PyUnicode_Substring(name, offset, size); } else { return Py_NewRef(name); } } static PyObject * SyntaxError_str(PyObject *op) { PySyntaxErrorObject *self = PySyntaxErrorObject_CAST(op); int have_lineno = 0; PyObject *filename; PyObject *result; /* Below, we always ignore overflow errors, just printing -1. Still, we cannot allow an OverflowError to be raised, so we need to call PyLong_AsLongAndOverflow. */ int overflow; /* XXX -- do all the additional formatting with filename and lineno here */ if (self->filename && PyUnicode_Check(self->filename)) { filename = my_basename(self->filename); if (filename == NULL) return NULL; } else { filename = NULL; } have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno); if (!filename && !have_lineno) return PyObject_Str(self->msg ? self->msg : Py_None); // Even if 'filename' can be an instance of a subclass of 'str', // we only render its "true" content and do not use str(filename). if (filename && have_lineno) result = PyUnicode_FromFormat("%S (%U, line %ld)", self->msg ? self->msg : Py_None, filename, PyLong_AsLongAndOverflow(self->lineno, &overflow)); else if (filename) result = PyUnicode_FromFormat("%S (%U)", self->msg ? self->msg : Py_None, filename); else /* only have_lineno */ result = PyUnicode_FromFormat("%S (line %ld)", self->msg ? self->msg : Py_None, PyLong_AsLongAndOverflow(self->lineno, &overflow)); Py_XDECREF(filename); return result; } static PyMemberDef SyntaxError_members[] = { {"msg", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0, PyDoc_STR("exception msg")}, {"filename", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0, PyDoc_STR("exception filename")}, {"lineno", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0, PyDoc_STR("exception lineno")}, {"offset", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0, PyDoc_STR("exception offset")}, {"text", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, text), 0, PyDoc_STR("exception text")}, {"end_lineno", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, end_lineno), 0, PyDoc_STR("exception end lineno")}, {"end_offset", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, end_offset), 0, PyDoc_STR("exception end offset")}, {"print_file_and_line", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, print_file_and_line), 0, PyDoc_STR("exception print_file_and_line")}, {"_metadata", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, metadata), 0, PyDoc_STR("exception private metadata")}, {NULL} /* Sentinel */ }; ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError, 0, 0, SyntaxError_members, 0, SyntaxError_str, 0, "Invalid syntax."); /* * IndentationError extends SyntaxError */ MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError, "Improper indentation."); /* * TabError extends IndentationError */ MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError, "Improper mixture of spaces and tabs."); /* * IncompleteInputError extends SyntaxError */ MiddlingExtendsExceptionEx(PyExc_SyntaxError, IncompleteInputError, _IncompleteInputError, SyntaxError, "incomplete input."); /* * LookupError extends Exception */ SimpleExtendsException(PyExc_Exception, LookupError, "Base class for lookup errors."); /* * IndexError extends LookupError */ SimpleExtendsException(PyExc_LookupError, IndexError, "Sequence index out of range."); /* * KeyError extends LookupError */ static PyObject * KeyError_str(PyObject *op) { /* If args is a tuple of exactly one item, apply repr to args[0]. This is done so that e.g. the exception raised by {}[''] prints KeyError: '' rather than the confusing KeyError alone. The downside is that if KeyError is raised with an explanatory string, that string will be displayed in quotes. Too bad. If args is anything else, use the default BaseException__str__(). */ PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op); if (PyTuple_GET_SIZE(self->args) == 1) { return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0)); } return BaseException_str(op); } ComplexExtendsException(PyExc_LookupError, KeyError, BaseException, 0, 0, 0, 0, KeyError_str, 0, "Mapping key not found."); /* * ValueError extends Exception */ SimpleExtendsException(PyExc_Exception, ValueError, "Inappropriate argument value (of correct type)."); /* * UnicodeError extends ValueError */ SimpleExtendsException(PyExc_ValueError, UnicodeError, "Unicode related error."); /* * Check the validity of 'attr' as a unicode or bytes object depending * on 'as_bytes'. * * The 'name' is the attribute name and is only used for error reporting. * * On success, this returns 0. * On failure, this sets a TypeError and returns -1. */ static int check_unicode_error_attribute(PyObject *attr, const char *name, int as_bytes) { assert(as_bytes == 0 || as_bytes == 1); if (attr == NULL) { PyErr_Format(PyExc_TypeError, "UnicodeError '%s' attribute is not set", name); return -1; } if (!(as_bytes ? PyBytes_Check(attr) : PyUnicode_Check(attr))) { PyErr_Format(PyExc_TypeError, "UnicodeError '%s' attribute must be a %s", name, as_bytes ? "bytes" : "string"); return -1; } return 0; } /* * Check the validity of 'attr' as a unicode or bytes object depending * on 'as_bytes' and return a new reference on it if it is the case. * * The 'name' is the attribute name and is only used for error reporting. * * On success, this returns a strong reference on 'attr'. * On failure, this sets a TypeError and returns NULL. */ static PyObject * as_unicode_error_attribute(PyObject *attr, const char *name, int as_bytes) { int rc = check_unicode_error_attribute(attr, name, as_bytes); return rc < 0 ? NULL : Py_NewRef(attr); } #define PyUnicodeError_Check(PTR) \ PyObject_TypeCheck((PTR), (PyTypeObject *)PyExc_UnicodeError) #define PyUnicodeError_CAST(PTR) \ (assert(PyUnicodeError_Check(PTR)), ((PyUnicodeErrorObject *)(PTR))) /* class names to use when reporting errors */ #define Py_UNICODE_ENCODE_ERROR_NAME "UnicodeEncodeError" #define Py_UNICODE_DECODE_ERROR_NAME "UnicodeDecodeError" #define Py_UNICODE_TRANSLATE_ERROR_NAME "UnicodeTranslateError" /* * Check that 'self' is a UnicodeError object. * * On success, this returns 0. * On failure, this sets a TypeError exception and returns -1. * * The 'expect_type' is the name of the expected type, which is * only used for error reporting. * * As an implementation detail, the `PyUnicode*Error_*` functions * currently allow *any* subclass of UnicodeError as 'self'. * * Use one of the `Py_UNICODE_*_ERROR_NAME` macros to avoid typos. */ static inline int check_unicode_error_type(PyObject *self, const char *expect_type) { assert(self != NULL); if (!PyUnicodeError_Check(self)) { PyErr_Format(PyExc_TypeError, "expecting a %s object, got %T", expect_type, self); return -1; } return 0; } // --- PyUnicodeEncodeObject: internal helpers -------------------------------- // // In the helpers below, the caller is responsible to ensure that 'self' // is a PyUnicodeErrorObject, although this is verified on DEBUG builds // through PyUnicodeError_CAST(). /* * Return the underlying (str) 'encoding' attribute of a UnicodeError object. */ static inline PyObject * unicode_error_get_encoding_impl(PyObject *self) { assert(self != NULL); PyUnicodeErrorObject *exc = PyUnicodeError_CAST(self); return as_unicode_error_attribute(exc->encoding, "encoding", false); } /* * Return the underlying 'object' attribute of a UnicodeError object * as a bytes or a string instance, depending on the 'as_bytes' flag. */ static inline PyObject * unicode_error_get_object_impl(PyObject *self, int as_bytes) { assert(self != NULL); PyUnicodeErrorObject *exc = PyUnicodeError_CAST(self); return as_unicode_error_attribute(exc->object, "object", as_bytes); } /* * Return the underlying (str) 'reason' attribute of a UnicodeError object. */ static inline PyObject * unicode_error_get_reason_impl(PyObject *self) { assert(self != NULL); PyUnicodeErrorObject *exc = PyUnicodeError_CAST(self); return as_unicode_error_attribute(exc->reason, "reason", false); } /* * Set the underlying (str) 'reason' attribute of a UnicodeError object. * * Return 0 on success and -1 on failure. */ static inline int unicode_error_set_reason_impl(PyObject *self, const char *reason) { assert(self != NULL); PyObject *value = PyUnicode_FromString(reason); if (value == NULL) { return -1; } PyUnicodeErrorObject *exc = PyUnicodeError_CAST(self); Py_XSETREF(exc->reason, value); return 0; } /* * Set the 'start' attribute of a UnicodeError object. * * Return 0 on success and -1 on failure. */ static inline int unicode_error_set_start_impl(PyObject *self, Py_ssize_t start) { assert(self != NULL); PyUnicodeErrorObject *exc = PyUnicodeError_CAST(self); exc->start = start; return 0; } /* * Set the 'end' attribute of a UnicodeError object. * * Return 0 on success and -1 on failure. */ static inline int unicode_error_set_end_impl(PyObject *self, Py_ssize_t end) { assert(self != NULL); PyUnicodeErrorObject *exc = PyUnicodeError_CAST(self); exc->end = end; return 0; } // --- PyUnicodeEncodeObject: internal getters -------------------------------- /* * Adjust the (inclusive) 'start' value of a UnicodeError object. * * The 'start' can be negative or not, but when adjusting the value, * we clip it in [0, max(0, objlen - 1)] and do not interpret it as * a relative offset. * * This function always succeeds. */ static Py_ssize_t unicode_error_adjust_start(Py_ssize_t start, Py_ssize_t objlen) { assert(objlen >= 0); if (start < 0) { start = 0; } if (start >= objlen) { start = objlen == 0 ? 0 : objlen - 1; } return start; } /* Assert some properties of the adjusted 'start' value. */ #ifndef NDEBUG static void assert_adjusted_unicode_error_start(Py_ssize_t start, Py_ssize_t objlen) { assert(objlen >= 0); /* in the future, `min_start` may be something else */ Py_ssize_t min_start = 0; assert(start >= min_start); /* in the future, `max_start` may be something else */ Py_ssize_t max_start = Py_MAX(min_start, objlen - 1); assert(start <= max_start); } #else #define assert_adjusted_unicode_error_start(...) #endif /* * Adjust the (exclusive) 'end' value of a UnicodeError object. * * The 'end' can be negative or not, but when adjusting the value, * we clip it in [min(1, objlen), max(min(1, objlen), objlen)] and * do not interpret it as a relative offset. * * This function always succeeds. */ static Py_ssize_t unicode_error_adjust_end(Py_ssize_t end, Py_ssize_t objlen) { assert(objlen >= 0); if (end < 1) { end = 1; } if (end > objlen) { end = objlen; } return end; } #define PyUnicodeError_Check(PTR) \ PyObject_TypeCheck((PTR), (PyTypeObject *)PyExc_UnicodeError) #define PyUnicodeErrorObject_CAST(op) \ (assert(PyUnicodeError_Check(op)), ((PyUnicodeErrorObject *)(op))) /* Assert some properties of the adjusted 'end' value. */ #ifndef NDEBUG static void assert_adjusted_unicode_error_end(Py_ssize_t end, Py_ssize_t objlen) { assert(objlen >= 0); /* in the future, `min_end` may be something else */ Py_ssize_t min_end = Py_MIN(1, objlen); assert(end >= min_end); /* in the future, `max_end` may be something else */ Py_ssize_t max_end = Py_MAX(min_end, objlen); assert(end <= max_end); } #else #define assert_adjusted_unicode_error_end(...) #endif /* * Adjust the length of the range described by a UnicodeError object. * * The 'start' and 'end' arguments must have been obtained by * unicode_error_adjust_start() and unicode_error_adjust_end(). * * The result is clipped in [0, objlen]. By construction, it * will always be smaller than 'objlen' as 'start' and 'end' * are smaller than 'objlen'. */ static Py_ssize_t unicode_error_adjust_len(Py_ssize_t start, Py_ssize_t end, Py_ssize_t objlen) { assert_adjusted_unicode_error_start(start, objlen); assert_adjusted_unicode_error_end(end, objlen); Py_ssize_t ranlen = end - start; assert(ranlen <= objlen); return ranlen < 0 ? 0 : ranlen; } /* Assert some properties of the adjusted range 'len' value. */ #ifndef NDEBUG static void assert_adjusted_unicode_error_len(Py_ssize_t ranlen, Py_ssize_t objlen) { assert(objlen >= 0); assert(ranlen >= 0); assert(ranlen <= objlen); } #else #define assert_adjusted_unicode_error_len(...) #endif /* * Get various common parameters of a UnicodeError object. * * The caller is responsible to ensure that 'self' is a PyUnicodeErrorObject, * although this condition is verified by this function on DEBUG builds. * * Return 0 on success and -1 on failure. * * Output parameters: * * obj A strong reference to the 'object' attribute. * objlen The 'object' length. * start The clipped 'start' attribute. * end The clipped 'end' attribute. * slen The length of the slice described by the clipped 'start' * and 'end' values. It always lies in [0, objlen]. * * An output parameter can be NULL to indicate that * the corresponding value does not need to be stored. * * Input parameter: * * as_bytes If true, the error's 'object' attribute must be a `bytes`, * i.e. 'self' is a `UnicodeDecodeError` instance. Otherwise, * the 'object' attribute must be a string. * * A TypeError is raised if the 'object' type is incompatible. */ int _PyUnicodeError_GetParams(PyObject *self, PyObject **obj, Py_ssize_t *objlen, Py_ssize_t *start, Py_ssize_t *end, Py_ssize_t *slen, int as_bytes) { assert(self != NULL); assert(as_bytes == 0 || as_bytes == 1); PyUnicodeErrorObject *exc = PyUnicodeError_CAST(self); PyObject *r = as_unicode_error_attribute(exc->object, "object", as_bytes); if (r == NULL) { return -1; } Py_ssize_t n = as_bytes ? PyBytes_GET_SIZE(r) : PyUnicode_GET_LENGTH(r); if (objlen != NULL) { *objlen = n; } Py_ssize_t start_value = -1; if (start != NULL || slen != NULL) { start_value = unicode_error_adjust_start(exc->start, n); } if (start != NULL) { assert_adjusted_unicode_error_start(start_value, n); *start = start_value; } Py_ssize_t end_value = -1; if (end != NULL || slen != NULL) { end_value = unicode_error_adjust_end(exc->end, n); } if (end != NULL) { assert_adjusted_unicode_error_end(end_value, n); *end = end_value; } if (slen != NULL) { *slen = unicode_error_adjust_len(start_value, end_value, n); assert_adjusted_unicode_error_len(*slen, n); } if (obj != NULL) { *obj = r; } else { Py_DECREF(r); } return 0; } // --- PyUnicodeEncodeObject: 'encoding' getters ------------------------------ // Note: PyUnicodeTranslateError does not have an 'encoding' attribute. PyObject * PyUnicodeEncodeError_GetEncoding(PyObject *self) { int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME); return rc < 0 ? NULL : unicode_error_get_encoding_impl(self); } PyObject * PyUnicodeDecodeError_GetEncoding(PyObject *self) { int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME); return rc < 0 ? NULL : unicode_error_get_encoding_impl(self); } // --- PyUnicodeEncodeObject: 'object' getters -------------------------------- PyObject * PyUnicodeEncodeError_GetObject(PyObject *self) { int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME); return rc < 0 ? NULL : unicode_error_get_object_impl(self, false); } PyObject * PyUnicodeDecodeError_GetObject(PyObject *self) { int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME); return rc < 0 ? NULL : unicode_error_get_object_impl(self, true); } PyObject * PyUnicodeTranslateError_GetObject(PyObject *self) { int rc = check_unicode_error_type(self, Py_UNICODE_TRANSLATE_ERROR_NAME); return rc < 0 ? NULL : unicode_error_get_object_impl(self, false); } // --- PyUnicodeEncodeObject: 'start' getters --------------------------------- /* * Specialization of _PyUnicodeError_GetParams() for the 'start' attribute. * * The caller is responsible to ensure that 'self' is a PyUnicodeErrorObject, * although this condition is verified by this function on DEBUG builds. */ static inline int unicode_error_get_start_impl(PyObject *self, Py_ssize_t *start, int as_bytes) { assert(self != NULL); return _PyUnicodeError_GetParams(self, NULL, NULL, start, NULL, NULL, as_bytes); } int PyUnicodeEncodeError_GetStart(PyObject *self, Py_ssize_t *start) { int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME); return rc < 0 ? -1 : unicode_error_get_start_impl(self, start, false); } int PyUnicodeDecodeError_GetStart(PyObject *self, Py_ssize_t *start) { int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME); return rc < 0 ? -1 : unicode_error_get_start_impl(self, start, true); } int PyUnicodeTranslateError_GetStart(PyObject *self, Py_ssize_t *start) { int rc = check_unicode_error_type(self, Py_UNICODE_TRANSLATE_ERROR_NAME); return rc < 0 ? -1 : unicode_error_get_start_impl(self, start, false); } // --- PyUnicodeEncodeObject: 'start' setters --------------------------------- int PyUnicodeEncodeError_SetStart(PyObject *self, Py_ssize_t start) { int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME); return rc < 0 ? -1 : unicode_error_set_start_impl(self, start); } int PyUnicodeDecodeError_SetStart(PyObject *self, Py_ssize_t start) { int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME); return rc < 0 ? -1 : unicode_error_set_start_impl(self, start); } int PyUnicodeTranslateError_SetStart(PyObject *self, Py_ssize_t start) { int rc = check_unicode_error_type(self, Py_UNICODE_TRANSLATE_ERROR_NAME); return rc < 0 ? -1 : unicode_error_set_start_impl(self, start); } // --- PyUnicodeEncodeObject: 'end' getters ----------------------------------- /* * Specialization of _PyUnicodeError_GetParams() for the 'end' attribute. * * The caller is responsible to ensure that 'self' is a PyUnicodeErrorObject, * although this condition is verified by this function on DEBUG builds. */ static inline int unicode_error_get_end_impl(PyObject *self, Py_ssize_t *end, int as_bytes) { assert(self != NULL); return _PyUnicodeError_GetParams(self, NULL, NULL, NULL, end, NULL, as_bytes); } int PyUnicodeEncodeError_GetEnd(PyObject *self, Py_ssize_t *end) { int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME); return rc < 0 ? -1 : unicode_error_get_end_impl(self, end, false); } int PyUnicodeDecodeError_GetEnd(PyObject *self, Py_ssize_t *end) { int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME); return rc < 0 ? -1 : unicode_error_get_end_impl(self, end, true); } int PyUnicodeTranslateError_GetEnd(PyObject *self, Py_ssize_t *end) { int rc = check_unicode_error_type(self, Py_UNICODE_TRANSLATE_ERROR_NAME); return rc < 0 ? -1 : unicode_error_get_end_impl(self, end, false); } // --- PyUnicodeEncodeObject: 'end' setters ----------------------------------- int PyUnicodeEncodeError_SetEnd(PyObject *self, Py_ssize_t end) { int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME); return rc < 0 ? -1 : unicode_error_set_end_impl(self, end); } int PyUnicodeDecodeError_SetEnd(PyObject *self, Py_ssize_t end) { int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME); return rc < 0 ? -1 : unicode_error_set_end_impl(self, end); } int PyUnicodeTranslateError_SetEnd(PyObject *self, Py_ssize_t end) { int rc = check_unicode_error_type(self, Py_UNICODE_TRANSLATE_ERROR_NAME); return rc < 0 ? -1 : unicode_error_set_end_impl(self, end); } // --- PyUnicodeEncodeObject: 'reason' getters -------------------------------- PyObject * PyUnicodeEncodeError_GetReason(PyObject *self) { int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME); return rc < 0 ? NULL : unicode_error_get_reason_impl(self); } PyObject * PyUnicodeDecodeError_GetReason(PyObject *self) { int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME); return rc < 0 ? NULL : unicode_error_get_reason_impl(self); } PyObject * PyUnicodeTranslateError_GetReason(PyObject *self) { int rc = check_unicode_error_type(self, Py_UNICODE_TRANSLATE_ERROR_NAME); return rc < 0 ? NULL : unicode_error_get_reason_impl(self); } // --- PyUnicodeEncodeObject: 'reason' setters -------------------------------- int PyUnicodeEncodeError_SetReason(PyObject *self, const char *reason) { int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME); return rc < 0 ? -1 : unicode_error_set_reason_impl(self, reason); } int PyUnicodeDecodeError_SetReason(PyObject *self, const char *reason) { int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME); return rc < 0 ? -1 : unicode_error_set_reason_impl(self, reason); } int PyUnicodeTranslateError_SetReason(PyObject *self, const char *reason) { int rc = check_unicode_error_type(self, Py_UNICODE_TRANSLATE_ERROR_NAME); return rc < 0 ? -1 : unicode_error_set_reason_impl(self, reason); } static int UnicodeError_clear(PyObject *self) { PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self); Py_CLEAR(exc->encoding); Py_CLEAR(exc->object); Py_CLEAR(exc->reason); return BaseException_clear(self); } static void UnicodeError_dealloc(PyObject *self) { PyTypeObject *type = Py_TYPE(self); _PyObject_GC_UNTRACK(self); (void)UnicodeError_clear(self); type->tp_free(self); } static int UnicodeError_traverse(PyObject *self, visitproc visit, void *arg) { PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self); Py_VISIT(exc->encoding); Py_VISIT(exc->object); Py_VISIT(exc->reason); return BaseException_traverse(self, visit, arg); } static PyMemberDef UnicodeError_members[] = { {"encoding", _Py_T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0, PyDoc_STR("exception encoding")}, {"object", _Py_T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0, PyDoc_STR("exception object")}, {"start", Py_T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0, PyDoc_STR("exception start")}, {"end", Py_T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0, PyDoc_STR("exception end")}, {"reason", _Py_T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0, PyDoc_STR("exception reason")}, {NULL} /* Sentinel */ }; /* * UnicodeEncodeError extends UnicodeError */ static int UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds) { if (BaseException_init(self, args, kwds) == -1) { return -1; } PyObject *encoding = NULL, *object = NULL, *reason = NULL; // borrowed Py_ssize_t start = -1, end = -1; if (!PyArg_ParseTuple(args, "UUnnU", &encoding, &object, &start, &end, &reason)) { return -1; } PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self); Py_XSETREF(exc->encoding, Py_NewRef(encoding)); Py_XSETREF(exc->object, Py_NewRef(object)); exc->start = start; exc->end = end; Py_XSETREF(exc->reason, Py_NewRef(reason)); return 0; } static PyObject * UnicodeEncodeError_str(PyObject *self) { PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self); PyObject *result = NULL; PyObject *reason_str = NULL; PyObject *encoding_str = NULL; if (exc->object == NULL) { /* Not properly initialized. */ return Py_GetConstant(Py_CONSTANT_EMPTY_STR); } /* Get reason and encoding as strings, which they might not be if they've been modified after we were constructed. */ reason_str = PyObject_Str(exc->reason); if (reason_str == NULL) { goto done; } encoding_str = PyObject_Str(exc->encoding); if (encoding_str == NULL) { goto done; } // calls to PyObject_Str(...) above might mutate 'exc->object' if (check_unicode_error_attribute(exc->object, "object", false) < 0) { goto done; } Py_ssize_t len = PyUnicode_GET_LENGTH(exc->object); Py_ssize_t start = exc->start, end = exc->end; if ((start >= 0 && start < len) && (end >= 0 && end <= len) && end == start + 1) { Py_UCS4 badchar = PyUnicode_ReadChar(exc->object, start); const char *fmt; if (badchar <= 0xff) { fmt = "'%U' codec can't encode character '\\x%02x' in position %zd: %U"; } else if (badchar <= 0xffff) { fmt = "'%U' codec can't encode character '\\u%04x' in position %zd: %U"; } else { fmt = "'%U' codec can't encode character '\\U%08x' in position %zd: %U"; } result = PyUnicode_FromFormat( fmt, encoding_str, (int)badchar, start, reason_str); } else { result = PyUnicode_FromFormat( "'%U' codec can't encode characters in position %zd-%zd: %U", encoding_str, start, end - 1, reason_str); } done: Py_XDECREF(reason_str); Py_XDECREF(encoding_str); return result; } static PyTypeObject _PyExc_UnicodeEncodeError = { PyVarObject_HEAD_INIT(NULL, 0) "UnicodeEncodeError", sizeof(PyUnicodeErrorObject), 0, UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, UnicodeEncodeError_str, 0, 0, 0, Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, PyDoc_STR("Unicode encoding error."), UnicodeError_traverse, UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members, 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict), UnicodeEncodeError_init, 0, BaseException_new, }; PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError; /* * UnicodeDecodeError extends UnicodeError */ static int UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds) { if (BaseException_init(self, args, kwds) == -1) { return -1; } PyObject *encoding = NULL, *object = NULL, *reason = NULL; // borrowed Py_ssize_t start = -1, end = -1; if (!PyArg_ParseTuple(args, "UOnnU", &encoding, &object, &start, &end, &reason)) { return -1; } if (PyBytes_Check(object)) { Py_INCREF(object); // make 'object' a strong reference } else { Py_buffer view; if (PyObject_GetBuffer(object, &view, PyBUF_SIMPLE) != 0) { return -1; } // 'object' is borrowed, so we can re-use the variable object = PyBytes_FromStringAndSize(view.buf, view.len); PyBuffer_Release(&view); if (object == NULL) { return -1; } } PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self); Py_XSETREF(exc->encoding, Py_NewRef(encoding)); Py_XSETREF(exc->object, object /* already a strong reference */); exc->start = start; exc->end = end; Py_XSETREF(exc->reason, Py_NewRef(reason)); return 0; } static PyObject * UnicodeDecodeError_str(PyObject *self) { PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self); PyObject *result = NULL; PyObject *reason_str = NULL; PyObject *encoding_str = NULL; if (exc->object == NULL) { /* Not properly initialized. */ return Py_GetConstant(Py_CONSTANT_EMPTY_STR); } /* Get reason and encoding as strings, which they might not be if they've been modified after we were constructed. */ reason_str = PyObject_Str(exc->reason); if (reason_str == NULL) { goto done; } encoding_str = PyObject_Str(exc->encoding); if (encoding_str == NULL) { goto done; } // calls to PyObject_Str(...) above might mutate 'exc->object' if (check_unicode_error_attribute(exc->object, "object", true) < 0) { goto done; } Py_ssize_t len = PyBytes_GET_SIZE(exc->object); Py_ssize_t start = exc->start, end = exc->end; if ((start >= 0 && start < len) && (end >= 0 && end <= len) && end == start + 1) { int badbyte = (int)(PyBytes_AS_STRING(exc->object)[start] & 0xff); result = PyUnicode_FromFormat( "'%U' codec can't decode byte 0x%02x in position %zd: %U", encoding_str, badbyte, start, reason_str); } else { result = PyUnicode_FromFormat( "'%U' codec can't decode bytes in position %zd-%zd: %U", encoding_str, start, end - 1, reason_str); } done: Py_XDECREF(reason_str); Py_XDECREF(encoding_str); return result; } static PyTypeObject _PyExc_UnicodeDecodeError = { PyVarObject_HEAD_INIT(NULL, 0) "UnicodeDecodeError", sizeof(PyUnicodeErrorObject), 0, UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, UnicodeDecodeError_str, 0, 0, 0, Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, PyDoc_STR("Unicode decoding error."), UnicodeError_traverse, UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members, 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict), UnicodeDecodeError_init, 0, BaseException_new, }; PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError; PyObject * PyUnicodeDecodeError_Create( const char *encoding, const char *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason) { return PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns", encoding, object, length, start, end, reason); } /* * UnicodeTranslateError extends UnicodeError */ static int UnicodeTranslateError_init(PyObject *self, PyObject *args, PyObject *kwds) { if (BaseException_init(self, args, kwds) == -1) { return -1; } PyObject *object = NULL, *reason = NULL; // borrowed Py_ssize_t start = -1, end = -1; if (!PyArg_ParseTuple(args, "UnnU", &object, &start, &end, &reason)) { return -1; } PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self); Py_XSETREF(exc->object, Py_NewRef(object)); exc->start = start; exc->end = end; Py_XSETREF(exc->reason, Py_NewRef(reason)); return 0; } static PyObject * UnicodeTranslateError_str(PyObject *self) { PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self); PyObject *result = NULL; PyObject *reason_str = NULL; if (exc->object == NULL) { /* Not properly initialized. */ return Py_GetConstant(Py_CONSTANT_EMPTY_STR); } /* Get reason as a string, which it might not be if it's been modified after we were constructed. */ reason_str = PyObject_Str(exc->reason); if (reason_str == NULL) { goto done; } // call to PyObject_Str(...) above might mutate 'exc->object' if (check_unicode_error_attribute(exc->object, "object", false) < 0) { goto done; } Py_ssize_t len = PyUnicode_GET_LENGTH(exc->object); Py_ssize_t start = exc->start, end = exc->end; if ((start >= 0 && start < len) && (end >= 0 && end <= len) && end == start + 1) { Py_UCS4 badchar = PyUnicode_ReadChar(exc->object, start); const char *fmt; if (badchar <= 0xff) { fmt = "can't translate character '\\x%02x' in position %zd: %U"; } else if (badchar <= 0xffff) { fmt = "can't translate character '\\u%04x' in position %zd: %U"; } else { fmt = "can't translate character '\\U%08x' in position %zd: %U"; } result = PyUnicode_FromFormat( fmt, (int)badchar, start, reason_str); } else { result = PyUnicode_FromFormat( "can't translate characters in position %zd-%zd: %U", start, end - 1, reason_str); } done: Py_XDECREF(reason_str); return result; } static PyTypeObject _PyExc_UnicodeTranslateError = { PyVarObject_HEAD_INIT(NULL, 0) "UnicodeTranslateError", sizeof(PyUnicodeErrorObject), 0, UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, UnicodeTranslateError_str, 0, 0, 0, Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, PyDoc_STR("Unicode translation error."), UnicodeError_traverse, UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members, 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict), UnicodeTranslateError_init, 0, BaseException_new, }; PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError; PyObject * _PyUnicodeTranslateError_Create( PyObject *object, Py_ssize_t start, Py_ssize_t end, const char *reason) { return PyObject_CallFunction(PyExc_UnicodeTranslateError, "Onns", object, start, end, reason); } /* * AssertionError extends Exception */ SimpleExtendsException(PyExc_Exception, AssertionError, "Assertion failed."); /* * ArithmeticError extends Exception */ SimpleExtendsException(PyExc_Exception, ArithmeticError, "Base class for arithmetic errors."); /* * FloatingPointError extends ArithmeticError */ SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError, "Floating-point operation failed."); /* * OverflowError extends ArithmeticError */ SimpleExtendsException(PyExc_ArithmeticError, OverflowError, "Result too large to be represented."); /* * ZeroDivisionError extends ArithmeticError */ SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError, "Second argument to a division or modulo operation was zero."); /* * SystemError extends Exception */ SimpleExtendsException(PyExc_Exception, SystemError, "Internal error in the Python interpreter.\n" "\n" "Please report this to the Python maintainer, along with the traceback,\n" "the Python version, and the hardware/OS platform and version."); /* * ReferenceError extends Exception */ SimpleExtendsException(PyExc_Exception, ReferenceError, "Weak ref proxy used after referent went away."); /* * MemoryError extends Exception */ #define MEMERRORS_SAVE 16 #ifdef Py_GIL_DISABLED # define MEMERRORS_LOCK(state) PyMutex_LockFlags(&state->memerrors_lock, _Py_LOCK_DONT_DETACH) # define MEMERRORS_UNLOCK(state) PyMutex_Unlock(&state->memerrors_lock) #else # define MEMERRORS_LOCK(state) ((void)0) # define MEMERRORS_UNLOCK(state) ((void)0) #endif static PyObject * get_memory_error(int allow_allocation, PyObject *args, PyObject *kwds) { PyBaseExceptionObject *self = NULL; struct _Py_exc_state *state = get_exc_state(); MEMERRORS_LOCK(state); if (state->memerrors_freelist != NULL) { /* Fetch MemoryError from freelist and initialize it */ self = state->memerrors_freelist; state->memerrors_freelist = (PyBaseExceptionObject *) self->dict; state->memerrors_numfree--; self->dict = NULL; self->args = (PyObject *)&_Py_SINGLETON(tuple_empty); _Py_NewReference((PyObject *)self); _PyObject_GC_TRACK(self); } MEMERRORS_UNLOCK(state); if (self != NULL) { return (PyObject *)self; } if (!allow_allocation) { PyInterpreterState *interp = _PyInterpreterState_GET(); return Py_NewRef( &_Py_INTERP_SINGLETON(interp, last_resort_memory_error)); } return BaseException_new((PyTypeObject *)PyExc_MemoryError, args, kwds); } static PyObject * MemoryError_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { /* If this is a subclass of MemoryError, don't use the freelist * and just return a fresh object */ if (type != (PyTypeObject *) PyExc_MemoryError) { return BaseException_new(type, args, kwds); } return get_memory_error(1, args, kwds); } PyObject * _PyErr_NoMemory(PyThreadState *tstate) { if (Py_IS_TYPE(PyExc_MemoryError, NULL)) { /* PyErr_NoMemory() has been called before PyExc_MemoryError has been initialized by _PyExc_Init() */ Py_FatalError("Out of memory and PyExc_MemoryError is not " "initialized yet"); } PyObject *err = get_memory_error(0, NULL, NULL); if (err != NULL) { _PyErr_SetRaisedException(tstate, err); } return NULL; } static void MemoryError_dealloc(PyObject *op) { PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op); _PyObject_GC_UNTRACK(self); (void)BaseException_clear(op); /* If this is a subclass of MemoryError, we don't need to * do anything in the free-list*/ if (!Py_IS_TYPE(self, (PyTypeObject *) PyExc_MemoryError)) { Py_TYPE(self)->tp_free(op); return; } struct _Py_exc_state *state = get_exc_state(); MEMERRORS_LOCK(state); if (state->memerrors_numfree < MEMERRORS_SAVE) { self->dict = (PyObject *) state->memerrors_freelist; state->memerrors_freelist = self; state->memerrors_numfree++; MEMERRORS_UNLOCK(state); return; } MEMERRORS_UNLOCK(state); Py_TYPE(self)->tp_free((PyObject *)self); } static int preallocate_memerrors(void) { /* We create enough MemoryErrors and then decref them, which will fill up the freelist. */ int i; PyObject *errors[MEMERRORS_SAVE]; for (i = 0; i < MEMERRORS_SAVE; i++) { errors[i] = MemoryError_new((PyTypeObject *) PyExc_MemoryError, NULL, NULL); if (!errors[i]) { return -1; } } for (i = 0; i < MEMERRORS_SAVE; i++) { Py_DECREF(errors[i]); } return 0; } static void free_preallocated_memerrors(struct _Py_exc_state *state) { while (state->memerrors_freelist != NULL) { PyObject *self = (PyObject *) state->memerrors_freelist; state->memerrors_freelist = (PyBaseExceptionObject *)state->memerrors_freelist->dict; Py_TYPE(self)->tp_free(self); } } PyTypeObject _PyExc_MemoryError = { PyVarObject_HEAD_INIT(NULL, 0) "MemoryError", sizeof(PyBaseExceptionObject), 0, MemoryError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, PyDoc_STR("Out of memory."), BaseException_traverse, BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_PyExc_Exception, 0, 0, 0, offsetof(PyBaseExceptionObject, dict), BaseException_init, 0, MemoryError_new }; PyObject *PyExc_MemoryError = (PyObject *) &_PyExc_MemoryError; /* * BufferError extends Exception */ SimpleExtendsException(PyExc_Exception, BufferError, "Buffer error."); /* Warning category docstrings */ /* * Warning extends Exception */ SimpleExtendsException(PyExc_Exception, Warning, "Base class for warning categories."); /* * UserWarning extends Warning */ SimpleExtendsException(PyExc_Warning, UserWarning, "Base class for warnings generated by user code."); /* * DeprecationWarning extends Warning */ SimpleExtendsException(PyExc_Warning, DeprecationWarning, "Base class for warnings about deprecated features."); /* * PendingDeprecationWarning extends Warning */ SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning, "Base class for warnings about features which will be deprecated\n" "in the future."); /* * SyntaxWarning extends Warning */ SimpleExtendsException(PyExc_Warning, SyntaxWarning, "Base class for warnings about dubious syntax."); /* * RuntimeWarning extends Warning */ SimpleExtendsException(PyExc_Warning, RuntimeWarning, "Base class for warnings about dubious runtime behavior."); /* * FutureWarning extends Warning */ SimpleExtendsException(PyExc_Warning, FutureWarning, "Base class for warnings about constructs that will change semantically\n" "in the future."); /* * ImportWarning extends Warning */ SimpleExtendsException(PyExc_Warning, ImportWarning, "Base class for warnings about probable mistakes in module imports"); /* * UnicodeWarning extends Warning */ SimpleExtendsException(PyExc_Warning, UnicodeWarning, "Base class for warnings about Unicode related problems, mostly\n" "related to conversion problems."); /* * BytesWarning extends Warning */ SimpleExtendsException(PyExc_Warning, BytesWarning, "Base class for warnings about bytes and buffer related problems, mostly\n" "related to conversion from str or comparing to str."); /* * EncodingWarning extends Warning */ SimpleExtendsException(PyExc_Warning, EncodingWarning, "Base class for warnings about encodings."); /* * ResourceWarning extends Warning */ SimpleExtendsException(PyExc_Warning, ResourceWarning, "Base class for warnings about resource usage."); #ifdef MS_WINDOWS #include /* The following constants were added to errno.h in VS2010 but have preferred WSA equivalents. */ #undef EADDRINUSE #undef EADDRNOTAVAIL #undef EAFNOSUPPORT #undef EALREADY #undef ECONNABORTED #undef ECONNREFUSED #undef ECONNRESET #undef EDESTADDRREQ #undef EHOSTUNREACH #undef EINPROGRESS #undef EISCONN #undef ELOOP #undef EMSGSIZE #undef ENETDOWN #undef ENETRESET #undef ENETUNREACH #undef ENOBUFS #undef ENOPROTOOPT #undef ENOTCONN #undef ENOTSOCK #undef EOPNOTSUPP #undef EPROTONOSUPPORT #undef EPROTOTYPE #undef EWOULDBLOCK #if defined(WSAEALREADY) && !defined(EALREADY) #define EALREADY WSAEALREADY #endif #if defined(WSAECONNABORTED) && !defined(ECONNABORTED) #define ECONNABORTED WSAECONNABORTED #endif #if defined(WSAECONNREFUSED) && !defined(ECONNREFUSED) #define ECONNREFUSED WSAECONNREFUSED #endif #if defined(WSAECONNRESET) && !defined(ECONNRESET) #define ECONNRESET WSAECONNRESET #endif #if defined(WSAEINPROGRESS) && !defined(EINPROGRESS) #define EINPROGRESS WSAEINPROGRESS #endif #if defined(WSAESHUTDOWN) && !defined(ESHUTDOWN) #define ESHUTDOWN WSAESHUTDOWN #endif #if defined(WSAEWOULDBLOCK) && !defined(EWOULDBLOCK) #define EWOULDBLOCK WSAEWOULDBLOCK #endif #endif /* MS_WINDOWS */ struct static_exception { PyTypeObject *exc; const char *name; }; static struct static_exception static_exceptions[] = { #define ITEM(NAME) {&_PyExc_##NAME, #NAME} // Level 1 ITEM(BaseException), // Level 2: BaseException subclasses ITEM(BaseExceptionGroup), ITEM(Exception), ITEM(GeneratorExit), ITEM(KeyboardInterrupt), ITEM(SystemExit), // Level 3: Exception(BaseException) subclasses ITEM(ArithmeticError), ITEM(AssertionError), ITEM(AttributeError), ITEM(BufferError), ITEM(EOFError), //ITEM(ExceptionGroup), ITEM(ImportError), ITEM(LookupError), ITEM(MemoryError), ITEM(NameError), ITEM(OSError), ITEM(ReferenceError), ITEM(RuntimeError), ITEM(StopAsyncIteration), ITEM(StopIteration), ITEM(SyntaxError), ITEM(SystemError), ITEM(TypeError), ITEM(ValueError), ITEM(Warning), // Level 4: ArithmeticError(Exception) subclasses ITEM(FloatingPointError), ITEM(OverflowError), ITEM(ZeroDivisionError), // Level 4: Warning(Exception) subclasses ITEM(BytesWarning), ITEM(DeprecationWarning), ITEM(EncodingWarning), ITEM(FutureWarning), ITEM(ImportWarning), ITEM(PendingDeprecationWarning), ITEM(ResourceWarning), ITEM(RuntimeWarning), ITEM(SyntaxWarning), ITEM(UnicodeWarning), ITEM(UserWarning), // Level 4: OSError(Exception) subclasses ITEM(BlockingIOError), ITEM(ChildProcessError), ITEM(ConnectionError), ITEM(FileExistsError), ITEM(FileNotFoundError), ITEM(InterruptedError), ITEM(IsADirectoryError), ITEM(NotADirectoryError), ITEM(PermissionError), ITEM(ProcessLookupError), ITEM(TimeoutError), // Level 4: Other subclasses ITEM(IndentationError), // base: SyntaxError(Exception) {&_PyExc_IncompleteInputError, "_IncompleteInputError"}, // base: SyntaxError(Exception) ITEM(IndexError), // base: LookupError(Exception) ITEM(KeyError), // base: LookupError(Exception) ITEM(ModuleNotFoundError), // base: ImportError(Exception) ITEM(NotImplementedError), // base: RuntimeError(Exception) ITEM(PythonFinalizationError), // base: RuntimeError(Exception) ITEM(RecursionError), // base: RuntimeError(Exception) ITEM(UnboundLocalError), // base: NameError(Exception) ITEM(UnicodeError), // base: ValueError(Exception) // Level 5: ConnectionError(OSError) subclasses ITEM(BrokenPipeError), ITEM(ConnectionAbortedError), ITEM(ConnectionRefusedError), ITEM(ConnectionResetError), // Level 5: IndentationError(SyntaxError) subclasses ITEM(TabError), // base: IndentationError // Level 5: UnicodeError(ValueError) subclasses ITEM(UnicodeDecodeError), ITEM(UnicodeEncodeError), ITEM(UnicodeTranslateError), #undef ITEM }; int _PyExc_InitTypes(PyInterpreterState *interp) { for (size_t i=0; i < Py_ARRAY_LENGTH(static_exceptions); i++) { PyTypeObject *exc = static_exceptions[i].exc; if (_PyStaticType_InitBuiltin(interp, exc) < 0) { return -1; } if (exc->tp_new == BaseException_new && exc->tp_init == BaseException_init) { exc->tp_vectorcall = BaseException_vectorcall; } } return 0; } static void _PyExc_FiniTypes(PyInterpreterState *interp) { for (Py_ssize_t i=Py_ARRAY_LENGTH(static_exceptions) - 1; i >= 0; i--) { PyTypeObject *exc = static_exceptions[i].exc; _PyStaticType_FiniBuiltin(interp, exc); } } PyStatus _PyExc_InitGlobalObjects(PyInterpreterState *interp) { if (preallocate_memerrors() < 0) { return _PyStatus_NO_MEMORY(); } return _PyStatus_OK(); } PyStatus _PyExc_InitState(PyInterpreterState *interp) { struct _Py_exc_state *state = &interp->exc_state; #define ADD_ERRNO(TYPE, CODE) \ do { \ PyObject *_code = PyLong_FromLong(CODE); \ assert(_PyObject_RealIsSubclass(PyExc_ ## TYPE, PyExc_OSError)); \ if (!_code || PyDict_SetItem(state->errnomap, _code, PyExc_ ## TYPE)) { \ Py_XDECREF(_code); \ return _PyStatus_ERR("errmap insertion problem."); \ } \ Py_DECREF(_code); \ } while (0) /* Add exceptions to errnomap */ assert(state->errnomap == NULL); state->errnomap = PyDict_New(); if (!state->errnomap) { return _PyStatus_NO_MEMORY(); } ADD_ERRNO(BlockingIOError, EAGAIN); ADD_ERRNO(BlockingIOError, EALREADY); ADD_ERRNO(BlockingIOError, EINPROGRESS); ADD_ERRNO(BlockingIOError, EWOULDBLOCK); ADD_ERRNO(BrokenPipeError, EPIPE); #ifdef ESHUTDOWN ADD_ERRNO(BrokenPipeError, ESHUTDOWN); #endif ADD_ERRNO(ChildProcessError, ECHILD); ADD_ERRNO(ConnectionAbortedError, ECONNABORTED); ADD_ERRNO(ConnectionRefusedError, ECONNREFUSED); ADD_ERRNO(ConnectionResetError, ECONNRESET); ADD_ERRNO(FileExistsError, EEXIST); ADD_ERRNO(FileNotFoundError, ENOENT); ADD_ERRNO(IsADirectoryError, EISDIR); ADD_ERRNO(NotADirectoryError, ENOTDIR); ADD_ERRNO(InterruptedError, EINTR); ADD_ERRNO(PermissionError, EACCES); ADD_ERRNO(PermissionError, EPERM); #ifdef ENOTCAPABLE // Extension for WASI capability-based security. Process lacks // capability to access a resource. ADD_ERRNO(PermissionError, ENOTCAPABLE); #endif ADD_ERRNO(ProcessLookupError, ESRCH); ADD_ERRNO(TimeoutError, ETIMEDOUT); #ifdef WSAETIMEDOUT ADD_ERRNO(TimeoutError, WSAETIMEDOUT); #endif return _PyStatus_OK(); #undef ADD_ERRNO } /* Add exception types to the builtins module */ int _PyBuiltins_AddExceptions(PyObject *bltinmod) { PyObject *mod_dict = PyModule_GetDict(bltinmod); if (mod_dict == NULL) { return -1; } for (size_t i=0; i < Py_ARRAY_LENGTH(static_exceptions); i++) { struct static_exception item = static_exceptions[i]; if (PyDict_SetItemString(mod_dict, item.name, (PyObject*)item.exc)) { return -1; } } PyObject *PyExc_ExceptionGroup = create_exception_group_class(); if (!PyExc_ExceptionGroup) { return -1; } if (PyDict_SetItemString(mod_dict, "ExceptionGroup", PyExc_ExceptionGroup)) { return -1; } if (PyDict_SetItemString(mod_dict, "EnvironmentError", PyExc_OSError)) { return -1; } if (PyDict_SetItemString(mod_dict, "IOError", PyExc_OSError)) { return -1; } #ifdef MS_WINDOWS if (PyDict_SetItemString(mod_dict, "WindowsError", PyExc_OSError)) { return -1; } #endif return 0; } void _PyExc_ClearExceptionGroupType(PyInterpreterState *interp) { struct _Py_exc_state *state = &interp->exc_state; Py_CLEAR(state->PyExc_ExceptionGroup); } void _PyExc_Fini(PyInterpreterState *interp) { struct _Py_exc_state *state = &interp->exc_state; free_preallocated_memerrors(state); Py_CLEAR(state->errnomap); _PyExc_FiniTypes(interp); } int _PyException_AddNote(PyObject *exc, PyObject *note) { if (!PyExceptionInstance_Check(exc)) { PyErr_Format(PyExc_TypeError, "exc must be an exception, not '%s'", Py_TYPE(exc)->tp_name); return -1; } PyObject *r = BaseException_add_note(exc, note); int res = r == NULL ? -1 : 0; Py_XDECREF(r); return res; } /* Boolean type, a subtype of int */ #include "Python.h" #include "pycore_long.h" // FALSE_TAG TRUE_TAG #include "pycore_modsupport.h" // _PyArg_NoKwnames() #include "pycore_object.h" // _Py_FatalRefcountError() #include "pycore_runtime.h" // _Py_ID() #include /* We define bool_repr to return "False" or "True" */ static PyObject * bool_repr(PyObject *self) { return self == Py_True ? &_Py_ID(True) : &_Py_ID(False); } /* Function to return a bool from a C long */ PyObject *PyBool_FromLong(long ok) { return ok ? Py_True : Py_False; } /* We define bool_new to always return either Py_True or Py_False */ static PyObject * bool_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *x = Py_False; long ok; if (!_PyArg_NoKeywords("bool", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "bool", 0, 1, &x)) return NULL; ok = PyObject_IsTrue(x); if (ok < 0) return NULL; return PyBool_FromLong(ok); } static PyObject * bool_vectorcall(PyObject *type, PyObject * const*args, size_t nargsf, PyObject *kwnames) { long ok = 0; if (!_PyArg_NoKwnames("bool", kwnames)) { return NULL; } Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); if (!_PyArg_CheckPositional("bool", nargs, 0, 1)) { return NULL; } assert(PyType_Check(type)); if (nargs) { ok = PyObject_IsTrue(args[0]); if (ok < 0) { return NULL; } } return PyBool_FromLong(ok); } /* Arithmetic operations redefined to return bool if both args are bool. */ static PyObject * bool_invert(PyObject *v) { if (PyErr_WarnEx(PyExc_DeprecationWarning, "Bitwise inversion '~' on bool is deprecated and will be removed in " "Python 3.16. This returns the bitwise inversion of the underlying int " "object and is usually not what you expect from negating " "a bool. Use the 'not' operator for boolean negation or " "~int(x) if you really want the bitwise inversion of the " "underlying int.", 1) < 0) { return NULL; } return PyLong_Type.tp_as_number->nb_invert(v); } static PyObject * bool_and(PyObject *a, PyObject *b) { if (!PyBool_Check(a) || !PyBool_Check(b)) return PyLong_Type.tp_as_number->nb_and(a, b); return PyBool_FromLong((a == Py_True) & (b == Py_True)); } static PyObject * bool_or(PyObject *a, PyObject *b) { if (!PyBool_Check(a) || !PyBool_Check(b)) return PyLong_Type.tp_as_number->nb_or(a, b); return PyBool_FromLong((a == Py_True) | (b == Py_True)); } static PyObject * bool_xor(PyObject *a, PyObject *b) { if (!PyBool_Check(a) || !PyBool_Check(b)) return PyLong_Type.tp_as_number->nb_xor(a, b); return PyBool_FromLong((a == Py_True) ^ (b == Py_True)); } /* Doc string */ PyDoc_STRVAR(bool_doc, "bool(object=False, /)\n\ --\n\ \n\ Returns True when the argument is true, False otherwise.\n\ The builtins True and False are the only two instances of the class bool.\n\ The class bool is a subclass of the class int, and cannot be subclassed."); /* Arithmetic methods -- only so we can override &, |, ^. */ static PyNumberMethods bool_as_number = { 0, /* nb_add */ 0, /* nb_subtract */ 0, /* nb_multiply */ 0, /* nb_remainder */ 0, /* nb_divmod */ 0, /* nb_power */ 0, /* nb_negative */ 0, /* nb_positive */ 0, /* nb_absolute */ 0, /* nb_bool */ bool_invert, /* nb_invert */ 0, /* nb_lshift */ 0, /* nb_rshift */ bool_and, /* nb_and */ bool_xor, /* nb_xor */ bool_or, /* nb_or */ 0, /* nb_int */ 0, /* nb_reserved */ 0, /* nb_float */ 0, /* nb_inplace_add */ 0, /* nb_inplace_subtract */ 0, /* nb_inplace_multiply */ 0, /* nb_inplace_remainder */ 0, /* nb_inplace_power */ 0, /* nb_inplace_lshift */ 0, /* nb_inplace_rshift */ 0, /* nb_inplace_and */ 0, /* nb_inplace_xor */ 0, /* nb_inplace_or */ 0, /* nb_floor_divide */ 0, /* nb_true_divide */ 0, /* nb_inplace_floor_divide */ 0, /* nb_inplace_true_divide */ 0, /* nb_index */ }; static void bool_dealloc(PyObject *boolean) { /* This should never get called, but we also don't want to SEGV if * we accidentally decref Booleans out of existence. Instead, * since bools are immortal, re-set the reference count. */ _Py_SetImmortal(boolean); } /* The type object for bool. Note that this cannot be subclassed! */ PyTypeObject PyBool_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "bool", offsetof(struct _longobject, long_value.ob_digit), /* tp_basicsize */ sizeof(digit), /* tp_itemsize */ bool_dealloc, /* tp_dealloc */ 0, /* tp_vectorcall_offset */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ bool_repr, /* tp_repr */ &bool_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ bool_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ &PyLong_Type, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ bool_new, /* tp_new */ .tp_vectorcall = bool_vectorcall, }; /* The objects representing bool values False and True */ struct _longobject _Py_FalseStruct = { PyObject_HEAD_INIT(&PyBool_Type) { .lv_tag = _PyLong_FALSE_TAG, { 0 } } }; struct _longobject _Py_TrueStruct = { PyObject_HEAD_INIT(&PyBool_Type) { .lv_tag = _PyLong_TRUE_TAG, { 1 } } }; /* File object implementation (what's left of it -- see io.py) */ #include "Python.h" #include "pycore_call.h" // _PyObject_CallNoArgs() #include "pycore_runtime.h" // _PyRuntime #include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8String() #ifdef HAVE_UNISTD_H # include // isatty() #endif #if defined(HAVE_GETC_UNLOCKED) && !defined(_Py_MEMORY_SANITIZER) /* clang MemorySanitizer doesn't yet understand getc_unlocked. */ # define GETC(f) getc_unlocked(f) # define FLOCKFILE(f) flockfile(f) # define FUNLOCKFILE(f) funlockfile(f) #else # define GETC(f) getc(f) # define FLOCKFILE(f) # define FUNLOCKFILE(f) #endif /* Newline flags */ #define NEWLINE_UNKNOWN 0 /* No newline seen, yet */ #define NEWLINE_CR 1 /* \r newline seen */ #define NEWLINE_LF 2 /* \n newline seen */ #define NEWLINE_CRLF 4 /* \r\n newline seen */ /* External C interface */ PyObject * PyFile_FromFd(int fd, const char *name, const char *mode, int buffering, const char *encoding, const char *errors, const char *newline, int closefd) { PyObject *open, *stream; /* import _io in case we are being used to open io.py */ open = PyImport_ImportModuleAttrString("_io", "open"); if (open == NULL) return NULL; stream = PyObject_CallFunction(open, "isisssO", fd, mode, buffering, encoding, errors, newline, closefd ? Py_True : Py_False); Py_DECREF(open); if (stream == NULL) return NULL; /* ignore name attribute because the name attribute of _BufferedIOMixin and TextIOWrapper is read only */ return stream; } PyObject * PyFile_GetLine(PyObject *f, int n) { PyObject *result; if (f == NULL) { PyErr_BadInternalCall(); return NULL; } if (n <= 0) { result = PyObject_CallMethodNoArgs(f, &_Py_ID(readline)); } else { result = _PyObject_CallMethod(f, &_Py_ID(readline), "i", n); } if (result != NULL && !PyBytes_Check(result) && !PyUnicode_Check(result)) { PyErr_Format(PyExc_TypeError, "%T.readline() must return a str, not %T", f, result); Py_SETREF(result, NULL); } if (n < 0 && result != NULL && PyBytes_Check(result)) { const char *s = PyBytes_AS_STRING(result); Py_ssize_t len = PyBytes_GET_SIZE(result); if (len == 0) { Py_SETREF(result, NULL); PyErr_SetString(PyExc_EOFError, "EOF when reading a line"); } else if (s[len-1] == '\n') { (void) _PyBytes_Resize(&result, len-1); } } if (n < 0 && result != NULL && PyUnicode_Check(result)) { Py_ssize_t len = PyUnicode_GET_LENGTH(result); if (len == 0) { Py_SETREF(result, NULL); PyErr_SetString(PyExc_EOFError, "EOF when reading a line"); } else if (PyUnicode_READ_CHAR(result, len-1) == '\n') { PyObject *v; v = PyUnicode_Substring(result, 0, len-1); Py_SETREF(result, v); } } return result; } /* Interfaces to write objects/strings to file-like objects */ int PyFile_WriteObject(PyObject *v, PyObject *f, int flags) { PyObject *writer, *value, *result; if (f == NULL) { PyErr_SetString(PyExc_TypeError, "writeobject with NULL file"); return -1; } writer = PyObject_GetAttr(f, &_Py_ID(write)); if (writer == NULL) return -1; if (flags & Py_PRINT_RAW) { value = PyObject_Str(v); } else value = PyObject_Repr(v); if (value == NULL) { Py_DECREF(writer); return -1; } result = PyObject_CallOneArg(writer, value); Py_DECREF(value); Py_DECREF(writer); if (result == NULL) return -1; Py_DECREF(result); return 0; } int PyFile_WriteString(const char *s, PyObject *f) { if (f == NULL) { /* Should be caused by a pre-existing error */ if (!PyErr_Occurred()) PyErr_SetString(PyExc_SystemError, "null file for PyFile_WriteString"); return -1; } else if (!PyErr_Occurred()) { PyObject *v = PyUnicode_FromString(s); int err; if (v == NULL) return -1; err = PyFile_WriteObject(v, f, Py_PRINT_RAW); Py_DECREF(v); return err; } else return -1; } /* Try to get a file-descriptor from a Python object. If the object is an integer, its value is returned. If not, the object's fileno() method is called if it exists; the method must return an integer, which is returned as the file descriptor value. -1 is returned on failure. */ int PyObject_AsFileDescriptor(PyObject *o) { int fd; PyObject *meth; if (PyLong_Check(o)) { if (PyBool_Check(o)) { if (PyErr_WarnEx(PyExc_RuntimeWarning, "bool is used as a file descriptor", 1)) { return -1; } } fd = PyLong_AsInt(o); } else if (PyObject_GetOptionalAttr(o, &_Py_ID(fileno), &meth) < 0) { return -1; } else if (meth != NULL) { PyObject *fno = _PyObject_CallNoArgs(meth); Py_DECREF(meth); if (fno == NULL) return -1; if (PyLong_Check(fno)) { fd = PyLong_AsInt(fno); Py_DECREF(fno); } else { PyErr_Format(PyExc_TypeError, "%T.fileno() must return an int, not %T", o, fno); Py_DECREF(fno); return -1; } } else { PyErr_SetString(PyExc_TypeError, "argument must be an int, or have a fileno() method."); return -1; } if (fd == -1 && PyErr_Occurred()) return -1; if (fd < 0) { PyErr_Format(PyExc_ValueError, "file descriptor cannot be a negative integer (%i)", fd); return -1; } return fd; } int _PyLong_FileDescriptor_Converter(PyObject *o, void *ptr) { int fd = PyObject_AsFileDescriptor(o); if (fd == -1) { return 0; } *(int *)ptr = fd; return 1; } char * _Py_UniversalNewlineFgetsWithSize(char *buf, int n, FILE *stream, PyObject *fobj, size_t* size) { char *p = buf; int c; if (fobj) { errno = ENXIO; /* What can you do... */ return NULL; } FLOCKFILE(stream); while (--n > 0 && (c = GETC(stream)) != EOF ) { if (c == '\r') { // A \r is translated into a \n, and we skip an adjacent \n, if any. c = GETC(stream); if (c != '\n') { ungetc(c, stream); c = '\n'; } } *p++ = c; if (c == '\n') { break; } } FUNLOCKFILE(stream); *p = '\0'; if (p == buf) { return NULL; } *size = p - buf; return buf; } /* ** Py_UniversalNewlineFgets is an fgets variation that understands ** all of \r, \n and \r\n conventions. ** The stream should be opened in binary mode. ** The fobj parameter exists solely for legacy reasons and must be NULL. ** Note that we need no error handling: fgets() treats error and eof ** identically. */ char * Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj) { size_t size; return _Py_UniversalNewlineFgetsWithSize(buf, n, stream, fobj, &size); } /* **************************** std printer **************************** * The stdprinter is used during the boot strapping phase as a preliminary * file like object for sys.stderr. */ typedef struct { PyObject_HEAD int fd; } PyStdPrinter_Object; PyObject * PyFile_NewStdPrinter(int fd) { PyStdPrinter_Object *self; if (fd != fileno(stdout) && fd != fileno(stderr)) { /* not enough infrastructure for PyErr_BadInternalCall() */ return NULL; } self = PyObject_New(PyStdPrinter_Object, &PyStdPrinter_Type); if (self != NULL) { self->fd = fd; } return (PyObject*)self; } static PyObject * stdprinter_write(PyObject *op, PyObject *args) { PyStdPrinter_Object *self = (PyStdPrinter_Object*)op; PyObject *unicode; PyObject *bytes = NULL; const char *str; Py_ssize_t n; int err; /* The function can clear the current exception */ assert(!PyErr_Occurred()); if (self->fd < 0) { /* fd might be invalid on Windows * I can't raise an exception here. It may lead to an * unlimited recursion in the case stderr is invalid. */ Py_RETURN_NONE; } if (!PyArg_ParseTuple(args, "U", &unicode)) { return NULL; } /* Encode Unicode to UTF-8/backslashreplace */ str = PyUnicode_AsUTF8AndSize(unicode, &n); if (str == NULL) { PyErr_Clear(); bytes = _PyUnicode_AsUTF8String(unicode, "backslashreplace"); if (bytes == NULL) return NULL; str = PyBytes_AS_STRING(bytes); n = PyBytes_GET_SIZE(bytes); } n = _Py_write(self->fd, str, n); /* save errno, it can be modified indirectly by Py_XDECREF() */ err = errno; Py_XDECREF(bytes); if (n == -1) { if (err == EAGAIN) { PyErr_Clear(); Py_RETURN_NONE; } return NULL; } return PyLong_FromSsize_t(n); } static PyObject * stdprinter_fileno(PyObject *op, PyObject *Py_UNUSED(ignored)) { PyStdPrinter_Object *self = (PyStdPrinter_Object*)op; return PyLong_FromLong((long) self->fd); } static PyObject * stdprinter_repr(PyObject *op) { PyStdPrinter_Object *self = (PyStdPrinter_Object*)op; return PyUnicode_FromFormat("", self->fd, self); } static PyObject * stdprinter_noop(PyObject *self, PyObject *Py_UNUSED(ignored)) { Py_RETURN_NONE; } static PyObject * stdprinter_isatty(PyObject *op, PyObject *Py_UNUSED(ignored)) { PyStdPrinter_Object *self = (PyStdPrinter_Object*)op; long res; if (self->fd < 0) { Py_RETURN_FALSE; } Py_BEGIN_ALLOW_THREADS res = isatty(self->fd); Py_END_ALLOW_THREADS return PyBool_FromLong(res); } static PyMethodDef stdprinter_methods[] = { {"close", stdprinter_noop, METH_NOARGS, ""}, {"flush", stdprinter_noop, METH_NOARGS, ""}, {"fileno", stdprinter_fileno, METH_NOARGS, ""}, {"isatty", stdprinter_isatty, METH_NOARGS, ""}, {"write", stdprinter_write, METH_VARARGS, ""}, {NULL, NULL} /*sentinel */ }; static PyObject * get_closed(PyObject *self, void *Py_UNUSED(closure)) { Py_RETURN_FALSE; } static PyObject * get_mode(PyObject *self, void *Py_UNUSED(closure)) { return PyUnicode_FromString("w"); } static PyObject * get_encoding(PyObject *self, void *Py_UNUSED(closure)) { Py_RETURN_NONE; } static PyGetSetDef stdprinter_getsetlist[] = { {"closed", get_closed, NULL, "True if the file is closed"}, {"encoding", get_encoding, NULL, "Encoding of the file"}, {"mode", get_mode, NULL, "String giving the file mode"}, {0}, }; PyTypeObject PyStdPrinter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "stderrprinter", /* tp_name */ sizeof(PyStdPrinter_Object), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ 0, /* tp_dealloc */ 0, /* tp_vectorcall_offset */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ stdprinter_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ stdprinter_methods, /* tp_methods */ 0, /* tp_members */ stdprinter_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ 0, /* tp_new */ PyObject_Free, /* tp_free */ }; /* ************************** open_code hook *************************** * The open_code hook allows embedders to override the method used to * open files that are going to be used by the runtime to execute code */ int PyFile_SetOpenCodeHook(Py_OpenCodeHookFunction hook, void *userData) { if (Py_IsInitialized() && PySys_Audit("setopencodehook", NULL) < 0) { return -1; } if (_PyRuntime.open_code_hook) { if (Py_IsInitialized()) { PyErr_SetString(PyExc_SystemError, "failed to change existing open_code hook"); } return -1; } _PyRuntime.open_code_hook = hook; _PyRuntime.open_code_userdata = userData; return 0; } PyObject * PyFile_OpenCodeObject(PyObject *path) { PyObject *f = NULL; if (!PyUnicode_Check(path)) { PyErr_Format(PyExc_TypeError, "'path' must be 'str', not '%.200s'", Py_TYPE(path)->tp_name); return NULL; } Py_OpenCodeHookFunction hook = _PyRuntime.open_code_hook; if (hook) { f = hook(path, _PyRuntime.open_code_userdata); } else { PyObject *open = PyImport_ImportModuleAttrString("_io", "open"); if (open) { f = PyObject_CallFunction(open, "Os", path, "rb"); Py_DECREF(open); } } return f; } PyObject * PyFile_OpenCode(const char *utf8path) { PyObject *pathobj = PyUnicode_FromString(utf8path); PyObject *f; if (!pathobj) { return NULL; } f = PyFile_OpenCodeObject(pathobj); Py_DECREF(pathobj); return f; } int _PyFile_Flush(PyObject *file) { PyObject *tmp = PyObject_CallMethodNoArgs(file, &_Py_ID(flush)); if (tmp == NULL) { return -1; } Py_DECREF(tmp); return 0; } /* Ordered Dictionary object implementation. This implementation is necessarily explicitly equivalent to the pure Python OrderedDict class in Lib/collections/__init__.py. The strategy there involves using a doubly-linked-list to capture the order. We keep to that strategy, using a lower-level linked-list. About the Linked-List ===================== For the linked list we use a basic doubly-linked-list. Using a circularly- linked-list does have some benefits, but they don't apply so much here since OrderedDict is focused on the ends of the list (for the most part). Furthermore, there are some features of generic linked-lists that we simply don't need for OrderedDict. Thus a simple custom implementation meets our needs. Alternatives to our simple approach include the QCIRCLE_* macros from BSD's queue.h, and the linux's list.h. Getting O(1) Node Lookup ------------------------ One invariant of Python's OrderedDict is that it preserves time complexity of dict's methods, particularly the O(1) operations. Simply adding a linked-list on top of dict is not sufficient here; operations for nodes in the middle of the linked-list implicitly require finding the node first. With a simple linked-list like we're using, that is an O(n) operation. Consequently, methods like __delitem__() would change from O(1) to O(n), which is unacceptable. In order to preserve O(1) performance for node removal (finding nodes), we must do better than just looping through the linked-list. Here are options we've considered: 1. use a second dict to map keys to nodes (a la the pure Python version). 2. keep a simple hash table mirroring the order of dict's, mapping each key to the corresponding node in the linked-list. 3. use a version of shared keys (split dict) that allows non-unicode keys. 4. have the value stored for each key be a (value, node) pair, and adjust __getitem__(), get(), etc. accordingly. The approach with the least performance impact (time and space) is #2, mirroring the key order of dict's dk_entries with an array of node pointers. While _Py_dict_lookup() does not give us the index into the array, we make use of pointer arithmetic to get that index. An alternative would be to refactor _Py_dict_lookup() to provide the index, explicitly exposing the implementation detail. We could even just use a custom lookup function for OrderedDict that facilitates our need. However, both approaches are significantly more complicated than just using pointer arithmetic. The catch with mirroring the hash table ordering is that we have to keep the ordering in sync through any dict resizes. However, that order only matters during node lookup. We can simply defer any potential resizing until we need to do a lookup. Linked-List Nodes ----------------- The current implementation stores a pointer to the associated key only. One alternative would be to store a pointer to the PyDictKeyEntry instead. This would save one pointer de-reference per item, which is nice during calls to values() and items(). However, it adds unnecessary overhead otherwise, so we stick with just the key. Linked-List API --------------- As noted, the linked-list implemented here does not have all the bells and whistles. However, we recognize that the implementation may need to change to accommodate performance improvements or extra functionality. To that end, we use a simple API to interact with the linked-list. Here's a summary of the methods/macros: Node info: * _odictnode_KEY(node) * _odictnode_VALUE(od, node) * _odictnode_PREV(node) * _odictnode_NEXT(node) Linked-List info: * _odict_FIRST(od) * _odict_LAST(od) * _odict_EMPTY(od) * _odict_FOREACH(od, node) - used in place of `for (node=...)` For adding nodes: * _odict_add_head(od, node) * _odict_add_tail(od, node) * _odict_add_new_node(od, key, hash) For removing nodes: * _odict_clear_node(od, node, key, hash) * _odict_clear_nodes(od, clear_each) Others: * _odict_find_node_hash(od, key, hash) * _odict_find_node(od, key) * _odict_keys_equal(od1, od2) And here's a look at how the linked-list relates to the OrderedDict API: ============ === === ==== ==== ==== === ==== ===== ==== ==== === ==== === === method key val prev next mem 1st last empty iter find add rmv clr keq ============ === === ==== ==== ==== === ==== ===== ==== ==== === ==== === === __del__ ~ X __delitem__ free ~ node __eq__ ~ X __iter__ X X __new__ X X __reduce__ X ~ X __repr__ X X X __reversed__ X X __setitem__ key __sizeof__ size X clear ~ ~ X copy X X X items X X X keys X X move_to_end X X X ~ h/t key pop free key popitem X X free X X node setdefault ~ ? ~ values X X ============ === === ==== ==== ==== === ==== ===== ==== ==== === ==== === === __delitem__ is the only method that directly relies on finding an arbitrary node in the linked-list. Everything else is iteration or relates to the ends of the linked-list. Situation that Endangers Consistency ------------------------------------ Using a raw linked-list for OrderedDict exposes a key situation that can cause problems. If a node is stored in a variable, there is a chance that the node may have been deallocated before the variable gets used, thus potentially leading to a segmentation fault. A key place where this shows up is during iteration through the linked list (via _odict_FOREACH or otherwise). A number of solutions are available to resolve this situation: * defer looking up the node until as late as possible and certainly after any code that could possibly result in a deletion; * if the node is needed both before and after a point where the node might be removed, do a check before using the node at the "after" location to see if the node is still valid; * like the last one, but simply pull the node again to ensure it's right; * keep the key in the variable instead of the node and then look up the node using the key at the point where the node is needed (this is what we do for the iterators). Another related problem, preserving consistent ordering during iteration, is described below. That one is not exclusive to using linked-lists. Challenges from Subclassing dict ================================ OrderedDict subclasses dict, which is an unusual relationship between two builtin types (other than the base object type). Doing so results in some complication and deserves further explanation. There are two things to consider here. First, in what circumstances or with what adjustments can OrderedDict be used as a drop-in replacement for dict (at the C level)? Second, how can the OrderedDict implementation leverage the dict implementation effectively without introducing unnecessary coupling or inefficiencies? This second point is reflected here and in the implementation, so the further focus is on the first point. It is worth noting that for overridden methods, the dict implementation is deferred to as much as possible. Furthermore, coupling is limited to as little as is reasonable. Concrete API Compatibility -------------------------- Use of the concrete C-API for dict (PyDict_*) with OrderedDict is problematic. (See http://bugs.python.org/issue10977.) The concrete API has a number of hard-coded assumptions tied to the dict implementation. This is, in part, due to performance reasons, which is understandable given the part dict plays in Python. Any attempt to replace dict with OrderedDict for any role in the interpreter (e.g. **kwds) faces a challenge. Such any effort must recognize that the instances in affected locations currently interact with the concrete API. Here are some ways to address this challenge: 1. Change the relevant usage of the concrete API in CPython and add PyDict_CheckExact() calls to each of the concrete API functions. 2. Adjust the relevant concrete API functions to explicitly accommodate OrderedDict. 3. As with #1, add the checks, but improve the abstract API with smart fast paths for dict and OrderedDict, and refactor CPython to use the abstract API. Improvements to the abstract API would be valuable regardless. Adding the checks to the concrete API would help make any interpreter switch to OrderedDict less painful for extension modules. However, this won't work. The equivalent C API call to `dict.__setitem__(obj, k, v)` is `PyDict_SetItem(obj, k, v)`. This illustrates how subclasses in C call the base class's methods, since there is no equivalent of super() in the C API. Calling into Python for parent class API would work, but some extension modules already rely on this feature of the concrete API. For reference, here is a breakdown of some of the dict concrete API: ========================== ============= ======================= concrete API uses abstract API ========================== ============= ======================= PyDict_Check PyMapping_Check (PyDict_CheckExact) - (PyDict_New) - (PyDictProxy_New) - PyDict_Clear - PyDict_Contains PySequence_Contains PyDict_Copy - PyDict_SetItem PyObject_SetItem PyDict_SetItemString PyMapping_SetItemString PyDict_DelItem PyMapping_DelItem PyDict_DelItemString PyMapping_DelItemString PyDict_GetItem - PyDict_GetItemWithError PyObject_GetItem PyDict_GetItemString PyMapping_GetItemString PyDict_Items PyMapping_Items PyDict_Keys PyMapping_Keys PyDict_Values PyMapping_Values PyDict_Size PyMapping_Size PyMapping_Length PyDict_Next PyIter_Next _PyDict_Next - PyDict_Merge - PyDict_Update - PyDict_MergeFromSeq2 - PyDict_ClearFreeList - - PyMapping_HasKeyString - PyMapping_HasKey ========================== ============= ======================= The dict Interface Relative to OrderedDict ========================================== Since OrderedDict subclasses dict, understanding the various methods and attributes of dict is important for implementing OrderedDict. Relevant Type Slots ------------------- ================= ================ =================== ================ slot attribute object dict ================= ================ =================== ================ tp_dealloc - object_dealloc dict_dealloc tp_repr __repr__ object_repr dict_repr sq_contains __contains__ - dict_contains mp_length __len__ - dict_length mp_subscript __getitem__ - dict_subscript mp_ass_subscript __setitem__ - dict_ass_sub __delitem__ tp_hash __hash__ Py_HashPointer ..._HashNotImpl tp_str __str__ object_str - tp_getattro __getattribute__ ..._GenericGetAttr (repeated) __getattr__ tp_setattro __setattr__ ..._GenericSetAttr (disabled) tp_doc __doc__ (literal) dictionary_doc tp_traverse - - dict_traverse tp_clear - - dict_tp_clear tp_richcompare __eq__ object_richcompare dict_richcompare __ne__ tp_weaklistoffset (__weakref__) - - tp_iter __iter__ - dict_iter tp_dictoffset (__dict__) - - tp_init __init__ object_init dict_init tp_alloc - PyType_GenericAlloc (repeated) tp_new __new__ object_new dict_new tp_free - PyObject_Free PyObject_GC_Del ================= ================ =================== ================ Relevant Methods ---------------- ================ =================== =============== method object dict ================ =================== =============== __reduce__ object_reduce - __sizeof__ object_sizeof dict_sizeof clear - dict_clear copy - dict_copy fromkeys - dict_fromkeys get - dict_get items - dictitems_new keys - dictkeys_new pop - dict_pop popitem - dict_popitem setdefault - dict_setdefault update - dict_update values - dictvalues_new ================ =================== =============== Pure Python OrderedDict ======================= As already noted, compatibility with the pure Python OrderedDict implementation is a key goal of this C implementation. To further that goal, here's a summary of how OrderedDict-specific methods are implemented in collections/__init__.py. Also provided is an indication of which methods directly mutate or iterate the object, as well as any relationship with the underlying linked-list. ============= ============== == ================ === === ==== method impl used ll uses inq mut iter ============= ============== == ================ === === ==== __contains__ dict - - X __delitem__ OrderedDict Y dict.__delitem__ X __eq__ OrderedDict N OrderedDict ~ dict.__eq__ __iter__ __getitem__ dict - - X __iter__ OrderedDict Y - X __init__ OrderedDict N update __len__ dict - - X __ne__ MutableMapping - __eq__ ~ __reduce__ OrderedDict N OrderedDict ~ __iter__ __getitem__ __repr__ OrderedDict N __class__ ~ items __reversed__ OrderedDict Y - X __setitem__ OrderedDict Y __contains__ X dict.__setitem__ __sizeof__ OrderedDict Y __len__ ~ __dict__ clear OrderedDict Y dict.clear X copy OrderedDict N __class__ __init__ fromkeys OrderedDict N __setitem__ get dict - - ~ items MutableMapping - ItemsView X keys MutableMapping - KeysView X move_to_end OrderedDict Y - X pop OrderedDict N __contains__ X __getitem__ __delitem__ popitem OrderedDict Y dict.pop X setdefault OrderedDict N __contains__ ~ __getitem__ __setitem__ update MutableMapping - __setitem__ ~ values MutableMapping - ValuesView X ============= ============== == ================ === === ==== __reversed__ and move_to_end are both exclusive to OrderedDict. C OrderedDict Implementation ============================ ================= ================ slot impl ================= ================ tp_dealloc odict_dealloc tp_repr odict_repr mp_ass_subscript odict_ass_sub tp_doc odict_doc tp_traverse odict_traverse tp_clear odict_tp_clear tp_richcompare odict_richcompare tp_weaklistoffset (offset) tp_iter odict_iter tp_dictoffset (offset) tp_init odict_init tp_alloc (repeated) ================= ================ ================= ================ method impl ================= ================ __reduce__ odict_reduce __sizeof__ odict_sizeof clear odict_clear copy odict_copy fromkeys odict_fromkeys items odictitems_new keys odictkeys_new pop odict_pop popitem odict_popitem setdefault odict_setdefault update odict_update values odictvalues_new ================= ================ Inherited unchanged from object/dict: ================ ========================== method type field ================ ========================== - tp_free __contains__ tp_as_sequence.sq_contains __getattr__ tp_getattro __getattribute__ tp_getattro __getitem__ tp_as_mapping.mp_subscript __hash__ tp_hash __len__ tp_as_mapping.mp_length __setattr__ tp_setattro __str__ tp_str get - ================ ========================== Other Challenges ================ Preserving Ordering During Iteration ------------------------------------ During iteration through an OrderedDict, it is possible that items could get added, removed, or reordered. For a linked-list implementation, as with some other implementations, that situation may lead to undefined behavior. The documentation for dict mentions this in the `iter()` section of http://docs.python.org/3.4/library/stdtypes.html#dictionary-view-objects. In this implementation we follow dict's lead (as does the pure Python implementation) for __iter__(), keys(), values(), and items(). For internal iteration (using _odict_FOREACH or not), there is still the risk that not all nodes that we expect to be seen in the loop actually get seen. Thus, we are careful in each of those places to ensure that they are. This comes, of course, at a small price at each location. The solutions are much the same as those detailed in the `Situation that Endangers Consistency` section above. Potential Optimizations ======================= * Allocate the nodes as a block via od_fast_nodes instead of individually. - Set node->key to NULL to indicate the node is not-in-use. - Add _odict_EXISTS()? - How to maintain consistency across resizes? Existing node pointers would be invalidated after a resize, which is particularly problematic for the iterators. * Use a more stream-lined implementation of update() and, likely indirectly, __init__(). */ /* TODO sooner: - reentrancy (make sure everything is at a thread-safe state when calling into Python). I've already checked this multiple times, but want to make one more pass. - add unit tests for reentrancy? later: - make the dict views support the full set API (the pure Python impl does) - implement a fuller MutableMapping API in C? - move the MutableMapping implementation to abstract.c? - optimize mutablemapping_update - use PyObject_Malloc (small object allocator) for odict nodes? - support subclasses better (e.g. in odict_richcompare) */ #include "Python.h" #include "pycore_call.h" // _PyObject_CallNoArgs() #include "pycore_ceval.h" // _PyEval_GetBuiltin() #include "pycore_critical_section.h" //_Py_BEGIN_CRITICAL_SECTION #include "pycore_dict.h" // _Py_dict_lookup() #include "pycore_object.h" // _PyObject_GC_UNTRACK() #include "pycore_pyerrors.h" // _PyErr_ChainExceptions1() #include "pycore_tuple.h" // _PyTuple_Recycle() #include // offsetof() #include "pycore_weakref.h" // FT_CLEAR_WEAKREFS() #include "clinic/odictobject.c.h" /*[clinic input] class OrderedDict "PyODictObject *" "&PyODict_Type" [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=ca0641cf6143d4af]*/ typedef struct _odictnode _ODictNode; /* PyODictObject */ struct _odictobject { PyDictObject od_dict; /* the underlying dict */ _ODictNode *od_first; /* first node in the linked list, if any */ _ODictNode *od_last; /* last node in the linked list, if any */ /* od_fast_nodes, od_fast_nodes_size and od_resize_sentinel are managed * by _odict_resize(). * Note that we rely on implementation details of dict for both. */ _ODictNode **od_fast_nodes; /* hash table that mirrors the dict table */ Py_ssize_t od_fast_nodes_size; void *od_resize_sentinel; /* changes if odict should be resized */ size_t od_state; /* incremented whenever the LL changes */ PyObject *od_inst_dict; /* OrderedDict().__dict__ */ PyObject *od_weakreflist; /* holds weakrefs to the odict */ }; #define _PyODictObject_CAST(op) _Py_CAST(PyODictObject*, (op)) /* ---------------------------------------------- * odict keys (a simple doubly-linked list) */ struct _odictnode { PyObject *key; Py_hash_t hash; _ODictNode *next; _ODictNode *prev; }; #define _odictnode_KEY(node) \ (node->key) #define _odictnode_HASH(node) \ (node->hash) /* borrowed reference */ #define _odictnode_VALUE(node, od) \ PyODict_GetItemWithError((PyObject *)od, _odictnode_KEY(node)) #define _odictnode_PREV(node) (node->prev) #define _odictnode_NEXT(node) (node->next) #define _odict_FIRST(od) (_PyODictObject_CAST(od)->od_first) #define _odict_LAST(od) (_PyODictObject_CAST(od)->od_last) #define _odict_EMPTY(od) (_odict_FIRST(od) == NULL) #define _odict_FOREACH(od, node) \ for (node = _odict_FIRST(od); node != NULL; node = _odictnode_NEXT(node)) /* Return the index into the hash table, regardless of a valid node. */ static Py_ssize_t _odict_get_index_raw(PyODictObject *od, PyObject *key, Py_hash_t hash) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od); PyObject *value = NULL; PyDictKeysObject *keys = ((PyDictObject *)od)->ma_keys; Py_ssize_t ix; #ifdef Py_GIL_DISABLED ix = _Py_dict_lookup_threadsafe((PyDictObject *)od, key, hash, &value); Py_XDECREF(value); #else ix = _Py_dict_lookup((PyDictObject *)od, key, hash, &value); #endif if (ix == DKIX_EMPTY) { return keys->dk_nentries; /* index of new entry */ } if (ix < 0) return -1; /* We use pointer arithmetic to get the entry's index into the table. */ return ix; } #define ONE ((Py_ssize_t)1) /* Replace od->od_fast_nodes with a new table matching the size of dict's. */ static int _odict_resize(PyODictObject *od) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od); Py_ssize_t size, i; _ODictNode **fast_nodes, *node; /* Initialize a new "fast nodes" table. */ size = ONE << (((PyDictObject *)od)->ma_keys->dk_log2_size); fast_nodes = PyMem_NEW(_ODictNode *, size); if (fast_nodes == NULL) { PyErr_NoMemory(); return -1; } for (i = 0; i < size; i++) fast_nodes[i] = NULL; /* Copy the current nodes into the table. */ _odict_FOREACH(od, node) { i = _odict_get_index_raw(od, _odictnode_KEY(node), _odictnode_HASH(node)); if (i < 0) { PyMem_Free(fast_nodes); return -1; } fast_nodes[i] = node; } /* Replace the old fast nodes table. */ PyMem_Free(od->od_fast_nodes); od->od_fast_nodes = fast_nodes; od->od_fast_nodes_size = size; od->od_resize_sentinel = ((PyDictObject *)od)->ma_keys; return 0; } /* Return the index into the hash table, regardless of a valid node. */ static Py_ssize_t _odict_get_index(PyODictObject *od, PyObject *key, Py_hash_t hash) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od); PyDictKeysObject *keys; assert(key != NULL); keys = ((PyDictObject *)od)->ma_keys; /* Ensure od_fast_nodes and dk_entries are in sync. */ if (od->od_resize_sentinel != keys || od->od_fast_nodes_size != (ONE << (keys->dk_log2_size))) { int resize_res = _odict_resize(od); if (resize_res < 0) return -1; } return _odict_get_index_raw(od, key, hash); } /* Returns NULL if there was some error or the key was not found. */ static _ODictNode * _odict_find_node_hash(PyODictObject *od, PyObject *key, Py_hash_t hash) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od); Py_ssize_t index; if (_odict_EMPTY(od)) return NULL; index = _odict_get_index(od, key, hash); if (index < 0) return NULL; assert(od->od_fast_nodes != NULL); return od->od_fast_nodes[index]; } static _ODictNode * _odict_find_node(PyODictObject *od, PyObject *key) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od); Py_ssize_t index; Py_hash_t hash; if (_odict_EMPTY(od)) return NULL; hash = PyObject_Hash(key); if (hash == -1) return NULL; index = _odict_get_index(od, key, hash); if (index < 0) return NULL; assert(od->od_fast_nodes != NULL); return od->od_fast_nodes[index]; } static void _odict_add_head(PyODictObject *od, _ODictNode *node) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od); _odictnode_PREV(node) = NULL; _odictnode_NEXT(node) = _odict_FIRST(od); if (_odict_FIRST(od) == NULL) _odict_LAST(od) = node; else _odictnode_PREV(_odict_FIRST(od)) = node; _odict_FIRST(od) = node; od->od_state++; } static void _odict_add_tail(PyODictObject *od, _ODictNode *node) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od); _odictnode_PREV(node) = _odict_LAST(od); _odictnode_NEXT(node) = NULL; if (_odict_LAST(od) == NULL) _odict_FIRST(od) = node; else _odictnode_NEXT(_odict_LAST(od)) = node; _odict_LAST(od) = node; od->od_state++; } /* adds the node to the end of the list */ static int _odict_add_new_node(PyODictObject *od, PyObject *key, Py_hash_t hash) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od); Py_ssize_t i; _ODictNode *node; Py_INCREF(key); i = _odict_get_index(od, key, hash); if (i < 0) { if (!PyErr_Occurred()) PyErr_SetObject(PyExc_KeyError, key); Py_DECREF(key); return -1; } assert(od->od_fast_nodes != NULL); if (od->od_fast_nodes[i] != NULL) { /* We already have a node for the key so there's no need to add one. */ Py_DECREF(key); return 0; } /* must not be added yet */ node = (_ODictNode *)PyMem_Malloc(sizeof(_ODictNode)); if (node == NULL) { Py_DECREF(key); PyErr_NoMemory(); return -1; } _odictnode_KEY(node) = key; _odictnode_HASH(node) = hash; _odict_add_tail(od, node); od->od_fast_nodes[i] = node; return 0; } /* Putting the decref after the free causes problems. */ #define _odictnode_DEALLOC(node) \ do { \ Py_DECREF(_odictnode_KEY(node)); \ PyMem_Free((void *)node); \ } while (0) /* Repeated calls on the same node are no-ops. */ static void _odict_remove_node(PyODictObject *od, _ODictNode *node) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od); if (_odict_FIRST(od) == node) _odict_FIRST(od) = _odictnode_NEXT(node); else if (_odictnode_PREV(node) != NULL) _odictnode_NEXT(_odictnode_PREV(node)) = _odictnode_NEXT(node); if (_odict_LAST(od) == node) _odict_LAST(od) = _odictnode_PREV(node); else if (_odictnode_NEXT(node) != NULL) _odictnode_PREV(_odictnode_NEXT(node)) = _odictnode_PREV(node); _odictnode_PREV(node) = NULL; _odictnode_NEXT(node) = NULL; od->od_state++; } /* If someone calls PyDict_DelItem() directly on an OrderedDict, we'll get all sorts of problems here. In PyODict_DelItem we make sure to call _odict_clear_node first. This matters in the case of colliding keys. Suppose we add 3 keys: [A, B, C], where the hash of C collides with A and the next possible index in the hash table is occupied by B. If we remove B then for C the dict's looknode func will give us the old index of B instead of the index we got before deleting B. However, the node for C in od_fast_nodes is still at the old dict index of C. Thus to be sure things don't get out of sync, we clear the node in od_fast_nodes *before* calling PyDict_DelItem. The same must be done for any other OrderedDict operations where we modify od_fast_nodes. */ static int _odict_clear_node(PyODictObject *od, _ODictNode *node, PyObject *key, Py_hash_t hash) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od); Py_ssize_t i; assert(key != NULL); if (_odict_EMPTY(od)) { /* Let later code decide if this is a KeyError. */ return 0; } i = _odict_get_index(od, key, hash); if (i < 0) return PyErr_Occurred() ? -1 : 0; assert(od->od_fast_nodes != NULL); if (node == NULL) node = od->od_fast_nodes[i]; assert(node == od->od_fast_nodes[i]); if (node == NULL) { /* Let later code decide if this is a KeyError. */ return 0; } // Now clear the node. od->od_fast_nodes[i] = NULL; _odict_remove_node(od, node); _odictnode_DEALLOC(node); return 0; } static void _odict_clear_nodes(PyODictObject *od) { _ODictNode *node, *next; PyMem_Free(od->od_fast_nodes); od->od_fast_nodes = NULL; od->od_fast_nodes_size = 0; od->od_resize_sentinel = NULL; node = _odict_FIRST(od); _odict_FIRST(od) = NULL; _odict_LAST(od) = NULL; while (node != NULL) { next = _odictnode_NEXT(node); _odictnode_DEALLOC(node); node = next; } od->od_state++; } /* There isn't any memory management of nodes past this point. */ #undef _odictnode_DEALLOC static int _odict_keys_equal(PyODictObject *a, PyODictObject *b) { _ODictNode *node_a, *node_b; // keep operands' state to detect undesired mutations const size_t state_a = a->od_state; const size_t state_b = b->od_state; node_a = _odict_FIRST(a); node_b = _odict_FIRST(b); while (1) { if (node_a == NULL && node_b == NULL) { /* success: hit the end of each at the same time */ return 1; } else if (node_a == NULL || node_b == NULL) { /* unequal length */ return 0; } else { PyObject *key_a = Py_NewRef(_odictnode_KEY(node_a)); PyObject *key_b = Py_NewRef(_odictnode_KEY(node_b)); int res = PyObject_RichCompareBool(key_a, key_b, Py_EQ); Py_DECREF(key_a); Py_DECREF(key_b); if (res < 0) { return res; } else if (a->od_state != state_a || b->od_state != state_b) { PyErr_SetString(PyExc_RuntimeError, "OrderedDict mutated during iteration"); return -1; } else if (res == 0) { // This check comes after the check on the state // in order for the exception to be set correctly. return 0; } /* otherwise it must match, so move on to the next one */ node_a = _odictnode_NEXT(node_a); node_b = _odictnode_NEXT(node_b); } } } /* ---------------------------------------------- * OrderedDict mapping methods */ /* mp_ass_subscript: __setitem__() and __delitem__() */ static int odict_mp_ass_sub(PyObject *od, PyObject *v, PyObject *w) { if (w == NULL) return PyODict_DelItem(od, v); else return PyODict_SetItem(od, v, w); } /* tp_as_mapping */ static PyMappingMethods odict_as_mapping = { 0, /*mp_length*/ 0, /*mp_subscript*/ odict_mp_ass_sub, /*mp_ass_subscript*/ }; /* ---------------------------------------------- * OrderedDict number methods */ static int mutablemapping_update_arg(PyObject*, PyObject*); static PyObject * odict_or(PyObject *left, PyObject *right) { PyTypeObject *type; PyObject *other; if (PyODict_Check(left)) { type = Py_TYPE(left); other = right; } else { type = Py_TYPE(right); other = left; } if (!PyDict_Check(other)) { Py_RETURN_NOTIMPLEMENTED; } PyObject *new = PyObject_CallOneArg((PyObject*)type, left); if (!new) { return NULL; } if (mutablemapping_update_arg(new, right) < 0) { Py_DECREF(new); return NULL; } return new; } static PyObject * odict_inplace_or(PyObject *self, PyObject *other) { if (mutablemapping_update_arg(self, other) < 0) { return NULL; } return Py_NewRef(self); } /* tp_as_number */ static PyNumberMethods odict_as_number = { .nb_or = odict_or, .nb_inplace_or = odict_inplace_or, }; /* ---------------------------------------------- * OrderedDict methods */ /* fromkeys() */ /*[clinic input] @permit_long_summary @classmethod OrderedDict.fromkeys iterable as seq: object value: object = None Create a new ordered dictionary with keys from iterable and values set to value. [clinic start generated code]*/ static PyObject * OrderedDict_fromkeys_impl(PyTypeObject *type, PyObject *seq, PyObject *value) /*[clinic end generated code: output=c10390d452d78d6d input=1277ae0769083848]*/ { return _PyDict_FromKeys((PyObject *)type, seq, value); } /*[clinic input] @critical_section OrderedDict.__sizeof__ -> Py_ssize_t [clinic start generated code]*/ static Py_ssize_t OrderedDict___sizeof___impl(PyODictObject *self) /*[clinic end generated code: output=1a8560db8cf83ac5 input=655e989ae24daa6a]*/ { Py_ssize_t res = _PyDict_SizeOf_LockHeld((PyDictObject *)self); res += sizeof(_ODictNode *) * self->od_fast_nodes_size; /* od_fast_nodes */ if (!_odict_EMPTY(self)) { res += sizeof(_ODictNode) * PyODict_SIZE(self); /* linked-list */ } return res; } /*[clinic input] OrderedDict.__reduce__ self as od: self(type="PyODictObject *") Return state information for pickling [clinic start generated code]*/ static PyObject * OrderedDict___reduce___impl(PyODictObject *od) /*[clinic end generated code: output=71eeb81f760a6a8e input=b0467c7ec400fe5e]*/ { PyObject *state, *result = NULL; PyObject *items_iter, *items, *args = NULL; /* capture any instance state */ state = _PyObject_GetState((PyObject *)od); if (state == NULL) goto Done; /* build the result */ args = PyTuple_New(0); if (args == NULL) goto Done; items = PyObject_CallMethodNoArgs((PyObject *)od, &_Py_ID(items)); if (items == NULL) goto Done; items_iter = PyObject_GetIter(items); Py_DECREF(items); if (items_iter == NULL) goto Done; result = PyTuple_Pack(5, Py_TYPE(od), args, state, Py_None, items_iter); Py_DECREF(items_iter); Done: Py_XDECREF(state); Py_XDECREF(args); return result; } /* setdefault(): Skips __missing__() calls. */ static int PyODict_SetItem_LockHeld(PyObject *self, PyObject *key, PyObject *value); /*[clinic input] @critical_section OrderedDict.setdefault key: object default: object = None Insert key with a value of default if key is not in the dictionary. Return the value for key if key is in the dictionary, else default. [clinic start generated code]*/ static PyObject * OrderedDict_setdefault_impl(PyODictObject *self, PyObject *key, PyObject *default_value) /*[clinic end generated code: output=97537cb7c28464b6 input=d7b93e92734f99b5]*/ { PyObject *result = NULL; if (PyODict_CheckExact(self)) { result = PyODict_GetItemWithError(self, key); /* borrowed */ if (result == NULL) { if (PyErr_Occurred()) return NULL; assert(_odict_find_node(self, key) == NULL); if (PyODict_SetItem_LockHeld((PyObject *)self, key, default_value) >= 0) { result = Py_NewRef(default_value); } } else { Py_INCREF(result); } } else { int exists = PySequence_Contains((PyObject *)self, key); if (exists < 0) { return NULL; } else if (exists) { result = PyObject_GetItem((PyObject *)self, key); } else if (PyObject_SetItem((PyObject *)self, key, default_value) >= 0) { result = Py_NewRef(default_value); } } return result; } /* pop() */ static PyObject * _odict_popkey_hash(PyObject *od, PyObject *key, PyObject *failobj, Py_hash_t hash) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od); PyObject *value = NULL; _ODictNode *node = _odict_find_node_hash(_PyODictObject_CAST(od), key, hash); if (node != NULL) { /* Pop the node first to avoid a possible dict resize (due to eval loop reentrancy) and complications due to hash collision resolution. */ int res = _odict_clear_node(_PyODictObject_CAST(od), node, key, hash); if (res < 0) { goto done; } /* Now delete the value from the dict. */ if (_PyDict_Pop_KnownHash((PyDictObject *)od, key, hash, &value) == 0) { value = Py_NewRef(failobj); } } else if (value == NULL && !PyErr_Occurred()) { /* Apply the fallback value, if necessary. */ if (failobj) { value = Py_NewRef(failobj); } else { PyErr_SetObject(PyExc_KeyError, key); } } done: return value; } /* Skips __missing__() calls. */ /*[clinic input] @critical_section @permit_long_summary OrderedDict.pop key: object default: object = NULL od.pop(key[,default]) -> v, remove specified key and return the corresponding value. If the key is not found, return the default if given; otherwise, raise a KeyError. [clinic start generated code]*/ static PyObject * OrderedDict_pop_impl(PyODictObject *self, PyObject *key, PyObject *default_value) /*[clinic end generated code: output=7a6447d104e7494b input=0742e3c9bf076a72]*/ { Py_hash_t hash = PyObject_Hash(key); if (hash == -1) return NULL; return _odict_popkey_hash((PyObject *)self, key, default_value, hash); } /* popitem() */ /*[clinic input] @critical_section OrderedDict.popitem last: bool = True Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order if last is true or FIFO order if false. [clinic start generated code]*/ static PyObject * OrderedDict_popitem_impl(PyODictObject *self, int last) /*[clinic end generated code: output=98e7d986690d49eb input=8aafc7433e0a40e7]*/ { PyObject *key, *value, *item = NULL; _ODictNode *node; /* pull the item */ if (_odict_EMPTY(self)) { PyErr_SetString(PyExc_KeyError, "dictionary is empty"); return NULL; } node = last ? _odict_LAST(self) : _odict_FIRST(self); key = Py_NewRef(_odictnode_KEY(node)); value = _odict_popkey_hash((PyObject *)self, key, NULL, _odictnode_HASH(node)); if (value == NULL) return NULL; item = PyTuple_Pack(2, key, value); Py_DECREF(key); Py_DECREF(value); return item; } /* keys() */ /* MutableMapping.keys() does not have a docstring. */ PyDoc_STRVAR(odict_keys__doc__, ""); static PyObject * odictkeys_new(PyObject *od, PyObject *Py_UNUSED(ignored)); /* forward */ static int _PyODict_SetItem_KnownHash_LockHeld(PyObject *od, PyObject *key, PyObject *value, Py_hash_t hash); /* forward */ /* values() */ /* MutableMapping.values() does not have a docstring. */ PyDoc_STRVAR(odict_values__doc__, ""); static PyObject * odictvalues_new(PyObject *od, PyObject *Py_UNUSED(ignored)); /* forward */ /* items() */ /* MutableMapping.items() does not have a docstring. */ PyDoc_STRVAR(odict_items__doc__, ""); static PyObject * odictitems_new(PyObject *od, PyObject *Py_UNUSED(ignored)); /* forward */ /* update() */ /* MutableMapping.update() does not have a docstring. */ PyDoc_STRVAR(odict_update__doc__, ""); /* forward */ static PyObject * mutablemapping_update(PyObject *, PyObject *, PyObject *); #define odict_update mutablemapping_update /*[clinic input] @critical_section OrderedDict.clear Remove all items from ordered dict. [clinic start generated code]*/ static PyObject * OrderedDict_clear_impl(PyODictObject *self) /*[clinic end generated code: output=a1a76d1322f556c5 input=08b12322e74c535c]*/ { _PyDict_Clear_LockHeld((PyObject *)self); _odict_clear_nodes(self); Py_RETURN_NONE; } /* copy() */ /*[clinic input] @critical_section OrderedDict.copy self as od: self A shallow copy of ordered dict. [clinic start generated code]*/ static PyObject * OrderedDict_copy_impl(PyObject *od) /*[clinic end generated code: output=9cdbe7394aecc576 input=e329951ae617ed48]*/ { _ODictNode *node; PyObject *od_copy; if (PyODict_CheckExact(od)) od_copy = PyODict_New(); else od_copy = _PyObject_CallNoArgs((PyObject *)Py_TYPE(od)); if (od_copy == NULL) return NULL; if (PyODict_CheckExact(od)) { _odict_FOREACH(od, node) { PyObject *key = _odictnode_KEY(node); PyObject *value = _odictnode_VALUE(node, od); if (value == NULL) { if (!PyErr_Occurred()) PyErr_SetObject(PyExc_KeyError, key); goto fail; } if (_PyODict_SetItem_KnownHash_LockHeld((PyObject *)od_copy, key, value, _odictnode_HASH(node)) != 0) goto fail; } } else { _odict_FOREACH(od, node) { int res; PyObject *value = PyObject_GetItem((PyObject *)od, _odictnode_KEY(node)); if (value == NULL) goto fail; res = PyObject_SetItem((PyObject *)od_copy, _odictnode_KEY(node), value); Py_DECREF(value); if (res != 0) goto fail; } } return od_copy; fail: Py_DECREF(od_copy); return NULL; } /* __reversed__() */ PyDoc_STRVAR(odict_reversed__doc__, "od.__reversed__() <==> reversed(od)"); #define _odict_ITER_REVERSED 1 #define _odict_ITER_KEYS 2 #define _odict_ITER_VALUES 4 #define _odict_ITER_ITEMS (_odict_ITER_KEYS|_odict_ITER_VALUES) /* forward */ static PyObject * odictiter_new(PyODictObject *, int); static PyObject * odict_reversed(PyObject *op, PyObject *Py_UNUSED(ignored)) { PyODictObject *od = _PyODictObject_CAST(op); return odictiter_new(od, _odict_ITER_KEYS|_odict_ITER_REVERSED); } /* move_to_end() */ /*[clinic input] @critical_section OrderedDict.move_to_end key: object last: bool = True Move an existing element to the end (or beginning if last is false). Raise KeyError if the element does not exist. [clinic start generated code]*/ static PyObject * OrderedDict_move_to_end_impl(PyODictObject *self, PyObject *key, int last) /*[clinic end generated code: output=fafa4c5cc9b92f20 input=09f8bc7053c0f6d4]*/ { _ODictNode *node; if (_odict_EMPTY(self)) { PyErr_SetObject(PyExc_KeyError, key); return NULL; } node = last ? _odict_LAST(self) : _odict_FIRST(self); if (key != _odictnode_KEY(node)) { node = _odict_find_node(self, key); if (node == NULL) { if (!PyErr_Occurred()) PyErr_SetObject(PyExc_KeyError, key); return NULL; } if (last) { /* Only move if not already the last one. */ if (node != _odict_LAST(self)) { _odict_remove_node(self, node); _odict_add_tail(self, node); } } else { /* Only move if not already the first one. */ if (node != _odict_FIRST(self)) { _odict_remove_node(self, node); _odict_add_head(self, node); } } } Py_RETURN_NONE; } /* tp_methods */ static PyMethodDef odict_methods[] = { /* overridden dict methods */ ORDEREDDICT_FROMKEYS_METHODDEF ORDEREDDICT___SIZEOF___METHODDEF ORDEREDDICT___REDUCE___METHODDEF ORDEREDDICT_SETDEFAULT_METHODDEF ORDEREDDICT_POP_METHODDEF ORDEREDDICT_POPITEM_METHODDEF {"keys", odictkeys_new, METH_NOARGS, odict_keys__doc__}, {"values", odictvalues_new, METH_NOARGS, odict_values__doc__}, {"items", odictitems_new, METH_NOARGS, odict_items__doc__}, {"update", _PyCFunction_CAST(odict_update), METH_VARARGS | METH_KEYWORDS, odict_update__doc__}, ORDEREDDICT_CLEAR_METHODDEF ORDEREDDICT_COPY_METHODDEF /* new methods */ {"__reversed__", odict_reversed, METH_NOARGS, odict_reversed__doc__}, ORDEREDDICT_MOVE_TO_END_METHODDEF {NULL, NULL} /* sentinel */ }; /* ---------------------------------------------- * OrderedDict members */ /* tp_getset */ static PyGetSetDef odict_getset[] = { {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict}, {NULL} }; /* ---------------------------------------------- * OrderedDict type slot methods */ /* tp_dealloc */ static void odict_dealloc(PyObject *op) { PyODictObject *self = _PyODictObject_CAST(op); PyObject_GC_UnTrack(self); Py_XDECREF(self->od_inst_dict); FT_CLEAR_WEAKREFS(op, self->od_weakreflist); _odict_clear_nodes(self); PyDict_Type.tp_dealloc((PyObject *)self); } /* tp_repr */ static PyObject * odict_repr(PyObject *op) { PyODictObject *self = _PyODictObject_CAST(op); int i; PyObject *result = NULL, *dcopy = NULL; if (PyODict_SIZE(self) == 0) return PyUnicode_FromFormat("%s()", _PyType_Name(Py_TYPE(self))); i = Py_ReprEnter((PyObject *)self); if (i != 0) { return i > 0 ? PyUnicode_FromString("...") : NULL; } dcopy = PyDict_Copy((PyObject *)self); if (dcopy == NULL) { goto Done; } result = PyUnicode_FromFormat("%s(%R)", _PyType_Name(Py_TYPE(self)), dcopy); Py_DECREF(dcopy); Done: Py_ReprLeave((PyObject *)self); return result; } /* tp_doc */ PyDoc_STRVAR(odict_doc, "Dictionary that remembers insertion order"); /* tp_traverse */ static int odict_traverse(PyObject *op, visitproc visit, void *arg) { PyODictObject *od = _PyODictObject_CAST(op); _ODictNode *node; Py_VISIT(od->od_inst_dict); _odict_FOREACH(od, node) { Py_VISIT(_odictnode_KEY(node)); } return PyDict_Type.tp_traverse((PyObject *)od, visit, arg); } /* tp_clear */ static int odict_tp_clear(PyObject *op) { PyODictObject *od = _PyODictObject_CAST(op); Py_CLEAR(od->od_inst_dict); // cannot use lock held variant as critical section is not held here PyDict_Clear(op); _odict_clear_nodes(od); return 0; } /* tp_richcompare */ static PyObject * odict_richcompare_lock_held(PyObject *v, PyObject *w, int op) { if (!PyODict_Check(v) || !PyDict_Check(w)) { Py_RETURN_NOTIMPLEMENTED; } if (op == Py_EQ || op == Py_NE) { PyObject *res, *cmp; int eq; cmp = PyDict_Type.tp_richcompare(v, w, op); if (cmp == NULL) return NULL; if (!PyODict_Check(w)) return cmp; if (op == Py_EQ && cmp == Py_False) return cmp; if (op == Py_NE && cmp == Py_True) return cmp; Py_DECREF(cmp); /* Try comparing odict keys. */ eq = _odict_keys_equal(_PyODictObject_CAST(v), _PyODictObject_CAST(w)); if (eq < 0) return NULL; res = (eq == (op == Py_EQ)) ? Py_True : Py_False; return Py_NewRef(res); } else { Py_RETURN_NOTIMPLEMENTED; } } static PyObject * odict_richcompare(PyObject *v, PyObject *w, int op) { PyObject *res; Py_BEGIN_CRITICAL_SECTION2(v, w); res = odict_richcompare_lock_held(v, w, op); Py_END_CRITICAL_SECTION2(); return res; } /* tp_iter */ static PyObject * odict_iter(PyObject *op) { return odictiter_new(_PyODictObject_CAST(op), _odict_ITER_KEYS); } /* tp_init */ static int odict_init(PyObject *self, PyObject *args, PyObject *kwds) { PyObject *res; Py_ssize_t len = PyObject_Length(args); if (len == -1) return -1; if (len > 1) { const char *msg = "expected at most 1 argument, got %zd"; PyErr_Format(PyExc_TypeError, msg, len); return -1; } /* __init__() triggering update() is just the way things are! */ res = odict_update(self, args, kwds); if (res == NULL) { return -1; } else { Py_DECREF(res); return 0; } } /* PyODict_Type */ PyTypeObject PyODict_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "collections.OrderedDict", /* tp_name */ sizeof(PyODictObject), /* tp_basicsize */ 0, /* tp_itemsize */ odict_dealloc, /* tp_dealloc */ 0, /* tp_vectorcall_offset */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ odict_repr, /* tp_repr */ &odict_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ &odict_as_mapping, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,/* tp_flags */ odict_doc, /* tp_doc */ odict_traverse, /* tp_traverse */ odict_tp_clear, /* tp_clear */ odict_richcompare, /* tp_richcompare */ offsetof(PyODictObject, od_weakreflist), /* tp_weaklistoffset */ odict_iter, /* tp_iter */ 0, /* tp_iternext */ odict_methods, /* tp_methods */ 0, /* tp_members */ odict_getset, /* tp_getset */ &PyDict_Type, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(PyODictObject, od_inst_dict), /* tp_dictoffset */ odict_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ }; /* ---------------------------------------------- * the public OrderedDict API */ PyObject * PyODict_New(void) { return PyDict_Type.tp_new(&PyODict_Type, NULL, NULL); } static int _PyODict_SetItem_KnownHash_LockHeld(PyObject *od, PyObject *key, PyObject *value, Py_hash_t hash) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od); int res = _PyDict_SetItem_KnownHash_LockHeld((PyDictObject *)od, key, value, hash); if (res == 0) { res = _odict_add_new_node(_PyODictObject_CAST(od), key, hash); if (res < 0) { /* Revert setting the value on the dict */ PyObject *exc = PyErr_GetRaisedException(); (void) _PyDict_DelItem_KnownHash(od, key, hash); _PyErr_ChainExceptions1(exc); } } return res; } static int PyODict_SetItem_LockHeld(PyObject *od, PyObject *key, PyObject *value) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od); Py_hash_t hash = PyObject_Hash(key); if (hash == -1) { return -1; } return _PyODict_SetItem_KnownHash_LockHeld(od, key, value, hash); } int PyODict_SetItem(PyObject *od, PyObject *key, PyObject *value) { int res; Py_BEGIN_CRITICAL_SECTION(od); res = PyODict_SetItem_LockHeld(od, key, value); Py_END_CRITICAL_SECTION(); return res; } int PyODict_DelItem_LockHeld(PyObject *od, PyObject *key) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od); int res; Py_hash_t hash = PyObject_Hash(key); if (hash == -1) return -1; res = _odict_clear_node(_PyODictObject_CAST(od), NULL, key, hash); if (res < 0) return -1; return _PyDict_DelItem_KnownHash_LockHeld(od, key, hash); } int PyODict_DelItem(PyObject *od, PyObject *key) { int res; Py_BEGIN_CRITICAL_SECTION(od); res = PyODict_DelItem_LockHeld(od, key); Py_END_CRITICAL_SECTION(); return res; } /* ------------------------------------------- * The OrderedDict views (keys/values/items) */ typedef struct { PyObject_HEAD int kind; PyODictObject *di_odict; Py_ssize_t di_size; size_t di_state; PyObject *di_current; PyObject *di_result; /* reusable result tuple for iteritems */ } odictiterobject; static void odictiter_dealloc(PyObject *op) { odictiterobject *di = (odictiterobject*)op; _PyObject_GC_UNTRACK(di); Py_XDECREF(di->di_odict); Py_XDECREF(di->di_current); if ((di->kind & _odict_ITER_ITEMS) == _odict_ITER_ITEMS) { Py_DECREF(di->di_result); } PyObject_GC_Del(di); } static int odictiter_traverse(PyObject *op, visitproc visit, void *arg) { odictiterobject *di = (odictiterobject*)op; Py_VISIT(di->di_odict); Py_VISIT(di->di_current); /* A key could be any type, not just str. */ Py_VISIT(di->di_result); return 0; } /* In order to protect against modifications during iteration, we track * the current key instead of the current node. */ static PyObject * odictiter_nextkey_lock_held(odictiterobject *di) { assert(di->di_odict != NULL); _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(di->di_odict); PyObject *key = NULL; _ODictNode *node; int reversed = di->kind & _odict_ITER_REVERSED; if (di->di_current == NULL) goto done; /* We're already done. */ /* Check for unsupported changes. */ if (di->di_odict->od_state != di->di_state) { PyErr_SetString(PyExc_RuntimeError, "OrderedDict mutated during iteration"); goto done; } if (di->di_size != PyODict_SIZE(di->di_odict)) { PyErr_SetString(PyExc_RuntimeError, "OrderedDict changed size during iteration"); di->di_size = -1; /* Make this state sticky */ return NULL; } /* Get the key. */ node = _odict_find_node(di->di_odict, di->di_current); if (node == NULL) { if (!PyErr_Occurred()) PyErr_SetObject(PyExc_KeyError, di->di_current); /* Must have been deleted. */ Py_CLEAR(di->di_current); return NULL; } key = di->di_current; /* Advance to the next key. */ node = reversed ? _odictnode_PREV(node) : _odictnode_NEXT(node); if (node == NULL) { /* Reached the end. */ di->di_current = NULL; } else { di->di_current = Py_NewRef(_odictnode_KEY(node)); } return key; done: Py_CLEAR(di->di_odict); return key; } static PyObject * odictiter_nextkey(odictiterobject *di) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(di); if (di->di_odict == NULL) { return NULL; } PyObject *res; Py_BEGIN_CRITICAL_SECTION(di->di_odict); res = odictiter_nextkey_lock_held(di); Py_END_CRITICAL_SECTION(); return res; } static PyObject * odictiter_iternext_lock_held(PyObject *op) { odictiterobject *di = (odictiterobject*)op; PyObject *result, *value; PyObject *key = odictiter_nextkey(di); /* new reference */ if (key == NULL) return NULL; /* Handle the keys case. */ if (! (di->kind & _odict_ITER_VALUES)) { return key; } if (PyDict_GetItemRef((PyObject *)di->di_odict, key, &value) != 1) { if (!PyErr_Occurred()) PyErr_SetObject(PyExc_KeyError, key); Py_DECREF(key); goto done; } /* Handle the values case. */ if (!(di->kind & _odict_ITER_KEYS)) { Py_DECREF(key); return value; } /* Handle the items case. */ result = di->di_result; if (_PyObject_IsUniquelyReferenced(result)) { /* not in use so we can reuse it * (the common case during iteration) */ Py_INCREF(result); Py_DECREF(PyTuple_GET_ITEM(result, 0)); /* borrowed */ Py_DECREF(PyTuple_GET_ITEM(result, 1)); /* borrowed */ // bpo-42536: The GC may have untracked this result tuple. Since we're // recycling it, make sure it's tracked again: _PyTuple_Recycle(result); } else { result = PyTuple_New(2); if (result == NULL) { Py_DECREF(key); Py_DECREF(value); goto done; } } PyTuple_SET_ITEM(result, 0, key); /* steals reference */ PyTuple_SET_ITEM(result, 1, value); /* steals reference */ return result; done: Py_CLEAR(di->di_current); Py_CLEAR(di->di_odict); return NULL; } static PyObject * odictiter_iternext(PyObject *op) { PyObject *res; Py_BEGIN_CRITICAL_SECTION(op); res = odictiter_iternext_lock_held(op); Py_END_CRITICAL_SECTION(); return res; } /* No need for tp_clear because odictiterobject is not mutable. */ PyDoc_STRVAR(reduce_doc, "Return state information for pickling"); static PyObject * odictiter_reduce(PyObject *op, PyObject *Py_UNUSED(ignored)) { odictiterobject *di = (odictiterobject*)op; /* copy the iterator state */ odictiterobject tmp = *di; Py_XINCREF(tmp.di_odict); Py_XINCREF(tmp.di_current); /* iterate the temporary into a list */ PyObject *list = PySequence_List((PyObject*)&tmp); Py_XDECREF(tmp.di_odict); Py_XDECREF(tmp.di_current); if (list == NULL) { return NULL; } return Py_BuildValue("N(N)", _PyEval_GetBuiltin(&_Py_ID(iter)), list); } static PyMethodDef odictiter_methods[] = { {"__reduce__", odictiter_reduce, METH_NOARGS, reduce_doc}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyODictIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "odict_iterator", /* tp_name */ sizeof(odictiterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ odictiter_dealloc, /* tp_dealloc */ 0, /* tp_vectorcall_offset */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ odictiter_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ odictiter_iternext, /* tp_iternext */ odictiter_methods, /* tp_methods */ 0, }; static PyObject * odictiter_new(PyODictObject *od, int kind) { odictiterobject *di; _ODictNode *node; int reversed = kind & _odict_ITER_REVERSED; di = PyObject_GC_New(odictiterobject, &PyODictIter_Type); if (di == NULL) return NULL; if ((kind & _odict_ITER_ITEMS) == _odict_ITER_ITEMS) { di->di_result = PyTuple_Pack(2, Py_None, Py_None); if (di->di_result == NULL) { Py_DECREF(di); return NULL; } } else { di->di_result = NULL; } di->kind = kind; node = reversed ? _odict_LAST(od) : _odict_FIRST(od); di->di_current = node ? Py_NewRef(_odictnode_KEY(node)) : NULL; di->di_size = PyODict_SIZE(od); di->di_state = od->od_state; di->di_odict = (PyODictObject*)Py_NewRef(od); _PyObject_GC_TRACK(di); return (PyObject *)di; } /* keys() */ static PyObject * odictkeys_iter(PyObject *op) { _PyDictViewObject *dv = (_PyDictViewObject*)op; if (dv->dv_dict == NULL) { Py_RETURN_NONE; } return odictiter_new(_PyODictObject_CAST(dv->dv_dict), _odict_ITER_KEYS); } static PyObject * odictkeys_reversed(PyObject *op, PyObject *Py_UNUSED(ignored)) { _PyDictViewObject *dv = (_PyDictViewObject*)op; if (dv->dv_dict == NULL) { Py_RETURN_NONE; } return odictiter_new(_PyODictObject_CAST(dv->dv_dict), _odict_ITER_KEYS|_odict_ITER_REVERSED); } static PyMethodDef odictkeys_methods[] = { {"__reversed__", odictkeys_reversed, METH_NOARGS, NULL}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyODictKeys_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "odict_keys", /* tp_name */ 0, /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_vectorcall_offset */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ odictkeys_iter, /* tp_iter */ 0, /* tp_iternext */ odictkeys_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ &PyDictKeys_Type, /* tp_base */ }; static PyObject * odictkeys_new(PyObject *od, PyObject *Py_UNUSED(ignored)) { return _PyDictView_New(od, &PyODictKeys_Type); } /* items() */ static PyObject * odictitems_iter(PyObject *op) { _PyDictViewObject *dv = (_PyDictViewObject*)op; if (dv->dv_dict == NULL) { Py_RETURN_NONE; } return odictiter_new(_PyODictObject_CAST(dv->dv_dict), _odict_ITER_KEYS|_odict_ITER_VALUES); } static PyObject * odictitems_reversed(PyObject *op, PyObject *Py_UNUSED(ignored)) { _PyDictViewObject *dv = (_PyDictViewObject*)op; if (dv->dv_dict == NULL) { Py_RETURN_NONE; } return odictiter_new(_PyODictObject_CAST(dv->dv_dict), _odict_ITER_KEYS|_odict_ITER_VALUES|_odict_ITER_REVERSED); } static PyMethodDef odictitems_methods[] = { {"__reversed__", odictitems_reversed, METH_NOARGS, NULL}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyODictItems_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "odict_items", /* tp_name */ 0, /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_vectorcall_offset */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ odictitems_iter, /* tp_iter */ 0, /* tp_iternext */ odictitems_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ &PyDictItems_Type, /* tp_base */ }; static PyObject * odictitems_new(PyObject *od, PyObject *Py_UNUSED(ignored)) { return _PyDictView_New(od, &PyODictItems_Type); } /* values() */ static PyObject * odictvalues_iter(PyObject *op) { _PyDictViewObject *dv = (_PyDictViewObject*)op; if (dv->dv_dict == NULL) { Py_RETURN_NONE; } return odictiter_new(_PyODictObject_CAST(dv->dv_dict), _odict_ITER_VALUES); } static PyObject * odictvalues_reversed(PyObject *op, PyObject *Py_UNUSED(ignored)) { _PyDictViewObject *dv = (_PyDictViewObject*)op; if (dv->dv_dict == NULL) { Py_RETURN_NONE; } return odictiter_new(_PyODictObject_CAST(dv->dv_dict), _odict_ITER_VALUES|_odict_ITER_REVERSED); } static PyMethodDef odictvalues_methods[] = { {"__reversed__", odictvalues_reversed, METH_NOARGS, NULL}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyODictValues_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "odict_values", /* tp_name */ 0, /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_vectorcall_offset */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ odictvalues_iter, /* tp_iter */ 0, /* tp_iternext */ odictvalues_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ &PyDictValues_Type, /* tp_base */ }; static PyObject * odictvalues_new(PyObject *od, PyObject *Py_UNUSED(ignored)) { return _PyDictView_New(od, &PyODictValues_Type); } /* ---------------------------------------------- MutableMapping implementations Mapping: ============ =========== method uses ============ =========== __contains__ __getitem__ __eq__ items __getitem__ + __iter__ + __len__ + __ne__ __eq__ get __getitem__ items ItemsView keys KeysView values ValuesView ============ =========== ItemsView uses __len__, __iter__, and __getitem__. KeysView uses __len__, __iter__, and __contains__. ValuesView uses __len__, __iter__, and __getitem__. MutableMapping: ============ =========== method uses ============ =========== __delitem__ + __setitem__ + clear popitem pop __getitem__ __delitem__ popitem __iter__ _getitem__ __delitem__ setdefault __getitem__ __setitem__ update __setitem__ ============ =========== */ static int mutablemapping_add_pairs(PyObject *self, PyObject *pairs) { PyObject *pair, *iterator, *unexpected; int res = 0; iterator = PyObject_GetIter(pairs); if (iterator == NULL) return -1; PyErr_Clear(); while ((pair = PyIter_Next(iterator)) != NULL) { /* could be more efficient (see UNPACK_SEQUENCE in ceval.c) */ PyObject *key = NULL, *value = NULL; PyObject *pair_iterator = PyObject_GetIter(pair); if (pair_iterator == NULL) goto Done; key = PyIter_Next(pair_iterator); if (key == NULL) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_ValueError, "need more than 0 values to unpack"); goto Done; } value = PyIter_Next(pair_iterator); if (value == NULL) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_ValueError, "need more than 1 value to unpack"); goto Done; } unexpected = PyIter_Next(pair_iterator); if (unexpected != NULL) { Py_DECREF(unexpected); PyErr_SetString(PyExc_ValueError, "too many values to unpack (expected 2)"); goto Done; } else if (PyErr_Occurred()) goto Done; res = PyObject_SetItem(self, key, value); Done: Py_DECREF(pair); Py_XDECREF(pair_iterator); Py_XDECREF(key); Py_XDECREF(value); if (PyErr_Occurred()) break; } Py_DECREF(iterator); if (res < 0 || PyErr_Occurred() != NULL) return -1; else return 0; } static int mutablemapping_update_arg(PyObject *self, PyObject *arg) { int res = 0; if (PyDict_CheckExact(arg)) { PyObject *items = PyDict_Items(arg); if (items == NULL) { return -1; } res = mutablemapping_add_pairs(self, items); Py_DECREF(items); return res; } PyObject *func; if (PyObject_GetOptionalAttr(arg, &_Py_ID(keys), &func) < 0) { return -1; } if (func != NULL) { PyObject *keys = _PyObject_CallNoArgs(func); Py_DECREF(func); if (keys == NULL) { return -1; } PyObject *iterator = PyObject_GetIter(keys); Py_DECREF(keys); if (iterator == NULL) { return -1; } PyObject *key; while (res == 0 && (key = PyIter_Next(iterator))) { PyObject *value = PyObject_GetItem(arg, key); if (value != NULL) { res = PyObject_SetItem(self, key, value); Py_DECREF(value); } else { res = -1; } Py_DECREF(key); } Py_DECREF(iterator); if (res != 0 || PyErr_Occurred()) { return -1; } return 0; } if (PyObject_GetOptionalAttr(arg, &_Py_ID(items), &func) < 0) { return -1; } if (func != NULL) { PyObject *items = _PyObject_CallNoArgs(func); Py_DECREF(func); if (items == NULL) { return -1; } res = mutablemapping_add_pairs(self, items); Py_DECREF(items); return res; } res = mutablemapping_add_pairs(self, arg); return res; } static PyObject * mutablemapping_update(PyObject *self, PyObject *args, PyObject *kwargs) { int res; /* first handle args, if any */ assert(args == NULL || PyTuple_Check(args)); Py_ssize_t len = (args != NULL) ? PyTuple_GET_SIZE(args) : 0; if (len > 1) { const char *msg = "update() takes at most 1 positional argument (%zd given)"; PyErr_Format(PyExc_TypeError, msg, len); return NULL; } if (len) { PyObject *other = PyTuple_GET_ITEM(args, 0); /* borrowed reference */ assert(other != NULL); Py_INCREF(other); res = mutablemapping_update_arg(self, other); Py_DECREF(other); if (res < 0) { return NULL; } } /* now handle kwargs */ assert(kwargs == NULL || PyDict_Check(kwargs)); if (kwargs != NULL && PyDict_GET_SIZE(kwargs)) { PyObject *items = PyDict_Items(kwargs); if (items == NULL) return NULL; res = mutablemapping_add_pairs(self, items); Py_DECREF(items); if (res == -1) return NULL; } Py_RETURN_NONE; } /* implements the unicode (as opposed to string) version of the built-in formatters for string, int, float. that is, the versions of int.__float__, etc., that take and return unicode objects */ #include "Python.h" #include "pycore_fileutils.h" // _Py_GetLocaleconvNumeric() #include "pycore_long.h" // _PyLong_FormatWriter() #include "pycore_unicodeobject.h" // PyUnicode_MAX_CHAR_VALUE() #include /* _PyUnicode_InsertThousandsGrouping() helper functions */ typedef struct { const char *grouping; char previous; Py_ssize_t i; /* Where we're currently pointing in grouping. */ } GroupGenerator; static void GroupGenerator_init(GroupGenerator *self, const char *grouping) { self->grouping = grouping; self->i = 0; self->previous = 0; } /* Returns the next grouping, or 0 to signify end. */ static Py_ssize_t GroupGenerator_next(GroupGenerator *self) { /* Note that we don't really do much error checking here. If a grouping string contains just CHAR_MAX, for example, then just terminate the generator. That shouldn't happen, but at least we fail gracefully. */ switch (self->grouping[self->i]) { case 0: return self->previous; case CHAR_MAX: /* Stop the generator. */ return 0; default: { char ch = self->grouping[self->i]; self->previous = ch; self->i++; return (Py_ssize_t)ch; } } } /* Fill in some digits, leading zeros, and thousands separator. All are optional, depending on when we're called. */ static void InsertThousandsGrouping_fill(_PyUnicodeWriter *writer, Py_ssize_t *buffer_pos, PyObject *digits, Py_ssize_t *digits_pos, Py_ssize_t n_chars, Py_ssize_t n_zeros, PyObject *thousands_sep, Py_ssize_t thousands_sep_len, Py_UCS4 *maxchar, int forward) { if (!writer) { /* if maxchar > 127, maxchar is already set */ if (*maxchar == 127 && thousands_sep) { Py_UCS4 maxchar2 = PyUnicode_MAX_CHAR_VALUE(thousands_sep); *maxchar = Py_MAX(*maxchar, maxchar2); } return; } if (thousands_sep) { if (!forward) { *buffer_pos -= thousands_sep_len; } /* Copy the thousands_sep chars into the buffer. */ _PyUnicode_FastCopyCharacters(writer->buffer, *buffer_pos, thousands_sep, 0, thousands_sep_len); if (forward) { *buffer_pos += thousands_sep_len; } } if (!forward) { *buffer_pos -= n_chars; *digits_pos -= n_chars; } _PyUnicode_FastCopyCharacters(writer->buffer, *buffer_pos, digits, *digits_pos, n_chars); if (forward) { *buffer_pos += n_chars; *digits_pos += n_chars; } if (n_zeros) { if (!forward) { *buffer_pos -= n_zeros; } int kind = PyUnicode_KIND(writer->buffer); void *data = PyUnicode_DATA(writer->buffer); _PyUnicode_Fill(kind, data, '0', *buffer_pos, n_zeros); if (forward) { *buffer_pos += n_zeros; } } } /** * InsertThousandsGrouping: * @writer: Unicode writer. * @n_buffer: Number of characters in @buffer. * @digits: Digits we're reading from. If count is non-NULL, this is unused. * @d_pos: Start of digits string. * @n_digits: The number of digits in the string, in which we want * to put the grouping chars. * @min_width: The minimum width of the digits in the output string. * Output will be zero-padded on the left to fill. * @grouping: see definition in localeconv(). * @thousands_sep: see definition in localeconv(). * * There are 2 modes: counting and filling. If @writer is NULL, * we are in counting mode, else filling mode. * If counting, the required buffer size is returned. * If filling, we know the buffer will be large enough, so we don't * need to pass in the buffer size. * Inserts thousand grouping characters (as defined by grouping and * thousands_sep) into @writer. * * Return value: -1 on error, number of characters otherwise. **/ static 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, int forward) { min_width = Py_MAX(0, min_width); if (writer) { assert(digits != NULL); assert(maxchar == NULL); } else { assert(digits == NULL); assert(maxchar != NULL); } assert(0 <= d_pos); assert(0 <= n_digits); assert(grouping != NULL); Py_ssize_t count = 0; Py_ssize_t n_zeros; int loop_broken = 0; int use_separator = 0; /* First time through, don't append the separator. They only go between groups. */ Py_ssize_t buffer_pos; Py_ssize_t digits_pos; Py_ssize_t len; Py_ssize_t n_chars; Py_ssize_t remaining = n_digits; /* Number of chars remaining to be looked at */ /* A generator that returns all of the grouping widths, until it returns 0. */ GroupGenerator groupgen; GroupGenerator_init(&groupgen, grouping); const Py_ssize_t thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep); /* if digits are not grouped, thousands separator should be an empty string */ assert(!(grouping[0] == CHAR_MAX && thousands_sep_len != 0)); digits_pos = d_pos + (forward ? 0 : n_digits); if (writer) { buffer_pos = writer->pos + (forward ? 0 : n_buffer); assert(buffer_pos <= PyUnicode_GET_LENGTH(writer->buffer)); assert(digits_pos <= PyUnicode_GET_LENGTH(digits)); } else { buffer_pos = forward ? 0 : n_buffer; } if (!writer) { *maxchar = 127; } while ((len = GroupGenerator_next(&groupgen)) > 0) { len = Py_MIN(len, Py_MAX(Py_MAX(remaining, min_width), 1)); n_zeros = Py_MAX(0, len - remaining); n_chars = Py_MAX(0, Py_MIN(remaining, len)); /* Use n_zero zero's and n_chars chars */ /* Count only, don't do anything. */ count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars; /* Copy into the writer. */ InsertThousandsGrouping_fill(writer, &buffer_pos, digits, &digits_pos, n_chars, n_zeros, use_separator ? thousands_sep : NULL, thousands_sep_len, maxchar, forward); /* Use a separator next time. */ use_separator = 1; remaining -= n_chars; min_width -= len; if (remaining <= 0 && min_width <= 0) { loop_broken = 1; break; } min_width -= thousands_sep_len; } if (!loop_broken) { /* We left the loop without using a break statement. */ len = Py_MAX(Py_MAX(remaining, min_width), 1); n_zeros = Py_MAX(0, len - remaining); n_chars = Py_MAX(0, Py_MIN(remaining, len)); /* Use n_zero zero's and n_chars chars */ count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars; /* Copy into the writer. */ InsertThousandsGrouping_fill(writer, &buffer_pos, digits, &digits_pos, n_chars, n_zeros, use_separator ? thousands_sep : NULL, thousands_sep_len, maxchar, forward); } return count; } /* Raises an exception about an unknown presentation type for this * type. */ static void unknown_presentation_type(Py_UCS4 presentation_type, const char* type_name) { /* %c might be out-of-range, hence the two cases. */ if (presentation_type > 32 && presentation_type < 128) PyErr_Format(PyExc_ValueError, "Unknown format code '%c' " "for object of type '%.200s'", (char)presentation_type, type_name); else PyErr_Format(PyExc_ValueError, "Unknown format code '\\x%x' " "for object of type '%.200s'", (unsigned int)presentation_type, type_name); } static void invalid_thousands_separator_type(char specifier, Py_UCS4 presentation_type) { assert(specifier == ',' || specifier == '_'); if (presentation_type > 32 && presentation_type < 128) PyErr_Format(PyExc_ValueError, "Cannot specify '%c' with '%c'.", specifier, (char)presentation_type); else PyErr_Format(PyExc_ValueError, "Cannot specify '%c' with '\\x%x'.", specifier, (unsigned int)presentation_type); } static void invalid_comma_and_underscore(void) { PyErr_Format(PyExc_ValueError, "Cannot specify both ',' and '_'."); } /* get_integer consumes 0 or more decimal digit characters from an input string, updates *result with the corresponding positive integer, and returns the number of digits consumed. returns -1 on error. */ static int get_integer(PyObject *str, Py_ssize_t *ppos, Py_ssize_t end, Py_ssize_t *result) { Py_ssize_t accumulator, digitval, pos = *ppos; int numdigits; int kind = PyUnicode_KIND(str); const void *data = PyUnicode_DATA(str); accumulator = numdigits = 0; for (; pos < end; pos++, numdigits++) { digitval = Py_UNICODE_TODECIMAL(PyUnicode_READ(kind, data, pos)); if (digitval < 0) break; /* Detect possible overflow before it happens: accumulator * 10 + digitval > PY_SSIZE_T_MAX if and only if accumulator > (PY_SSIZE_T_MAX - digitval) / 10. */ if (accumulator > (PY_SSIZE_T_MAX - digitval) / 10) { PyErr_Format(PyExc_ValueError, "Too many decimal digits in format string"); *ppos = pos; return -1; } accumulator = accumulator * 10 + digitval; } *ppos = pos; *result = accumulator; return numdigits; } /************************************************************************/ /*********** standard format specifier parsing **************************/ /************************************************************************/ /* returns true if this character is a specifier alignment token */ Py_LOCAL_INLINE(int) is_alignment_token(Py_UCS4 c) { switch (c) { case '<': case '>': case '=': case '^': return 1; default: return 0; } } /* returns true if this character is a sign element */ Py_LOCAL_INLINE(int) is_sign_element(Py_UCS4 c) { switch (c) { case ' ': case '+': case '-': return 1; default: return 0; } } /* Locale type codes. LT_NO_LOCALE must be zero. */ enum LocaleType { LT_NO_LOCALE = 0, LT_DEFAULT_LOCALE = ',', LT_UNDERSCORE_LOCALE = '_', LT_UNDER_FOUR_LOCALE, LT_CURRENT_LOCALE }; typedef struct { Py_UCS4 fill_char; Py_UCS4 align; int alternate; int no_neg_0; Py_UCS4 sign; Py_ssize_t width; enum LocaleType thousands_separators; Py_ssize_t precision; enum LocaleType frac_thousands_separator; Py_UCS4 type; } InternalFormatSpec; /* ptr points to the start of the format_spec, end points just past its end. fills in format with the parsed information. returns 1 on success, 0 on failure. if failure, sets the exception */ static int parse_internal_render_format_spec(PyObject *obj, PyObject *format_spec, Py_ssize_t start, Py_ssize_t end, InternalFormatSpec *format, char default_type, char default_align) { Py_ssize_t pos = start; int kind = PyUnicode_KIND(format_spec); const void *data = PyUnicode_DATA(format_spec); /* end-pos is used throughout this code to specify the length of the input string */ #define READ_spec(index) PyUnicode_READ(kind, data, index) Py_ssize_t consumed; int align_specified = 0; int fill_char_specified = 0; format->fill_char = ' '; format->align = default_align; format->alternate = 0; format->no_neg_0 = 0; format->sign = '\0'; format->width = -1; format->thousands_separators = LT_NO_LOCALE; format->frac_thousands_separator = LT_NO_LOCALE; format->precision = -1; format->type = default_type; /* If the second char is an alignment token, then parse the fill char */ if (end-pos >= 2 && is_alignment_token(READ_spec(pos+1))) { format->align = READ_spec(pos+1); format->fill_char = READ_spec(pos); fill_char_specified = 1; align_specified = 1; pos += 2; } else if (end-pos >= 1 && is_alignment_token(READ_spec(pos))) { format->align = READ_spec(pos); align_specified = 1; ++pos; } /* Parse the various sign options */ if (end-pos >= 1 && is_sign_element(READ_spec(pos))) { format->sign = READ_spec(pos); ++pos; } /* If the next character is z, request coercion of negative 0. Applies only to floats. */ if (end-pos >= 1 && READ_spec(pos) == 'z') { format->no_neg_0 = 1; ++pos; } /* If the next character is #, we're in alternate mode. This only applies to integers. */ if (end-pos >= 1 && READ_spec(pos) == '#') { format->alternate = 1; ++pos; } /* The special case for 0-padding (backwards compat) */ if (!fill_char_specified && end-pos >= 1 && READ_spec(pos) == '0') { format->fill_char = '0'; if (!align_specified && default_align == '>') { format->align = '='; } ++pos; } consumed = get_integer(format_spec, &pos, end, &format->width); if (consumed == -1) /* Overflow error. Exception already set. */ return 0; /* If consumed is 0, we didn't consume any characters for the width. In that case, reset the width to -1, because get_integer() will have set it to zero. -1 is how we record that the width wasn't specified. */ if (consumed == 0) format->width = -1; /* Comma signifies add thousands separators */ if (end-pos && READ_spec(pos) == ',') { format->thousands_separators = LT_DEFAULT_LOCALE; ++pos; } /* Underscore signifies add thousands separators */ if (end-pos && READ_spec(pos) == '_') { if (format->thousands_separators != LT_NO_LOCALE) { invalid_comma_and_underscore(); return 0; } format->thousands_separators = LT_UNDERSCORE_LOCALE; ++pos; } if (end-pos && READ_spec(pos) == ',') { if (format->thousands_separators == LT_UNDERSCORE_LOCALE) { invalid_comma_and_underscore(); return 0; } } /* Parse field precision */ if (end-pos && READ_spec(pos) == '.') { ++pos; consumed = get_integer(format_spec, &pos, end, &format->precision); if (consumed == -1) /* Overflow error. Exception already set. */ return 0; if (end-pos && READ_spec(pos) == ',') { if (consumed == 0) { format->precision = -1; } format->frac_thousands_separator = LT_DEFAULT_LOCALE; ++pos; ++consumed; } if (end-pos && READ_spec(pos) == '_') { if (format->frac_thousands_separator != LT_NO_LOCALE) { invalid_comma_and_underscore(); return 0; } if (consumed == 0) { format->precision = -1; } format->frac_thousands_separator = LT_UNDERSCORE_LOCALE; ++pos; ++consumed; } if (end-pos && READ_spec(pos) == ',') { if (format->frac_thousands_separator == LT_UNDERSCORE_LOCALE) { invalid_comma_and_underscore(); return 0; } } /* Not having a precision or underscore/comma after a dot is an error. */ if (consumed == 0) { PyErr_Format(PyExc_ValueError, "Format specifier missing precision"); return 0; } } /* Finally, parse the type field. */ if (end-pos > 1) { /* More than one char remains, so this is an invalid format specifier. */ /* Create a temporary object that contains the format spec we're operating on. It's format_spec[start:end] (in Python syntax). */ PyObject* actual_format_spec = PyUnicode_FromKindAndData(kind, (char*)data + kind*start, end-start); if (actual_format_spec != NULL) { PyErr_Format(PyExc_ValueError, "Invalid format specifier '%U' for object of type '%.200s'", actual_format_spec, Py_TYPE(obj)->tp_name); Py_DECREF(actual_format_spec); } return 0; } if (end-pos == 1) { format->type = READ_spec(pos); ++pos; } /* Do as much validating as we can, just by looking at the format specifier. Do not take into account what type of formatting we're doing (int, float, string). */ if (format->thousands_separators) { switch (format->type) { case 'd': case 'e': case 'f': case 'g': case 'E': case 'G': case '%': case 'F': case '\0': /* These are allowed. See PEP 378.*/ break; case 'b': case 'o': case 'x': case 'X': /* Underscores are allowed in bin/oct/hex. See PEP 515. */ if (format->thousands_separators == LT_UNDERSCORE_LOCALE) { /* Every four digits, not every three, in bin/oct/hex. */ format->thousands_separators = LT_UNDER_FOUR_LOCALE; break; } _Py_FALLTHROUGH; default: invalid_thousands_separator_type(format->thousands_separators, format->type); return 0; } } if (format->type == 'n' && format->frac_thousands_separator != LT_NO_LOCALE) { invalid_thousands_separator_type(format->frac_thousands_separator, format->type); return 0; } assert (format->align <= 127); assert (format->sign <= 127); return 1; } /* Calculate the padding needed. */ static void calc_padding(Py_ssize_t nchars, Py_ssize_t width, Py_UCS4 align, Py_ssize_t *n_lpadding, Py_ssize_t *n_rpadding, Py_ssize_t *n_total) { if (width >= 0) { if (nchars > width) *n_total = nchars; else *n_total = width; } else { /* not specified, use all of the chars and no more */ *n_total = nchars; } /* Figure out how much leading space we need, based on the aligning */ if (align == '>') *n_lpadding = *n_total - nchars; else if (align == '^') *n_lpadding = (*n_total - nchars) / 2; else if (align == '<' || align == '=') *n_lpadding = 0; else { /* We should never have an unspecified alignment. */ Py_UNREACHABLE(); } *n_rpadding = *n_total - nchars - *n_lpadding; } /* Do the padding, and return a pointer to where the caller-supplied content goes. */ static int fill_padding(_PyUnicodeWriter *writer, Py_ssize_t nchars, Py_UCS4 fill_char, Py_ssize_t n_lpadding, Py_ssize_t n_rpadding) { Py_ssize_t pos; /* Pad on left. */ if (n_lpadding) { pos = writer->pos; _PyUnicode_FastFill(writer->buffer, pos, n_lpadding, fill_char); } /* Pad on right. */ if (n_rpadding) { pos = writer->pos + nchars + n_lpadding; _PyUnicode_FastFill(writer->buffer, pos, n_rpadding, fill_char); } /* Pointer to the user content. */ writer->pos += n_lpadding; return 0; } /************************************************************************/ /*********** common routines for numeric formatting *********************/ /************************************************************************/ /* Locale info needed for formatting integers and the part of floats before and including the decimal. Note that locales only support 8-bit chars, not unicode. */ typedef struct { PyObject *decimal_point; PyObject *thousands_sep; PyObject *frac_thousands_sep; const char *grouping; char *grouping_buffer; } LocaleInfo; #define LocaleInfo_STATIC_INIT {0, 0, 0, 0} /* describes the layout for an integer, see the comment in calc_number_widths() for details */ typedef struct { Py_ssize_t n_lpadding; Py_ssize_t n_prefix; Py_ssize_t n_spadding; Py_ssize_t n_rpadding; char sign; Py_ssize_t n_sign; /* number of digits needed for sign (0/1) */ Py_ssize_t n_grouped_digits; /* Space taken up by the digits, including any grouping chars. */ Py_ssize_t n_decimal; /* 0 if only an integer */ Py_ssize_t n_remainder; /* Digits in decimal and/or exponent part, excluding the decimal itself, if present. */ Py_ssize_t n_frac; Py_ssize_t n_grouped_frac_digits; /* These 2 are not the widths of fields, but are needed by STRINGLIB_GROUPING. */ Py_ssize_t n_digits; /* The number of digits before a decimal or exponent. */ Py_ssize_t n_min_width; /* The min_width we used when we computed the n_grouped_digits width. */ } NumberFieldWidths; /* Given a number of the form: digits[remainder] where ptr points to the start and end points to the end, find where the integer part ends. This could be a decimal, an exponent, both, or neither. If a decimal point is present, set *has_decimal and increment remainder beyond it. Results are undefined (but shouldn't crash) for improperly formatted strings. */ static void parse_number(PyObject *s, Py_ssize_t pos, Py_ssize_t end, Py_ssize_t *n_remainder, Py_ssize_t *n_frac, int *has_decimal) { Py_ssize_t frac; int kind = PyUnicode_KIND(s); const void *data = PyUnicode_DATA(s); while (posn_digits = n_end - n_start - n_frac - n_remainder - (has_decimal?1:0); spec->n_lpadding = 0; spec->n_prefix = n_prefix; spec->n_decimal = has_decimal ? PyUnicode_GET_LENGTH(locale->decimal_point) : 0; spec->n_remainder = n_remainder; spec->n_frac = n_frac; spec->n_spadding = 0; spec->n_rpadding = 0; spec->sign = '\0'; spec->n_sign = 0; /* the output will look like: | | | | | | sign is computed from format->sign and the actual sign of the number prefix is given (it's for the '0x' prefix) digits is already known the total width is either given, or computed from the actual digits only one of lpadding, spadding, and rpadding can be non-zero, and it's calculated from the width and other fields */ /* compute the various parts we're going to write */ switch (format->sign) { case '+': /* always put a + or - */ spec->n_sign = 1; spec->sign = (sign_char == '-' ? '-' : '+'); break; case ' ': spec->n_sign = 1; spec->sign = (sign_char == '-' ? '-' : ' '); break; default: /* Not specified, or the default (-) */ if (sign_char == '-') { spec->n_sign = 1; spec->sign = '-'; } } if (spec->n_frac == 0) { spec->n_grouped_frac_digits = 0; } else { Py_UCS4 grouping_maxchar; spec->n_grouped_frac_digits = _PyUnicode_InsertThousandsGrouping( NULL, 0, NULL, 0, spec->n_frac, spec->n_frac, locale->grouping, locale->frac_thousands_sep, &grouping_maxchar, 1); if (spec->n_grouped_frac_digits == -1) { return -1; } *maxchar = Py_MAX(*maxchar, grouping_maxchar); } /* The number of chars used for non-digits and non-padding. */ n_non_digit_non_padding = spec->n_sign + spec->n_prefix + spec->n_decimal + + spec->n_frac + spec->n_remainder; /* min_width can go negative, that's okay. format->width == -1 means we don't care. */ if (format->fill_char == '0' && format->align == '=') spec->n_min_width = (format->width - n_non_digit_non_padding + spec->n_frac - spec->n_grouped_frac_digits); else spec->n_min_width = 0; if (spec->n_digits == 0) /* This case only occurs when using 'c' formatting, we need to special case it because the grouping code always wants to have at least one character. */ spec->n_grouped_digits = 0; else { Py_UCS4 grouping_maxchar; spec->n_grouped_digits = _PyUnicode_InsertThousandsGrouping( NULL, 0, NULL, 0, spec->n_digits, spec->n_min_width, locale->grouping, locale->thousands_sep, &grouping_maxchar, 0); if (spec->n_grouped_digits == -1) { return -1; } *maxchar = Py_MAX(*maxchar, grouping_maxchar); } /* Given the desired width and the total of digit and non-digit space we consume, see if we need any padding. format->width can be negative (meaning no padding), but this code still works in that case. */ n_padding = format->width - (n_non_digit_non_padding + spec->n_grouped_digits + spec->n_grouped_frac_digits - spec->n_frac); if (n_padding > 0) { /* Some padding is needed. Determine if it's left, space, or right. */ switch (format->align) { case '<': spec->n_rpadding = n_padding; break; case '^': spec->n_lpadding = n_padding / 2; spec->n_rpadding = n_padding - spec->n_lpadding; break; case '=': spec->n_spadding = n_padding; break; case '>': spec->n_lpadding = n_padding; break; default: /* Shouldn't get here */ Py_UNREACHABLE(); } } if (spec->n_lpadding || spec->n_spadding || spec->n_rpadding) *maxchar = Py_MAX(*maxchar, format->fill_char); if (spec->n_decimal) *maxchar = Py_MAX(*maxchar, PyUnicode_MAX_CHAR_VALUE(locale->decimal_point)); return spec->n_lpadding + spec->n_sign + spec->n_prefix + spec->n_spadding + spec->n_grouped_digits + spec->n_decimal + spec->n_grouped_frac_digits + spec->n_remainder + spec->n_rpadding; } /* Fill in the digit parts of a number's string representation, as determined in calc_number_widths(). Return -1 on error, or 0 on success. */ static int fill_number(_PyUnicodeWriter *writer, const NumberFieldWidths *spec, PyObject *digits, Py_ssize_t d_start, PyObject *prefix, Py_ssize_t p_start, Py_UCS4 fill_char, LocaleInfo *locale, int toupper) { /* Used to keep track of digits, decimal, and remainder. */ Py_ssize_t d_pos = d_start; const int kind = writer->kind; const void *data = writer->data; Py_ssize_t r; if (spec->n_lpadding) { _PyUnicode_FastFill(writer->buffer, writer->pos, spec->n_lpadding, fill_char); writer->pos += spec->n_lpadding; } if (spec->n_sign == 1) { PyUnicode_WRITE(kind, data, writer->pos, spec->sign); writer->pos++; } if (spec->n_prefix) { _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos, prefix, p_start, spec->n_prefix); if (toupper) { Py_ssize_t t; for (t = 0; t < spec->n_prefix; t++) { Py_UCS4 c = PyUnicode_READ(kind, data, writer->pos + t); c = Py_TOUPPER(c); assert (c <= 127); PyUnicode_WRITE(kind, data, writer->pos + t, c); } } writer->pos += spec->n_prefix; } if (spec->n_spadding) { _PyUnicode_FastFill(writer->buffer, writer->pos, spec->n_spadding, fill_char); writer->pos += spec->n_spadding; } /* Only for type 'c' special case, it has no digits. */ if (spec->n_digits != 0) { /* Fill the digits with InsertThousandsGrouping. */ r = _PyUnicode_InsertThousandsGrouping( writer, spec->n_grouped_digits, digits, d_pos, spec->n_digits, spec->n_min_width, locale->grouping, locale->thousands_sep, NULL, 0); if (r == -1) return -1; assert(r == spec->n_grouped_digits); d_pos += spec->n_digits; } if (toupper) { Py_ssize_t t; for (t = 0; t < spec->n_grouped_digits; t++) { Py_UCS4 c = PyUnicode_READ(kind, data, writer->pos + t); c = Py_TOUPPER(c); if (c > 127) { PyErr_SetString(PyExc_SystemError, "non-ascii grouped digit"); return -1; } PyUnicode_WRITE(kind, data, writer->pos + t, c); } } writer->pos += spec->n_grouped_digits; if (spec->n_decimal) { _PyUnicode_FastCopyCharacters( writer->buffer, writer->pos, locale->decimal_point, 0, spec->n_decimal); writer->pos += spec->n_decimal; d_pos += 1; } if (spec->n_frac) { r = _PyUnicode_InsertThousandsGrouping( writer, spec->n_grouped_frac_digits, digits, d_pos, spec->n_frac, spec->n_frac, locale->grouping, locale->frac_thousands_sep, NULL, 1); if (r == -1) { return -1; } assert(r == spec->n_grouped_frac_digits); d_pos += spec->n_frac; writer->pos += spec->n_grouped_frac_digits; } if (spec->n_remainder) { _PyUnicode_FastCopyCharacters( writer->buffer, writer->pos, digits, d_pos, spec->n_remainder); writer->pos += spec->n_remainder; /* d_pos += spec->n_remainder; */ } if (spec->n_rpadding) { _PyUnicode_FastFill(writer->buffer, writer->pos, spec->n_rpadding, fill_char); writer->pos += spec->n_rpadding; } return 0; } static const char no_grouping[1] = {CHAR_MAX}; /* Find the decimal point character(s?), thousands_separator(s?), and grouping description, either for the current locale if type is LT_CURRENT_LOCALE, a hard-coded locale if LT_DEFAULT_LOCALE or LT_UNDERSCORE_LOCALE/LT_UNDER_FOUR_LOCALE, or none if LT_NO_LOCALE. */ static int get_locale_info(enum LocaleType type, enum LocaleType frac_type, LocaleInfo *locale_info) { switch (type) { case LT_CURRENT_LOCALE: { struct lconv *lc = localeconv(); if (_Py_GetLocaleconvNumeric(lc, &locale_info->decimal_point, &locale_info->thousands_sep) < 0) { return -1; } /* localeconv() grouping can become a dangling pointer or point to a different string if another thread calls localeconv() during the string formatting. Copy the string to avoid this risk. */ locale_info->grouping_buffer = _PyMem_Strdup(lc->grouping); if (locale_info->grouping_buffer == NULL) { PyErr_NoMemory(); return -1; } locale_info->grouping = locale_info->grouping_buffer; break; } case LT_DEFAULT_LOCALE: case LT_UNDERSCORE_LOCALE: case LT_UNDER_FOUR_LOCALE: locale_info->decimal_point = PyUnicode_FromOrdinal('.'); locale_info->thousands_sep = PyUnicode_FromOrdinal( type == LT_DEFAULT_LOCALE ? ',' : '_'); if (!locale_info->decimal_point || !locale_info->thousands_sep) return -1; if (type != LT_UNDER_FOUR_LOCALE) locale_info->grouping = "\3"; /* Group every 3 characters. The (implicit) trailing 0 means repeat infinitely. */ else locale_info->grouping = "\4"; /* Bin/oct/hex group every four. */ break; case LT_NO_LOCALE: locale_info->decimal_point = PyUnicode_FromOrdinal('.'); locale_info->thousands_sep = Py_GetConstant(Py_CONSTANT_EMPTY_STR); if (!locale_info->decimal_point || !locale_info->thousands_sep) return -1; locale_info->grouping = no_grouping; break; } if (frac_type != LT_NO_LOCALE) { locale_info->frac_thousands_sep = PyUnicode_FromOrdinal( frac_type == LT_DEFAULT_LOCALE ? ',' : '_'); if (!locale_info->frac_thousands_sep) { return -1; } if (locale_info->grouping == no_grouping) { locale_info->grouping = "\3"; } } else { locale_info->frac_thousands_sep = Py_GetConstant(Py_CONSTANT_EMPTY_STR); } return 0; } static void free_locale_info(LocaleInfo *locale_info) { Py_XDECREF(locale_info->decimal_point); Py_XDECREF(locale_info->thousands_sep); Py_XDECREF(locale_info->frac_thousands_sep); PyMem_Free(locale_info->grouping_buffer); } /************************************************************************/ /*********** string formatting ******************************************/ /************************************************************************/ static int format_string_internal(PyObject *value, const InternalFormatSpec *format, _PyUnicodeWriter *writer) { Py_ssize_t lpad; Py_ssize_t rpad; Py_ssize_t total; Py_ssize_t len; int result = -1; Py_UCS4 maxchar; len = PyUnicode_GET_LENGTH(value); /* sign is not allowed on strings */ if (format->sign != '\0') { if (format->sign == ' ') { PyErr_SetString(PyExc_ValueError, "Space not allowed in string format specifier"); } else { PyErr_SetString(PyExc_ValueError, "Sign not allowed in string format specifier"); } goto done; } /* negative 0 coercion is not allowed on strings */ if (format->no_neg_0) { PyErr_SetString(PyExc_ValueError, "Negative zero coercion (z) not allowed in string format " "specifier"); goto done; } /* alternate is not allowed on strings */ if (format->alternate) { PyErr_SetString(PyExc_ValueError, "Alternate form (#) not allowed in string format " "specifier"); goto done; } /* '=' alignment not allowed on strings */ if (format->align == '=') { PyErr_SetString(PyExc_ValueError, "'=' alignment not allowed " "in string format specifier"); goto done; } if ((format->width == -1 || format->width <= len) && (format->precision == -1 || format->precision >= len)) { /* Fast path */ return _PyUnicodeWriter_WriteStr(writer, value); } /* if precision is specified, output no more that format.precision characters */ if (format->precision >= 0 && len >= format->precision) { len = format->precision; } calc_padding(len, format->width, format->align, &lpad, &rpad, &total); maxchar = writer->maxchar; if (lpad != 0 || rpad != 0) maxchar = Py_MAX(maxchar, format->fill_char); if (PyUnicode_MAX_CHAR_VALUE(value) > maxchar) { Py_UCS4 valmaxchar = _PyUnicode_FindMaxChar(value, 0, len); maxchar = Py_MAX(maxchar, valmaxchar); } /* allocate the resulting string */ if (_PyUnicodeWriter_Prepare(writer, total, maxchar) == -1) goto done; /* Write into that space. First the padding. */ result = fill_padding(writer, len, format->fill_char, lpad, rpad); if (result == -1) goto done; /* Then the source string. */ if (len) { _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos, value, 0, len); } writer->pos += (len + rpad); result = 0; done: return result; } /************************************************************************/ /*********** long formatting ********************************************/ /************************************************************************/ static int format_long_internal(PyObject *value, const InternalFormatSpec *format, _PyUnicodeWriter *writer) { int result = -1; Py_UCS4 maxchar = 127; PyObject *tmp = NULL; Py_ssize_t inumeric_chars; Py_UCS4 sign_char = '\0'; Py_ssize_t n_digits; /* count of digits need from the computed string */ Py_ssize_t n_remainder = 0; /* Used only for 'c' formatting, which produces non-digits */ Py_ssize_t n_prefix = 0; /* Count of prefix chars, (e.g., '0x') */ Py_ssize_t n_total; Py_ssize_t prefix = 0; NumberFieldWidths spec; long x; /* Locale settings, either from the actual locale or from a hard-code pseudo-locale */ LocaleInfo locale = LocaleInfo_STATIC_INIT; /* no precision allowed on integers */ if (format->precision != -1) { PyErr_SetString(PyExc_ValueError, "Precision not allowed in integer format specifier"); goto done; } /* no negative zero coercion on integers */ if (format->no_neg_0) { PyErr_SetString(PyExc_ValueError, "Negative zero coercion (z) not allowed in integer" " format specifier"); goto done; } /* special case for character formatting */ if (format->type == 'c') { /* error to specify a sign */ if (format->sign != '\0') { PyErr_SetString(PyExc_ValueError, "Sign not allowed with integer" " format specifier 'c'"); goto done; } /* error to request alternate format */ if (format->alternate) { PyErr_SetString(PyExc_ValueError, "Alternate form (#) not allowed with integer" " format specifier 'c'"); goto done; } /* taken from unicodeobject.c formatchar() */ /* Integer input truncated to a character */ x = PyLong_AsLong(value); if (x == -1 && PyErr_Occurred()) goto done; if (x < 0 || x > 0x10ffff) { PyErr_SetString(PyExc_OverflowError, "%c arg not in range(0x110000)"); goto done; } tmp = PyUnicode_FromOrdinal(x); inumeric_chars = 0; n_digits = 1; maxchar = Py_MAX(maxchar, (Py_UCS4)x); /* As a sort-of hack, we tell calc_number_widths that we only have "remainder" characters. calc_number_widths thinks these are characters that don't get formatted, only copied into the output string. We do this for 'c' formatting, because the characters are likely to be non-digits. */ n_remainder = 1; } else { int base; int leading_chars_to_skip = 0; /* Number of characters added by PyNumber_ToBase that we want to skip over. */ /* Compute the base and how many characters will be added by PyNumber_ToBase */ switch (format->type) { case 'b': base = 2; leading_chars_to_skip = 2; /* 0b */ break; case 'o': base = 8; leading_chars_to_skip = 2; /* 0o */ break; case 'x': case 'X': base = 16; leading_chars_to_skip = 2; /* 0x */ break; default: /* shouldn't be needed, but stops a compiler warning */ case 'd': case 'n': base = 10; break; } if (format->sign != '+' && format->sign != ' ' && format->width == -1 && format->type != 'X' && format->type != 'n' && !format->thousands_separators && PyLong_CheckExact(value)) { /* Fast path */ return _PyLong_FormatWriter(writer, value, base, format->alternate); } /* The number of prefix chars is the same as the leading chars to skip */ if (format->alternate) n_prefix = leading_chars_to_skip; /* Do the hard part, converting to a string in a given base */ tmp = _PyLong_Format(value, base); if (tmp == NULL) goto done; inumeric_chars = 0; n_digits = PyUnicode_GET_LENGTH(tmp); prefix = inumeric_chars; /* Is a sign character present in the output? If so, remember it and skip it */ if (PyUnicode_READ_CHAR(tmp, inumeric_chars) == '-') { sign_char = '-'; ++prefix; ++leading_chars_to_skip; } /* Skip over the leading chars (0x, 0b, etc.) */ n_digits -= leading_chars_to_skip; inumeric_chars += leading_chars_to_skip; } /* Determine the grouping, separator, and decimal point, if any. */ if (get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE : format->thousands_separators, 0, &locale) == -1) goto done; /* Calculate how much memory we'll need. */ n_total = calc_number_widths(&spec, n_prefix, sign_char, inumeric_chars, inumeric_chars + n_digits, n_remainder, 0, 0, &locale, format, &maxchar); if (n_total == -1) { goto done; } /* Allocate the memory. */ if (_PyUnicodeWriter_Prepare(writer, n_total, maxchar) == -1) goto done; /* Populate the memory. */ result = fill_number(writer, &spec, tmp, inumeric_chars, tmp, prefix, format->fill_char, &locale, format->type == 'X'); done: Py_XDECREF(tmp); free_locale_info(&locale); return result; } /************************************************************************/ /*********** float formatting *******************************************/ /************************************************************************/ /* much of this is taken from unicodeobject.c */ static int format_float_internal(PyObject *value, const InternalFormatSpec *format, _PyUnicodeWriter *writer) { char *buf = NULL; /* buffer returned from PyOS_double_to_string */ Py_ssize_t n_digits; Py_ssize_t n_remainder; Py_ssize_t n_frac; Py_ssize_t n_total; int has_decimal; double val; int precision, default_precision = 6; Py_UCS4 type = format->type; int add_pct = 0; Py_ssize_t index; NumberFieldWidths spec; int flags = 0; int result = -1; Py_UCS4 maxchar = 127; Py_UCS4 sign_char = '\0'; int float_type; /* Used to see if we have a nan, inf, or regular float. */ PyObject *unicode_tmp = NULL; /* Locale settings, either from the actual locale or from a hard-code pseudo-locale */ LocaleInfo locale = LocaleInfo_STATIC_INIT; if (format->precision > INT_MAX) { PyErr_SetString(PyExc_ValueError, "precision too big"); goto done; } precision = (int)format->precision; if (format->alternate) flags |= Py_DTSF_ALT; if (format->no_neg_0) flags |= Py_DTSF_NO_NEG_0; if (type == '\0') { /* Omitted type specifier. Behaves in the same way as repr(x) and str(x) if no precision is given, else like 'g', but with at least one digit after the decimal point. */ flags |= Py_DTSF_ADD_DOT_0; type = 'r'; default_precision = 0; } if (type == 'n') /* 'n' is the same as 'g', except for the locale used to format the result. We take care of that later. */ type = 'g'; val = PyFloat_AsDouble(value); if (val == -1.0 && PyErr_Occurred()) goto done; if (type == '%') { type = 'f'; val *= 100; add_pct = 1; } if (precision < 0) precision = default_precision; else if (type == 'r') type = 'g'; /* Cast "type", because if we're in unicode we need to pass an 8-bit char. This is safe, because we've restricted what "type" can be. */ buf = PyOS_double_to_string(val, (char)type, precision, flags, &float_type); if (buf == NULL) goto done; n_digits = strlen(buf); if (add_pct) { /* We know that buf has a trailing zero (since we just called strlen() on it), and we don't use that fact any more. So we can just write over the trailing zero. */ buf[n_digits] = '%'; n_digits += 1; } if (format->sign != '+' && format->sign != ' ' && format->width == -1 && format->type != 'n' && !format->thousands_separators && !format->frac_thousands_separator) { /* Fast path */ result = _PyUnicodeWriter_WriteASCIIString(writer, buf, n_digits); PyMem_Free(buf); return result; } /* Since there is no unicode version of PyOS_double_to_string, just use the 8 bit version and then convert to unicode. */ unicode_tmp = _PyUnicode_FromASCII(buf, n_digits); PyMem_Free(buf); if (unicode_tmp == NULL) goto done; /* Is a sign character present in the output? If so, remember it and skip it */ index = 0; if (PyUnicode_READ_CHAR(unicode_tmp, index) == '-') { sign_char = '-'; ++index; --n_digits; } /* Determine if we have any "remainder" (after the digits, might include decimal or exponent or both (or neither)) */ parse_number(unicode_tmp, index, index + n_digits, &n_remainder, &n_frac, &has_decimal); /* Determine the grouping, separator, and decimal point, if any. */ if (get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE : format->thousands_separators, format->frac_thousands_separator, &locale) == -1) goto done; /* Calculate how much memory we'll need. */ n_total = calc_number_widths(&spec, 0, sign_char, index, index + n_digits, n_remainder, n_frac, has_decimal, &locale, format, &maxchar); if (n_total == -1) { goto done; } /* Allocate the memory. */ if (_PyUnicodeWriter_Prepare(writer, n_total, maxchar) == -1) goto done; /* Populate the memory. */ result = fill_number(writer, &spec, unicode_tmp, index, NULL, 0, format->fill_char, &locale, 0); done: Py_XDECREF(unicode_tmp); free_locale_info(&locale); return result; } /************************************************************************/ /*********** complex formatting *****************************************/ /************************************************************************/ static int format_complex_internal(PyObject *value, const InternalFormatSpec *format, _PyUnicodeWriter *writer) { double re; double im; char *re_buf = NULL; /* buffer returned from PyOS_double_to_string */ char *im_buf = NULL; /* buffer returned from PyOS_double_to_string */ InternalFormatSpec tmp_format = *format; Py_ssize_t n_re_digits; Py_ssize_t n_im_digits; Py_ssize_t n_re_remainder; Py_ssize_t n_im_remainder; Py_ssize_t n_re_frac; Py_ssize_t n_im_frac; Py_ssize_t n_re_total; Py_ssize_t n_im_total; int re_has_decimal; int im_has_decimal; int precision, default_precision = 6; Py_UCS4 type = format->type; Py_ssize_t i_re; Py_ssize_t i_im; NumberFieldWidths re_spec; NumberFieldWidths im_spec; int flags = 0; int result = -1; Py_UCS4 maxchar = 127; int rkind; void *rdata; Py_UCS4 re_sign_char = '\0'; Py_UCS4 im_sign_char = '\0'; int re_float_type; /* Used to see if we have a nan, inf, or regular float. */ int im_float_type; int add_parens = 0; int skip_re = 0; Py_ssize_t lpad; Py_ssize_t rpad; Py_ssize_t total; PyObject *re_unicode_tmp = NULL; PyObject *im_unicode_tmp = NULL; /* Locale settings, either from the actual locale or from a hard-code pseudo-locale */ LocaleInfo locale = LocaleInfo_STATIC_INIT; if (format->precision > INT_MAX) { PyErr_SetString(PyExc_ValueError, "precision too big"); goto done; } precision = (int)format->precision; /* Zero padding is not allowed. */ if (format->fill_char == '0') { PyErr_SetString(PyExc_ValueError, "Zero padding is not allowed in complex format " "specifier"); goto done; } /* Neither is '=' alignment . */ if (format->align == '=') { PyErr_SetString(PyExc_ValueError, "'=' alignment flag is not allowed in complex format " "specifier"); goto done; } re = PyComplex_RealAsDouble(value); if (re == -1.0 && PyErr_Occurred()) goto done; im = PyComplex_ImagAsDouble(value); if (im == -1.0 && PyErr_Occurred()) goto done; if (format->alternate) flags |= Py_DTSF_ALT; if (format->no_neg_0) flags |= Py_DTSF_NO_NEG_0; if (type == '\0') { /* Omitted type specifier. Should be like str(self). */ type = 'r'; default_precision = 0; if (re == 0.0 && copysign(1.0, re) == 1.0) skip_re = 1; else add_parens = 1; } if (type == 'n') /* 'n' is the same as 'g', except for the locale used to format the result. We take care of that later. */ type = 'g'; if (precision < 0) precision = default_precision; else if (type == 'r') type = 'g'; /* Cast "type", because if we're in unicode we need to pass an 8-bit char. This is safe, because we've restricted what "type" can be. */ re_buf = PyOS_double_to_string(re, (char)type, precision, flags, &re_float_type); if (re_buf == NULL) goto done; im_buf = PyOS_double_to_string(im, (char)type, precision, flags, &im_float_type); if (im_buf == NULL) goto done; n_re_digits = strlen(re_buf); n_im_digits = strlen(im_buf); /* Since there is no unicode version of PyOS_double_to_string, just use the 8 bit version and then convert to unicode. */ re_unicode_tmp = _PyUnicode_FromASCII(re_buf, n_re_digits); if (re_unicode_tmp == NULL) goto done; i_re = 0; im_unicode_tmp = _PyUnicode_FromASCII(im_buf, n_im_digits); if (im_unicode_tmp == NULL) goto done; i_im = 0; /* Is a sign character present in the output? If so, remember it and skip it */ if (PyUnicode_READ_CHAR(re_unicode_tmp, i_re) == '-') { re_sign_char = '-'; ++i_re; --n_re_digits; } if (PyUnicode_READ_CHAR(im_unicode_tmp, i_im) == '-') { im_sign_char = '-'; ++i_im; --n_im_digits; } /* Determine if we have any "remainder" (after the digits, might include decimal or exponent or both (or neither)) */ parse_number(re_unicode_tmp, i_re, i_re + n_re_digits, &n_re_remainder, &n_re_frac, &re_has_decimal); parse_number(im_unicode_tmp, i_im, i_im + n_im_digits, &n_im_remainder, &n_im_frac, &im_has_decimal); /* Determine the grouping, separator, and decimal point, if any. */ if (get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE : format->thousands_separators, format->frac_thousands_separator, &locale) == -1) goto done; /* Turn off any padding. We'll do it later after we've composed the numbers without padding. */ tmp_format.fill_char = '\0'; tmp_format.align = '<'; tmp_format.width = -1; /* Calculate how much memory we'll need. */ n_re_total = calc_number_widths(&re_spec, 0, re_sign_char, i_re, i_re + n_re_digits, n_re_remainder, n_re_frac, re_has_decimal, &locale, &tmp_format, &maxchar); if (n_re_total == -1) { goto done; } /* Same formatting, but always include a sign, unless the real part is * going to be omitted, in which case we use whatever sign convention was * requested by the original format. */ if (!skip_re) tmp_format.sign = '+'; n_im_total = calc_number_widths(&im_spec, 0, im_sign_char, i_im, i_im + n_im_digits, n_im_remainder, n_im_frac, im_has_decimal, &locale, &tmp_format, &maxchar); if (n_im_total == -1) { goto done; } if (skip_re) n_re_total = 0; /* Add 1 for the 'j', and optionally 2 for parens. */ calc_padding(n_re_total + n_im_total + 1 + add_parens * 2, format->width, format->align, &lpad, &rpad, &total); if (lpad || rpad) maxchar = Py_MAX(maxchar, format->fill_char); if (_PyUnicodeWriter_Prepare(writer, total, maxchar) == -1) goto done; rkind = writer->kind; rdata = writer->data; /* Populate the memory. First, the padding. */ result = fill_padding(writer, n_re_total + n_im_total + 1 + add_parens * 2, format->fill_char, lpad, rpad); if (result == -1) goto done; if (add_parens) { PyUnicode_WRITE(rkind, rdata, writer->pos, '('); writer->pos++; } if (!skip_re) { result = fill_number(writer, &re_spec, re_unicode_tmp, i_re, NULL, 0, 0, &locale, 0); if (result == -1) goto done; } result = fill_number(writer, &im_spec, im_unicode_tmp, i_im, NULL, 0, 0, &locale, 0); if (result == -1) goto done; PyUnicode_WRITE(rkind, rdata, writer->pos, 'j'); writer->pos++; if (add_parens) { PyUnicode_WRITE(rkind, rdata, writer->pos, ')'); writer->pos++; } writer->pos += rpad; done: PyMem_Free(re_buf); PyMem_Free(im_buf); Py_XDECREF(re_unicode_tmp); Py_XDECREF(im_unicode_tmp); free_locale_info(&locale); return result; } /************************************************************************/ /*********** built in formatters ****************************************/ /************************************************************************/ static int format_obj(PyObject *obj, _PyUnicodeWriter *writer) { PyObject *str; int err; str = PyObject_Str(obj); if (str == NULL) return -1; err = _PyUnicodeWriter_WriteStr(writer, str); Py_DECREF(str); return err; } int _PyUnicode_FormatAdvancedWriter(_PyUnicodeWriter *writer, PyObject *obj, PyObject *format_spec, Py_ssize_t start, Py_ssize_t end) { InternalFormatSpec format; assert(PyUnicode_Check(obj)); /* check for the special case of zero length format spec, make it equivalent to str(obj) */ if (start == end) { if (PyUnicode_CheckExact(obj)) return _PyUnicodeWriter_WriteStr(writer, obj); else return format_obj(obj, writer); } /* parse the format_spec */ if (!parse_internal_render_format_spec(obj, format_spec, start, end, &format, 's', '<')) return -1; /* type conversion? */ switch (format.type) { case 's': /* no type conversion needed, already a string. do the formatting */ return format_string_internal(obj, &format, writer); default: /* unknown */ unknown_presentation_type(format.type, Py_TYPE(obj)->tp_name); return -1; } } int _PyLong_FormatAdvancedWriter(_PyUnicodeWriter *writer, PyObject *obj, PyObject *format_spec, Py_ssize_t start, Py_ssize_t end) { PyObject *tmp = NULL; InternalFormatSpec format; int result = -1; /* check for the special case of zero length format spec, make it equivalent to str(obj) */ if (start == end) { if (PyLong_CheckExact(obj)) return _PyLong_FormatWriter(writer, obj, 10, 0); else return format_obj(obj, writer); } /* parse the format_spec */ if (!parse_internal_render_format_spec(obj, format_spec, start, end, &format, 'd', '>')) goto done; /* type conversion? */ switch (format.type) { case 'b': case 'c': case 'd': case 'o': case 'x': case 'X': case 'n': /* no type conversion needed, already an int. do the formatting */ result = format_long_internal(obj, &format, writer); break; case 'e': case 'E': case 'f': case 'F': case 'g': case 'G': case '%': /* convert to float */ tmp = PyNumber_Float(obj); if (tmp == NULL) goto done; result = format_float_internal(tmp, &format, writer); break; default: /* unknown */ unknown_presentation_type(format.type, Py_TYPE(obj)->tp_name); goto done; } done: Py_XDECREF(tmp); return result; } int _PyFloat_FormatAdvancedWriter(_PyUnicodeWriter *writer, PyObject *obj, PyObject *format_spec, Py_ssize_t start, Py_ssize_t end) { InternalFormatSpec format; /* check for the special case of zero length format spec, make it equivalent to str(obj) */ if (start == end) return format_obj(obj, writer); /* parse the format_spec */ if (!parse_internal_render_format_spec(obj, format_spec, start, end, &format, '\0', '>')) return -1; /* type conversion? */ switch (format.type) { case '\0': /* No format code: like 'g', but with at least one decimal. */ case 'e': case 'E': case 'f': case 'F': case 'g': case 'G': case 'n': case '%': /* no conversion, already a float. do the formatting */ return format_float_internal(obj, &format, writer); default: /* unknown */ unknown_presentation_type(format.type, Py_TYPE(obj)->tp_name); return -1; } } int _PyComplex_FormatAdvancedWriter(_PyUnicodeWriter *writer, PyObject *obj, PyObject *format_spec, Py_ssize_t start, Py_ssize_t end) { InternalFormatSpec format; /* check for the special case of zero length format spec, make it equivalent to str(obj) */ if (start == end) return format_obj(obj, writer); /* parse the format_spec */ if (!parse_internal_render_format_spec(obj, format_spec, start, end, &format, '\0', '>')) return -1; /* type conversion? */ switch (format.type) { case '\0': /* No format code: like 'g', but with at least one decimal. */ case 'e': case 'E': case 'f': case 'F': case 'g': case 'G': case 'n': /* no conversion, already a complex. do the formatting */ return format_complex_internal(obj, &format, writer); default: /* unknown */ unknown_presentation_type(format.type, Py_TYPE(obj)->tp_name); return -1; } } /* enumerate object */ #include "Python.h" #include "pycore_call.h" // _PyObject_CallNoArgs() #include "pycore_long.h" // _PyLong_GetOne() #include "pycore_modsupport.h" // _PyArg_NoKwnames() #include "pycore_object.h" // _PyObject_GC_TRACK() #include "pycore_unicodeobject.h" // _PyUnicode_EqualToASCIIString #include "pycore_tuple.h" // _PyTuple_Recycle() #include "clinic/enumobject.c.h" /*[clinic input] class enumerate "enumobject *" "&PyEnum_Type" class reversed "reversedobject *" "&PyReversed_Type" [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=d2dfdf1a88c88975]*/ typedef struct { PyObject_HEAD Py_ssize_t en_index; /* current index of enumeration */ PyObject* en_sit; /* secondary iterator of enumeration */ PyObject* en_result; /* result tuple */ PyObject* en_longindex; /* index for sequences >= PY_SSIZE_T_MAX */ PyObject* one; /* borrowed reference */ } enumobject; #define _enumobject_CAST(op) ((enumobject *)(op)) /*[clinic input] @classmethod enumerate.__new__ as enum_new iterable: object an object supporting iteration start: object = 0 Return an enumerate object. The enumerate object yields pairs containing a count (from start, which defaults to zero) and a value yielded by the iterable argument. enumerate is useful for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ... [clinic start generated code]*/ static PyObject * enum_new_impl(PyTypeObject *type, PyObject *iterable, PyObject *start) /*[clinic end generated code: output=e95e6e439f812c10 input=782e4911efcb8acf]*/ { enumobject *en; en = (enumobject *)type->tp_alloc(type, 0); if (en == NULL) return NULL; if (start != NULL) { start = PyNumber_Index(start); if (start == NULL) { Py_DECREF(en); return NULL; } assert(PyLong_Check(start)); en->en_index = PyLong_AsSsize_t(start); if (en->en_index == -1 && PyErr_Occurred()) { PyErr_Clear(); en->en_index = PY_SSIZE_T_MAX; en->en_longindex = start; } else { en->en_longindex = NULL; Py_DECREF(start); } } else { en->en_index = 0; en->en_longindex = NULL; } en->en_sit = PyObject_GetIter(iterable); if (en->en_sit == NULL) { Py_DECREF(en); return NULL; } en->en_result = PyTuple_Pack(2, Py_None, Py_None); if (en->en_result == NULL) { Py_DECREF(en); return NULL; } en->one = _PyLong_GetOne(); /* borrowed reference */ return (PyObject *)en; } static int check_keyword(PyObject *kwnames, int index, const char *name) { PyObject *kw = PyTuple_GET_ITEM(kwnames, index); if (!_PyUnicode_EqualToASCIIString(kw, name)) { PyErr_Format(PyExc_TypeError, "'%S' is an invalid keyword argument for enumerate()", kw); return 0; } return 1; } // TODO: Use AC when bpo-43447 is supported static PyObject * enumerate_vectorcall(PyObject *type, PyObject *const *args, size_t nargsf, PyObject *kwnames) { PyTypeObject *tp = _PyType_CAST(type); Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); Py_ssize_t nkwargs = 0; if (kwnames != NULL) { nkwargs = PyTuple_GET_SIZE(kwnames); } // Manually implement enumerate(iterable, start=...) if (nargs + nkwargs == 2) { if (nkwargs == 1) { if (!check_keyword(kwnames, 0, "start")) { return NULL; } } else if (nkwargs == 2) { PyObject *kw0 = PyTuple_GET_ITEM(kwnames, 0); if (_PyUnicode_EqualToASCIIString(kw0, "start")) { if (!check_keyword(kwnames, 1, "iterable")) { return NULL; } return enum_new_impl(tp, args[1], args[0]); } if (!check_keyword(kwnames, 0, "iterable") || !check_keyword(kwnames, 1, "start")) { return NULL; } } return enum_new_impl(tp, args[0], args[1]); } if (nargs + nkwargs == 1) { if (nkwargs == 1 && !check_keyword(kwnames, 0, "iterable")) { return NULL; } return enum_new_impl(tp, args[0], NULL); } if (nargs == 0) { PyErr_SetString(PyExc_TypeError, "enumerate() missing required argument 'iterable'"); return NULL; } PyErr_Format(PyExc_TypeError, "enumerate() takes at most 2 arguments (%d given)", nargs + nkwargs); return NULL; } static void enum_dealloc(PyObject *op) { enumobject *en = _enumobject_CAST(op); PyObject_GC_UnTrack(en); Py_XDECREF(en->en_sit); Py_XDECREF(en->en_result); Py_XDECREF(en->en_longindex); Py_TYPE(en)->tp_free(en); } static int enum_traverse(PyObject *op, visitproc visit, void *arg) { enumobject *en = _enumobject_CAST(op); Py_VISIT(en->en_sit); Py_VISIT(en->en_result); Py_VISIT(en->en_longindex); return 0; } // increment en_longindex with lock held, return the next index to be used // or NULL on error static inline PyObject * increment_longindex_lock_held(enumobject *en) { PyObject *next_index = en->en_longindex; if (next_index == NULL) { next_index = PyLong_FromSsize_t(PY_SSIZE_T_MAX); if (next_index == NULL) { return NULL; } } assert(next_index != NULL); PyObject *stepped_up = PyNumber_Add(next_index, en->one); if (stepped_up == NULL) { return NULL; } en->en_longindex = stepped_up; return next_index; } static PyObject * enum_next_long(enumobject *en, PyObject* next_item) { PyObject *result = en->en_result; PyObject *next_index; PyObject *old_index; PyObject *old_item; Py_BEGIN_CRITICAL_SECTION(en); next_index = increment_longindex_lock_held(en); Py_END_CRITICAL_SECTION(); if (next_index == NULL) { Py_DECREF(next_item); return NULL; } if (_PyObject_IsUniquelyReferenced(result)) { Py_INCREF(result); old_index = PyTuple_GET_ITEM(result, 0); old_item = PyTuple_GET_ITEM(result, 1); PyTuple_SET_ITEM(result, 0, next_index); PyTuple_SET_ITEM(result, 1, next_item); Py_DECREF(old_index); Py_DECREF(old_item); // bpo-42536: The GC may have untracked this result tuple. Since we're // recycling it, make sure it's tracked again: _PyTuple_Recycle(result); return result; } result = PyTuple_New(2); if (result == NULL) { Py_DECREF(next_index); Py_DECREF(next_item); return NULL; } PyTuple_SET_ITEM(result, 0, next_index); PyTuple_SET_ITEM(result, 1, next_item); return result; } static PyObject * enum_next(PyObject *op) { enumobject *en = _enumobject_CAST(op); PyObject *next_index; PyObject *next_item; PyObject *result = en->en_result; PyObject *it = en->en_sit; PyObject *old_index; PyObject *old_item; next_item = (*Py_TYPE(it)->tp_iternext)(it); if (next_item == NULL) return NULL; Py_ssize_t en_index = FT_ATOMIC_LOAD_SSIZE_RELAXED(en->en_index); if (en_index == PY_SSIZE_T_MAX) return enum_next_long(en, next_item); next_index = PyLong_FromSsize_t(en_index); if (next_index == NULL) { Py_DECREF(next_item); return NULL; } FT_ATOMIC_STORE_SSIZE_RELAXED(en->en_index, en_index + 1); if (_PyObject_IsUniquelyReferenced(result)) { Py_INCREF(result); old_index = PyTuple_GET_ITEM(result, 0); old_item = PyTuple_GET_ITEM(result, 1); PyTuple_SET_ITEM(result, 0, next_index); PyTuple_SET_ITEM(result, 1, next_item); Py_DECREF(old_index); Py_DECREF(old_item); // bpo-42536: The GC may have untracked this result tuple. Since we're // recycling it, make sure it's tracked again: _PyTuple_Recycle(result); return result; } result = PyTuple_New(2); if (result == NULL) { Py_DECREF(next_index); Py_DECREF(next_item); return NULL; } PyTuple_SET_ITEM(result, 0, next_index); PyTuple_SET_ITEM(result, 1, next_item); return result; } static PyObject * enum_reduce(PyObject *op, PyObject *Py_UNUSED(ignored)) { enumobject *en = _enumobject_CAST(op); PyObject *result; Py_BEGIN_CRITICAL_SECTION(en); if (en->en_longindex != NULL) result = Py_BuildValue("O(OO)", Py_TYPE(en), en->en_sit, en->en_longindex); else result = Py_BuildValue("O(On)", Py_TYPE(en), en->en_sit, en->en_index); Py_END_CRITICAL_SECTION(); return result; } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); static PyMethodDef enum_methods[] = { {"__reduce__", enum_reduce, METH_NOARGS, reduce_doc}, {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, PyDoc_STR("See PEP 585")}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyEnum_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "enumerate", /* tp_name */ sizeof(enumobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ enum_dealloc, /* tp_dealloc */ 0, /* tp_vectorcall_offset */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ enum_new__doc__, /* tp_doc */ enum_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ enum_next, /* tp_iternext */ enum_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ enum_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ .tp_vectorcall = enumerate_vectorcall }; /* Reversed Object ***************************************************************/ typedef struct { PyObject_HEAD Py_ssize_t index; PyObject* seq; } reversedobject; #define _reversedobject_CAST(op) ((reversedobject *)(op)) /*[clinic input] @classmethod reversed.__new__ as reversed_new object as seq: object / Return a reverse iterator over the values of the given sequence. [clinic start generated code]*/ static PyObject * reversed_new_impl(PyTypeObject *type, PyObject *seq) /*[clinic end generated code: output=f7854cc1df26f570 input=4781869729e3ba50]*/ { Py_ssize_t n; PyObject *reversed_meth; reversedobject *ro; reversed_meth = _PyObject_LookupSpecial(seq, &_Py_ID(__reversed__)); if (reversed_meth == Py_None) { Py_DECREF(reversed_meth); PyErr_Format(PyExc_TypeError, "'%.200s' object is not reversible", Py_TYPE(seq)->tp_name); return NULL; } if (reversed_meth != NULL) { PyObject *res = _PyObject_CallNoArgs(reversed_meth); Py_DECREF(reversed_meth); return res; } else if (PyErr_Occurred()) return NULL; if (!PySequence_Check(seq)) { PyErr_Format(PyExc_TypeError, "'%.200s' object is not reversible", Py_TYPE(seq)->tp_name); return NULL; } n = PySequence_Size(seq); if (n == -1) return NULL; ro = (reversedobject *)type->tp_alloc(type, 0); if (ro == NULL) return NULL; ro->index = n-1; ro->seq = Py_NewRef(seq); return (PyObject *)ro; } static PyObject * reversed_vectorcall(PyObject *type, PyObject * const*args, size_t nargsf, PyObject *kwnames) { if (!_PyArg_NoKwnames("reversed", kwnames)) { return NULL; } Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); if (!_PyArg_CheckPositional("reversed", nargs, 1, 1)) { return NULL; } return reversed_new_impl(_PyType_CAST(type), args[0]); } static void reversed_dealloc(PyObject *op) { reversedobject *ro = _reversedobject_CAST(op); PyObject_GC_UnTrack(ro); Py_XDECREF(ro->seq); Py_TYPE(ro)->tp_free(ro); } static int reversed_traverse(PyObject *op, visitproc visit, void *arg) { reversedobject *ro = _reversedobject_CAST(op); Py_VISIT(ro->seq); return 0; } static PyObject * reversed_next(PyObject *op) { reversedobject *ro = _reversedobject_CAST(op); PyObject *item; Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(ro->index); if (index >= 0) { item = PySequence_GetItem(ro->seq, index); if (item != NULL) { FT_ATOMIC_STORE_SSIZE_RELAXED(ro->index, index - 1); return item; } if (PyErr_ExceptionMatches(PyExc_IndexError) || PyErr_ExceptionMatches(PyExc_StopIteration)) PyErr_Clear(); } FT_ATOMIC_STORE_SSIZE_RELAXED(ro->index, -1); #ifndef Py_GIL_DISABLED Py_CLEAR(ro->seq); #endif return NULL; } static PyObject * reversed_len(PyObject *op, PyObject *Py_UNUSED(ignored)) { reversedobject *ro = _reversedobject_CAST(op); Py_ssize_t position, seqsize; Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(ro->index); if (index == -1) return PyLong_FromLong(0); assert(ro->seq != NULL); seqsize = PySequence_Size(ro->seq); if (seqsize == -1) return NULL; position = index + 1; return PyLong_FromSsize_t((seqsize < position) ? 0 : position); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyObject * reversed_reduce(PyObject *op, PyObject *Py_UNUSED(ignored)) { reversedobject *ro = _reversedobject_CAST(op); Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(ro->index); if (index != -1) { return Py_BuildValue("O(O)n", Py_TYPE(ro), ro->seq, ro->index); } else { return Py_BuildValue("O(())", Py_TYPE(ro)); } } static PyObject * reversed_setstate(PyObject *op, PyObject *state) { reversedobject *ro = _reversedobject_CAST(op); Py_ssize_t index = PyLong_AsSsize_t(state); if (index == -1 && PyErr_Occurred()) return NULL; Py_ssize_t ro_index = FT_ATOMIC_LOAD_SSIZE_RELAXED(ro->index); // if the iterator is exhausted we do not set the state // this is for backwards compatibility reasons. in practice this situation // will not occur, see gh-120971 if (ro_index != -1) { Py_ssize_t n = PySequence_Size(ro->seq); if (n < 0) return NULL; if (index < -1) index = -1; else if (index > n-1) index = n-1; FT_ATOMIC_STORE_SSIZE_RELAXED(ro->index, index); } Py_RETURN_NONE; } PyDoc_STRVAR(setstate_doc, "Set state information for unpickling."); static PyMethodDef reversediter_methods[] = { {"__length_hint__", reversed_len, METH_NOARGS, length_hint_doc}, {"__reduce__", reversed_reduce, METH_NOARGS, reduce_doc}, {"__setstate__", reversed_setstate, METH_O, setstate_doc}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyReversed_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "reversed", /* tp_name */ sizeof(reversedobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ reversed_dealloc, /* tp_dealloc */ 0, /* tp_vectorcall_offset */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ reversed_new__doc__, /* tp_doc */ reversed_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ reversed_next, /* tp_iternext */ reversediter_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ reversed_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ .tp_vectorcall = reversed_vectorcall, }; /* Function object implementation */ #include "Python.h" #include "pycore_code.h" // _PyCode_VerifyStateless() #include "pycore_dict.h" // _Py_INCREF_DICT() #include "pycore_function.h" // _PyFunction_Vectorcall #include "pycore_long.h" // _PyLong_GetOne() #include "pycore_modsupport.h" // _PyArg_NoKeywords() #include "pycore_object.h" // _PyObject_GC_UNTRACK() #include "pycore_pyerrors.h" // _PyErr_Occurred() #include "pycore_setobject.h" // _PySet_NextEntry() #include "pycore_stats.h" #include "pycore_weakref.h" // FT_CLEAR_WEAKREFS() #include "pycore_optimizer.h" // _PyJit_Tracer_InvalidateDependency static const char * func_event_name(PyFunction_WatchEvent event) { switch (event) { #define CASE(op) \ case PyFunction_EVENT_##op: \ return "PyFunction_EVENT_" #op; PY_FOREACH_FUNC_EVENT(CASE) #undef CASE } Py_UNREACHABLE(); } static void notify_func_watchers(PyInterpreterState *interp, PyFunction_WatchEvent event, PyFunctionObject *func, PyObject *new_value) { uint8_t bits = interp->active_func_watchers; int i = 0; while (bits) { assert(i < FUNC_MAX_WATCHERS); if (bits & 1) { PyFunction_WatchCallback cb = interp->func_watchers[i]; // callback must be non-null if the watcher bit is set assert(cb != NULL); if (cb(event, func, new_value) < 0) { PyErr_FormatUnraisable( "Exception ignored in %s watcher callback for function %U at %p", func_event_name(event), func->func_qualname, func); } } i++; bits >>= 1; } } static inline void handle_func_event(PyFunction_WatchEvent event, PyFunctionObject *func, PyObject *new_value) { assert(Py_REFCNT(func) > 0); PyInterpreterState *interp = _PyInterpreterState_GET(); assert(interp->_initialized); if (interp->active_func_watchers) { notify_func_watchers(interp, event, func, new_value); } switch (event) { case PyFunction_EVENT_MODIFY_CODE: case PyFunction_EVENT_MODIFY_DEFAULTS: case PyFunction_EVENT_MODIFY_KWDEFAULTS: case PyFunction_EVENT_MODIFY_QUALNAME: RARE_EVENT_INTERP_INC(interp, func_modification); break; default: break; } } int PyFunction_AddWatcher(PyFunction_WatchCallback callback) { PyInterpreterState *interp = _PyInterpreterState_GET(); assert(interp->_initialized); for (int i = 0; i < FUNC_MAX_WATCHERS; i++) { if (interp->func_watchers[i] == NULL) { interp->func_watchers[i] = callback; interp->active_func_watchers |= (1 << i); return i; } } PyErr_SetString(PyExc_RuntimeError, "no more func watcher IDs available"); return -1; } int PyFunction_ClearWatcher(int watcher_id) { PyInterpreterState *interp = _PyInterpreterState_GET(); if (watcher_id < 0 || watcher_id >= FUNC_MAX_WATCHERS) { PyErr_Format(PyExc_ValueError, "invalid func watcher ID %d", watcher_id); return -1; } if (!interp->func_watchers[watcher_id]) { PyErr_Format(PyExc_ValueError, "no func watcher set for ID %d", watcher_id); return -1; } interp->func_watchers[watcher_id] = NULL; interp->active_func_watchers &= ~(1 << watcher_id); return 0; } PyFunctionObject * _PyFunction_FromConstructor(PyFrameConstructor *constr) { PyObject *module; if (PyDict_GetItemRef(constr->fc_globals, &_Py_ID(__name__), &module) < 0) { return NULL; } PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type); if (op == NULL) { Py_XDECREF(module); return NULL; } _Py_INCREF_DICT(constr->fc_globals); op->func_globals = constr->fc_globals; _Py_INCREF_BUILTINS(constr->fc_builtins); op->func_builtins = constr->fc_builtins; op->func_name = Py_NewRef(constr->fc_name); op->func_qualname = Py_NewRef(constr->fc_qualname); _Py_INCREF_CODE((PyCodeObject *)constr->fc_code); op->func_code = constr->fc_code; op->func_defaults = Py_XNewRef(constr->fc_defaults); op->func_kwdefaults = Py_XNewRef(constr->fc_kwdefaults); op->func_closure = Py_XNewRef(constr->fc_closure); op->func_doc = Py_NewRef(Py_None); op->func_dict = NULL; op->func_weakreflist = NULL; op->func_module = module; op->func_annotations = NULL; op->func_annotate = NULL; op->func_typeparams = NULL; op->vectorcall = _PyFunction_Vectorcall; op->func_version = FUNC_VERSION_UNSET; // NOTE: functions created via FrameConstructor do not use deferred // reference counting because they are typically not part of cycles // nor accessed by multiple threads. _PyObject_GC_TRACK(op); handle_func_event(PyFunction_EVENT_CREATE, op, NULL); return op; } PyObject * PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname) { assert(globals != NULL); assert(PyDict_Check(globals)); _Py_INCREF_DICT(globals); PyCodeObject *code_obj = (PyCodeObject *)code; _Py_INCREF_CODE(code_obj); assert(code_obj->co_name != NULL); PyObject *name = Py_NewRef(code_obj->co_name); if (!qualname) { qualname = code_obj->co_qualname; } assert(qualname != NULL); Py_INCREF(qualname); PyObject *consts = code_obj->co_consts; assert(PyTuple_Check(consts)); PyObject *doc; if (code_obj->co_flags & CO_HAS_DOCSTRING) { assert(PyTuple_Size(consts) >= 1); doc = PyTuple_GetItem(consts, 0); if (!PyUnicode_Check(doc)) { doc = Py_None; } } else { doc = Py_None; } Py_INCREF(doc); // __module__: Use globals['__name__'] if it exists, or NULL. PyObject *module; PyObject *builtins = NULL; if (PyDict_GetItemRef(globals, &_Py_ID(__name__), &module) < 0) { goto error; } builtins = _PyDict_LoadBuiltinsFromGlobals(globals); if (builtins == NULL) { goto error; } PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type); if (op == NULL) { goto error; } /* Note: No failures from this point on, since func_dealloc() does not expect a partially-created object. */ op->func_globals = globals; op->func_builtins = builtins; op->func_name = name; op->func_qualname = qualname; op->func_code = (PyObject*)code_obj; op->func_defaults = NULL; // No default positional arguments op->func_kwdefaults = NULL; // No default keyword arguments op->func_closure = NULL; op->func_doc = doc; op->func_dict = NULL; op->func_weakreflist = NULL; op->func_module = module; op->func_annotations = NULL; op->func_annotate = NULL; op->func_typeparams = NULL; op->vectorcall = _PyFunction_Vectorcall; op->func_version = FUNC_VERSION_UNSET; if (((code_obj->co_flags & CO_NESTED) == 0) || (code_obj->co_flags & CO_METHOD)) { // Use deferred reference counting for top-level functions, but not // nested functions because they are more likely to capture variables, // which makes prompt deallocation more important. // // Nested methods (functions defined in class scope) are also deferred, // since they will likely be cleaned up by GC anyway. _PyObject_SetDeferredRefcount((PyObject *)op); } _PyObject_GC_TRACK(op); handle_func_event(PyFunction_EVENT_CREATE, op, NULL); return (PyObject *)op; error: Py_DECREF(globals); Py_DECREF(code_obj); Py_DECREF(name); Py_DECREF(qualname); Py_DECREF(doc); Py_XDECREF(module); Py_XDECREF(builtins); return NULL; } /* (This is purely internal documentation. There are no public APIs here.) Function (and code) versions ---------------------------- The Tier 1 specializer generates CALL variants that can be invalidated by changes to critical function attributes: - __code__ - __defaults__ - __kwdefaults__ - __closure__ For this purpose function objects have a 32-bit func_version member that the specializer writes to the specialized instruction's inline cache and which is checked by a guard on the specialized instructions. The MAKE_FUNCTION bytecode sets func_version from the code object's co_version field. The latter is initialized from a counter in the interpreter state (interp->func_state.next_version) and never changes. When this counter overflows, it remains zero and the specializer loses the ability to specialize calls to new functions. The func_version is reset to zero when any of the critical attributes is modified; after this point the specializer will no longer specialize calls to this function, and the guard will always fail. The function and code version cache ----------------------------------- The Tier 2 optimizer now has a problem, since it needs to find the function and code objects given only the version number from the inline cache. Our solution is to maintain a cache mapping version numbers to function and code objects. To limit the cache size we could hash the version number, but for now we simply use it modulo the table size. There are some corner cases (e.g. generator expressions) where we will be unable to find the function object in the cache but we can still find the code object. For this reason the cache stores both the function object and the code object. The cache doesn't contain strong references; cache entries are invalidated whenever the function or code object is deallocated. Invariants ---------- These should hold at any time except when one of the cache-mutating functions is running. - For any slot s at index i: - s->func == NULL or s->func->func_version % FUNC_VERSION_CACHE_SIZE == i - s->code == NULL or s->code->co_version % FUNC_VERSION_CACHE_SIZE == i if s->func != NULL, then s->func->func_code == s->code */ #ifndef Py_GIL_DISABLED static inline struct _func_version_cache_item * get_cache_item(PyInterpreterState *interp, uint32_t version) { return interp->func_state.func_version_cache + (version % FUNC_VERSION_CACHE_SIZE); } #endif void _PyFunction_SetVersion(PyFunctionObject *func, uint32_t version) { assert(func->func_version == FUNC_VERSION_UNSET); assert(version >= FUNC_VERSION_FIRST_VALID); // This should only be called from MAKE_FUNCTION. No code is specialized // based on the version, so we do not need to stop the world to set it. func->func_version = version; #ifndef Py_GIL_DISABLED PyInterpreterState *interp = _PyInterpreterState_GET(); struct _func_version_cache_item *slot = get_cache_item(interp, version); slot->func = func; slot->code = func->func_code; #endif } static void func_clear_version(PyInterpreterState *interp, PyFunctionObject *func) { if (func->func_version < FUNC_VERSION_FIRST_VALID) { // Version was never set or has already been cleared. return; } #ifndef Py_GIL_DISABLED struct _func_version_cache_item *slot = get_cache_item(interp, func->func_version); if (slot->func == func) { slot->func = NULL; // Leave slot->code alone, there may be use for it. } #endif func->func_version = FUNC_VERSION_CLEARED; } // Called when any of the critical function attributes are changed static void _PyFunction_ClearVersion(PyFunctionObject *func) { if (func->func_version < FUNC_VERSION_FIRST_VALID) { // Version was never set or has already been cleared. return; } PyInterpreterState *interp = _PyInterpreterState_GET(); _PyEval_StopTheWorld(interp); func_clear_version(interp, func); _PyEval_StartTheWorld(interp); } void _PyFunction_ClearCodeByVersion(uint32_t version) { #ifndef Py_GIL_DISABLED PyInterpreterState *interp = _PyInterpreterState_GET(); struct _func_version_cache_item *slot = get_cache_item(interp, version); if (slot->code) { assert(PyCode_Check(slot->code)); PyCodeObject *code = (PyCodeObject *)slot->code; if (code->co_version == version) { slot->code = NULL; slot->func = NULL; } } #endif } PyFunctionObject * _PyFunction_LookupByVersion(uint32_t version, PyObject **p_code) { #ifdef Py_GIL_DISABLED return NULL; #else PyInterpreterState *interp = _PyInterpreterState_GET(); struct _func_version_cache_item *slot = get_cache_item(interp, version); if (slot->code) { assert(PyCode_Check(slot->code)); PyCodeObject *code = (PyCodeObject *)slot->code; if (code->co_version == version) { *p_code = slot->code; } } else { *p_code = NULL; } if (slot->func && slot->func->func_version == version) { assert(slot->func->func_code == slot->code); return slot->func; } return NULL; #endif } uint32_t _PyFunction_GetVersionForCurrentState(PyFunctionObject *func) { return func->func_version; } PyObject * PyFunction_New(PyObject *code, PyObject *globals) { return PyFunction_NewWithQualName(code, globals, NULL); } PyObject * PyFunction_GetCode(PyObject *op) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return ((PyFunctionObject *) op) -> func_code; } PyObject * PyFunction_GetGlobals(PyObject *op) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return ((PyFunctionObject *) op) -> func_globals; } PyObject * PyFunction_GetModule(PyObject *op) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return ((PyFunctionObject *) op) -> func_module; } PyObject * PyFunction_GetDefaults(PyObject *op) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return ((PyFunctionObject *) op) -> func_defaults; } int PyFunction_SetDefaults(PyObject *op, PyObject *defaults) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return -1; } if (defaults == Py_None) defaults = NULL; else if (defaults && PyTuple_Check(defaults)) { Py_INCREF(defaults); } else { PyErr_SetString(PyExc_SystemError, "non-tuple default args"); return -1; } handle_func_event(PyFunction_EVENT_MODIFY_DEFAULTS, (PyFunctionObject *) op, defaults); _PyFunction_ClearVersion((PyFunctionObject *)op); Py_XSETREF(((PyFunctionObject *)op)->func_defaults, defaults); return 0; } void PyFunction_SetVectorcall(PyFunctionObject *func, vectorcallfunc vectorcall) { assert(func != NULL); _PyFunction_ClearVersion(func); func->vectorcall = vectorcall; } PyObject * PyFunction_GetKwDefaults(PyObject *op) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return ((PyFunctionObject *) op) -> func_kwdefaults; } int PyFunction_SetKwDefaults(PyObject *op, PyObject *defaults) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return -1; } if (defaults == Py_None) defaults = NULL; else if (defaults && PyDict_Check(defaults)) { Py_INCREF(defaults); } else { PyErr_SetString(PyExc_SystemError, "non-dict keyword only default args"); return -1; } handle_func_event(PyFunction_EVENT_MODIFY_KWDEFAULTS, (PyFunctionObject *) op, defaults); _PyFunction_ClearVersion((PyFunctionObject *)op); Py_XSETREF(((PyFunctionObject *)op)->func_kwdefaults, defaults); return 0; } PyObject * PyFunction_GetClosure(PyObject *op) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return ((PyFunctionObject *) op) -> func_closure; } int PyFunction_SetClosure(PyObject *op, PyObject *closure) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return -1; } if (closure == Py_None) closure = NULL; else if (PyTuple_Check(closure)) { Py_INCREF(closure); } else { PyErr_Format(PyExc_SystemError, "expected tuple for closure, got '%.100s'", Py_TYPE(closure)->tp_name); return -1; } _PyFunction_ClearVersion((PyFunctionObject *)op); Py_XSETREF(((PyFunctionObject *)op)->func_closure, closure); return 0; } static PyObject * func_get_annotation_dict(PyFunctionObject *op) { if (op->func_annotations == NULL) { if (op->func_annotate == NULL || !PyCallable_Check(op->func_annotate)) { Py_RETURN_NONE; } PyObject *one = _PyLong_GetOne(); PyObject *ann_dict = _PyObject_CallOneArg(op->func_annotate, one); if (ann_dict == NULL) { return NULL; } if (!PyDict_Check(ann_dict)) { PyErr_Format(PyExc_TypeError, "__annotate__() must return a dict, not %T", ann_dict); Py_DECREF(ann_dict); return NULL; } Py_XSETREF(op->func_annotations, ann_dict); return ann_dict; } if (PyTuple_CheckExact(op->func_annotations)) { PyObject *ann_tuple = op->func_annotations; PyObject *ann_dict = PyDict_New(); if (ann_dict == NULL) { return NULL; } assert(PyTuple_GET_SIZE(ann_tuple) % 2 == 0); for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(ann_tuple); i += 2) { int err = PyDict_SetItem(ann_dict, PyTuple_GET_ITEM(ann_tuple, i), PyTuple_GET_ITEM(ann_tuple, i + 1)); if (err < 0) { Py_DECREF(ann_dict); return NULL; } } Py_SETREF(op->func_annotations, ann_dict); } assert(PyDict_Check(op->func_annotations)); return op->func_annotations; } PyObject * PyFunction_GetAnnotations(PyObject *op) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return func_get_annotation_dict((PyFunctionObject *)op); } int PyFunction_SetAnnotations(PyObject *op, PyObject *annotations) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return -1; } if (annotations == Py_None) annotations = NULL; else if (annotations && PyDict_Check(annotations)) { Py_INCREF(annotations); } else { PyErr_SetString(PyExc_SystemError, "non-dict annotations"); return -1; } PyFunctionObject *func = (PyFunctionObject *)op; Py_XSETREF(func->func_annotations, annotations); Py_CLEAR(func->func_annotate); return 0; } /* Methods */ #define OFF(x) offsetof(PyFunctionObject, x) static PyMemberDef func_memberlist[] = { {"__closure__", _Py_T_OBJECT, OFF(func_closure), Py_READONLY}, {"__doc__", _Py_T_OBJECT, OFF(func_doc), 0}, {"__globals__", _Py_T_OBJECT, OFF(func_globals), Py_READONLY}, {"__module__", _Py_T_OBJECT, OFF(func_module), 0}, {"__builtins__", _Py_T_OBJECT, OFF(func_builtins), Py_READONLY}, {NULL} /* Sentinel */ }; /*[clinic input] class function "PyFunctionObject *" "&PyFunction_Type" [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=70af9c90aa2e71b0]*/ #include "clinic/funcobject.c.h" static PyObject * func_get_code(PyObject *self, void *Py_UNUSED(ignored)) { PyFunctionObject *op = _PyFunction_CAST(self); if (PySys_Audit("object.__getattr__", "Os", op, "__code__") < 0) { return NULL; } return Py_NewRef(op->func_code); } static int func_set_code(PyObject *self, PyObject *value, void *Py_UNUSED(ignored)) { PyFunctionObject *op = _PyFunction_CAST(self); /* Not legal to del f.func_code or to set it to anything * other than a code object. */ if (value == NULL || !PyCode_Check(value)) { PyErr_SetString(PyExc_TypeError, "__code__ must be set to a code object"); return -1; } if (PySys_Audit("object.__setattr__", "OsO", op, "__code__", value) < 0) { return -1; } int nfree = ((PyCodeObject *)value)->co_nfreevars; Py_ssize_t nclosure = (op->func_closure == NULL ? 0 : PyTuple_GET_SIZE(op->func_closure)); if (nclosure != nfree) { PyErr_Format(PyExc_ValueError, "%U() requires a code object with %zd free vars," " not %zd", op->func_name, nclosure, nfree); return -1; } PyObject *func_code = PyFunction_GET_CODE(op); int old_flags = ((PyCodeObject *)func_code)->co_flags; int new_flags = ((PyCodeObject *)value)->co_flags; int mask = CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR; if ((old_flags & mask) != (new_flags & mask)) { if (PyErr_Warn(PyExc_DeprecationWarning, "Assigning a code object of non-matching type is deprecated " "(e.g., from a generator to a plain function)") < 0) { return -1; } } handle_func_event(PyFunction_EVENT_MODIFY_CODE, op, value); _PyFunction_ClearVersion(op); Py_XSETREF(op->func_code, Py_NewRef(value)); return 0; } static PyObject * func_get_name(PyObject *self, void *Py_UNUSED(ignored)) { PyFunctionObject *op = _PyFunction_CAST(self); return Py_NewRef(op->func_name); } static int func_set_name(PyObject *self, PyObject *value, void *Py_UNUSED(ignored)) { PyFunctionObject *op = _PyFunction_CAST(self); /* Not legal to del f.func_name or to set it to anything * other than a string object. */ if (value == NULL || !PyUnicode_Check(value)) { PyErr_SetString(PyExc_TypeError, "__name__ must be set to a string object"); return -1; } Py_XSETREF(op->func_name, Py_NewRef(value)); return 0; } static PyObject * func_get_qualname(PyObject *self, void *Py_UNUSED(ignored)) { PyFunctionObject *op = _PyFunction_CAST(self); return Py_NewRef(op->func_qualname); } static int func_set_qualname(PyObject *self, PyObject *value, void *Py_UNUSED(ignored)) { PyFunctionObject *op = _PyFunction_CAST(self); /* Not legal to del f.__qualname__ or to set it to anything * other than a string object. */ if (value == NULL || !PyUnicode_Check(value)) { PyErr_SetString(PyExc_TypeError, "__qualname__ must be set to a string object"); return -1; } handle_func_event(PyFunction_EVENT_MODIFY_QUALNAME, (PyFunctionObject *) op, value); Py_XSETREF(op->func_qualname, Py_NewRef(value)); return 0; } static PyObject * func_get_defaults(PyObject *self, void *Py_UNUSED(ignored)) { PyFunctionObject *op = _PyFunction_CAST(self); if (PySys_Audit("object.__getattr__", "Os", op, "__defaults__") < 0) { return NULL; } if (op->func_defaults == NULL) { Py_RETURN_NONE; } return Py_NewRef(op->func_defaults); } static int func_set_defaults(PyObject *self, PyObject *value, void *Py_UNUSED(ignored)) { /* Legal to del f.func_defaults. * Can only set func_defaults to NULL or a tuple. */ PyFunctionObject *op = _PyFunction_CAST(self); if (value == Py_None) value = NULL; if (value != NULL && !PyTuple_Check(value)) { PyErr_SetString(PyExc_TypeError, "__defaults__ must be set to a tuple object"); return -1; } if (value) { if (PySys_Audit("object.__setattr__", "OsO", op, "__defaults__", value) < 0) { return -1; } } else if (PySys_Audit("object.__delattr__", "Os", op, "__defaults__") < 0) { return -1; } handle_func_event(PyFunction_EVENT_MODIFY_DEFAULTS, op, value); _PyFunction_ClearVersion(op); Py_XSETREF(op->func_defaults, Py_XNewRef(value)); return 0; } static PyObject * func_get_kwdefaults(PyObject *self, void *Py_UNUSED(ignored)) { PyFunctionObject *op = _PyFunction_CAST(self); if (PySys_Audit("object.__getattr__", "Os", op, "__kwdefaults__") < 0) { return NULL; } if (op->func_kwdefaults == NULL) { Py_RETURN_NONE; } return Py_NewRef(op->func_kwdefaults); } static int func_set_kwdefaults(PyObject *self, PyObject *value, void *Py_UNUSED(ignored)) { PyFunctionObject *op = _PyFunction_CAST(self); if (value == Py_None) value = NULL; /* Legal to del f.func_kwdefaults. * Can only set func_kwdefaults to NULL or a dict. */ if (value != NULL && !PyDict_Check(value)) { PyErr_SetString(PyExc_TypeError, "__kwdefaults__ must be set to a dict object"); return -1; } if (value) { if (PySys_Audit("object.__setattr__", "OsO", op, "__kwdefaults__", value) < 0) { return -1; } } else if (PySys_Audit("object.__delattr__", "Os", op, "__kwdefaults__") < 0) { return -1; } handle_func_event(PyFunction_EVENT_MODIFY_KWDEFAULTS, op, value); _PyFunction_ClearVersion(op); Py_XSETREF(op->func_kwdefaults, Py_XNewRef(value)); return 0; } /*[clinic input] @critical_section @getter function.__annotate__ Get the code object for a function. [clinic start generated code]*/ static PyObject * function___annotate___get_impl(PyFunctionObject *self) /*[clinic end generated code: output=5ec7219ff2bda9e6 input=7f3db11e3c3329f3]*/ { if (self->func_annotate == NULL) { Py_RETURN_NONE; } return Py_NewRef(self->func_annotate); } /*[clinic input] @critical_section @setter function.__annotate__ [clinic start generated code]*/ static int function___annotate___set_impl(PyFunctionObject *self, PyObject *value) /*[clinic end generated code: output=05b7dfc07ada66cd input=eb6225e358d97448]*/ { if (value == NULL) { PyErr_SetString(PyExc_TypeError, "__annotate__ cannot be deleted"); return -1; } if (Py_IsNone(value)) { Py_XSETREF(self->func_annotate, value); return 0; } else if (PyCallable_Check(value)) { Py_XSETREF(self->func_annotate, Py_XNewRef(value)); Py_CLEAR(self->func_annotations); return 0; } else { PyErr_SetString(PyExc_TypeError, "__annotate__ must be callable or None"); return -1; } } /*[clinic input] @critical_section @getter function.__annotations__ Dict of annotations in a function object. [clinic start generated code]*/ static PyObject * function___annotations___get_impl(PyFunctionObject *self) /*[clinic end generated code: output=a4cf4c884c934cbb input=92643d7186c1ad0c]*/ { PyObject *d = NULL; if (self->func_annotations == NULL && (self->func_annotate == NULL || !PyCallable_Check(self->func_annotate))) { self->func_annotations = PyDict_New(); if (self->func_annotations == NULL) return NULL; } d = func_get_annotation_dict(self); return Py_XNewRef(d); } /*[clinic input] @critical_section @setter function.__annotations__ [clinic start generated code]*/ static int function___annotations___set_impl(PyFunctionObject *self, PyObject *value) /*[clinic end generated code: output=a61795d4a95eede4 input=5302641f686f0463]*/ { if (value == Py_None) value = NULL; /* Legal to del f.func_annotations. * Can only set func_annotations to NULL (through C api) * or a dict. */ if (value != NULL && !PyDict_Check(value)) { PyErr_SetString(PyExc_TypeError, "__annotations__ must be set to a dict object"); return -1; } Py_XSETREF(self->func_annotations, Py_XNewRef(value)); Py_CLEAR(self->func_annotate); return 0; } /*[clinic input] @critical_section @getter function.__type_params__ Get the declared type parameters for a function. [clinic start generated code]*/ static PyObject * function___type_params___get_impl(PyFunctionObject *self) /*[clinic end generated code: output=eb844d7ffca517a8 input=0864721484293724]*/ { if (self->func_typeparams == NULL) { return PyTuple_New(0); } assert(PyTuple_Check(self->func_typeparams)); return Py_NewRef(self->func_typeparams); } /*[clinic input] @critical_section @setter function.__type_params__ [clinic start generated code]*/ static int function___type_params___set_impl(PyFunctionObject *self, PyObject *value) /*[clinic end generated code: output=038b4cda220e56fb input=3862fbd4db2b70e8]*/ { /* Not legal to del f.__type_params__ or to set it to anything * other than a tuple object. */ if (value == NULL || !PyTuple_Check(value)) { PyErr_SetString(PyExc_TypeError, "__type_params__ must be set to a tuple"); return -1; } Py_XSETREF(self->func_typeparams, Py_NewRef(value)); return 0; } PyObject * _Py_set_function_type_params(PyThreadState *Py_UNUSED(ignored), PyObject *func, PyObject *type_params) { assert(PyFunction_Check(func)); assert(PyTuple_Check(type_params)); PyFunctionObject *f = (PyFunctionObject *)func; Py_XSETREF(f->func_typeparams, Py_NewRef(type_params)); return Py_NewRef(func); } static PyGetSetDef func_getsetlist[] = { {"__code__", func_get_code, func_set_code}, {"__defaults__", func_get_defaults, func_set_defaults}, {"__kwdefaults__", func_get_kwdefaults, func_set_kwdefaults}, FUNCTION___ANNOTATIONS___GETSETDEF FUNCTION___ANNOTATE___GETSETDEF {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict}, {"__name__", func_get_name, func_set_name}, {"__qualname__", func_get_qualname, func_set_qualname}, FUNCTION___TYPE_PARAMS___GETSETDEF {NULL} /* Sentinel */ }; /* function.__new__() maintains the following invariants for closures. The closure must correspond to the free variables of the code object. if len(code.co_freevars) == 0: closure = NULL else: len(closure) == len(code.co_freevars) for every elt in closure, type(elt) == cell */ /*[clinic input] @classmethod function.__new__ as func_new code: object(type="PyCodeObject *", subclass_of="&PyCode_Type") a code object globals: object(subclass_of="&PyDict_Type") the globals dictionary name: object = None a string that overrides the name from the code object argdefs as defaults: object = None a tuple that specifies the default argument values closure: object = None a tuple that supplies the bindings for free variables kwdefaults: object = None a dictionary that specifies the default keyword argument values Create a function object. [clinic start generated code]*/ static PyObject * func_new_impl(PyTypeObject *type, PyCodeObject *code, PyObject *globals, PyObject *name, PyObject *defaults, PyObject *closure, PyObject *kwdefaults) /*[clinic end generated code: output=de72f4c22ac57144 input=20c9c9f04ad2d3f2]*/ { PyFunctionObject *newfunc; Py_ssize_t nclosure; if (name != Py_None && !PyUnicode_Check(name)) { PyErr_SetString(PyExc_TypeError, "arg 3 (name) must be None or string"); return NULL; } if (defaults != Py_None && !PyTuple_Check(defaults)) { PyErr_SetString(PyExc_TypeError, "arg 4 (defaults) must be None or tuple"); return NULL; } if (!PyTuple_Check(closure)) { if (code->co_nfreevars && closure == Py_None) { PyErr_SetString(PyExc_TypeError, "arg 5 (closure) must be tuple"); return NULL; } else if (closure != Py_None) { PyErr_SetString(PyExc_TypeError, "arg 5 (closure) must be None or tuple"); return NULL; } } if (kwdefaults != Py_None && !PyDict_Check(kwdefaults)) { PyErr_SetString(PyExc_TypeError, "arg 6 (kwdefaults) must be None or dict"); return NULL; } /* check that the closure is well-formed */ nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure); if (code->co_nfreevars != nclosure) return PyErr_Format(PyExc_ValueError, "%U requires closure of length %zd, not %zd", code->co_name, code->co_nfreevars, nclosure); if (nclosure) { Py_ssize_t i; for (i = 0; i < nclosure; i++) { PyObject *o = PyTuple_GET_ITEM(closure, i); if (!PyCell_Check(o)) { return PyErr_Format(PyExc_TypeError, "arg 5 (closure) expected cell, found %s", Py_TYPE(o)->tp_name); } } } if (PySys_Audit("function.__new__", "O", code) < 0) { return NULL; } newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code, globals); if (newfunc == NULL) { return NULL; } if (name != Py_None) { Py_SETREF(newfunc->func_name, Py_NewRef(name)); } if (defaults != Py_None) { newfunc->func_defaults = Py_NewRef(defaults); } if (closure != Py_None) { newfunc->func_closure = Py_NewRef(closure); } if (kwdefaults != Py_None) { newfunc->func_kwdefaults = Py_NewRef(kwdefaults); } return (PyObject *)newfunc; } static int func_clear(PyObject *self) { PyFunctionObject *op = _PyFunction_CAST(self); func_clear_version(_PyInterpreterState_GET(), op); PyObject *globals = op->func_globals; op->func_globals = NULL; if (globals != NULL) { _Py_DECREF_DICT(globals); } PyObject *builtins = op->func_builtins; op->func_builtins = NULL; if (builtins != NULL) { _Py_DECREF_BUILTINS(builtins); } Py_CLEAR(op->func_module); Py_CLEAR(op->func_defaults); Py_CLEAR(op->func_kwdefaults); Py_CLEAR(op->func_doc); Py_CLEAR(op->func_dict); Py_CLEAR(op->func_closure); Py_CLEAR(op->func_annotations); Py_CLEAR(op->func_annotate); Py_CLEAR(op->func_typeparams); // Don't Py_CLEAR(op->func_code), since code is always required // to be non-NULL. Similarly, name and qualname shouldn't be NULL. // However, name and qualname could be str subclasses, so they // could have reference cycles. The solution is to replace them // with a genuinely immutable string. Py_SETREF(op->func_name, &_Py_STR(empty)); Py_SETREF(op->func_qualname, &_Py_STR(empty)); return 0; } static void func_dealloc(PyObject *self) { PyFunctionObject *op = _PyFunction_CAST(self); _PyObject_ResurrectStart(self); handle_func_event(PyFunction_EVENT_DESTROY, op, NULL); if (_PyObject_ResurrectEnd(self)) { return; } #if _Py_TIER2 _Py_Executors_InvalidateDependency(_PyInterpreterState_GET(), self, 1); _PyJit_Tracer_InvalidateDependency(_PyThreadState_GET(), self); #endif _PyObject_GC_UNTRACK(op); FT_CLEAR_WEAKREFS(self, op->func_weakreflist); (void)func_clear((PyObject*)op); // These aren't cleared by func_clear(). _Py_DECREF_CODE((PyCodeObject *)op->func_code); Py_DECREF(op->func_name); Py_DECREF(op->func_qualname); PyObject_GC_Del(op); } static PyObject* func_repr(PyObject *self) { PyFunctionObject *op = _PyFunction_CAST(self); return PyUnicode_FromFormat("", op->func_qualname, op); } static int func_traverse(PyObject *self, visitproc visit, void *arg) { PyFunctionObject *f = _PyFunction_CAST(self); Py_VISIT(f->func_code); Py_VISIT(f->func_globals); Py_VISIT(f->func_builtins); Py_VISIT(f->func_module); Py_VISIT(f->func_defaults); Py_VISIT(f->func_kwdefaults); Py_VISIT(f->func_doc); Py_VISIT(f->func_name); Py_VISIT(f->func_dict); Py_VISIT(f->func_closure); Py_VISIT(f->func_annotations); Py_VISIT(f->func_annotate); Py_VISIT(f->func_typeparams); Py_VISIT(f->func_qualname); return 0; } /* Bind a function to an object */ static PyObject * func_descr_get(PyObject *func, PyObject *obj, PyObject *type) { if (obj == Py_None || obj == NULL) { return Py_NewRef(func); } return PyMethod_New(func, obj); } PyTypeObject PyFunction_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "function", sizeof(PyFunctionObject), 0, func_dealloc, /* tp_dealloc */ offsetof(PyFunctionObject, vectorcall), /* tp_vectorcall_offset */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ func_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ PyVectorcall_Call, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_VECTORCALL | Py_TPFLAGS_METHOD_DESCRIPTOR, /* tp_flags */ func_new__doc__, /* tp_doc */ func_traverse, /* tp_traverse */ func_clear, /* tp_clear */ 0, /* tp_richcompare */ offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ func_memberlist, /* tp_members */ func_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ func_descr_get, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ func_new, /* tp_new */ }; int _PyFunction_VerifyStateless(PyThreadState *tstate, PyObject *func) { assert(!PyErr_Occurred()); assert(PyFunction_Check(func)); // Check the globals. PyObject *globalsns = PyFunction_GET_GLOBALS(func); if (globalsns != NULL && !PyDict_Check(globalsns)) { _PyErr_Format(tstate, PyExc_TypeError, "unsupported globals %R", globalsns); return -1; } // Check the builtins. PyObject *builtinsns = _PyFunction_GET_BUILTINS(func); if (builtinsns != NULL && !PyDict_Check(builtinsns)) { _PyErr_Format(tstate, PyExc_TypeError, "unsupported builtins %R", builtinsns); return -1; } // Disallow __defaults__. PyObject *defaults = PyFunction_GET_DEFAULTS(func); if (defaults != NULL) { assert(PyTuple_Check(defaults)); // per PyFunction_New() if (PyTuple_GET_SIZE(defaults) > 0) { _PyErr_SetString(tstate, PyExc_ValueError, "defaults not supported"); return -1; } } // Disallow __kwdefaults__. PyObject *kwdefaults = PyFunction_GET_KW_DEFAULTS(func); if (kwdefaults != NULL) { assert(PyDict_Check(kwdefaults)); // per PyFunction_New() if (PyDict_Size(kwdefaults) > 0) { _PyErr_SetString(tstate, PyExc_ValueError, "keyword defaults not supported"); return -1; } } // Disallow __closure__. PyObject *closure = PyFunction_GET_CLOSURE(func); if (closure != NULL) { assert(PyTuple_Check(closure)); // per PyFunction_New() if (PyTuple_GET_SIZE(closure) > 0) { _PyErr_SetString(tstate, PyExc_ValueError, "closures not supported"); return -1; } } // Check the code. PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); if (_PyCode_VerifyStateless(tstate, co, NULL, globalsns, builtinsns) < 0) { return -1; } return 0; } static int functools_copy_attr(PyObject *wrapper, PyObject *wrapped, PyObject *name) { PyObject *value; int res = PyObject_GetOptionalAttr(wrapped, name, &value); if (value != NULL) { res = PyObject_SetAttr(wrapper, name, value); Py_DECREF(value); } return res; } // Similar to functools.wraps(wrapper, wrapped) static int functools_wraps(PyObject *wrapper, PyObject *wrapped) { #define COPY_ATTR(ATTR) \ do { \ if (functools_copy_attr(wrapper, wrapped, &_Py_ID(ATTR)) < 0) { \ return -1; \ } \ } while (0) \ COPY_ATTR(__module__); COPY_ATTR(__name__); COPY_ATTR(__qualname__); COPY_ATTR(__doc__); return 0; #undef COPY_ATTR } // Used for wrapping __annotations__ and __annotate__ on classmethod // and staticmethod objects. static PyObject * descriptor_get_wrapped_attribute(PyObject *wrapped, PyObject *obj, PyObject *name) { PyObject *dict = PyObject_GenericGetDict(obj, NULL); if (dict == NULL) { return NULL; } PyObject *res; if (PyDict_GetItemRef(dict, name, &res) < 0) { Py_DECREF(dict); return NULL; } if (res != NULL) { Py_DECREF(dict); return res; } res = PyObject_GetAttr(wrapped, name); if (res == NULL) { Py_DECREF(dict); return NULL; } if (PyDict_SetItem(dict, name, res) < 0) { Py_DECREF(dict); Py_DECREF(res); return NULL; } Py_DECREF(dict); return res; } static int descriptor_set_wrapped_attribute(PyObject *oobj, PyObject *name, PyObject *value, char *type_name) { PyObject *dict = PyObject_GenericGetDict(oobj, NULL); if (dict == NULL) { return -1; } if (value == NULL) { if (PyDict_DelItem(dict, name) < 0) { if (PyErr_ExceptionMatches(PyExc_KeyError)) { PyErr_Clear(); PyErr_Format(PyExc_AttributeError, "'%.200s' object has no attribute '%U'", type_name, name); Py_DECREF(dict); return -1; } else { Py_DECREF(dict); return -1; } } Py_DECREF(dict); return 0; } else { Py_DECREF(dict); return PyDict_SetItem(dict, name, value); } } /* Class method object */ /* A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom: class C: @classmethod def f(cls, arg1, arg2, argN): ... It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()); the instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument. Class methods are different than C++ or Java static methods. If you want those, see static methods below. */ typedef struct { PyObject_HEAD PyObject *cm_callable; PyObject *cm_dict; } classmethod; #define _PyClassMethod_CAST(cm) \ (assert(PyObject_TypeCheck((cm), &PyClassMethod_Type)), \ _Py_CAST(classmethod*, cm)) static void cm_dealloc(PyObject *self) { classmethod *cm = _PyClassMethod_CAST(self); _PyObject_GC_UNTRACK((PyObject *)cm); Py_XDECREF(cm->cm_callable); Py_XDECREF(cm->cm_dict); Py_TYPE(cm)->tp_free((PyObject *)cm); } static int cm_traverse(PyObject *self, visitproc visit, void *arg) { classmethod *cm = _PyClassMethod_CAST(self); Py_VISIT(cm->cm_callable); Py_VISIT(cm->cm_dict); return 0; } static int cm_clear(PyObject *self) { classmethod *cm = _PyClassMethod_CAST(self); Py_CLEAR(cm->cm_callable); Py_CLEAR(cm->cm_dict); return 0; } static PyObject * cm_descr_get(PyObject *self, PyObject *obj, PyObject *type) { classmethod *cm = (classmethod *)self; if (cm->cm_callable == NULL) { PyErr_SetString(PyExc_RuntimeError, "uninitialized classmethod object"); return NULL; } if (type == NULL) type = (PyObject *)(Py_TYPE(obj)); return PyMethod_New(cm->cm_callable, type); } static int cm_init(PyObject *self, PyObject *args, PyObject *kwds) { classmethod *cm = (classmethod *)self; PyObject *callable; if (!_PyArg_NoKeywords("classmethod", kwds)) return -1; if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable)) return -1; Py_XSETREF(cm->cm_callable, Py_NewRef(callable)); if (functools_wraps((PyObject *)cm, cm->cm_callable) < 0) { return -1; } return 0; } static PyMemberDef cm_memberlist[] = { {"__func__", _Py_T_OBJECT, offsetof(classmethod, cm_callable), Py_READONLY}, {"__wrapped__", _Py_T_OBJECT, offsetof(classmethod, cm_callable), Py_READONLY}, {NULL} /* Sentinel */ }; static PyObject * cm_get___isabstractmethod__(PyObject *self, void *closure) { classmethod *cm = _PyClassMethod_CAST(self); int res = _PyObject_IsAbstract(cm->cm_callable); if (res == -1) { return NULL; } else if (res) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } static PyObject * cm_get___annotations__(PyObject *self, void *closure) { classmethod *cm = _PyClassMethod_CAST(self); return descriptor_get_wrapped_attribute(cm->cm_callable, self, &_Py_ID(__annotations__)); } static int cm_set___annotations__(PyObject *self, PyObject *value, void *closure) { return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotations__), value, "classmethod"); } static PyObject * cm_get___annotate__(PyObject *self, void *closure) { classmethod *cm = _PyClassMethod_CAST(self); return descriptor_get_wrapped_attribute(cm->cm_callable, self, &_Py_ID(__annotate__)); } static int cm_set___annotate__(PyObject *self, PyObject *value, void *closure) { return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotate__), value, "classmethod"); } static PyGetSetDef cm_getsetlist[] = { {"__isabstractmethod__", cm_get___isabstractmethod__, NULL, NULL, NULL}, {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL}, {"__annotations__", cm_get___annotations__, cm_set___annotations__, NULL, NULL}, {"__annotate__", cm_get___annotate__, cm_set___annotate__, NULL, NULL}, {NULL} /* Sentinel */ }; static PyMethodDef cm_methodlist[] = { {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, NULL}, {NULL} /* Sentinel */ }; static PyObject* cm_repr(PyObject *self) { classmethod *cm = _PyClassMethod_CAST(self); return PyUnicode_FromFormat("", cm->cm_callable); } PyDoc_STRVAR(classmethod_doc, "classmethod(function, /)\n\ --\n\ \n\ Convert a function to be a class method.\n\ \n\ A class method receives the class as implicit first argument,\n\ just like an instance method receives the instance.\n\ To declare a class method, use this idiom:\n\ \n\ class C:\n\ @classmethod\n\ def f(cls, arg1, arg2, argN):\n\ ...\n\ \n\ It can be called either on the class (e.g. C.f()) or on an instance\n\ (e.g. C().f()). The instance is ignored except for its class.\n\ If a class method is called for a derived class, the derived class\n\ object is passed as the implied first argument.\n\ \n\ Class methods are different than C++ or Java static methods.\n\ If you want those, see the staticmethod builtin."); PyTypeObject PyClassMethod_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "classmethod", sizeof(classmethod), 0, cm_dealloc, /* tp_dealloc */ 0, /* tp_vectorcall_offset */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ cm_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, classmethod_doc, /* tp_doc */ cm_traverse, /* tp_traverse */ cm_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ cm_methodlist, /* tp_methods */ cm_memberlist, /* tp_members */ cm_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ cm_descr_get, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(classmethod, cm_dict), /* tp_dictoffset */ cm_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; PyObject * PyClassMethod_New(PyObject *callable) { classmethod *cm = (classmethod *) PyType_GenericAlloc(&PyClassMethod_Type, 0); if (cm != NULL) { cm->cm_callable = Py_NewRef(callable); } return (PyObject *)cm; } /* Static method object */ /* A static method does not receive an implicit first argument. To declare a static method, use this idiom: class C: @staticmethod def f(arg1, arg2, argN): ... It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). Both the class and the instance are ignored, and neither is passed implicitly as the first argument to the method. Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see class methods above. */ typedef struct { PyObject_HEAD PyObject *sm_callable; PyObject *sm_dict; } staticmethod; #define _PyStaticMethod_CAST(cm) \ (assert(PyObject_TypeCheck((cm), &PyStaticMethod_Type)), \ _Py_CAST(staticmethod*, cm)) static void sm_dealloc(PyObject *self) { staticmethod *sm = _PyStaticMethod_CAST(self); _PyObject_GC_UNTRACK((PyObject *)sm); Py_XDECREF(sm->sm_callable); Py_XDECREF(sm->sm_dict); Py_TYPE(sm)->tp_free((PyObject *)sm); } static int sm_traverse(PyObject *self, visitproc visit, void *arg) { staticmethod *sm = _PyStaticMethod_CAST(self); Py_VISIT(sm->sm_callable); Py_VISIT(sm->sm_dict); return 0; } static int sm_clear(PyObject *self) { staticmethod *sm = _PyStaticMethod_CAST(self); Py_CLEAR(sm->sm_callable); Py_CLEAR(sm->sm_dict); return 0; } static PyObject * sm_descr_get(PyObject *self, PyObject *obj, PyObject *type) { staticmethod *sm = (staticmethod *)self; if (sm->sm_callable == NULL) { PyErr_SetString(PyExc_RuntimeError, "uninitialized staticmethod object"); return NULL; } return Py_NewRef(sm->sm_callable); } static int sm_init(PyObject *self, PyObject *args, PyObject *kwds) { staticmethod *sm = (staticmethod *)self; PyObject *callable; if (!_PyArg_NoKeywords("staticmethod", kwds)) return -1; if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable)) return -1; Py_XSETREF(sm->sm_callable, Py_NewRef(callable)); if (functools_wraps((PyObject *)sm, sm->sm_callable) < 0) { return -1; } return 0; } static PyObject* sm_call(PyObject *callable, PyObject *args, PyObject *kwargs) { staticmethod *sm = (staticmethod *)callable; return PyObject_Call(sm->sm_callable, args, kwargs); } static PyMemberDef sm_memberlist[] = { {"__func__", _Py_T_OBJECT, offsetof(staticmethod, sm_callable), Py_READONLY}, {"__wrapped__", _Py_T_OBJECT, offsetof(staticmethod, sm_callable), Py_READONLY}, {NULL} /* Sentinel */ }; static PyObject * sm_get___isabstractmethod__(PyObject *self, void *closure) { staticmethod *sm = _PyStaticMethod_CAST(self); int res = _PyObject_IsAbstract(sm->sm_callable); if (res == -1) { return NULL; } else if (res) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } static PyObject * sm_get___annotations__(PyObject *self, void *closure) { staticmethod *sm = _PyStaticMethod_CAST(self); return descriptor_get_wrapped_attribute(sm->sm_callable, self, &_Py_ID(__annotations__)); } static int sm_set___annotations__(PyObject *self, PyObject *value, void *closure) { return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotations__), value, "staticmethod"); } static PyObject * sm_get___annotate__(PyObject *self, void *closure) { staticmethod *sm = _PyStaticMethod_CAST(self); return descriptor_get_wrapped_attribute(sm->sm_callable, self, &_Py_ID(__annotate__)); } static int sm_set___annotate__(PyObject *self, PyObject *value, void *closure) { return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotate__), value, "staticmethod"); } static PyGetSetDef sm_getsetlist[] = { {"__isabstractmethod__", sm_get___isabstractmethod__, NULL, NULL, NULL}, {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL}, {"__annotations__", sm_get___annotations__, sm_set___annotations__, NULL, NULL}, {"__annotate__", sm_get___annotate__, sm_set___annotate__, NULL, NULL}, {NULL} /* Sentinel */ }; static PyMethodDef sm_methodlist[] = { {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, NULL}, {NULL} /* Sentinel */ }; static PyObject* sm_repr(PyObject *self) { staticmethod *sm = _PyStaticMethod_CAST(self); return PyUnicode_FromFormat("", sm->sm_callable); } PyDoc_STRVAR(staticmethod_doc, "staticmethod(function, /)\n\ --\n\ \n\ Convert a function to be a static method.\n\ \n\ A static method does not receive an implicit first argument.\n\ To declare a static method, use this idiom:\n\ \n\ class C:\n\ @staticmethod\n\ def f(arg1, arg2, argN):\n\ ...\n\ \n\ It can be called either on the class (e.g. C.f()) or on an instance\n\ (e.g. C().f()). Both the class and the instance are ignored, and\n\ neither is passed implicitly as the first argument to the method.\n\ \n\ Static methods in Python are similar to those found in Java or C++.\n\ For a more advanced concept, see the classmethod builtin."); PyTypeObject PyStaticMethod_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "staticmethod", sizeof(staticmethod), 0, sm_dealloc, /* tp_dealloc */ 0, /* tp_vectorcall_offset */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ sm_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ sm_call, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, staticmethod_doc, /* tp_doc */ sm_traverse, /* tp_traverse */ sm_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ sm_methodlist, /* tp_methods */ sm_memberlist, /* tp_members */ sm_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ sm_descr_get, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(staticmethod, sm_dict), /* tp_dictoffset */ sm_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; PyObject * PyStaticMethod_New(PyObject *callable) { staticmethod *sm = (staticmethod *) PyType_GenericAlloc(&PyStaticMethod_Type, 0); if (sm != NULL) { sm->sm_callable = Py_NewRef(callable); } return (PyObject *)sm; } /* PyByteArray (bytearray) implementation */ #include "Python.h" #include "pycore_abstract.h" // _PyIndex_Check() #include "pycore_bytes_methods.h" #include "pycore_bytesobject.h" #include "pycore_ceval.h" // _PyEval_GetBuiltin() #include "pycore_critical_section.h" #include "pycore_object.h" // _PyObject_GC_UNTRACK() #include "pycore_strhex.h" // _Py_strhex_with_sep() #include "pycore_long.h" // _PyLong_FromUnsignedChar() #include "pycore_pyatomic_ft_wrappers.h" #include "bytesobject.h" /*[clinic input] class bytearray "PyByteArrayObject *" "&PyByteArray_Type" [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=5535b77c37a119e0]*/ /* Max number of bytes a bytearray can contain */ #define PyByteArray_SIZE_MAX ((Py_ssize_t)(PY_SSIZE_T_MAX - _PyBytesObject_SIZE)) /* Helpers */ static int _getbytevalue(PyObject* arg, int *value) { int overflow; long face_value = PyLong_AsLongAndOverflow(arg, &overflow); if (face_value == -1 && PyErr_Occurred()) { *value = -1; return 0; } if (face_value < 0 || face_value >= 256) { /* this includes an overflow in converting to C long */ PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)"); *value = -1; return 0; } *value = face_value; return 1; } static void bytearray_reinit_from_bytes(PyByteArrayObject *self, Py_ssize_t size, Py_ssize_t alloc) { self->ob_bytes = self->ob_start = PyBytes_AS_STRING(self->ob_bytes_object); Py_SET_SIZE(self, size); FT_ATOMIC_STORE_SSIZE_RELAXED(self->ob_alloc, alloc); } static int bytearray_getbuffer_lock_held(PyObject *self, Py_buffer *view, int flags) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self); PyByteArrayObject *obj = _PyByteArray_CAST(self); if (view == NULL) { PyErr_SetString(PyExc_BufferError, "bytearray_getbuffer: view==NULL argument is obsolete"); return -1; } void *ptr = (void *) PyByteArray_AS_STRING(obj); if (PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags) < 0) { return -1; } obj->ob_exports++; return 0; } static int bytearray_getbuffer(PyObject *self, Py_buffer *view, int flags) { int ret; Py_BEGIN_CRITICAL_SECTION(self); ret = bytearray_getbuffer_lock_held(self, view, flags); Py_END_CRITICAL_SECTION(); return ret; } static void bytearray_releasebuffer(PyObject *self, Py_buffer *view) { Py_BEGIN_CRITICAL_SECTION(self); PyByteArrayObject *obj = _PyByteArray_CAST(self); obj->ob_exports--; assert(obj->ob_exports >= 0); Py_END_CRITICAL_SECTION(); } typedef PyObject* (*_ba_bytes_op)(const char *buf, Py_ssize_t len, PyObject *sub, Py_ssize_t start, Py_ssize_t end); static PyObject * _bytearray_with_buffer(PyByteArrayObject *self, _ba_bytes_op op, PyObject *sub, Py_ssize_t start, Py_ssize_t end) { PyObject *res; _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self); /* Increase exports to prevent bytearray storage from changing during op. */ self->ob_exports++; res = op(PyByteArray_AS_STRING(self), Py_SIZE(self), sub, start, end); self->ob_exports--; return res; } static int _canresize(PyByteArrayObject *self) { if (self->ob_exports > 0) { PyErr_SetString(PyExc_BufferError, "Existing exports of data: object cannot be re-sized"); return 0; } return 1; } #include "clinic/bytearrayobject.c.h" /* Direct API functions */ PyObject * PyByteArray_FromObject(PyObject *input) { return PyObject_CallOneArg((PyObject *)&PyByteArray_Type, input); } static PyObject * _PyByteArray_FromBufferObject(PyObject *obj) { PyObject *result; Py_buffer view; if (PyObject_GetBuffer(obj, &view, PyBUF_FULL_RO) < 0) { return NULL; } result = PyByteArray_FromStringAndSize(NULL, view.len); if (result != NULL && PyBuffer_ToContiguous(PyByteArray_AS_STRING(result), &view, view.len, 'C') < 0) { Py_CLEAR(result); } PyBuffer_Release(&view); return result; } PyObject * PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size) { PyByteArrayObject *new; if (size < 0) { PyErr_SetString(PyExc_SystemError, "Negative size passed to PyByteArray_FromStringAndSize"); return NULL; } new = PyObject_New(PyByteArrayObject, &PyByteArray_Type); if (new == NULL) { return NULL; } /* Fill values used in bytearray_dealloc. In an optimized build the memory isn't zeroed and ob_exports would be uninitialized when when PyBytes_FromStringAndSize errored leading to intermittent test failures. */ new->ob_exports = 0; /* Optimization: size=0 bytearray should not allocate space PyBytes_FromStringAndSize returns the empty bytes global when size=0 so no allocation occurs. */ new->ob_bytes_object = PyBytes_FromStringAndSize(NULL, size); if (new->ob_bytes_object == NULL) { Py_DECREF(new); return NULL; } bytearray_reinit_from_bytes(new, size, size); if (bytes != NULL && size > 0) { memcpy(new->ob_bytes, bytes, size); } return (PyObject *)new; } Py_ssize_t PyByteArray_Size(PyObject *self) { assert(self != NULL); assert(PyByteArray_Check(self)); return PyByteArray_GET_SIZE(self); } char * PyByteArray_AsString(PyObject *self) { assert(self != NULL); assert(PyByteArray_Check(self)); return PyByteArray_AS_STRING(self); } static int bytearray_resize_lock_held(PyObject *self, Py_ssize_t requested_size) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self); PyByteArrayObject *obj = ((PyByteArrayObject *)self); /* All computations are done unsigned to avoid integer overflows (see issue #22335). */ size_t alloc = (size_t) obj->ob_alloc; size_t logical_offset = (size_t) (obj->ob_start - obj->ob_bytes); size_t size = (size_t) requested_size; assert(self != NULL); assert(PyByteArray_Check(self)); assert(logical_offset <= alloc); if (requested_size < 0) { PyErr_Format(PyExc_ValueError, "Can only resize to positive sizes, got %zd", requested_size); return -1; } if (requested_size == Py_SIZE(self)) { return 0; } if (!_canresize(obj)) { return -1; } if (size + logical_offset <= alloc) { /* Current buffer is large enough to host the requested size, decide on a strategy. */ if (size < alloc / 2) { /* Major downsize; resize down to exact size */ alloc = size; } else { /* Minor downsize; quick exit */ Py_SET_SIZE(self, size); /* Add mid-buffer null; end provided by bytes. */ PyByteArray_AS_STRING(self)[size] = '\0'; /* Trailing null */ return 0; } } else { /* Need growing, decide on a strategy */ if (size <= alloc * 1.125) { /* Moderate upsize; overallocate similar to list_resize() */ alloc = size + (size >> 3) + (size < 9 ? 3 : 6); } else { /* Major upsize; resize up to exact size */ alloc = size; } } if (alloc > PyByteArray_SIZE_MAX) { PyErr_NoMemory(); return -1; } /* Re-align data to the start of the allocation. */ if (logical_offset > 0) { /* optimization tradeoff: This is faster than a new allocation when the number of bytes being removed in a resize is small; for large size changes it may be better to just make a new bytes object as _PyBytes_Resize will do a malloc + memcpy internally. */ memmove(obj->ob_bytes, obj->ob_start, Py_MIN(requested_size, Py_SIZE(self))); } int ret = _PyBytes_Resize(&obj->ob_bytes_object, alloc); if (ret == -1) { obj->ob_bytes_object = Py_GetConstant(Py_CONSTANT_EMPTY_BYTES); size = alloc = 0; } bytearray_reinit_from_bytes(obj, size, alloc); if (alloc != size) { /* Add mid-buffer null; end provided by bytes. */ obj->ob_bytes[size] = '\0'; } return ret; } int PyByteArray_Resize(PyObject *self, Py_ssize_t requested_size) { int ret; Py_BEGIN_CRITICAL_SECTION(self); ret = bytearray_resize_lock_held(self, requested_size); Py_END_CRITICAL_SECTION(); return ret; } PyObject * PyByteArray_Concat(PyObject *a, PyObject *b) { Py_buffer va, vb; PyByteArrayObject *result = NULL; va.len = -1; vb.len = -1; if (PyObject_GetBuffer(a, &va, PyBUF_SIMPLE) != 0 || PyObject_GetBuffer(b, &vb, PyBUF_SIMPLE) != 0) { PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s", Py_TYPE(b)->tp_name, Py_TYPE(a)->tp_name); goto done; } if (va.len > PyByteArray_SIZE_MAX - vb.len) { PyErr_NoMemory(); goto done; } result = (PyByteArrayObject *) \ PyByteArray_FromStringAndSize(NULL, va.len + vb.len); // result->ob_bytes is NULL if result is an empty bytearray: // if va.len + vb.len equals zero. if (result != NULL && result->ob_bytes != NULL) { memcpy(result->ob_bytes, va.buf, va.len); memcpy(result->ob_bytes + va.len, vb.buf, vb.len); } done: if (va.len != -1) PyBuffer_Release(&va); if (vb.len != -1) PyBuffer_Release(&vb); return (PyObject *)result; } /* Functions stuffed into the type object */ static Py_ssize_t bytearray_length(PyObject *op) { return PyByteArray_GET_SIZE(op); } static PyObject * bytearray_iconcat_lock_held(PyObject *op, PyObject *other) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op); PyByteArrayObject *self = _PyByteArray_CAST(op); Py_buffer vo; if (PyObject_GetBuffer(other, &vo, PyBUF_SIMPLE) != 0) { PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s", Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name); return NULL; } Py_ssize_t size = Py_SIZE(self); if (size > PyByteArray_SIZE_MAX - vo.len) { PyBuffer_Release(&vo); return PyErr_NoMemory(); } if (bytearray_resize_lock_held((PyObject *)self, size + vo.len) < 0) { PyBuffer_Release(&vo); return NULL; } memcpy(PyByteArray_AS_STRING(self) + size, vo.buf, vo.len); PyBuffer_Release(&vo); return Py_NewRef(self); } static PyObject * bytearray_iconcat(PyObject *op, PyObject *other) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(op); ret = bytearray_iconcat_lock_held(op, other); Py_END_CRITICAL_SECTION(); return ret; } static PyObject * bytearray_repeat_lock_held(PyObject *op, Py_ssize_t count) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op); PyByteArrayObject *self = _PyByteArray_CAST(op); if (count < 0) { count = 0; } const Py_ssize_t mysize = Py_SIZE(self); if (count > 0 && mysize > PyByteArray_SIZE_MAX / count) { return PyErr_NoMemory(); } Py_ssize_t size = mysize * count; PyByteArrayObject* result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size); const char* buf = PyByteArray_AS_STRING(self); if (result != NULL && size != 0) { _PyBytes_Repeat(result->ob_bytes, size, buf, mysize); } return (PyObject *)result; } static PyObject * bytearray_repeat(PyObject *op, Py_ssize_t count) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(op); ret = bytearray_repeat_lock_held(op, count); Py_END_CRITICAL_SECTION(); return ret; } static PyObject * bytearray_irepeat_lock_held(PyObject *op, Py_ssize_t count) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op); PyByteArrayObject *self = _PyByteArray_CAST(op); if (count < 0) { count = 0; } else if (count == 1) { return Py_NewRef(self); } const Py_ssize_t mysize = Py_SIZE(self); if (count > 0 && mysize > PyByteArray_SIZE_MAX / count) { return PyErr_NoMemory(); } const Py_ssize_t size = mysize * count; if (bytearray_resize_lock_held((PyObject *)self, size) < 0) { return NULL; } char* buf = PyByteArray_AS_STRING(self); _PyBytes_Repeat(buf, size, buf, mysize); return Py_NewRef(self); } static PyObject * bytearray_irepeat(PyObject *op, Py_ssize_t count) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(op); ret = bytearray_irepeat_lock_held(op, count); Py_END_CRITICAL_SECTION(); return ret; } static PyObject * bytearray_getitem_lock_held(PyObject *op, Py_ssize_t i) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op); PyByteArrayObject *self = _PyByteArray_CAST(op); if (i < 0 || i >= Py_SIZE(self)) { PyErr_SetString(PyExc_IndexError, "bytearray index out of range"); return NULL; } return _PyLong_FromUnsignedChar((unsigned char)(self->ob_start[i])); } static PyObject * bytearray_getitem(PyObject *op, Py_ssize_t i) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(op); ret = bytearray_getitem_lock_held(op, i); Py_END_CRITICAL_SECTION(); return ret; } static PyObject * bytearray_subscript_lock_held(PyObject *op, PyObject *index) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op); PyByteArrayObject *self = _PyByteArray_CAST(op); if (_PyIndex_Check(index)) { Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError); if (i == -1 && PyErr_Occurred()) return NULL; if (i < 0) i += PyByteArray_GET_SIZE(self); if (i < 0 || i >= Py_SIZE(self)) { PyErr_SetString(PyExc_IndexError, "bytearray index out of range"); return NULL; } return _PyLong_FromUnsignedChar((unsigned char)(self->ob_start[i])); } else if (PySlice_Check(index)) { Py_ssize_t start, stop, step, slicelength, i; size_t cur; if (PySlice_Unpack(index, &start, &stop, &step) < 0) { return NULL; } slicelength = PySlice_AdjustIndices(PyByteArray_GET_SIZE(self), &start, &stop, step); if (slicelength <= 0) return PyByteArray_FromStringAndSize("", 0); else if (step == 1) { return PyByteArray_FromStringAndSize( PyByteArray_AS_STRING(self) + start, slicelength); } else { char *source_buf = PyByteArray_AS_STRING(self); char *result_buf; PyObject *result; result = PyByteArray_FromStringAndSize(NULL, slicelength); if (result == NULL) return NULL; result_buf = PyByteArray_AS_STRING(result); for (cur = start, i = 0; i < slicelength; cur += step, i++) { result_buf[i] = source_buf[cur]; } return result; } } else { PyErr_Format(PyExc_TypeError, "bytearray indices must be integers or slices, not %.200s", Py_TYPE(index)->tp_name); return NULL; } } static PyObject * bytearray_subscript(PyObject *op, PyObject *index) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(op); ret = bytearray_subscript_lock_held(op, index); Py_END_CRITICAL_SECTION(); return ret; } static int bytearray_setslice_linear(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi, char *bytes, Py_ssize_t bytes_len) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self); Py_ssize_t avail = hi - lo; char *buf = PyByteArray_AS_STRING(self); Py_ssize_t growth = bytes_len - avail; int res = 0; assert(avail >= 0); if (growth < 0) { if (!_canresize(self)) return -1; if (lo == 0) { /* Shrink the buffer by advancing its logical start */ self->ob_start -= growth; /* 0 lo hi old_size | |<----avail----->|<-----tail------>| | |<-bytes_len->|<-----tail------>| 0 new_lo new_hi new_size */ } else { /* 0 lo hi old_size | |<----avail----->|<-----tomove------>| | |<-bytes_len->|<-----tomove------>| 0 lo new_hi new_size */ memmove(buf + lo + bytes_len, buf + hi, Py_SIZE(self) - hi); } if (bytearray_resize_lock_held((PyObject *)self, Py_SIZE(self) + growth) < 0) { /* Issue #19578: Handling the memory allocation failure here is tricky here because the bytearray object has already been modified. Depending on growth and lo, the behaviour is different. If growth < 0 and lo != 0, the operation is completed, but a MemoryError is still raised and the memory block is not shrunk. Otherwise, the bytearray is restored in its previous state and a MemoryError is raised. */ if (lo == 0) { self->ob_start += growth; return -1; } /* memmove() removed bytes, the bytearray object cannot be restored in its previous state. */ Py_SET_SIZE(self, Py_SIZE(self) + growth); res = -1; } buf = PyByteArray_AS_STRING(self); } else if (growth > 0) { if (Py_SIZE(self) > PyByteArray_SIZE_MAX - growth) { PyErr_NoMemory(); return -1; } if (bytearray_resize_lock_held((PyObject *)self, Py_SIZE(self) + growth) < 0) { return -1; } buf = PyByteArray_AS_STRING(self); /* Make the place for the additional bytes */ /* 0 lo hi old_size | |<-avail->|<-----tomove------>| | |<---bytes_len-->|<-----tomove------>| 0 lo new_hi new_size */ memmove(buf + lo + bytes_len, buf + hi, Py_SIZE(self) - lo - bytes_len); } if (bytes_len > 0) memcpy(buf + lo, bytes, bytes_len); return res; } static int bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi, PyObject *values) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self); Py_ssize_t needed; void *bytes; Py_buffer vbytes; int res = 0; vbytes.len = -1; if (values == (PyObject *)self) { /* Make a copy and call this function recursively */ int err; values = PyByteArray_FromStringAndSize(PyByteArray_AS_STRING(values), PyByteArray_GET_SIZE(values)); if (values == NULL) return -1; err = bytearray_setslice(self, lo, hi, values); Py_DECREF(values); return err; } if (values == NULL) { /* del b[lo:hi] */ bytes = NULL; needed = 0; } else { if (PyObject_GetBuffer(values, &vbytes, PyBUF_SIMPLE) != 0) { PyErr_Format(PyExc_TypeError, "can't set bytearray slice from %.100s", Py_TYPE(values)->tp_name); return -1; } needed = vbytes.len; bytes = vbytes.buf; } if (lo < 0) lo = 0; if (hi < lo) hi = lo; if (hi > Py_SIZE(self)) hi = Py_SIZE(self); res = bytearray_setslice_linear(self, lo, hi, bytes, needed); if (vbytes.len != -1) PyBuffer_Release(&vbytes); return res; } static int bytearray_setitem_lock_held(PyObject *op, Py_ssize_t i, PyObject *value) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op); PyByteArrayObject *self = _PyByteArray_CAST(op); // GH-91153: We need to do this *before* the size check, in case value has a // nasty __index__ method that changes the size of the bytearray: int ival = -1; if (value && !_getbytevalue(value, &ival)) { return -1; } if (i < 0) { i += Py_SIZE(self); } if (i < 0 || i >= Py_SIZE(self)) { PyErr_SetString(PyExc_IndexError, "bytearray index out of range"); return -1; } if (value == NULL) { return bytearray_setslice(self, i, i+1, NULL); } assert(0 <= ival && ival < 256); PyByteArray_AS_STRING(self)[i] = ival; return 0; } static int bytearray_setitem(PyObject *op, Py_ssize_t i, PyObject *value) { int ret; Py_BEGIN_CRITICAL_SECTION(op); ret = bytearray_setitem_lock_held(op, i, value); Py_END_CRITICAL_SECTION(); return ret; } static int bytearray_ass_subscript_lock_held(PyObject *op, PyObject *index, PyObject *values) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op); PyByteArrayObject *self = _PyByteArray_CAST(op); Py_ssize_t start, stop, step, slicelen; // Do not store a reference to the internal buffer since // index.__index__() or _getbytevalue() may alter 'self'. // See https://github.com/python/cpython/issues/91153. if (_PyIndex_Check(index)) { Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError); if (i == -1 && PyErr_Occurred()) { return -1; } int ival = -1; // GH-91153: We need to do this *before* the size check, in case values // has a nasty __index__ method that changes the size of the bytearray: if (values && !_getbytevalue(values, &ival)) { return -1; } if (i < 0) { i += PyByteArray_GET_SIZE(self); } if (i < 0 || i >= Py_SIZE(self)) { PyErr_SetString(PyExc_IndexError, "bytearray index out of range"); return -1; } if (values == NULL) { /* Fall through to slice assignment */ start = i; stop = i + 1; step = 1; slicelen = 1; } else { assert(0 <= ival && ival < 256); PyByteArray_AS_STRING(self)[i] = (char)ival; return 0; } } else if (PySlice_Check(index)) { if (PySlice_Unpack(index, &start, &stop, &step) < 0) { return -1; } slicelen = PySlice_AdjustIndices(PyByteArray_GET_SIZE(self), &start, &stop, step); } else { PyErr_Format(PyExc_TypeError, "bytearray indices must be integers or slices, not %.200s", Py_TYPE(index)->tp_name); return -1; } char *bytes; Py_ssize_t needed; if (values == NULL) { bytes = NULL; needed = 0; } else if (values == (PyObject *)self || !PyByteArray_Check(values)) { int err; if (PyNumber_Check(values) || PyUnicode_Check(values)) { PyErr_SetString(PyExc_TypeError, "can assign only bytes, buffers, or iterables " "of ints in range(0, 256)"); return -1; } /* Make a copy and call this function recursively */ values = PyByteArray_FromObject(values); if (values == NULL) return -1; err = bytearray_ass_subscript_lock_held((PyObject*)self, index, values); Py_DECREF(values); return err; } else { assert(PyByteArray_Check(values)); bytes = PyByteArray_AS_STRING(values); needed = Py_SIZE(values); } /* Make sure b[5:2] = ... inserts before 5, not before 2. */ if ((step < 0 && start < stop) || (step > 0 && start > stop)) { stop = start; } if (step == 1) { return bytearray_setslice_linear(self, start, stop, bytes, needed); } else { if (needed == 0) { /* Delete slice */ size_t cur; Py_ssize_t i; char *buf = PyByteArray_AS_STRING(self); if (!_canresize(self)) return -1; if (slicelen == 0) /* Nothing to do here. */ return 0; if (step < 0) { stop = start + 1; start = stop + step * (slicelen - 1) - 1; step = -step; } for (cur = start, i = 0; i < slicelen; cur += step, i++) { Py_ssize_t lim = step - 1; if (cur + step >= (size_t)PyByteArray_GET_SIZE(self)) lim = PyByteArray_GET_SIZE(self) - cur - 1; memmove(buf + cur - i, buf + cur + 1, lim); } /* Move the tail of the bytes, in one chunk */ cur = start + (size_t)slicelen*step; if (cur < (size_t)PyByteArray_GET_SIZE(self)) { memmove(buf + cur - slicelen, buf + cur, PyByteArray_GET_SIZE(self) - cur); } if (bytearray_resize_lock_held((PyObject *)self, PyByteArray_GET_SIZE(self) - slicelen) < 0) return -1; return 0; } else { /* Assign slice */ Py_ssize_t i; size_t cur; char *buf = PyByteArray_AS_STRING(self); if (needed != slicelen) { PyErr_Format(PyExc_ValueError, "attempt to assign bytes of size %zd " "to extended slice of size %zd", needed, slicelen); return -1; } for (cur = start, i = 0; i < slicelen; cur += step, i++) buf[cur] = bytes[i]; return 0; } } } static int bytearray_ass_subscript(PyObject *op, PyObject *index, PyObject *values) { int ret; if (values != NULL && PyByteArray_Check(values)) { Py_BEGIN_CRITICAL_SECTION2(op, values); ret = bytearray_ass_subscript_lock_held(op, index, values); Py_END_CRITICAL_SECTION2(); } else { Py_BEGIN_CRITICAL_SECTION(op); ret = bytearray_ass_subscript_lock_held(op, index, values); Py_END_CRITICAL_SECTION(); } return ret; } /*[clinic input] bytearray.__init__ source as arg: object = NULL encoding: str = NULL errors: str = NULL [clinic start generated code]*/ static int bytearray___init___impl(PyByteArrayObject *self, PyObject *arg, const char *encoding, const char *errors) /*[clinic end generated code: output=4ce1304649c2f8b3 input=1141a7122eefd7b9]*/ { Py_ssize_t count; PyObject *it; PyObject *(*iternext)(PyObject *); /* First __init__; set ob_bytes_object so ob_bytes is always non-null. */ if (self->ob_bytes_object == NULL) { self->ob_bytes_object = Py_GetConstant(Py_CONSTANT_EMPTY_BYTES); bytearray_reinit_from_bytes(self, 0, 0); self->ob_exports = 0; } if (Py_SIZE(self) != 0) { /* Empty previous contents (yes, do this first of all!) */ if (PyByteArray_Resize((PyObject *)self, 0) < 0) return -1; } /* Should be caused by first init or the resize to 0. */ assert(self->ob_bytes_object == Py_GetConstantBorrowed(Py_CONSTANT_EMPTY_BYTES)); assert(self->ob_exports == 0); /* Make a quick exit if no first argument */ if (arg == NULL) { if (encoding != NULL || errors != NULL) { PyErr_SetString(PyExc_TypeError, encoding != NULL ? "encoding without a string argument" : "errors without a string argument"); return -1; } return 0; } if (PyUnicode_Check(arg)) { /* Encode via the codec registry */ PyObject *encoded, *new; if (encoding == NULL) { PyErr_SetString(PyExc_TypeError, "string argument without an encoding"); return -1; } encoded = PyUnicode_AsEncodedString(arg, encoding, errors); if (encoded == NULL) { return -1; } assert(PyBytes_Check(encoded)); /* Most encodes return a new unique bytes, just use it as buffer. */ if (_PyObject_IsUniquelyReferenced(encoded) && PyBytes_CheckExact(encoded)) { Py_ssize_t size = Py_SIZE(encoded); self->ob_bytes_object = encoded; bytearray_reinit_from_bytes(self, size, size); return 0; } new = bytearray_iconcat((PyObject*)self, encoded); Py_DECREF(encoded); if (new == NULL) return -1; Py_DECREF(new); return 0; } /* If it's not unicode, there can't be encoding or errors */ if (encoding != NULL || errors != NULL) { PyErr_SetString(PyExc_TypeError, encoding != NULL ? "encoding without a string argument" : "errors without a string argument"); return -1; } /* Is it an int? */ if (_PyIndex_Check(arg)) { count = PyNumber_AsSsize_t(arg, PyExc_OverflowError); if (count == -1 && PyErr_Occurred()) { if (!PyErr_ExceptionMatches(PyExc_TypeError)) return -1; PyErr_Clear(); /* fall through */ } else { if (count < 0) { PyErr_SetString(PyExc_ValueError, "negative count"); return -1; } if (count > 0) { if (PyByteArray_Resize((PyObject *)self, count)) return -1; memset(PyByteArray_AS_STRING(self), 0, count); } return 0; } } /* Use the buffer API */ if (PyObject_CheckBuffer(arg)) { Py_ssize_t size; Py_buffer view; if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0) return -1; size = view.len; if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail; if (PyBuffer_ToContiguous(PyByteArray_AS_STRING(self), &view, size, 'C') < 0) goto fail; PyBuffer_Release(&view); return 0; fail: PyBuffer_Release(&view); return -1; } if (PyList_CheckExact(arg) || PyTuple_CheckExact(arg)) { Py_ssize_t size = PySequence_Fast_GET_SIZE(arg); if (PyByteArray_Resize((PyObject *)self, size) < 0) { return -1; } PyObject **items = PySequence_Fast_ITEMS(arg); char *s = PyByteArray_AS_STRING(self); for (Py_ssize_t i = 0; i < size; i++) { int value; if (!PyLong_CheckExact(items[i])) { /* Resize to 0 and go through slowpath */ if (Py_SIZE(self) != 0) { if (PyByteArray_Resize((PyObject *)self, 0) < 0) { return -1; } } goto slowpath; } int rc = _getbytevalue(items[i], &value); if (!rc) { return -1; } s[i] = value; } return 0; } slowpath: /* Get the iterator */ it = PyObject_GetIter(arg); if (it == NULL) { if (PyErr_ExceptionMatches(PyExc_TypeError)) { PyErr_Format(PyExc_TypeError, "cannot convert '%.200s' object to bytearray", Py_TYPE(arg)->tp_name); } return -1; } iternext = *Py_TYPE(it)->tp_iternext; /* Run the iterator to exhaustion */ for (;;) { PyObject *item; int rc, value; /* Get the next item */ item = iternext(it); if (item == NULL) { if (PyErr_Occurred()) { if (!PyErr_ExceptionMatches(PyExc_StopIteration)) goto error; PyErr_Clear(); } break; } /* Interpret it as an int (__index__) */ rc = _getbytevalue(item, &value); Py_DECREF(item); if (!rc) goto error; /* Append the byte */ if (Py_SIZE(self) + 1 < self->ob_alloc) { Py_SET_SIZE(self, Py_SIZE(self) + 1); PyByteArray_AS_STRING(self)[Py_SIZE(self)] = '\0'; } else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0) goto error; PyByteArray_AS_STRING(self)[Py_SIZE(self)-1] = value; } /* Clean up and return success */ Py_DECREF(it); return 0; error: /* Error handling when it != NULL */ Py_DECREF(it); return -1; } static PyObject * bytearray_repr_lock_held(PyObject *op) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op); const char *className = _PyType_Name(Py_TYPE(op)); PyObject *bytes_repr = _Py_bytes_repr(PyByteArray_AS_STRING(op), PyByteArray_GET_SIZE(op), 1, "bytearray"); if (bytes_repr == NULL) { return NULL; } PyObject *res = PyUnicode_FromFormat("%s(%U)", className, bytes_repr); Py_DECREF(bytes_repr); return res; } static PyObject * bytearray_repr(PyObject *op) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(op); ret = bytearray_repr_lock_held(op); Py_END_CRITICAL_SECTION(); return ret; } static PyObject * bytearray_str(PyObject *op) { if (_Py_GetConfig()->bytes_warning) { if (PyErr_WarnEx(PyExc_BytesWarning, "str() on a bytearray instance", 1)) { return NULL; } } return bytearray_repr(op); } static PyObject * bytearray_richcompare(PyObject *self, PyObject *other, int op) { Py_ssize_t self_size, other_size; Py_buffer self_bytes, other_bytes; int cmp; if (!PyObject_CheckBuffer(self) || !PyObject_CheckBuffer(other)) { if (PyUnicode_Check(self) || PyUnicode_Check(other)) { if (_Py_GetConfig()->bytes_warning && (op == Py_EQ || op == Py_NE)) { if (PyErr_WarnEx(PyExc_BytesWarning, "Comparison between bytearray and string", 1)) return NULL; } } Py_RETURN_NOTIMPLEMENTED; } /* Bytearrays can be compared to anything that supports the buffer API. */ if (PyObject_GetBuffer(self, &self_bytes, PyBUF_SIMPLE) != 0) { PyErr_Clear(); Py_RETURN_NOTIMPLEMENTED; } self_size = self_bytes.len; if (PyObject_GetBuffer(other, &other_bytes, PyBUF_SIMPLE) != 0) { PyErr_Clear(); PyBuffer_Release(&self_bytes); Py_RETURN_NOTIMPLEMENTED; } other_size = other_bytes.len; if (self_size != other_size && (op == Py_EQ || op == Py_NE)) { /* Shortcut: if the lengths differ, the objects differ */ PyBuffer_Release(&self_bytes); PyBuffer_Release(&other_bytes); return PyBool_FromLong((op == Py_NE)); } else { cmp = memcmp(self_bytes.buf, other_bytes.buf, Py_MIN(self_size, other_size)); /* In ISO C, memcmp() guarantees to use unsigned bytes! */ PyBuffer_Release(&self_bytes); PyBuffer_Release(&other_bytes); if (cmp != 0) { Py_RETURN_RICHCOMPARE(cmp, 0, op); } Py_RETURN_RICHCOMPARE(self_size, other_size, op); } } static void bytearray_dealloc(PyObject *op) { PyByteArrayObject *self = _PyByteArray_CAST(op); if (self->ob_exports > 0) { PyErr_SetString(PyExc_SystemError, "deallocated bytearray object has exported buffers"); PyErr_Print(); } Py_XDECREF(self->ob_bytes_object); Py_TYPE(self)->tp_free((PyObject *)self); } /* -------------------------------------------------------------------- */ /* Methods */ #define STRINGLIB_IS_UNICODE 0 #define FASTSEARCH fastsearch #define STRINGLIB(F) stringlib_##F #define STRINGLIB_CHAR char #define STRINGLIB_SIZEOF_CHAR 1 #define STRINGLIB_LEN PyByteArray_GET_SIZE #define STRINGLIB_STR PyByteArray_AS_STRING #define STRINGLIB_NEW PyByteArray_FromStringAndSize #define STRINGLIB_ISSPACE Py_ISSPACE #define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r')) #define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact #define STRINGLIB_FAST_MEMCHR memchr #define STRINGLIB_MUTABLE 1 #include "stringlib/fastsearch.h" #include "stringlib/count.h" #include "stringlib/find.h" #include "stringlib/join.h" #include "stringlib/partition.h" #include "stringlib/split.h" #include "stringlib/ctype.h" #include "stringlib/transmogrify.h" /*[clinic input] @permit_long_summary @critical_section @text_signature "($self, sub[, start[, end]], /)" bytearray.find sub: object start: slice_index(accept={int, NoneType}, c_default='0') = None Optional start position. Default: start of the bytes. end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None Optional stop position. Default: end of the bytes. / Return the lowest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start:end]. Return -1 on failure. [clinic start generated code]*/ static PyObject * bytearray_find_impl(PyByteArrayObject *self, PyObject *sub, Py_ssize_t start, Py_ssize_t end) /*[clinic end generated code: output=413e1cab2ae87da0 input=df3aa94840d893a7]*/ { return _bytearray_with_buffer(self, _Py_bytes_find, sub, start, end); } /*[clinic input] @permit_long_summary @critical_section bytearray.count = bytearray.find Return the number of non-overlapping occurrences of subsection 'sub' in bytes B[start:end]. [clinic start generated code]*/ static PyObject * bytearray_count_impl(PyByteArrayObject *self, PyObject *sub, Py_ssize_t start, Py_ssize_t end) /*[clinic end generated code: output=a21ee2692e4f1233 input=e8fcdca8272857e0]*/ { return _bytearray_with_buffer(self, _Py_bytes_count, sub, start, end); } /*[clinic input] bytearray.clear Remove all items from the bytearray. [clinic start generated code]*/ static PyObject * bytearray_clear_impl(PyByteArrayObject *self) /*[clinic end generated code: output=85c2fe6aede0956c input=ed6edae9de447ac4]*/ { if (PyByteArray_Resize((PyObject *)self, 0) < 0) return NULL; Py_RETURN_NONE; } /*[clinic input] @critical_section bytearray.copy Return a copy of B. [clinic start generated code]*/ static PyObject * bytearray_copy_impl(PyByteArrayObject *self) /*[clinic end generated code: output=68cfbcfed484c132 input=b96f8b01f73851ad]*/ { return PyByteArray_FromStringAndSize(PyByteArray_AS_STRING((PyObject *)self), PyByteArray_GET_SIZE(self)); } /*[clinic input] @permit_long_summary @critical_section bytearray.index = bytearray.find Return the lowest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start:end]. Raise ValueError if the subsection is not found. [clinic start generated code]*/ static PyObject * bytearray_index_impl(PyByteArrayObject *self, PyObject *sub, Py_ssize_t start, Py_ssize_t end) /*[clinic end generated code: output=067a1e78efc672a7 input=c37f177cfee19fe4]*/ { return _bytearray_with_buffer(self, _Py_bytes_index, sub, start, end); } /*[clinic input] @permit_long_summary @critical_section bytearray.rfind = bytearray.find Return the highest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start:end]. Return -1 on failure. [clinic start generated code]*/ static PyObject * bytearray_rfind_impl(PyByteArrayObject *self, PyObject *sub, Py_ssize_t start, Py_ssize_t end) /*[clinic end generated code: output=51bf886f932b283c input=1265b11c437d2750]*/ { return _bytearray_with_buffer(self, _Py_bytes_rfind, sub, start, end); } /*[clinic input] @permit_long_summary @critical_section bytearray.rindex = bytearray.find Return the highest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start:end]. Raise ValueError if the subsection is not found. [clinic start generated code]*/ static PyObject * bytearray_rindex_impl(PyByteArrayObject *self, PyObject *sub, Py_ssize_t start, Py_ssize_t end) /*[clinic end generated code: output=38e1cf66bafb08b9 input=7d198b3d6b0a62ce]*/ { return _bytearray_with_buffer(self, _Py_bytes_rindex, sub, start, end); } static int bytearray_contains(PyObject *self, PyObject *arg) { int ret = -1; Py_BEGIN_CRITICAL_SECTION(self); PyByteArrayObject *ba = _PyByteArray_CAST(self); /* Increase exports to prevent bytearray storage from changing during _Py_bytes_contains(). */ ba->ob_exports++; ret = _Py_bytes_contains(PyByteArray_AS_STRING(ba), PyByteArray_GET_SIZE(self), arg); ba->ob_exports--; Py_END_CRITICAL_SECTION(); return ret; } /*[clinic input] @permit_long_summary @critical_section @text_signature "($self, prefix[, start[, end]], /)" bytearray.startswith prefix as subobj: object A bytes or a tuple of bytes to try. start: slice_index(accept={int, NoneType}, c_default='0') = None Optional start position. Default: start of the bytearray. end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None Optional stop position. Default: end of the bytearray. / Return True if the bytearray starts with the specified prefix, False otherwise. [clinic start generated code]*/ static PyObject * bytearray_startswith_impl(PyByteArrayObject *self, PyObject *subobj, Py_ssize_t start, Py_ssize_t end) /*[clinic end generated code: output=a3d9b6d44d3662a6 input=93f9ffee684f109a]*/ { return _bytearray_with_buffer(self, _Py_bytes_startswith, subobj, start, end); } /*[clinic input] @permit_long_summary @critical_section @text_signature "($self, suffix[, start[, end]], /)" bytearray.endswith suffix as subobj: object A bytes or a tuple of bytes to try. start: slice_index(accept={int, NoneType}, c_default='0') = None Optional start position. Default: start of the bytearray. end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None Optional stop position. Default: end of the bytearray. / Return True if the bytearray ends with the specified suffix, False otherwise. [clinic start generated code]*/ static PyObject * bytearray_endswith_impl(PyByteArrayObject *self, PyObject *subobj, Py_ssize_t start, Py_ssize_t end) /*[clinic end generated code: output=e75ea8c227954caa input=d158b030a11d0b06]*/ { return _bytearray_with_buffer(self, _Py_bytes_endswith, subobj, start, end); } /*[clinic input] @critical_section bytearray.removeprefix as bytearray_removeprefix prefix: Py_buffer / Return a bytearray with the given prefix string removed if present. If the bytearray starts with the prefix string, return bytearray[len(prefix):]. Otherwise, return a copy of the original bytearray. [clinic start generated code]*/ static PyObject * bytearray_removeprefix_impl(PyByteArrayObject *self, Py_buffer *prefix) /*[clinic end generated code: output=6cabc585e7f502e0 input=4323ba6d275fe7a8]*/ { const char *self_start = PyByteArray_AS_STRING(self); Py_ssize_t self_len = PyByteArray_GET_SIZE(self); const char *prefix_start = prefix->buf; Py_ssize_t prefix_len = prefix->len; if (self_len >= prefix_len && memcmp(self_start, prefix_start, prefix_len) == 0) { return PyByteArray_FromStringAndSize(self_start + prefix_len, self_len - prefix_len); } return PyByteArray_FromStringAndSize(self_start, self_len); } /*[clinic input] @critical_section bytearray.removesuffix as bytearray_removesuffix suffix: Py_buffer / Return a bytearray with the given suffix string removed if present. If the bytearray ends with the suffix string and that suffix is not empty, return bytearray[:-len(suffix)]. Otherwise, return a copy of the original bytearray. [clinic start generated code]*/ static PyObject * bytearray_removesuffix_impl(PyByteArrayObject *self, Py_buffer *suffix) /*[clinic end generated code: output=2bc8cfb79de793d3 input=f71ba2e1a40c47dd]*/ { const char *self_start = PyByteArray_AS_STRING(self); Py_ssize_t self_len = PyByteArray_GET_SIZE(self); const char *suffix_start = suffix->buf; Py_ssize_t suffix_len = suffix->len; if (self_len >= suffix_len && memcmp(self_start + self_len - suffix_len, suffix_start, suffix_len) == 0) { return PyByteArray_FromStringAndSize(self_start, self_len - suffix_len); } return PyByteArray_FromStringAndSize(self_start, self_len); } /*[clinic input] bytearray.resize size: Py_ssize_t New size to resize to. / Resize the internal buffer of bytearray to len. [clinic start generated code]*/ static PyObject * bytearray_resize_impl(PyByteArrayObject *self, Py_ssize_t size) /*[clinic end generated code: output=f73524922990b2d9 input=6c9a260ca7f72071]*/ { Py_ssize_t start_size = PyByteArray_GET_SIZE(self); int result = PyByteArray_Resize((PyObject *)self, size); if (result < 0) { return NULL; } // Set new bytes to null bytes if (size > start_size) { memset(PyByteArray_AS_STRING(self) + start_size, 0, size - start_size); } Py_RETURN_NONE; } /*[clinic input] @critical_section bytearray.take_bytes n: object = None Bytes to take, negative indexes from end. None indicates all bytes. / Take *n* bytes from the bytearray and return them as a bytes object. [clinic start generated code]*/ static PyObject * bytearray_take_bytes_impl(PyByteArrayObject *self, PyObject *n) /*[clinic end generated code: output=3147fbc0bbbe8d94 input=b15b5172cdc6deda]*/ { Py_ssize_t to_take; Py_ssize_t size = Py_SIZE(self); if (Py_IsNone(n)) { to_take = size; } // Integer index, from start (zero, positive) or end (negative). else if (_PyIndex_Check(n)) { to_take = PyNumber_AsSsize_t(n, PyExc_IndexError); if (to_take == -1 && PyErr_Occurred()) { return NULL; } if (to_take < 0) { to_take += size; } } else { PyErr_SetString(PyExc_TypeError, "n must be an integer or None"); return NULL; } if (to_take < 0 || to_take > size) { PyErr_Format(PyExc_IndexError, "can't take %zd bytes outside size %zd", to_take, size); return NULL; } // Exports may change the contents. No mutable bytes allowed. if (!_canresize(self)) { return NULL; } if (to_take == 0 || size == 0) { return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES); } Py_ssize_t remaining_length = size - to_take; // optimization: If taking less than leaving, just copy the small to_take // portion out and move ob_start. if (to_take < remaining_length) { PyObject *ret = PyBytes_FromStringAndSize(self->ob_start, to_take); if (ret == NULL) { return NULL; } self->ob_start += to_take; Py_SET_SIZE(self, remaining_length); return ret; } // Copy remaining bytes to a new bytes. PyObject *remaining = PyBytes_FromStringAndSize(self->ob_start + to_take, remaining_length); if (remaining == NULL) { return NULL; } // If the bytes are offset inside the buffer must first align. if (self->ob_start != self->ob_bytes) { memmove(self->ob_bytes, self->ob_start, to_take); self->ob_start = self->ob_bytes; } if (_PyBytes_Resize(&self->ob_bytes_object, to_take) == -1) { Py_DECREF(remaining); return NULL; } // Point the bytearray towards the buffer with the remaining data. PyObject *result = self->ob_bytes_object; self->ob_bytes_object = remaining; bytearray_reinit_from_bytes(self, remaining_length, remaining_length); return result; } /*[clinic input] @critical_section bytearray.translate table: object Translation table, which must be a bytes object of length 256. / delete as deletechars: object(c_default="NULL") = b'' Return a copy with each character mapped by the given translation table. All characters occurring in the optional argument delete are removed. The remaining characters are mapped through the given translation table. [clinic start generated code]*/ static PyObject * bytearray_translate_impl(PyByteArrayObject *self, PyObject *table, PyObject *deletechars) /*[clinic end generated code: output=b6a8f01c2a74e446 input=cd6fa93ca04e05bc]*/ { char *input, *output; const char *table_chars; Py_ssize_t i, c; PyObject *input_obj = (PyObject*)self; const char *output_start; Py_ssize_t inlen; PyObject *result = NULL; int trans_table[256]; Py_buffer vtable, vdel; if (table == Py_None) { table_chars = NULL; table = NULL; } else if (PyObject_GetBuffer(table, &vtable, PyBUF_SIMPLE) != 0) { return NULL; } else { if (vtable.len != 256) { PyErr_SetString(PyExc_ValueError, "translation table must be 256 characters long"); PyBuffer_Release(&vtable); return NULL; } table_chars = (const char*)vtable.buf; } if (deletechars != NULL) { if (PyObject_GetBuffer(deletechars, &vdel, PyBUF_SIMPLE) != 0) { if (table != NULL) PyBuffer_Release(&vtable); return NULL; } } else { vdel.buf = NULL; vdel.len = 0; } inlen = PyByteArray_GET_SIZE(input_obj); result = PyByteArray_FromStringAndSize((char *)NULL, inlen); if (result == NULL) goto done; output_start = output = PyByteArray_AS_STRING(result); input = PyByteArray_AS_STRING(input_obj); if (vdel.len == 0 && table_chars != NULL) { /* If no deletions are required, use faster code */ for (i = inlen; --i >= 0; ) { c = Py_CHARMASK(*input++); *output++ = table_chars[c]; } goto done; } if (table_chars == NULL) { for (i = 0; i < 256; i++) trans_table[i] = Py_CHARMASK(i); } else { for (i = 0; i < 256; i++) trans_table[i] = Py_CHARMASK(table_chars[i]); } for (i = 0; i < vdel.len; i++) trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1; for (i = inlen; --i >= 0; ) { c = Py_CHARMASK(*input++); if (trans_table[c] != -1) *output++ = (char)trans_table[c]; } /* Fix the size of the resulting bytearray */ if (inlen > 0) if (PyByteArray_Resize(result, output - output_start) < 0) { Py_CLEAR(result); goto done; } done: if (table != NULL) PyBuffer_Release(&vtable); if (deletechars != NULL) PyBuffer_Release(&vdel); return result; } /*[clinic input] @permit_long_summary @permit_long_docstring_body @staticmethod bytearray.maketrans frm: Py_buffer to: Py_buffer / Return a translation table usable for the bytes or bytearray translate method. The returned table will be one where each byte in frm is mapped to the byte at the same position in to. The bytes objects frm and to must be of the same length. [clinic start generated code]*/ static PyObject * bytearray_maketrans_impl(Py_buffer *frm, Py_buffer *to) /*[clinic end generated code: output=1df267d99f56b15e input=1146b43a592eca13]*/ { return _Py_bytes_maketrans(frm, to); } /*[clinic input] @permit_long_docstring_body @critical_section bytearray.replace old: Py_buffer new: Py_buffer count: Py_ssize_t = -1 Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences. / Return a copy with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. [clinic start generated code]*/ static PyObject * bytearray_replace_impl(PyByteArrayObject *self, Py_buffer *old, Py_buffer *new, Py_ssize_t count) /*[clinic end generated code: output=d39884c4dc59412a input=66afec32f4e095e0]*/ { return stringlib_replace((PyObject *)self, (const char *)old->buf, old->len, (const char *)new->buf, new->len, count); } /*[clinic input] @permit_long_summary @critical_section bytearray.split sep: object = None The delimiter according which to split the bytearray. None (the default value) means split on ASCII whitespace characters (space, tab, return, newline, formfeed, vertical tab). maxsplit: Py_ssize_t = -1 Maximum number of splits to do. -1 (the default value) means no limit. Return a list of the sections in the bytearray, using sep as the delimiter. [clinic start generated code]*/ static PyObject * bytearray_split_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit) /*[clinic end generated code: output=833e2cf385d9a04d input=dd9f6e2910cc3a34]*/ { PyObject *list = NULL; /* Increase exports to prevent bytearray storage from changing during _Py_bytes_contains(). */ self->ob_exports++; const char *sbuf = PyByteArray_AS_STRING(self); Py_ssize_t slen = PyByteArray_GET_SIZE((PyObject *)self); if (maxsplit < 0) maxsplit = PY_SSIZE_T_MAX; if (sep == Py_None) { list = stringlib_split_whitespace((PyObject*)self, sbuf, slen, maxsplit); goto done; } Py_buffer vsub; if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0) { goto done; } list = stringlib_split((PyObject*)self, sbuf, slen, (const char *)vsub.buf, vsub.len, maxsplit); PyBuffer_Release(&vsub); done: self->ob_exports--; return list; } /*[clinic input] @permit_long_docstring_body @critical_section bytearray.partition sep: object / Partition the bytearray into three parts using the given separator. This will search for the separator sep in the bytearray. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it as new bytearray objects. If the separator is not found, returns a 3-tuple containing the copy of the original bytearray object and two empty bytearray objects. [clinic start generated code]*/ static PyObject * bytearray_partition_impl(PyByteArrayObject *self, PyObject *sep) /*[clinic end generated code: output=b5fa1e03f10cfccb input=b87276af883f39d9]*/ { PyObject *bytesep, *result; bytesep = _PyByteArray_FromBufferObject(sep); if (! bytesep) return NULL; result = stringlib_partition( (PyObject*) self, PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), bytesep, PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep) ); Py_DECREF(bytesep); return result; } /*[clinic input] @permit_long_docstring_body @critical_section bytearray.rpartition sep: object / Partition the bytearray into three parts using the given separator. This will search for the separator sep in the bytearray, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it as new bytearray objects. If the separator is not found, returns a 3-tuple containing two empty bytearray objects and the copy of the original bytearray object. [clinic start generated code]*/ static PyObject * bytearray_rpartition_impl(PyByteArrayObject *self, PyObject *sep) /*[clinic end generated code: output=0186ce7b1ef61289 input=5bdcfc4c333bcfab]*/ { PyObject *bytesep, *result; bytesep = _PyByteArray_FromBufferObject(sep); if (! bytesep) return NULL; result = stringlib_rpartition( (PyObject*) self, PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), bytesep, PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep) ); Py_DECREF(bytesep); return result; } /*[clinic input] @permit_long_summary @permit_long_docstring_body @critical_section bytearray.rsplit = bytearray.split Return a list of the sections in the bytearray, using sep as the delimiter. Splitting is done starting at the end of the bytearray and working to the front. [clinic start generated code]*/ static PyObject * bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit) /*[clinic end generated code: output=a55e0b5a03cb6190 input=60e9abf305128ff4]*/ { PyObject *list = NULL; /* Increase exports to prevent bytearray storage from changing during _Py_bytes_contains(). */ self->ob_exports++; const char *sbuf = PyByteArray_AS_STRING(self); Py_ssize_t slen = PyByteArray_GET_SIZE((PyObject *)self); if (maxsplit < 0) maxsplit = PY_SSIZE_T_MAX; if (sep == Py_None) { list = stringlib_rsplit_whitespace((PyObject*)self, sbuf, slen, maxsplit); goto done; } Py_buffer vsub; if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0) { goto done; } list = stringlib_rsplit((PyObject*)self, sbuf, slen, (const char *)vsub.buf, vsub.len, maxsplit); PyBuffer_Release(&vsub); done: self->ob_exports--; return list; } /*[clinic input] @critical_section bytearray.reverse Reverse the order of the values in B in place. [clinic start generated code]*/ static PyObject * bytearray_reverse_impl(PyByteArrayObject *self) /*[clinic end generated code: output=9f7616f29ab309d3 input=2f3d5ce3180ffc53]*/ { char swap, *head, *tail; Py_ssize_t i, j, n = Py_SIZE(self); j = n / 2; head = PyByteArray_AS_STRING(self); tail = head + n - 1; for (i = 0; i < j; i++) { swap = *head; *head++ = *tail; *tail-- = swap; } Py_RETURN_NONE; } /*[python input] class bytesvalue_converter(CConverter): type = 'int' converter = '_getbytevalue' [python start generated code]*/ /*[python end generated code: output=da39a3ee5e6b4b0d input=29c2e7c26c212812]*/ /*[clinic input] @critical_section bytearray.insert index: Py_ssize_t The index where the value is to be inserted. item: bytesvalue The item to be inserted. / Insert a single item into the bytearray before the given index. [clinic start generated code]*/ static PyObject * bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item) /*[clinic end generated code: output=76c775a70e7b07b7 input=b3e14ede546dd8cc]*/ { Py_ssize_t n = Py_SIZE(self); char *buf; if (bytearray_resize_lock_held((PyObject *)self, n + 1) < 0) return NULL; buf = PyByteArray_AS_STRING(self); if (index < 0) { index += n; if (index < 0) index = 0; } if (index > n) index = n; memmove(buf + index + 1, buf + index, n - index); buf[index] = item; Py_RETURN_NONE; } static PyObject * bytearray_isalnum(PyObject *self, PyObject *Py_UNUSED(ignored)) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(self); ret = stringlib_isalnum(self, NULL); Py_END_CRITICAL_SECTION(); return ret; } static PyObject * bytearray_isalpha(PyObject *self, PyObject *Py_UNUSED(ignored)) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(self); ret = stringlib_isalpha(self, NULL); Py_END_CRITICAL_SECTION(); return ret; } static PyObject * bytearray_isascii(PyObject *self, PyObject *Py_UNUSED(ignored)) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(self); ret = stringlib_isascii(self, NULL); Py_END_CRITICAL_SECTION(); return ret; } static PyObject * bytearray_isdigit(PyObject *self, PyObject *Py_UNUSED(ignored)) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(self); ret = stringlib_isdigit(self, NULL); Py_END_CRITICAL_SECTION(); return ret; } static PyObject * bytearray_islower(PyObject *self, PyObject *Py_UNUSED(ignored)) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(self); ret = stringlib_islower(self, NULL); Py_END_CRITICAL_SECTION(); return ret; } static PyObject * bytearray_isspace(PyObject *self, PyObject *Py_UNUSED(ignored)) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(self); ret = stringlib_isspace(self, NULL); Py_END_CRITICAL_SECTION(); return ret; } static PyObject * bytearray_istitle(PyObject *self, PyObject *Py_UNUSED(ignored)) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(self); ret = stringlib_istitle(self, NULL); Py_END_CRITICAL_SECTION(); return ret; } static PyObject * bytearray_isupper(PyObject *self, PyObject *Py_UNUSED(ignored)) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(self); ret = stringlib_isupper(self, NULL); Py_END_CRITICAL_SECTION(); return ret; } /*[clinic input] @critical_section bytearray.append item: bytesvalue The item to be appended. / Append a single item to the end of the bytearray. [clinic start generated code]*/ static PyObject * bytearray_append_impl(PyByteArrayObject *self, int item) /*[clinic end generated code: output=a154e19ed1886cb6 input=a874689bac8bd352]*/ { Py_ssize_t n = Py_SIZE(self); if (bytearray_resize_lock_held((PyObject *)self, n + 1) < 0) return NULL; PyByteArray_AS_STRING(self)[n] = item; Py_RETURN_NONE; } static PyObject * bytearray_capitalize(PyObject *self, PyObject *Py_UNUSED(ignored)) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(self); ret = stringlib_capitalize(self, NULL); Py_END_CRITICAL_SECTION(); return ret; } static PyObject * bytearray_center(PyObject *self, PyObject *const *args, Py_ssize_t nargs) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(self); ret = stringlib_center(self, args, nargs); Py_END_CRITICAL_SECTION(); return ret; } static PyObject * bytearray_expandtabs(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(self); ret = stringlib_expandtabs(self, args, nargs, kwnames); Py_END_CRITICAL_SECTION(); return ret; } /*[clinic input] @permit_long_summary @critical_section bytearray.extend iterable_of_ints: object The iterable of items to append. / Append all the items from the iterator or sequence to the end of the bytearray. [clinic start generated code]*/ static PyObject * bytearray_extend_impl(PyByteArrayObject *self, PyObject *iterable_of_ints) /*[clinic end generated code: output=2f25e0ce72b98748 input=aeed44b025146632]*/ { PyObject *it, *item, *bytearray_obj; Py_ssize_t buf_size = 0, len = 0; int value; char *buf; /* bytearray_setslice code only accepts something supporting PEP 3118. */ if (PyObject_CheckBuffer(iterable_of_ints)) { if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), iterable_of_ints) == -1) return NULL; Py_RETURN_NONE; } it = PyObject_GetIter(iterable_of_ints); if (it == NULL) { if (PyErr_ExceptionMatches(PyExc_TypeError)) { PyErr_Format(PyExc_TypeError, "can't extend bytearray with %.100s", Py_TYPE(iterable_of_ints)->tp_name); } return NULL; } /* Try to determine the length of the argument. 32 is arbitrary. */ buf_size = PyObject_LengthHint(iterable_of_ints, 32); if (buf_size == -1) { Py_DECREF(it); return NULL; } bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size); if (bytearray_obj == NULL) { Py_DECREF(it); return NULL; } buf = PyByteArray_AS_STRING(bytearray_obj); while ((item = PyIter_Next(it)) != NULL) { if (! _getbytevalue(item, &value)) { if (PyErr_ExceptionMatches(PyExc_TypeError) && PyUnicode_Check(iterable_of_ints)) { PyErr_Format(PyExc_TypeError, "expected iterable of integers; got: 'str'"); } Py_DECREF(item); Py_DECREF(it); Py_DECREF(bytearray_obj); return NULL; } Py_DECREF(item); if (len >= buf_size) { Py_ssize_t addition; if (len == PyByteArray_SIZE_MAX) { Py_DECREF(it); Py_DECREF(bytearray_obj); return PyErr_NoMemory(); } addition = len ? len >> 1 : 1; if (addition > PyByteArray_SIZE_MAX - len) buf_size = PyByteArray_SIZE_MAX; else buf_size = len + addition; if (bytearray_resize_lock_held((PyObject *)bytearray_obj, buf_size) < 0) { Py_DECREF(it); Py_DECREF(bytearray_obj); return NULL; } /* Recompute the `buf' pointer, since the resizing operation may have invalidated it. */ buf = PyByteArray_AS_STRING(bytearray_obj); } buf[len++] = value; } Py_DECREF(it); if (PyErr_Occurred()) { Py_DECREF(bytearray_obj); return NULL; } /* Resize down to exact size. */ if (bytearray_resize_lock_held((PyObject *)bytearray_obj, len) < 0) { Py_DECREF(bytearray_obj); return NULL; } if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1) { Py_DECREF(bytearray_obj); return NULL; } Py_DECREF(bytearray_obj); assert(!PyErr_Occurred()); Py_RETURN_NONE; } /*[clinic input] @critical_section bytearray.pop index: Py_ssize_t = -1 The index from where to remove the item. -1 (the default value) means remove the last item. / Remove and return a single item from B. If no index argument is given, will pop the last item. [clinic start generated code]*/ static PyObject * bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index) /*[clinic end generated code: output=e0ccd401f8021da8 input=fc0fd8de4f97661c]*/ { int value; Py_ssize_t n = Py_SIZE(self); char *buf; if (n == 0) { PyErr_SetString(PyExc_IndexError, "pop from empty bytearray"); return NULL; } if (index < 0) index += Py_SIZE(self); if (index < 0 || index >= Py_SIZE(self)) { PyErr_SetString(PyExc_IndexError, "pop index out of range"); return NULL; } if (!_canresize(self)) return NULL; buf = PyByteArray_AS_STRING(self); value = buf[index]; memmove(buf + index, buf + index + 1, n - index); if (bytearray_resize_lock_held((PyObject *)self, n - 1) < 0) return NULL; return _PyLong_FromUnsignedChar((unsigned char)value); } /*[clinic input] @critical_section bytearray.remove value: bytesvalue The value to remove. / Remove the first occurrence of a value in the bytearray. [clinic start generated code]*/ static PyObject * bytearray_remove_impl(PyByteArrayObject *self, int value) /*[clinic end generated code: output=d659e37866709c13 input=797588bc77f86afb]*/ { Py_ssize_t where, n = Py_SIZE(self); char *buf = PyByteArray_AS_STRING(self); where = stringlib_find_char(buf, n, value); if (where < 0) { PyErr_SetString(PyExc_ValueError, "value not found in bytearray"); return NULL; } if (!_canresize(self)) return NULL; memmove(buf + where, buf + where + 1, n - where); if (bytearray_resize_lock_held((PyObject *)self, n - 1) < 0) return NULL; Py_RETURN_NONE; } #define LEFTSTRIP 0 #define RIGHTSTRIP 1 #define BOTHSTRIP 2 static PyObject* bytearray_strip_impl_helper(PyByteArrayObject* self, PyObject* bytes, int striptype) { Py_ssize_t mysize, byteslen; const char* myptr; const char* bytesptr; Py_buffer vbytes; if (bytes == Py_None) { bytesptr = "\t\n\r\f\v "; byteslen = 6; } else { if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0) return NULL; bytesptr = (const char*)vbytes.buf; byteslen = vbytes.len; } myptr = PyByteArray_AS_STRING(self); mysize = Py_SIZE(self); Py_ssize_t left = 0; if (striptype != RIGHTSTRIP) { while (left < mysize && memchr(bytesptr, (unsigned char)myptr[left], byteslen)) left++; } Py_ssize_t right = mysize; if (striptype != LEFTSTRIP) { do { right--; } while (right >= left && memchr(bytesptr, (unsigned char)myptr[right], byteslen)); right++; } if (bytes != Py_None) PyBuffer_Release(&vbytes); return PyByteArray_FromStringAndSize(myptr + left, right - left); } /*[clinic input] @permit_long_docstring_body @critical_section bytearray.strip bytes: object = None / Strip leading and trailing bytes contained in the argument. If the argument is omitted or None, strip leading and trailing ASCII whitespace. [clinic start generated code]*/ static PyObject * bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes) /*[clinic end generated code: output=760412661a34ad5a input=6acaf88b2ec9daa7]*/ { return bytearray_strip_impl_helper(self, bytes, BOTHSTRIP); } static PyObject * bytearray_swapcase(PyObject *self, PyObject *Py_UNUSED(ignored)) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(self); ret = stringlib_swapcase(self, NULL); Py_END_CRITICAL_SECTION(); return ret; } static PyObject * bytearray_title(PyObject *self, PyObject *Py_UNUSED(ignored)) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(self); ret = stringlib_title(self, NULL); Py_END_CRITICAL_SECTION(); return ret; } static PyObject * bytearray_upper(PyObject *self, PyObject *Py_UNUSED(ignored)) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(self); ret = stringlib_upper(self, NULL); Py_END_CRITICAL_SECTION(); return ret; } static PyObject * bytearray_lower(PyObject *self, PyObject *Py_UNUSED(ignored)) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(self); ret = stringlib_lower(self, NULL); Py_END_CRITICAL_SECTION(); return ret; } static PyObject * bytearray_zfill(PyObject *self, PyObject *arg) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(self); ret = stringlib_zfill(self, arg); Py_END_CRITICAL_SECTION(); return ret; } /*[clinic input] @critical_section bytearray.lstrip bytes: object = None / Strip leading bytes contained in the argument. If the argument is omitted or None, strip leading ASCII whitespace. [clinic start generated code]*/ static PyObject * bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes) /*[clinic end generated code: output=d005c9d0ab909e66 input=ed86e00eb2023625]*/ { return bytearray_strip_impl_helper(self, bytes, LEFTSTRIP); } /*[clinic input] @critical_section bytearray.rstrip bytes: object = None / Strip trailing bytes contained in the argument. If the argument is omitted or None, strip trailing ASCII whitespace. [clinic start generated code]*/ static PyObject * bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes) /*[clinic end generated code: output=030e2fbd2f7276bd input=d9ca66cf20fe7649]*/ { return bytearray_strip_impl_helper(self, bytes, RIGHTSTRIP); } /*[clinic input] @critical_section bytearray.decode encoding: str(c_default="NULL") = 'utf-8' The encoding with which to decode the bytearray. errors: str(c_default="NULL") = 'strict' The error handling scheme to use for the handling of decoding errors. The default is 'strict' meaning that decoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error that can handle UnicodeDecodeErrors. Decode the bytearray using the codec registered for encoding. [clinic start generated code]*/ static PyObject * bytearray_decode_impl(PyByteArrayObject *self, const char *encoding, const char *errors) /*[clinic end generated code: output=f57d43f4a00b42c5 input=86c303ee376b8453]*/ { if (encoding == NULL) encoding = PyUnicode_GetDefaultEncoding(); return PyUnicode_FromEncodedObject((PyObject*)self, encoding, errors); } PyDoc_STRVAR(alloc_doc, "B.__alloc__() -> int\n\ \n\ Return the number of bytes actually allocated."); static PyObject * bytearray_alloc(PyObject *op, PyObject *Py_UNUSED(ignored)) { PyByteArrayObject *self = _PyByteArray_CAST(op); Py_ssize_t alloc = FT_ATOMIC_LOAD_SSIZE_RELAXED(self->ob_alloc); if (alloc > 0) { alloc += _PyBytesObject_SIZE; } return PyLong_FromSsize_t(alloc); } /*[clinic input] @critical_section bytearray.join iterable_of_bytes: object / Concatenate any number of bytes/bytearray objects. The bytearray whose method is called is inserted in between each pair. The result is returned as a new bytearray object. [clinic start generated code]*/ static PyObject * bytearray_join_impl(PyByteArrayObject *self, PyObject *iterable_of_bytes) /*[clinic end generated code: output=0ced382b5846a7ee input=49627e07ca31ca26]*/ { PyObject *ret; self->ob_exports++; // this protects `self` from being cleared/resized if `iterable_of_bytes` is a custom iterator ret = stringlib_bytes_join((PyObject*)self, iterable_of_bytes); self->ob_exports--; // unexport `self` return ret; } static PyObject * bytearray_ljust(PyObject *self, PyObject *const *args, Py_ssize_t nargs) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(self); ret = stringlib_ljust(self, args, nargs); Py_END_CRITICAL_SECTION(); return ret; } static PyObject * bytearray_rjust(PyObject *self, PyObject *const *args, Py_ssize_t nargs) { PyObject *ret; Py_BEGIN_CRITICAL_SECTION(self); ret = stringlib_rjust(self, args, nargs); Py_END_CRITICAL_SECTION(); return ret; } /*[clinic input] @permit_long_summary @permit_long_docstring_body @critical_section bytearray.splitlines keepends: bool = False Return a list of the lines in the bytearray, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. [clinic start generated code]*/ static PyObject * bytearray_splitlines_impl(PyByteArrayObject *self, int keepends) /*[clinic end generated code: output=4223c94b895f6ad9 input=21bc3f02bf1be832]*/ { return stringlib_splitlines( (PyObject*) self, PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), keepends ); } /*[clinic input] @classmethod bytearray.fromhex string: object / Create a bytearray object from a string of hexadecimal numbers. Spaces between two numbers are accepted. Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef') [clinic start generated code]*/ static PyObject * bytearray_fromhex_impl(PyTypeObject *type, PyObject *string) /*[clinic end generated code: output=8f0f0b6d30fb3ba0 input=7e314e5b2d7ab484]*/ { PyObject *result = _PyBytes_FromHex(string, type == &PyByteArray_Type); if (type != &PyByteArray_Type && result != NULL) { Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result)); } return result; } /*[clinic input] @critical_section bytearray.hex sep: object = NULL An optional single character or byte to separate hex bytes. bytes_per_sep: int = 1 How many bytes between separators. Positive values count from the right, negative values count from the left. Create a string of hexadecimal numbers from a bytearray object. Example: >>> value = bytearray([0xb9, 0x01, 0xef]) >>> value.hex() 'b901ef' >>> value.hex(':') 'b9:01:ef' >>> value.hex(':', 2) 'b9:01ef' >>> value.hex(':', -2) 'b901:ef' [clinic start generated code]*/ static PyObject * bytearray_hex_impl(PyByteArrayObject *self, PyObject *sep, int bytes_per_sep) /*[clinic end generated code: output=29c4e5ef72c565a0 input=7784107de7048873]*/ { char* argbuf = PyByteArray_AS_STRING(self); Py_ssize_t arglen = PyByteArray_GET_SIZE(self); // Prevent 'self' from being freed if computing len(sep) mutates 'self' // in _Py_strhex_with_sep(). // See: https://github.com/python/cpython/issues/143195. self->ob_exports++; PyObject *res = _Py_strhex_with_sep(argbuf, arglen, sep, bytes_per_sep); self->ob_exports--; return res; } static PyObject * _common_reduce(PyByteArrayObject *self, int proto) { PyObject *state; const char *buf; state = _PyObject_GetState((PyObject *)self); if (state == NULL) { return NULL; } if (!Py_SIZE(self)) { return Py_BuildValue("(O()N)", Py_TYPE(self), state); } buf = PyByteArray_AS_STRING(self); if (proto < 3) { /* use str based reduction for backwards compatibility with Python 2.x */ PyObject *latin1 = PyUnicode_DecodeLatin1(buf, Py_SIZE(self), NULL); return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", state); } else { /* use more efficient byte based reduction */ return Py_BuildValue("(O(y#)N)", Py_TYPE(self), buf, Py_SIZE(self), state); } } /*[clinic input] @critical_section bytearray.__reduce__ as bytearray_reduce Return state information for pickling. [clinic start generated code]*/ static PyObject * bytearray_reduce_impl(PyByteArrayObject *self) /*[clinic end generated code: output=52bf304086464cab input=0fac78e4b7d84dd2]*/ { return _common_reduce(self, 2); } /*[clinic input] @critical_section bytearray.__reduce_ex__ as bytearray_reduce_ex proto: int = 0 / Return state information for pickling. [clinic start generated code]*/ static PyObject * bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto) /*[clinic end generated code: output=52eac33377197520 input=751718f477033a29]*/ { return _common_reduce(self, proto); } /*[clinic input] bytearray.__sizeof__ as bytearray_sizeof Returns the size of the bytearray object in memory, in bytes. [clinic start generated code]*/ static PyObject * bytearray_sizeof_impl(PyByteArrayObject *self) /*[clinic end generated code: output=738abdd17951c427 input=e27320fd98a4bc5a]*/ { Py_ssize_t res = _PyObject_SIZE(Py_TYPE(self)); Py_ssize_t alloc = FT_ATOMIC_LOAD_SSIZE_RELAXED(self->ob_alloc); if (alloc > 0) { res += _PyBytesObject_SIZE + alloc; } return PyLong_FromSsize_t(res); } static PySequenceMethods bytearray_as_sequence = { bytearray_length, /* sq_length */ PyByteArray_Concat, /* sq_concat */ bytearray_repeat, /* sq_repeat */ bytearray_getitem, /* sq_item */ 0, /* sq_slice */ bytearray_setitem, /* sq_ass_item */ 0, /* sq_ass_slice */ bytearray_contains, /* sq_contains */ bytearray_iconcat, /* sq_inplace_concat */ bytearray_irepeat, /* sq_inplace_repeat */ }; static PyMappingMethods bytearray_as_mapping = { bytearray_length, bytearray_subscript, bytearray_ass_subscript, }; static PyBufferProcs bytearray_as_buffer = { bytearray_getbuffer, bytearray_releasebuffer, }; static PyMethodDef bytearray_methods[] = { {"__alloc__", bytearray_alloc, METH_NOARGS, alloc_doc}, BYTEARRAY_REDUCE_METHODDEF BYTEARRAY_REDUCE_EX_METHODDEF BYTEARRAY_SIZEOF_METHODDEF BYTEARRAY_APPEND_METHODDEF {"capitalize", bytearray_capitalize, METH_NOARGS, _Py_capitalize__doc__}, {"center", _PyCFunction_CAST(bytearray_center), METH_FASTCALL, stringlib_center__doc__}, BYTEARRAY_CLEAR_METHODDEF BYTEARRAY_COPY_METHODDEF BYTEARRAY_COUNT_METHODDEF BYTEARRAY_DECODE_METHODDEF BYTEARRAY_ENDSWITH_METHODDEF {"expandtabs", _PyCFunction_CAST(bytearray_expandtabs), METH_FASTCALL|METH_KEYWORDS, stringlib_expandtabs__doc__}, BYTEARRAY_EXTEND_METHODDEF BYTEARRAY_FIND_METHODDEF BYTEARRAY_FROMHEX_METHODDEF BYTEARRAY_HEX_METHODDEF BYTEARRAY_INDEX_METHODDEF BYTEARRAY_INSERT_METHODDEF {"isalnum", bytearray_isalnum, METH_NOARGS, _Py_isalnum__doc__}, {"isalpha", bytearray_isalpha, METH_NOARGS, _Py_isalpha__doc__}, {"isascii", bytearray_isascii, METH_NOARGS, _Py_isascii__doc__}, {"isdigit", bytearray_isdigit, METH_NOARGS, _Py_isdigit__doc__}, {"islower", bytearray_islower, METH_NOARGS, _Py_islower__doc__}, {"isspace", bytearray_isspace, METH_NOARGS, _Py_isspace__doc__}, {"istitle", bytearray_istitle, METH_NOARGS, _Py_istitle__doc__}, {"isupper", bytearray_isupper, METH_NOARGS, _Py_isupper__doc__}, BYTEARRAY_JOIN_METHODDEF {"ljust", _PyCFunction_CAST(bytearray_ljust), METH_FASTCALL, stringlib_ljust__doc__}, {"lower", bytearray_lower, METH_NOARGS, _Py_lower__doc__}, BYTEARRAY_LSTRIP_METHODDEF BYTEARRAY_MAKETRANS_METHODDEF BYTEARRAY_PARTITION_METHODDEF BYTEARRAY_POP_METHODDEF BYTEARRAY_REMOVE_METHODDEF BYTEARRAY_REPLACE_METHODDEF BYTEARRAY_REMOVEPREFIX_METHODDEF BYTEARRAY_REMOVESUFFIX_METHODDEF BYTEARRAY_RESIZE_METHODDEF BYTEARRAY_REVERSE_METHODDEF BYTEARRAY_RFIND_METHODDEF BYTEARRAY_RINDEX_METHODDEF {"rjust", _PyCFunction_CAST(bytearray_rjust), METH_FASTCALL, stringlib_rjust__doc__}, BYTEARRAY_RPARTITION_METHODDEF BYTEARRAY_RSPLIT_METHODDEF BYTEARRAY_RSTRIP_METHODDEF BYTEARRAY_SPLIT_METHODDEF BYTEARRAY_SPLITLINES_METHODDEF BYTEARRAY_STARTSWITH_METHODDEF BYTEARRAY_STRIP_METHODDEF {"swapcase", bytearray_swapcase, METH_NOARGS, _Py_swapcase__doc__}, BYTEARRAY_TAKE_BYTES_METHODDEF {"title", bytearray_title, METH_NOARGS, _Py_title__doc__}, BYTEARRAY_TRANSLATE_METHODDEF {"upper", bytearray_upper, METH_NOARGS, _Py_upper__doc__}, {"zfill", bytearray_zfill, METH_O, stringlib_zfill__doc__}, {NULL} }; static PyObject * bytearray_mod_lock_held(PyObject *v, PyObject *w) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(v); if (!PyByteArray_Check(v)) Py_RETURN_NOTIMPLEMENTED; PyByteArrayObject *self = _PyByteArray_CAST(v); /* Increase exports to prevent bytearray storage from changing during op. */ self->ob_exports++; PyObject *res = _PyBytes_FormatEx( PyByteArray_AS_STRING(v), PyByteArray_GET_SIZE(v), w, 1 ); self->ob_exports--; return res; } static PyObject * bytearray_mod(PyObject *v, PyObject *w) { PyObject *ret; if (PyByteArray_Check(w)) { Py_BEGIN_CRITICAL_SECTION2(v, w); ret = bytearray_mod_lock_held(v, w); Py_END_CRITICAL_SECTION2(); } else { Py_BEGIN_CRITICAL_SECTION(v); ret = bytearray_mod_lock_held(v, w); Py_END_CRITICAL_SECTION(); } return ret; } static PyNumberMethods bytearray_as_number = { 0, /*nb_add*/ 0, /*nb_subtract*/ 0, /*nb_multiply*/ bytearray_mod, /*nb_remainder*/ }; PyDoc_STRVAR(bytearray_doc, "bytearray(iterable_of_ints) -> bytearray\n\ bytearray(string, encoding[, errors]) -> bytearray\n\ bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer\n\ bytearray(int) -> bytes array of size given by the parameter initialized with null bytes\n\ bytearray() -> empty bytes array\n\ \n\ Construct a mutable bytearray object from:\n\ - an iterable yielding integers in range(256)\n\ - a text string encoded using the specified encoding\n\ - a bytes or a buffer object\n\ - any object implementing the buffer API.\n\ - an integer"); static PyObject *bytearray_iter(PyObject *seq); PyTypeObject PyByteArray_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "bytearray", sizeof(PyByteArrayObject), 0, bytearray_dealloc, /* tp_dealloc */ 0, /* tp_vectorcall_offset */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ bytearray_repr, /* tp_repr */ &bytearray_as_number, /* tp_as_number */ &bytearray_as_sequence, /* tp_as_sequence */ &bytearray_as_mapping, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ bytearray_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ &bytearray_as_buffer, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | _Py_TPFLAGS_MATCH_SELF, /* tp_flags */ bytearray_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ bytearray_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ bytearray_iter, /* tp_iter */ 0, /* tp_iternext */ bytearray_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ bytearray___init__, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ PyObject_Free, /* tp_free */ .tp_version_tag = _Py_TYPE_VERSION_BYTEARRAY, }; /*********************** Bytearray Iterator ****************************/ typedef struct { PyObject_HEAD Py_ssize_t it_index; PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */ } bytesiterobject; #define _bytesiterobject_CAST(op) ((bytesiterobject *)(op)) static void bytearrayiter_dealloc(PyObject *self) { bytesiterobject *it = _bytesiterobject_CAST(self); _PyObject_GC_UNTRACK(it); Py_XDECREF(it->it_seq); PyObject_GC_Del(it); } static int bytearrayiter_traverse(PyObject *self, visitproc visit, void *arg) { bytesiterobject *it = _bytesiterobject_CAST(self); Py_VISIT(it->it_seq); return 0; } static PyObject * bytearrayiter_next(PyObject *self) { bytesiterobject *it = _bytesiterobject_CAST(self); int val; assert(it != NULL); Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index); if (index < 0) { return NULL; } PyByteArrayObject *seq = it->it_seq; assert(PyByteArray_Check(seq)); Py_BEGIN_CRITICAL_SECTION(seq); if (index < Py_SIZE(seq)) { val = (unsigned char)PyByteArray_AS_STRING(seq)[index]; } else { val = -1; } Py_END_CRITICAL_SECTION(); if (val == -1) { FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, -1); #ifndef Py_GIL_DISABLED Py_CLEAR(it->it_seq); #endif return NULL; } FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, index + 1); return _PyLong_FromUnsignedChar((unsigned char)val); } static PyObject * bytearrayiter_length_hint(PyObject *self, PyObject *Py_UNUSED(ignored)) { bytesiterobject *it = _bytesiterobject_CAST(self); Py_ssize_t len = 0; Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index); if (index >= 0) { len = PyByteArray_GET_SIZE(it->it_seq) - index; if (len < 0) { len = 0; } } return PyLong_FromSsize_t(len); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyObject * bytearrayiter_reduce(PyObject *self, PyObject *Py_UNUSED(ignored)) { PyObject *iter = _PyEval_GetBuiltin(&_Py_ID(iter)); /* _PyEval_GetBuiltin can invoke arbitrary code, * call must be before access of iterator pointers. * see issue #101765 */ bytesiterobject *it = _bytesiterobject_CAST(self); Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index); if (index >= 0) { return Py_BuildValue("N(O)n", iter, it->it_seq, index); } return Py_BuildValue("N(())", iter); } static PyObject * bytearrayiter_setstate(PyObject *self, PyObject *state) { Py_ssize_t index = PyLong_AsSsize_t(state); if (index == -1 && PyErr_Occurred()) { return NULL; } bytesiterobject *it = _bytesiterobject_CAST(self); if (FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index) >= 0) { if (index < -1) { index = -1; } else { Py_ssize_t size = PyByteArray_GET_SIZE(it->it_seq); if (index > size) { index = size; /* iterator at end */ } } FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, index); } Py_RETURN_NONE; } PyDoc_STRVAR(setstate_doc, "Set state information for unpickling."); static PyMethodDef bytearrayiter_methods[] = { {"__length_hint__", bytearrayiter_length_hint, METH_NOARGS, length_hint_doc}, {"__reduce__", bytearrayiter_reduce, METH_NOARGS, bytearray_reduce__doc__}, {"__setstate__", bytearrayiter_setstate, METH_O, setstate_doc}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyByteArrayIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "bytearray_iterator", /* tp_name */ sizeof(bytesiterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ bytearrayiter_dealloc, /* tp_dealloc */ 0, /* tp_vectorcall_offset */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ bytearrayiter_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ bytearrayiter_next, /* tp_iternext */ bytearrayiter_methods, /* tp_methods */ 0, }; static PyObject * bytearray_iter(PyObject *seq) { bytesiterobject *it; if (!PyByteArray_Check(seq)) { PyErr_BadInternalCall(); return NULL; } it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type); if (it == NULL) return NULL; it->it_index = 0; // -1 indicates exhausted it->it_seq = (PyByteArrayObject *)Py_NewRef(seq); _PyObject_GC_TRACK(it); return (PyObject *)it; } /* Abstract Object Interface (many thanks to Jim Fulton) */ #include "Python.h" #include "pycore_abstract.h" // _PyIndex_Check() #include "pycore_call.h" // _PyObject_CallNoArgs() #include "pycore_ceval.h" // _Py_EnterRecursiveCallTstate() #include "pycore_crossinterp.h" // _Py_CallInInterpreter() #include "pycore_genobject.h" // _PyGen_FetchStopIterationValue() #include "pycore_list.h" // _PyList_AppendTakeRef() #include "pycore_long.h" // _PyLong_IsNegative() #include "pycore_object.h" // _Py_CheckSlotResult() #include "pycore_pybuffer.h" // _PyBuffer_ReleaseInInterpreterAndRawFree() #include "pycore_pyerrors.h" // _PyErr_Occurred() #include "pycore_pystate.h" // _PyThreadState_GET() #include "pycore_tuple.h" // _PyTuple_FromArraySteal() #include "pycore_unionobject.h" // _PyUnion_Check() #include // offsetof() /* Shorthands to return certain errors */ static PyObject * type_error(const char *msg, PyObject *obj) { PyErr_Format(PyExc_TypeError, msg, Py_TYPE(obj)->tp_name); return NULL; } static PyObject * null_error(void) { PyThreadState *tstate = _PyThreadState_GET(); if (!_PyErr_Occurred(tstate)) { _PyErr_SetString(tstate, PyExc_SystemError, "null argument to internal routine"); } return NULL; } /* Operations on any object */ PyObject * PyObject_Type(PyObject *o) { PyObject *v; if (o == NULL) { return null_error(); } v = (PyObject *)Py_TYPE(o); return Py_NewRef(v); } Py_ssize_t PyObject_Size(PyObject *o) { if (o == NULL) { null_error(); return -1; } PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; if (m && m->sq_length) { Py_ssize_t len = m->sq_length(o); assert(_Py_CheckSlotResult(o, "__len__", len >= 0)); return len; } return PyMapping_Size(o); } #undef PyObject_Length Py_ssize_t PyObject_Length(PyObject *o) { return PyObject_Size(o); } #define PyObject_Length PyObject_Size int _PyObject_HasLen(PyObject *o) { return (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) || (Py_TYPE(o)->tp_as_mapping && Py_TYPE(o)->tp_as_mapping->mp_length); } /* The length hint function returns a non-negative value from o.__len__() or o.__length_hint__(). If those methods aren't found the defaultvalue is returned. If one of the calls fails with an exception other than TypeError this function returns -1. */ Py_ssize_t PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue) { PyObject *hint, *result; Py_ssize_t res; if (_PyObject_HasLen(o)) { res = PyObject_Length(o); if (res < 0) { PyThreadState *tstate = _PyThreadState_GET(); assert(_PyErr_Occurred(tstate)); if (!_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) { return -1; } _PyErr_Clear(tstate); } else { return res; } } hint = _PyObject_LookupSpecial(o, &_Py_ID(__length_hint__)); if (hint == NULL) { if (PyErr_Occurred()) { return -1; } return defaultvalue; } result = _PyObject_CallNoArgs(hint); Py_DECREF(hint); if (result == NULL) { PyThreadState *tstate = _PyThreadState_GET(); if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) { _PyErr_Clear(tstate); return defaultvalue; } return -1; } else if (result == Py_NotImplemented) { Py_DECREF(result); return defaultvalue; } if (!PyLong_Check(result)) { PyErr_Format(PyExc_TypeError, "%T.__length_hint__() must return an int, not %T", o, result); Py_DECREF(result); return -1; } res = PyLong_AsSsize_t(result); Py_DECREF(result); if (res < 0 && PyErr_Occurred()) { return -1; } if (res < 0) { PyErr_Format(PyExc_ValueError, "%T.__length_hint__() must return a non-negative int", o); return -1; } return res; } PyObject * PyObject_GetItem(PyObject *o, PyObject *key) { if (o == NULL || key == NULL) { return null_error(); } PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping; if (m && m->mp_subscript) { PyObject *item = m->mp_subscript(o, key); assert(_Py_CheckSlotResult(o, "__getitem__", item != NULL)); return item; } PySequenceMethods *ms = Py_TYPE(o)->tp_as_sequence; if (ms && ms->sq_item) { if (_PyIndex_Check(key)) { Py_ssize_t key_value; key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); if (key_value == -1 && PyErr_Occurred()) return NULL; return PySequence_GetItem(o, key_value); } else { return type_error("sequence index must " "be integer, not '%.200s'", key); } } if (PyType_Check(o)) { PyObject *meth, *result; // Special case type[int], but disallow other types so str[int] fails if ((PyTypeObject*)o == &PyType_Type) { return Py_GenericAlias(o, key); } if (PyObject_GetOptionalAttr(o, &_Py_ID(__class_getitem__), &meth) < 0) { return NULL; } if (meth && meth != Py_None) { result = PyObject_CallOneArg(meth, key); Py_DECREF(meth); return result; } Py_XDECREF(meth); PyErr_Format(PyExc_TypeError, "type '%.200s' is not subscriptable", ((PyTypeObject *)o)->tp_name); return NULL; } return type_error("'%.200s' object is not subscriptable", o); } int PyMapping_GetOptionalItem(PyObject *obj, PyObject *key, PyObject **result) { if (PyDict_CheckExact(obj)) { return PyDict_GetItemRef(obj, key, result); } *result = PyObject_GetItem(obj, key); if (*result) { return 1; } assert(PyErr_Occurred()); if (!PyErr_ExceptionMatches(PyExc_KeyError)) { return -1; } PyErr_Clear(); return 0; } PyObject* _PyMapping_GetOptionalItem2(PyObject *obj, PyObject *key, int *err) { PyObject* result; *err = PyMapping_GetOptionalItem(obj, key, &result); return result; } int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value) { if (o == NULL || key == NULL || value == NULL) { null_error(); return -1; } PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping; if (m && m->mp_ass_subscript) { int res = m->mp_ass_subscript(o, key, value); assert(_Py_CheckSlotResult(o, "__setitem__", res >= 0)); return res; } if (Py_TYPE(o)->tp_as_sequence) { if (_PyIndex_Check(key)) { Py_ssize_t key_value; key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); if (key_value == -1 && PyErr_Occurred()) return -1; return PySequence_SetItem(o, key_value, value); } else if (Py_TYPE(o)->tp_as_sequence->sq_ass_item) { type_error("sequence index must be " "integer, not '%.200s'", key); return -1; } } type_error("'%.200s' object does not support item assignment", o); return -1; } int PyObject_DelItem(PyObject *o, PyObject *key) { if (o == NULL || key == NULL) { null_error(); return -1; } PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping; if (m && m->mp_ass_subscript) { int res = m->mp_ass_subscript(o, key, (PyObject*)NULL); assert(_Py_CheckSlotResult(o, "__delitem__", res >= 0)); return res; } if (Py_TYPE(o)->tp_as_sequence) { if (_PyIndex_Check(key)) { Py_ssize_t key_value; key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); if (key_value == -1 && PyErr_Occurred()) return -1; return PySequence_DelItem(o, key_value); } else if (Py_TYPE(o)->tp_as_sequence->sq_ass_item) { type_error("sequence index must be " "integer, not '%.200s'", key); return -1; } } type_error("'%.200s' object does not support item deletion", o); return -1; } int PyObject_DelItemString(PyObject *o, const char *key) { PyObject *okey; int ret; if (o == NULL || key == NULL) { null_error(); return -1; } okey = PyUnicode_FromString(key); if (okey == NULL) return -1; ret = PyObject_DelItem(o, okey); Py_DECREF(okey); return ret; } /* Return 1 if the getbuffer function is available, otherwise return 0. */ int PyObject_CheckBuffer(PyObject *obj) { PyBufferProcs *tp_as_buffer = Py_TYPE(obj)->tp_as_buffer; return (tp_as_buffer != NULL && tp_as_buffer->bf_getbuffer != NULL); } // Old buffer protocols (deprecated, abi only) /* Checks whether an arbitrary object supports the (character, single segment) buffer interface. Returns 1 on success, 0 on failure. We release the buffer right after use of this function which could cause issues later on. Don't use these functions in new code. */ PyAPI_FUNC(int) /* abi_only */ PyObject_CheckReadBuffer(PyObject *obj) { PyBufferProcs *pb = Py_TYPE(obj)->tp_as_buffer; Py_buffer view; if (pb == NULL || pb->bf_getbuffer == NULL) return 0; if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE) == -1) { PyErr_Clear(); return 0; } PyBuffer_Release(&view); return 1; } static int as_read_buffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len) { Py_buffer view; if (obj == NULL || buffer == NULL || buffer_len == NULL) { null_error(); return -1; } if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) != 0) return -1; *buffer = view.buf; *buffer_len = view.len; PyBuffer_Release(&view); return 0; } /* 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. */ PyAPI_FUNC(int) /* abi_only */ PyObject_AsCharBuffer(PyObject *obj, const char **buffer, Py_ssize_t *buffer_len) { return as_read_buffer(obj, (const void **)buffer, buffer_len); } /* 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. */ PyAPI_FUNC(int) /* abi_only */ PyObject_AsReadBuffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len) { return as_read_buffer(obj, buffer, 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. */ PyAPI_FUNC(int) /* abi_only */ PyObject_AsWriteBuffer(PyObject *obj, void **buffer, Py_ssize_t *buffer_len) { PyBufferProcs *pb; Py_buffer view; if (obj == NULL || buffer == NULL || buffer_len == NULL) { null_error(); return -1; } pb = Py_TYPE(obj)->tp_as_buffer; if (pb == NULL || pb->bf_getbuffer == NULL || ((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITABLE) != 0)) { PyErr_SetString(PyExc_TypeError, "expected a writable bytes-like object"); return -1; } *buffer = view.buf; *buffer_len = view.len; PyBuffer_Release(&view); return 0; } /* Buffer C-API for Python 3.0 */ int PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { if (flags != PyBUF_SIMPLE) { /* fast path */ if (flags == PyBUF_READ || flags == PyBUF_WRITE) { PyErr_BadInternalCall(); return -1; } } PyBufferProcs *pb = Py_TYPE(obj)->tp_as_buffer; if (pb == NULL || pb->bf_getbuffer == NULL) { PyErr_Format(PyExc_TypeError, "a bytes-like object is required, not '%.100s'", Py_TYPE(obj)->tp_name); return -1; } int res = (*pb->bf_getbuffer)(obj, view, flags); assert(_Py_CheckSlotResult(obj, "getbuffer", res >= 0)); return res; } static int _IsFortranContiguous(const Py_buffer *view) { Py_ssize_t sd, dim; int i; /* 1) len = product(shape) * itemsize 2) itemsize > 0 3) len = 0 <==> exists i: shape[i] = 0 */ if (view->len == 0) return 1; if (view->strides == NULL) { /* C-contiguous by definition */ /* Trivially F-contiguous */ if (view->ndim <= 1) return 1; /* ndim > 1 implies shape != NULL */ assert(view->shape != NULL); /* Effectively 1-d */ sd = 0; for (i=0; indim; i++) { if (view->shape[i] > 1) sd += 1; } return sd <= 1; } /* strides != NULL implies both of these */ assert(view->ndim > 0); assert(view->shape != NULL); sd = view->itemsize; for (i=0; indim; i++) { dim = view->shape[i]; if (dim > 1 && view->strides[i] != sd) { return 0; } sd *= dim; } return 1; } static int _IsCContiguous(const Py_buffer *view) { Py_ssize_t sd, dim; int i; /* 1) len = product(shape) * itemsize 2) itemsize > 0 3) len = 0 <==> exists i: shape[i] = 0 */ if (view->len == 0) return 1; if (view->strides == NULL) return 1; /* C-contiguous by definition */ /* strides != NULL implies both of these */ assert(view->ndim > 0); assert(view->shape != NULL); sd = view->itemsize; for (i=view->ndim-1; i>=0; i--) { dim = view->shape[i]; if (dim > 1 && view->strides[i] != sd) { return 0; } sd *= dim; } return 1; } int PyBuffer_IsContiguous(const Py_buffer *view, char order) { if (view->suboffsets != NULL) return 0; if (order == 'C') return _IsCContiguous(view); else if (order == 'F') return _IsFortranContiguous(view); else if (order == 'A') return (_IsCContiguous(view) || _IsFortranContiguous(view)); return 0; } void* PyBuffer_GetPointer(const Py_buffer *view, const Py_ssize_t *indices) { char* pointer; int i; pointer = (char *)view->buf; for (i = 0; i < view->ndim; i++) { pointer += view->strides[i]*indices[i]; if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) { pointer = *((char**)pointer) + view->suboffsets[i]; } } return (void*)pointer; } static void _Py_add_one_to_index_F(int nd, Py_ssize_t *index, const Py_ssize_t *shape) { int k; for (k=0; k=0; k--) { if (index[k] < shape[k]-1) { index[k]++; break; } else { index[k] = 0; } } } Py_ssize_t PyBuffer_SizeFromFormat(const char *format) { PyObject *calcsize = NULL; PyObject *res = NULL; PyObject *fmt = NULL; Py_ssize_t itemsize = -1; calcsize = PyImport_ImportModuleAttrString("struct", "calcsize"); if (calcsize == NULL) { goto done; } fmt = PyUnicode_FromString(format); if (fmt == NULL) { goto done; } res = PyObject_CallFunctionObjArgs(calcsize, fmt, NULL); if (res == NULL) { goto done; } itemsize = PyLong_AsSsize_t(res); if (itemsize < 0) { goto done; } done: Py_XDECREF(calcsize); Py_XDECREF(fmt); Py_XDECREF(res); return itemsize; } int PyBuffer_FromContiguous(const Py_buffer *view, const void *buf, Py_ssize_t len, char fort) { int k; void (*addone)(int, Py_ssize_t *, const Py_ssize_t *); Py_ssize_t *indices, elements; char *ptr; const char *src; if (len > view->len) { len = view->len; } if (PyBuffer_IsContiguous(view, fort)) { /* simplest copy is all that is needed */ memcpy(view->buf, buf, len); return 0; } /* Otherwise a more elaborate scheme is needed */ /* view->ndim <= 64 */ indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim)); if (indices == NULL) { PyErr_NoMemory(); return -1; } for (k=0; kndim;k++) { indices[k] = 0; } if (fort == 'F') { addone = _Py_add_one_to_index_F; } else { addone = _Py_add_one_to_index_C; } src = buf; /* XXX : This is not going to be the fastest code in the world several optimizations are possible. */ elements = len / view->itemsize; while (elements--) { ptr = PyBuffer_GetPointer(view, indices); memcpy(ptr, src, view->itemsize); src += view->itemsize; addone(view->ndim, indices, view->shape); } PyMem_Free(indices); return 0; } int PyObject_CopyData(PyObject *dest, PyObject *src) { Py_buffer view_dest, view_src; int k; Py_ssize_t *indices, elements; char *dptr, *sptr; if (!PyObject_CheckBuffer(dest) || !PyObject_CheckBuffer(src)) { PyErr_SetString(PyExc_TypeError, "both destination and source must be "\ "bytes-like objects"); return -1; } if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1; if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) { PyBuffer_Release(&view_dest); return -1; } if (view_dest.len < view_src.len) { PyErr_SetString(PyExc_BufferError, "destination is too small to receive data from source"); PyBuffer_Release(&view_dest); PyBuffer_Release(&view_src); return -1; } if ((PyBuffer_IsContiguous(&view_dest, 'C') && PyBuffer_IsContiguous(&view_src, 'C')) || (PyBuffer_IsContiguous(&view_dest, 'F') && PyBuffer_IsContiguous(&view_src, 'F'))) { /* simplest copy is all that is needed */ memcpy(view_dest.buf, view_src.buf, view_src.len); PyBuffer_Release(&view_dest); PyBuffer_Release(&view_src); return 0; } /* Otherwise a more elaborate copy scheme is needed */ /* XXX(nnorwitz): need to check for overflow! */ indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim); if (indices == NULL) { PyErr_NoMemory(); PyBuffer_Release(&view_dest); PyBuffer_Release(&view_src); return -1; } for (k=0; k=0; k--) { strides[k] = sd; sd *= shape[k]; } } return; } int PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len, int readonly, int flags) { if (view == NULL) { PyErr_SetString(PyExc_BufferError, "PyBuffer_FillInfo: view==NULL argument is obsolete"); return -1; } if (flags != PyBUF_SIMPLE) { /* fast path */ if (flags == PyBUF_READ || flags == PyBUF_WRITE) { PyErr_BadInternalCall(); return -1; } if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) && (readonly == 1)) { PyErr_SetString(PyExc_BufferError, "Object is not writable."); return -1; } } view->obj = Py_XNewRef(obj); view->buf = buf; view->len = len; view->readonly = readonly; view->itemsize = 1; view->format = NULL; if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) view->format = "B"; view->ndim = 1; view->shape = NULL; if ((flags & PyBUF_ND) == PyBUF_ND) view->shape = &(view->len); view->strides = NULL; if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) view->strides = &(view->itemsize); view->suboffsets = NULL; view->internal = NULL; return 0; } void PyBuffer_Release(Py_buffer *view) { PyObject *obj = view->obj; PyBufferProcs *pb; if (obj == NULL) return; pb = Py_TYPE(obj)->tp_as_buffer; if (pb && pb->bf_releasebuffer) { pb->bf_releasebuffer(obj, view); } view->obj = NULL; Py_DECREF(obj); } static int _buffer_release_call(void *arg) { PyBuffer_Release((Py_buffer *)arg); return 0; } int _PyBuffer_ReleaseInInterpreter(PyInterpreterState *interp, Py_buffer *view) { return _Py_CallInInterpreter(interp, _buffer_release_call, view); } int _PyBuffer_ReleaseInInterpreterAndRawFree(PyInterpreterState *interp, Py_buffer *view) { return _Py_CallInInterpreterAndRawFree(interp, _buffer_release_call, view); } PyObject * PyObject_Format(PyObject *obj, PyObject *format_spec) { PyObject *meth; PyObject *empty = NULL; PyObject *result = NULL; if (format_spec != NULL && !PyUnicode_Check(format_spec)) { PyErr_Format(PyExc_SystemError, "Format specifier must be a string, not %.200s", Py_TYPE(format_spec)->tp_name); return NULL; } /* Fast path for common types. */ if (format_spec == NULL || PyUnicode_GET_LENGTH(format_spec) == 0) { if (PyUnicode_CheckExact(obj)) { return Py_NewRef(obj); } if (PyLong_CheckExact(obj)) { return PyObject_Str(obj); } } /* If no format_spec is provided, use an empty string */ if (format_spec == NULL) { empty = Py_GetConstant(Py_CONSTANT_EMPTY_STR); format_spec = empty; } /* Find the (unbound!) __format__ method */ meth = _PyObject_LookupSpecial(obj, &_Py_ID(__format__)); if (meth == NULL) { PyThreadState *tstate = _PyThreadState_GET(); if (!_PyErr_Occurred(tstate)) { _PyErr_Format(tstate, PyExc_TypeError, "Type %.100s doesn't define __format__", Py_TYPE(obj)->tp_name); } goto done; } /* And call it. */ result = PyObject_CallOneArg(meth, format_spec); Py_DECREF(meth); if (result && !PyUnicode_Check(result)) { PyErr_Format(PyExc_TypeError, "%T.__format__() must return a str, not %T", obj, result); Py_SETREF(result, NULL); goto done; } done: Py_XDECREF(empty); return result; } /* Operations on numbers */ int PyNumber_Check(PyObject *o) { if (o == NULL) return 0; PyNumberMethods *nb = Py_TYPE(o)->tp_as_number; return nb && (nb->nb_index || nb->nb_int || nb->nb_float || PyComplex_Check(o)); } /* Binary operators */ #define NB_SLOT(x) offsetof(PyNumberMethods, x) #define NB_BINOP(nb_methods, slot) \ (*(binaryfunc*)(& ((char*)nb_methods)[slot])) #define NB_TERNOP(nb_methods, slot) \ (*(ternaryfunc*)(& ((char*)nb_methods)[slot])) /* Calling scheme used for binary operations: Order operations are tried until either a valid result or error: w.op(v,w)[*], v.op(v,w), w.op(v,w) [*] only when Py_TYPE(v) != Py_TYPE(w) && Py_TYPE(w) is a subclass of Py_TYPE(v) */ static PyObject * binary_op1(PyObject *v, PyObject *w, const int op_slot #ifndef NDEBUG , const char *op_name #endif ) { binaryfunc slotv; if (Py_TYPE(v)->tp_as_number != NULL) { slotv = NB_BINOP(Py_TYPE(v)->tp_as_number, op_slot); } else { slotv = NULL; } binaryfunc slotw; if (!Py_IS_TYPE(w, Py_TYPE(v)) && Py_TYPE(w)->tp_as_number != NULL) { slotw = NB_BINOP(Py_TYPE(w)->tp_as_number, op_slot); if (slotw == slotv) { slotw = NULL; } } else { slotw = NULL; } if (slotv) { PyObject *x; if (slotw && PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v))) { x = slotw(v, w); if (x != Py_NotImplemented) return x; Py_DECREF(x); /* can't do it */ slotw = NULL; } x = slotv(v, w); assert(_Py_CheckSlotResult(v, op_name, x != NULL)); if (x != Py_NotImplemented) { return x; } Py_DECREF(x); /* can't do it */ } if (slotw) { PyObject *x = slotw(v, w); assert(_Py_CheckSlotResult(w, op_name, x != NULL)); if (x != Py_NotImplemented) { return x; } Py_DECREF(x); /* can't do it */ } Py_RETURN_NOTIMPLEMENTED; } #ifdef NDEBUG # define BINARY_OP1(v, w, op_slot, op_name) binary_op1(v, w, op_slot) #else # define BINARY_OP1(v, w, op_slot, op_name) binary_op1(v, w, op_slot, op_name) #endif static PyObject * binop_type_error(PyObject *v, PyObject *w, const char *op_name) { PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for %.100s: " "'%.100s' and '%.100s'", op_name, Py_TYPE(v)->tp_name, Py_TYPE(w)->tp_name); return NULL; } static PyObject * binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name) { PyObject *result = BINARY_OP1(v, w, op_slot, op_name); if (result == Py_NotImplemented) { Py_DECREF(result); return binop_type_error(v, w, op_name); } return result; } /* Calling scheme used for ternary operations: Order operations are tried until either a valid result or error: v.op(v,w,z), w.op(v,w,z), z.op(v,w,z) */ static PyObject * ternary_op(PyObject *v, PyObject *w, PyObject *z, const int op_slot, const char *op_name ) { PyNumberMethods *mv = Py_TYPE(v)->tp_as_number; PyNumberMethods *mw = Py_TYPE(w)->tp_as_number; ternaryfunc slotv; if (mv != NULL) { slotv = NB_TERNOP(mv, op_slot); } else { slotv = NULL; } ternaryfunc slotw; if (!Py_IS_TYPE(w, Py_TYPE(v)) && mw != NULL) { slotw = NB_TERNOP(mw, op_slot); if (slotw == slotv) { slotw = NULL; } } else { slotw = NULL; } if (slotv) { PyObject *x; if (slotw && PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v))) { x = slotw(v, w, z); if (x != Py_NotImplemented) { return x; } Py_DECREF(x); /* can't do it */ slotw = NULL; } x = slotv(v, w, z); assert(_Py_CheckSlotResult(v, op_name, x != NULL)); if (x != Py_NotImplemented) { return x; } Py_DECREF(x); /* can't do it */ } if (slotw) { PyObject *x = slotw(v, w, z); assert(_Py_CheckSlotResult(w, op_name, x != NULL)); if (x != Py_NotImplemented) { return x; } Py_DECREF(x); /* can't do it */ } PyNumberMethods *mz = Py_TYPE(z)->tp_as_number; if (mz != NULL) { ternaryfunc slotz = NB_TERNOP(mz, op_slot); if (slotz == slotv || slotz == slotw) { slotz = NULL; } if (slotz) { PyObject *x = slotz(v, w, z); assert(_Py_CheckSlotResult(z, op_name, x != NULL)); if (x != Py_NotImplemented) { return x; } Py_DECREF(x); /* can't do it */ } } if (z == Py_None) { PyErr_Format( PyExc_TypeError, "unsupported operand type(s) for %.100s: " "'%.100s' and '%.100s'", op_name, Py_TYPE(v)->tp_name, Py_TYPE(w)->tp_name); } else { PyErr_Format( PyExc_TypeError, "unsupported operand type(s) for %.100s: " "'%.100s', '%.100s', '%.100s'", op_name, Py_TYPE(v)->tp_name, Py_TYPE(w)->tp_name, Py_TYPE(z)->tp_name); } return NULL; } #define BINARY_FUNC(func, op, op_name) \ PyObject * \ func(PyObject *v, PyObject *w) { \ return binary_op(v, w, NB_SLOT(op), op_name); \ } BINARY_FUNC(PyNumber_Or, nb_or, "|") BINARY_FUNC(PyNumber_Xor, nb_xor, "^") BINARY_FUNC(PyNumber_And, nb_and, "&") BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<") BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>") BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-") BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()") PyObject * PyNumber_Add(PyObject *v, PyObject *w) { PyObject *result = BINARY_OP1(v, w, NB_SLOT(nb_add), "+"); if (result != Py_NotImplemented) { return result; } Py_DECREF(result); PySequenceMethods *m = Py_TYPE(v)->tp_as_sequence; if (m && m->sq_concat) { result = (*m->sq_concat)(v, w); assert(_Py_CheckSlotResult(v, "+", result != NULL)); return result; } return binop_type_error(v, w, "+"); } static PyObject * sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n) { Py_ssize_t count; if (_PyIndex_Check(n)) { count = PyNumber_AsSsize_t(n, PyExc_OverflowError); if (count == -1 && PyErr_Occurred()) { return NULL; } } else { return type_error("can't multiply sequence by " "non-int of type '%.200s'", n); } PyObject *res = (*repeatfunc)(seq, count); assert(_Py_CheckSlotResult(seq, "*", res != NULL)); return res; } PyObject * PyNumber_Multiply(PyObject *v, PyObject *w) { PyObject *result = BINARY_OP1(v, w, NB_SLOT(nb_multiply), "*"); if (result == Py_NotImplemented) { PySequenceMethods *mv = Py_TYPE(v)->tp_as_sequence; PySequenceMethods *mw = Py_TYPE(w)->tp_as_sequence; Py_DECREF(result); if (mv && mv->sq_repeat) { return sequence_repeat(mv->sq_repeat, v, w); } else if (mw && mw->sq_repeat) { return sequence_repeat(mw->sq_repeat, w, v); } result = binop_type_error(v, w, "*"); } return result; } BINARY_FUNC(PyNumber_MatrixMultiply, nb_matrix_multiply, "@") BINARY_FUNC(PyNumber_FloorDivide, nb_floor_divide, "//") BINARY_FUNC(PyNumber_TrueDivide, nb_true_divide, "/") BINARY_FUNC(PyNumber_Remainder, nb_remainder, "%") PyObject * PyNumber_Power(PyObject *v, PyObject *w, PyObject *z) { return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()"); } PyObject * _PyNumber_PowerNoMod(PyObject *lhs, PyObject *rhs) { return PyNumber_Power(lhs, rhs, Py_None); } /* Binary in-place operators */ /* The in-place operators are defined to fall back to the 'normal', non in-place operations, if the in-place methods are not in place. - If the left hand object has the appropriate struct members, and they are filled, call the appropriate function and return the result. No coercion is done on the arguments; the left-hand object is the one the operation is performed on, and it's up to the function to deal with the right-hand object. - Otherwise, in-place modification is not supported. Handle it exactly as a non in-place operation of the same kind. */ static PyObject * binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot #ifndef NDEBUG , const char *op_name #endif ) { PyNumberMethods *mv = Py_TYPE(v)->tp_as_number; if (mv != NULL) { binaryfunc slot = NB_BINOP(mv, iop_slot); if (slot) { PyObject *x = (slot)(v, w); assert(_Py_CheckSlotResult(v, op_name, x != NULL)); if (x != Py_NotImplemented) { return x; } Py_DECREF(x); } } #ifdef NDEBUG return binary_op1(v, w, op_slot); #else return binary_op1(v, w, op_slot, op_name); #endif } #ifdef NDEBUG # define BINARY_IOP1(v, w, iop_slot, op_slot, op_name) binary_iop1(v, w, iop_slot, op_slot) #else # define BINARY_IOP1(v, w, iop_slot, op_slot, op_name) binary_iop1(v, w, iop_slot, op_slot, op_name) #endif static PyObject * binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot, const char *op_name) { PyObject *result = BINARY_IOP1(v, w, iop_slot, op_slot, op_name); if (result == Py_NotImplemented) { Py_DECREF(result); return binop_type_error(v, w, op_name); } return result; } static PyObject * ternary_iop(PyObject *v, PyObject *w, PyObject *z, const int iop_slot, const int op_slot, const char *op_name) { PyNumberMethods *mv = Py_TYPE(v)->tp_as_number; if (mv != NULL) { ternaryfunc slot = NB_TERNOP(mv, iop_slot); if (slot) { PyObject *x = (slot)(v, w, z); if (x != Py_NotImplemented) { return x; } Py_DECREF(x); } } return ternary_op(v, w, z, op_slot, op_name); } #define INPLACE_BINOP(func, iop, op, op_name) \ PyObject * \ func(PyObject *v, PyObject *w) { \ return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \ } INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=") INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=") INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=") INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=") INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=") INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=") INPLACE_BINOP(PyNumber_InPlaceMatrixMultiply, nb_inplace_matrix_multiply, nb_matrix_multiply, "@=") INPLACE_BINOP(PyNumber_InPlaceFloorDivide, nb_inplace_floor_divide, nb_floor_divide, "//=") INPLACE_BINOP(PyNumber_InPlaceTrueDivide, nb_inplace_true_divide, nb_true_divide, "/=") INPLACE_BINOP(PyNumber_InPlaceRemainder, nb_inplace_remainder, nb_remainder, "%=") PyObject * PyNumber_InPlaceAdd(PyObject *v, PyObject *w) { PyObject *result = BINARY_IOP1(v, w, NB_SLOT(nb_inplace_add), NB_SLOT(nb_add), "+="); if (result == Py_NotImplemented) { PySequenceMethods *m = Py_TYPE(v)->tp_as_sequence; Py_DECREF(result); if (m != NULL) { binaryfunc func = m->sq_inplace_concat; if (func == NULL) func = m->sq_concat; if (func != NULL) { result = func(v, w); assert(_Py_CheckSlotResult(v, "+=", result != NULL)); return result; } } result = binop_type_error(v, w, "+="); } return result; } PyObject * PyNumber_InPlaceMultiply(PyObject *v, PyObject *w) { PyObject *result = BINARY_IOP1(v, w, NB_SLOT(nb_inplace_multiply), NB_SLOT(nb_multiply), "*="); if (result == Py_NotImplemented) { ssizeargfunc f = NULL; PySequenceMethods *mv = Py_TYPE(v)->tp_as_sequence; PySequenceMethods *mw = Py_TYPE(w)->tp_as_sequence; Py_DECREF(result); if (mv != NULL) { f = mv->sq_inplace_repeat; if (f == NULL) f = mv->sq_repeat; if (f != NULL) return sequence_repeat(f, v, w); } else if (mw != NULL) { /* Note that the right hand operand should not be * mutated in this case so sq_inplace_repeat is not * used. */ if (mw->sq_repeat) return sequence_repeat(mw->sq_repeat, w, v); } result = binop_type_error(v, w, "*="); } return result; } PyObject * PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z) { return ternary_iop(v, w, z, NB_SLOT(nb_inplace_power), NB_SLOT(nb_power), "**="); } PyObject * _PyNumber_InPlacePowerNoMod(PyObject *lhs, PyObject *rhs) { return PyNumber_InPlacePower(lhs, rhs, Py_None); } /* Unary operators and functions */ #define UNARY_FUNC(func, op, meth_name, descr) \ PyObject * \ func(PyObject *o) { \ if (o == NULL) { \ return null_error(); \ } \ \ PyNumberMethods *m = Py_TYPE(o)->tp_as_number; \ if (m && m->op) { \ PyObject *res = (*m->op)(o); \ assert(_Py_CheckSlotResult(o, #meth_name, res != NULL)); \ return res; \ } \ \ return type_error("bad operand type for "descr": '%.200s'", o); \ } UNARY_FUNC(PyNumber_Negative, nb_negative, __neg__, "unary -") UNARY_FUNC(PyNumber_Positive, nb_positive, __pos__, "unary +") UNARY_FUNC(PyNumber_Invert, nb_invert, __invert__, "unary ~") UNARY_FUNC(PyNumber_Absolute, nb_absolute, __abs__, "abs()") int PyIndex_Check(PyObject *obj) { return _PyIndex_Check(obj); } /* Return a Python int from the object item. Can return an instance of int subclass. Raise TypeError if the result is not an int or if the object cannot be interpreted as an index. */ PyObject * _PyNumber_Index(PyObject *item) { if (item == NULL) { return null_error(); } if (PyLong_Check(item)) { return Py_NewRef(item); } if (!_PyIndex_Check(item)) { PyErr_Format(PyExc_TypeError, "'%.200s' object cannot be interpreted " "as an integer", Py_TYPE(item)->tp_name); return NULL; } PyObject *result = Py_TYPE(item)->tp_as_number->nb_index(item); assert(_Py_CheckSlotResult(item, "__index__", result != NULL)); if (!result || PyLong_CheckExact(result)) { return result; } if (!PyLong_Check(result)) { PyErr_Format(PyExc_TypeError, "%T.__index__() must return an int, not %T", item, result); Py_DECREF(result); return NULL; } /* Issue #17576: warn if 'result' not of exact type int. */ if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, "%T.__index__() must return an int, not %T. " "The ability to return an instance of a strict subclass of int " "is deprecated, and may be removed in a future version of Python.", item, result)) { Py_DECREF(result); return NULL; } return result; } /* Return an exact Python int from the object item. Raise TypeError if the result is not an int or if the object cannot be interpreted as an index. */ PyObject * PyNumber_Index(PyObject *item) { PyObject *result = _PyNumber_Index(item); if (result != NULL && !PyLong_CheckExact(result)) { Py_SETREF(result, _PyLong_Copy((PyLongObject *)result)); } return result; } /* Return an error on Overflow only if err is not NULL*/ Py_ssize_t PyNumber_AsSsize_t(PyObject *item, PyObject *err) { Py_ssize_t result; PyObject *runerr; PyObject *value = _PyNumber_Index(item); if (value == NULL) return -1; /* We're done if PyLong_AsSsize_t() returns without error. */ result = PyLong_AsSsize_t(value); if (result != -1) goto finish; PyThreadState *tstate = _PyThreadState_GET(); runerr = _PyErr_Occurred(tstate); if (!runerr) { goto finish; } /* Error handling code -- only manage OverflowError differently */ if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) { goto finish; } _PyErr_Clear(tstate); /* If no error-handling desired then the default clipping is sufficient. */ if (!err) { assert(PyLong_Check(value)); /* Whether or not it is less than or equal to zero is determined by the sign of ob_size */ if (_PyLong_IsNegative((PyLongObject *)value)) result = PY_SSIZE_T_MIN; else result = PY_SSIZE_T_MAX; } else { /* Otherwise replace the error with caller's error object. */ _PyErr_Format(tstate, err, "cannot fit '%.200s' into an index-sized integer", Py_TYPE(item)->tp_name); } finish: Py_DECREF(value); return result; } PyObject * PyNumber_Long(PyObject *o) { PyObject *result; PyNumberMethods *m; Py_buffer view; if (o == NULL) { return null_error(); } if (PyLong_CheckExact(o)) { return Py_NewRef(o); } m = Py_TYPE(o)->tp_as_number; if (m && m->nb_int) { /* This should include subclasses of int */ /* Convert using the nb_int slot, which should return something of exact type int. */ result = m->nb_int(o); assert(_Py_CheckSlotResult(o, "__int__", result != NULL)); if (!result || PyLong_CheckExact(result)) { return result; } if (!PyLong_Check(result)) { PyErr_Format(PyExc_TypeError, "%T.__int__() must return an int, not %T", o, result); Py_DECREF(result); return NULL; } /* Issue #17576: warn if 'result' not of exact type int. */ if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, "%T.__int__() must return an int, not %T. " "The ability to return an instance of a strict subclass of int " "is deprecated, and may be removed in a future version of Python.", o, result)) { Py_DECREF(result); return NULL; } Py_SETREF(result, _PyLong_Copy((PyLongObject *)result)); return result; } if (m && m->nb_index) { return PyNumber_Index(o); } if (PyUnicode_Check(o)) /* The below check is done in PyLong_FromUnicodeObject(). */ return PyLong_FromUnicodeObject(o, 10); if (PyBytes_Check(o)) /* need to do extra error checking that PyLong_FromString() * doesn't do. In particular int('9\x005') must raise an * exception, not truncate at the null. */ return _PyLong_FromBytes(PyBytes_AS_STRING(o), PyBytes_GET_SIZE(o), 10); if (PyByteArray_Check(o)) return _PyLong_FromBytes(PyByteArray_AS_STRING(o), PyByteArray_GET_SIZE(o), 10); if (PyObject_GetBuffer(o, &view, PyBUF_SIMPLE) == 0) { PyObject *bytes; /* Copy to NUL-terminated buffer. */ bytes = PyBytes_FromStringAndSize((const char *)view.buf, view.len); if (bytes == NULL) { PyBuffer_Release(&view); return NULL; } result = _PyLong_FromBytes(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes), 10); Py_DECREF(bytes); PyBuffer_Release(&view); return result; } return type_error("int() argument must be a string, a bytes-like object " "or a real number, not '%.200s'", o); } PyObject * PyNumber_Float(PyObject *o) { if (o == NULL) { return null_error(); } if (PyFloat_CheckExact(o)) { return Py_NewRef(o); } PyNumberMethods *m = Py_TYPE(o)->tp_as_number; if (m && m->nb_float) { /* This should include subclasses of float */ PyObject *res = m->nb_float(o); assert(_Py_CheckSlotResult(o, "__float__", res != NULL)); if (!res || PyFloat_CheckExact(res)) { return res; } if (!PyFloat_Check(res)) { PyErr_Format(PyExc_TypeError, "%T.__float__() must return a float, not %T", o, res); Py_DECREF(res); return NULL; } /* Issue #26983: warn if 'res' not of exact type float. */ if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, "%T.__float__() must return a float, not %T. " "The ability to return an instance of a strict subclass of float " "is deprecated, and may be removed in a future version of Python.", o, res)) { Py_DECREF(res); return NULL; } double val = PyFloat_AS_DOUBLE(res); Py_DECREF(res); return PyFloat_FromDouble(val); } if (m && m->nb_index) { PyObject *res = _PyNumber_Index(o); if (!res) { return NULL; } double val = PyLong_AsDouble(res); Py_DECREF(res); if (val == -1.0 && PyErr_Occurred()) { return NULL; } return PyFloat_FromDouble(val); } /* A float subclass with nb_float == NULL */ if (PyFloat_Check(o)) { return PyFloat_FromDouble(PyFloat_AS_DOUBLE(o)); } return PyFloat_FromString(o); } PyObject * PyNumber_ToBase(PyObject *n, int base) { if (!(base == 2 || base == 8 || base == 10 || base == 16)) { PyErr_SetString(PyExc_SystemError, "PyNumber_ToBase: base must be 2, 8, 10 or 16"); return NULL; } PyObject *index = _PyNumber_Index(n); if (!index) return NULL; PyObject *res = _PyLong_Format(index, base); Py_DECREF(index); return res; } /* Operations on sequences */ int PySequence_Check(PyObject *s) { if (PyDict_Check(s)) return 0; return Py_TYPE(s)->tp_as_sequence && Py_TYPE(s)->tp_as_sequence->sq_item != NULL; } Py_ssize_t PySequence_Size(PyObject *s) { if (s == NULL) { null_error(); return -1; } PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence; if (m && m->sq_length) { Py_ssize_t len = m->sq_length(s); assert(_Py_CheckSlotResult(s, "__len__", len >= 0)); return len; } if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_length) { type_error("%.200s is not a sequence", s); return -1; } type_error("object of type '%.200s' has no len()", s); return -1; } #undef PySequence_Length Py_ssize_t PySequence_Length(PyObject *s) { return PySequence_Size(s); } #define PySequence_Length PySequence_Size PyObject * PySequence_Concat(PyObject *s, PyObject *o) { if (s == NULL || o == NULL) { return null_error(); } PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence; if (m && m->sq_concat) { PyObject *res = m->sq_concat(s, o); assert(_Py_CheckSlotResult(s, "+", res != NULL)); return res; } /* Instances of user classes defining an __add__() method only have an nb_add slot, not an sq_concat slot. So we fall back to nb_add if both arguments appear to be sequences. */ if (PySequence_Check(s) && PySequence_Check(o)) { PyObject *result = BINARY_OP1(s, o, NB_SLOT(nb_add), "+"); if (result != Py_NotImplemented) return result; Py_DECREF(result); } return type_error("'%.200s' object can't be concatenated", s); } PyObject * PySequence_Repeat(PyObject *o, Py_ssize_t count) { if (o == NULL) { return null_error(); } PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; if (m && m->sq_repeat) { PyObject *res = m->sq_repeat(o, count); assert(_Py_CheckSlotResult(o, "*", res != NULL)); return res; } /* Instances of user classes defining a __mul__() method only have an nb_multiply slot, not an sq_repeat slot. so we fall back to nb_multiply if o appears to be a sequence. */ if (PySequence_Check(o)) { PyObject *n, *result; n = PyLong_FromSsize_t(count); if (n == NULL) return NULL; result = BINARY_OP1(o, n, NB_SLOT(nb_multiply), "*"); Py_DECREF(n); if (result != Py_NotImplemented) return result; Py_DECREF(result); } return type_error("'%.200s' object can't be repeated", o); } PyObject * PySequence_InPlaceConcat(PyObject *s, PyObject *o) { if (s == NULL || o == NULL) { return null_error(); } PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence; if (m && m->sq_inplace_concat) { PyObject *res = m->sq_inplace_concat(s, o); assert(_Py_CheckSlotResult(s, "+=", res != NULL)); return res; } if (m && m->sq_concat) { PyObject *res = m->sq_concat(s, o); assert(_Py_CheckSlotResult(s, "+", res != NULL)); return res; } if (PySequence_Check(s) && PySequence_Check(o)) { PyObject *result = BINARY_IOP1(s, o, NB_SLOT(nb_inplace_add), NB_SLOT(nb_add), "+="); if (result != Py_NotImplemented) return result; Py_DECREF(result); } return type_error("'%.200s' object can't be concatenated", s); } PyObject * PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count) { if (o == NULL) { return null_error(); } PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; if (m && m->sq_inplace_repeat) { PyObject *res = m->sq_inplace_repeat(o, count); assert(_Py_CheckSlotResult(o, "*=", res != NULL)); return res; } if (m && m->sq_repeat) { PyObject *res = m->sq_repeat(o, count); assert(_Py_CheckSlotResult(o, "*", res != NULL)); return res; } if (PySequence_Check(o)) { PyObject *n, *result; n = PyLong_FromSsize_t(count); if (n == NULL) return NULL; result = BINARY_IOP1(o, n, NB_SLOT(nb_inplace_multiply), NB_SLOT(nb_multiply), "*="); Py_DECREF(n); if (result != Py_NotImplemented) return result; Py_DECREF(result); } return type_error("'%.200s' object can't be repeated", o); } PyObject * PySequence_GetItem(PyObject *s, Py_ssize_t i) { if (s == NULL) { return null_error(); } PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence; if (m && m->sq_item) { if (i < 0) { if (m->sq_length) { Py_ssize_t l = (*m->sq_length)(s); assert(_Py_CheckSlotResult(s, "__len__", l >= 0)); if (l < 0) { return NULL; } i += l; } } PyObject *res = m->sq_item(s, i); assert(_Py_CheckSlotResult(s, "__getitem__", res != NULL)); return res; } if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_subscript) { return type_error("%.200s is not a sequence", s); } return type_error("'%.200s' object does not support indexing", s); } PyObject * PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2) { if (!s) { return null_error(); } PyMappingMethods *mp = Py_TYPE(s)->tp_as_mapping; if (mp && mp->mp_subscript) { PyObject *slice = _PySlice_FromIndices(i1, i2); if (!slice) { return NULL; } PyObject *res = mp->mp_subscript(s, slice); assert(_Py_CheckSlotResult(s, "__getitem__", res != NULL)); Py_DECREF(slice); return res; } return type_error("'%.200s' object is unsliceable", s); } int PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o) { if (s == NULL) { null_error(); return -1; } PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence; if (m && m->sq_ass_item) { if (i < 0) { if (m->sq_length) { Py_ssize_t l = (*m->sq_length)(s); assert(_Py_CheckSlotResult(s, "__len__", l >= 0)); if (l < 0) { return -1; } i += l; } } int res = m->sq_ass_item(s, i, o); assert(_Py_CheckSlotResult(s, "__setitem__", res >= 0)); return res; } if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) { type_error("%.200s is not a sequence", s); return -1; } type_error("'%.200s' object does not support item assignment", s); return -1; } int PySequence_DelItem(PyObject *s, Py_ssize_t i) { if (s == NULL) { null_error(); return -1; } PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence; if (m && m->sq_ass_item) { if (i < 0) { if (m->sq_length) { Py_ssize_t l = (*m->sq_length)(s); assert(_Py_CheckSlotResult(s, "__len__", l >= 0)); if (l < 0) { return -1; } i += l; } } int res = m->sq_ass_item(s, i, (PyObject *)NULL); assert(_Py_CheckSlotResult(s, "__delitem__", res >= 0)); return res; } if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) { type_error("%.200s is not a sequence", s); return -1; } type_error("'%.200s' object doesn't support item deletion", s); return -1; } int PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o) { if (s == NULL) { null_error(); return -1; } PyMappingMethods *mp = Py_TYPE(s)->tp_as_mapping; if (mp && mp->mp_ass_subscript) { PyObject *slice = _PySlice_FromIndices(i1, i2); if (!slice) return -1; int res = mp->mp_ass_subscript(s, slice, o); assert(_Py_CheckSlotResult(s, "__setitem__", res >= 0)); Py_DECREF(slice); return res; } type_error("'%.200s' object doesn't support slice assignment", s); return -1; } int PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2) { if (s == NULL) { null_error(); return -1; } PyMappingMethods *mp = Py_TYPE(s)->tp_as_mapping; if (mp && mp->mp_ass_subscript) { PyObject *slice = _PySlice_FromIndices(i1, i2); if (!slice) { return -1; } int res = mp->mp_ass_subscript(s, slice, NULL); assert(_Py_CheckSlotResult(s, "__delitem__", res >= 0)); Py_DECREF(slice); return res; } type_error("'%.200s' object doesn't support slice deletion", s); return -1; } PyObject * PySequence_Tuple(PyObject *v) { PyObject *it; /* iter(v) */ if (v == NULL) { return null_error(); } /* Special-case the common tuple and list cases, for efficiency. */ if (PyTuple_CheckExact(v)) { /* Note that we can't know whether it's safe to return a tuple *subclass* instance as-is, hence the restriction to exact tuples here. In contrast, lists always make a copy, so there's no need for exactness below. */ return Py_NewRef(v); } if (PyList_CheckExact(v)) return PyList_AsTuple(v); /* Get iterator. */ it = PyObject_GetIter(v); if (it == NULL) return NULL; Py_ssize_t n; PyObject *buffer[8]; for (n = 0; n < 8; n++) { PyObject *item = PyIter_Next(it); if (item == NULL) { if (PyErr_Occurred()) { goto fail; } Py_DECREF(it); return _PyTuple_FromArraySteal(buffer, n); } buffer[n] = item; } PyListObject *list = (PyListObject *)PyList_New(16); if (list == NULL) { goto fail; } assert(n == 8); Py_SET_SIZE(list, n); for (Py_ssize_t j = 0; j < n; j++) { PyList_SET_ITEM(list, j, buffer[j]); } for (;;) { PyObject *item = PyIter_Next(it); if (item == NULL) { if (PyErr_Occurred()) { Py_DECREF(list); Py_DECREF(it); return NULL; } break; } if (_PyList_AppendTakeRef(list, item) < 0) { Py_DECREF(list); Py_DECREF(it); return NULL; } } Py_DECREF(it); PyObject *res = _PyList_AsTupleAndClear(list); Py_DECREF(list); return res; fail: Py_DECREF(it); while (n > 0) { n--; Py_DECREF(buffer[n]); } return NULL; } PyObject * PySequence_List(PyObject *v) { PyObject *result; /* result list */ PyObject *rv; /* return value from PyList_Extend */ if (v == NULL) { return null_error(); } result = PyList_New(0); if (result == NULL) return NULL; rv = _PyList_Extend((PyListObject *)result, v); if (rv == NULL) { Py_DECREF(result); return NULL; } Py_DECREF(rv); return result; } PyObject * PySequence_Fast(PyObject *v, const char *m) { PyObject *it; if (v == NULL) { return null_error(); } if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) { return Py_NewRef(v); } it = PyObject_GetIter(v); if (it == NULL) { PyThreadState *tstate = _PyThreadState_GET(); if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) { _PyErr_SetString(tstate, PyExc_TypeError, m); } return NULL; } v = PySequence_List(it); Py_DECREF(it); return v; } /* Iterate over seq. Result depends on the operation: PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq. PY_ITERSEARCH_INDEX: 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. */ Py_ssize_t _PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation) { Py_ssize_t n; int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */ PyObject *it; /* iter(seq) */ if (seq == NULL || obj == NULL) { null_error(); return -1; } it = PyObject_GetIter(seq); if (it == NULL) { if (PyErr_ExceptionMatches(PyExc_TypeError)) { if (operation == PY_ITERSEARCH_CONTAINS) { type_error( "argument of type '%.200s' is not a container or iterable", seq ); } else { type_error("argument of type '%.200s' is not iterable", seq); } } return -1; } n = wrapped = 0; for (;;) { int cmp; PyObject *item = PyIter_Next(it); if (item == NULL) { if (PyErr_Occurred()) goto Fail; break; } cmp = PyObject_RichCompareBool(item, obj, Py_EQ); Py_DECREF(item); if (cmp < 0) goto Fail; if (cmp > 0) { switch (operation) { case PY_ITERSEARCH_COUNT: if (n == PY_SSIZE_T_MAX) { PyErr_SetString(PyExc_OverflowError, "count exceeds C integer size"); goto Fail; } ++n; break; case PY_ITERSEARCH_INDEX: if (wrapped) { PyErr_SetString(PyExc_OverflowError, "index exceeds C integer size"); goto Fail; } goto Done; case PY_ITERSEARCH_CONTAINS: n = 1; goto Done; default: Py_UNREACHABLE(); } } if (operation == PY_ITERSEARCH_INDEX) { if (n == PY_SSIZE_T_MAX) wrapped = 1; ++n; } } if (operation != PY_ITERSEARCH_INDEX) goto Done; PyErr_SetString(PyExc_ValueError, "sequence.index(x): x not in sequence"); /* fall into failure code */ Fail: n = -1; /* fall through */ Done: Py_DECREF(it); return n; } /* Return # of times o appears in s. */ Py_ssize_t PySequence_Count(PyObject *s, PyObject *o) { return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT); } /* Return -1 if error; 1 if ob in seq; 0 if ob not in seq. * Use sq_contains if possible, else defer to _PySequence_IterSearch(). */ int PySequence_Contains(PyObject *seq, PyObject *ob) { PySequenceMethods *sqm = Py_TYPE(seq)->tp_as_sequence; if (sqm != NULL && sqm->sq_contains != NULL) { int res = (*sqm->sq_contains)(seq, ob); assert(_Py_CheckSlotResult(seq, "__contains__", res >= 0)); return res; } Py_ssize_t result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS); return Py_SAFE_DOWNCAST(result, Py_ssize_t, int); } /* Backwards compatibility */ #undef PySequence_In int PySequence_In(PyObject *w, PyObject *v) { return PySequence_Contains(w, v); } Py_ssize_t PySequence_Index(PyObject *s, PyObject *o) { return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX); } /* Operations on mappings */ int PyMapping_Check(PyObject *o) { return o && Py_TYPE(o)->tp_as_mapping && Py_TYPE(o)->tp_as_mapping->mp_subscript; } Py_ssize_t PyMapping_Size(PyObject *o) { if (o == NULL) { null_error(); return -1; } PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping; if (m && m->mp_length) { Py_ssize_t len = m->mp_length(o); assert(_Py_CheckSlotResult(o, "__len__", len >= 0)); return len; } if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) { type_error("%.200s is not a mapping", o); return -1; } /* PyMapping_Size() can be called from PyObject_Size(). */ type_error("object of type '%.200s' has no len()", o); return -1; } #undef PyMapping_Length Py_ssize_t PyMapping_Length(PyObject *o) { return PyMapping_Size(o); } #define PyMapping_Length PyMapping_Size PyObject * PyMapping_GetItemString(PyObject *o, const char *key) { PyObject *okey, *r; if (key == NULL) { return null_error(); } okey = PyUnicode_FromString(key); if (okey == NULL) return NULL; r = PyObject_GetItem(o, okey); Py_DECREF(okey); return r; } int PyMapping_GetOptionalItemString(PyObject *obj, const char *key, PyObject **result) { if (key == NULL) { *result = NULL; null_error(); return -1; } PyObject *okey = PyUnicode_FromString(key); if (okey == NULL) { *result = NULL; return -1; } int rc = PyMapping_GetOptionalItem(obj, okey, result); Py_DECREF(okey); return rc; } int PyMapping_SetItemString(PyObject *o, const char *key, PyObject *value) { PyObject *okey; int r; if (key == NULL) { null_error(); return -1; } okey = PyUnicode_FromString(key); if (okey == NULL) return -1; r = PyObject_SetItem(o, okey, value); Py_DECREF(okey); return r; } int PyMapping_HasKeyStringWithError(PyObject *obj, const char *key) { PyObject *res; int rc = PyMapping_GetOptionalItemString(obj, key, &res); Py_XDECREF(res); return rc; } int PyMapping_HasKeyWithError(PyObject *obj, PyObject *key) { PyObject *res; int rc = PyMapping_GetOptionalItem(obj, key, &res); Py_XDECREF(res); return rc; } int PyMapping_HasKeyString(PyObject *obj, const char *key) { PyObject *value; int rc; if (obj == NULL) { // For backward compatibility. // PyMapping_GetOptionalItemString() crashes if obj is NULL. null_error(); rc = -1; } else { rc = PyMapping_GetOptionalItemString(obj, key, &value); } if (rc < 0) { PyErr_FormatUnraisable( "Exception ignored in PyMapping_HasKeyString(); consider using " "PyMapping_HasKeyStringWithError(), " "PyMapping_GetOptionalItemString() or PyMapping_GetItemString()"); return 0; } Py_XDECREF(value); return rc; } int PyMapping_HasKey(PyObject *obj, PyObject *key) { PyObject *value; int rc; if (obj == NULL || key == NULL) { // For backward compatibility. // PyMapping_GetOptionalItem() crashes if any of them is NULL. null_error(); rc = -1; } else { rc = PyMapping_GetOptionalItem(obj, key, &value); } if (rc < 0) { PyErr_FormatUnraisable( "Exception ignored in PyMapping_HasKey(); consider using " "PyMapping_HasKeyWithError(), " "PyMapping_GetOptionalItem() or PyObject_GetItem()"); return 0; } Py_XDECREF(value); return rc; } /* This function is quite similar to PySequence_Fast(), but specialized to be a helper for PyMapping_Keys(), PyMapping_Items() and PyMapping_Values(). */ static PyObject * method_output_as_list(PyObject *o, PyObject *meth) { PyObject *it, *result, *meth_output; assert(o != NULL); meth_output = PyObject_CallMethodNoArgs(o, meth); if (meth_output == NULL || PyList_CheckExact(meth_output)) { return meth_output; } it = PyObject_GetIter(meth_output); if (it == NULL) { PyThreadState *tstate = _PyThreadState_GET(); if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) { _PyErr_Format(tstate, PyExc_TypeError, "%T.%U() must return an iterable, not %T", o, meth, meth_output); } Py_DECREF(meth_output); return NULL; } Py_DECREF(meth_output); result = PySequence_List(it); Py_DECREF(it); return result; } PyObject * PyMapping_Keys(PyObject *o) { if (o == NULL) { return null_error(); } if (PyDict_CheckExact(o)) { return PyDict_Keys(o); } return method_output_as_list(o, &_Py_ID(keys)); } PyObject * PyMapping_Items(PyObject *o) { if (o == NULL) { return null_error(); } if (PyDict_CheckExact(o)) { return PyDict_Items(o); } return method_output_as_list(o, &_Py_ID(items)); } PyObject * PyMapping_Values(PyObject *o) { if (o == NULL) { return null_error(); } if (PyDict_CheckExact(o)) { return PyDict_Values(o); } return method_output_as_list(o, &_Py_ID(values)); } /* isinstance(), issubclass() */ /* abstract_get_bases() has logically 4 return states: * * 1. getattr(cls, '__bases__') could raise an AttributeError * 2. getattr(cls, '__bases__') could raise some other exception * 3. getattr(cls, '__bases__') could return a tuple * 4. getattr(cls, '__bases__') could return something other than a tuple * * Only state #3 is a non-error state and only it returns a non-NULL object * (it returns the retrieved tuple). * * Any raised AttributeErrors are masked by clearing the exception and * returning NULL. If an object other than a tuple comes out of __bases__, * then again, the return value is NULL. So yes, these two situations * produce exactly the same results: NULL is returned and no error is set. * * If some exception other than AttributeError is raised, then NULL is also * returned, but the exception is not cleared. That's because we want the * exception to be propagated along. * * Callers are expected to test for PyErr_Occurred() when the return value * is NULL to decide whether a valid exception should be propagated or not. * When there's no exception to propagate, it's customary for the caller to * set a TypeError. */ static PyObject * abstract_get_bases(PyObject *cls) { PyObject *bases; (void)PyObject_GetOptionalAttr(cls, &_Py_ID(__bases__), &bases); if (bases != NULL && !PyTuple_Check(bases)) { Py_DECREF(bases); return NULL; } return bases; } static int abstract_issubclass(PyObject *derived, PyObject *cls) { PyObject *bases = NULL; Py_ssize_t i, n; int r = 0; while (1) { if (derived == cls) { Py_XDECREF(bases); /* See below comment */ return 1; } /* Use XSETREF to drop bases reference *after* finishing with derived; bases might be the only reference to it. XSETREF is used instead of SETREF, because bases is NULL on the first iteration of the loop. */ Py_XSETREF(bases, abstract_get_bases(derived)); if (bases == NULL) { if (PyErr_Occurred()) return -1; return 0; } n = PyTuple_GET_SIZE(bases); if (n == 0) { Py_DECREF(bases); return 0; } /* Avoid recursivity in the single inheritance case */ if (n == 1) { derived = PyTuple_GET_ITEM(bases, 0); continue; } break; } assert(n >= 2); if (_Py_EnterRecursiveCall(" in __issubclass__")) { Py_DECREF(bases); return -1; } for (i = 0; i < n; i++) { r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls); if (r != 0) { break; } } _Py_LeaveRecursiveCall(); Py_DECREF(bases); return r; } static int check_class(PyObject *cls, const char *error) { PyObject *bases = abstract_get_bases(cls); if (bases == NULL) { /* Do not mask errors. */ PyThreadState *tstate = _PyThreadState_GET(); if (!_PyErr_Occurred(tstate)) { _PyErr_SetString(tstate, PyExc_TypeError, error); } return 0; } Py_DECREF(bases); return -1; } static int object_isinstance(PyObject *inst, PyObject *cls) { PyObject *icls; int retval; if (PyType_Check(cls)) { retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls); if (retval == 0) { retval = PyObject_GetOptionalAttr(inst, &_Py_ID(__class__), &icls); if (icls != NULL) { if (icls != (PyObject *)(Py_TYPE(inst)) && PyType_Check(icls)) { retval = PyType_IsSubtype( (PyTypeObject *)icls, (PyTypeObject *)cls); } else { retval = 0; } Py_DECREF(icls); } } } else { if (!check_class(cls, "isinstance() arg 2 must be a type, a tuple of types, or a union")) return -1; retval = PyObject_GetOptionalAttr(inst, &_Py_ID(__class__), &icls); if (icls != NULL) { retval = abstract_issubclass(icls, cls); Py_DECREF(icls); } } return retval; } static int object_recursive_isinstance(PyThreadState *tstate, PyObject *inst, PyObject *cls) { /* Quick test for an exact match */ if (Py_IS_TYPE(inst, (PyTypeObject *)cls)) { return 1; } /* We know what type's __instancecheck__ does. */ if (PyType_CheckExact(cls)) { return object_isinstance(inst, cls); } if (_PyUnion_Check(cls)) { cls = _Py_union_args(cls); } if (PyTuple_Check(cls)) { /* Not a general sequence -- that opens up the road to recursion and stack overflow. */ if (_Py_EnterRecursiveCallTstate(tstate, " in __instancecheck__")) { return -1; } Py_ssize_t n = PyTuple_GET_SIZE(cls); int r = 0; for (Py_ssize_t i = 0; i < n; ++i) { PyObject *item = PyTuple_GET_ITEM(cls, i); r = object_recursive_isinstance(tstate, inst, item); if (r != 0) { /* either found it, or got an error */ break; } } _Py_LeaveRecursiveCallTstate(tstate); return r; } PyObject *checker = _PyObject_LookupSpecial(cls, &_Py_ID(__instancecheck__)); if (checker != NULL) { if (_Py_EnterRecursiveCallTstate(tstate, " in __instancecheck__")) { Py_DECREF(checker); return -1; } PyObject *res = PyObject_CallOneArg(checker, inst); _Py_LeaveRecursiveCallTstate(tstate); Py_DECREF(checker); if (res == NULL) { return -1; } int ok = PyObject_IsTrue(res); Py_DECREF(res); return ok; } else if (_PyErr_Occurred(tstate)) { return -1; } /* cls has no __instancecheck__() method */ return object_isinstance(inst, cls); } int PyObject_IsInstance(PyObject *inst, PyObject *cls) { PyThreadState *tstate = _PyThreadState_GET(); return object_recursive_isinstance(tstate, inst, cls); } static int recursive_issubclass(PyObject *derived, PyObject *cls) { if (PyType_Check(cls) && PyType_Check(derived)) { /* Fast path (non-recursive) */ return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls); } if (!check_class(derived, "issubclass() arg 1 must be a class")) return -1; if (!_PyUnion_Check(cls) && !check_class(cls, "issubclass() arg 2 must be a class," " a tuple of classes, or a union")) { return -1; } return abstract_issubclass(derived, cls); } static int object_issubclass(PyThreadState *tstate, PyObject *derived, PyObject *cls) { PyObject *checker; /* We know what type's __subclasscheck__ does. */ if (PyType_CheckExact(cls)) { /* Quick test for an exact match */ if (derived == cls) return 1; return recursive_issubclass(derived, cls); } if (_PyUnion_Check(cls)) { cls = _Py_union_args(cls); } if (PyTuple_Check(cls)) { if (_Py_EnterRecursiveCallTstate(tstate, " in __subclasscheck__")) { return -1; } Py_ssize_t n = PyTuple_GET_SIZE(cls); int r = 0; for (Py_ssize_t i = 0; i < n; ++i) { PyObject *item = PyTuple_GET_ITEM(cls, i); r = object_issubclass(tstate, derived, item); if (r != 0) /* either found it, or got an error */ break; } _Py_LeaveRecursiveCallTstate(tstate); return r; } checker = _PyObject_LookupSpecial(cls, &_Py_ID(__subclasscheck__)); if (checker != NULL) { int ok = -1; if (_Py_EnterRecursiveCallTstate(tstate, " in __subclasscheck__")) { Py_DECREF(checker); return ok; } PyObject *res = PyObject_CallOneArg(checker, derived); _Py_LeaveRecursiveCallTstate(tstate); Py_DECREF(checker); if (res != NULL) { ok = PyObject_IsTrue(res); Py_DECREF(res); } return ok; } else if (_PyErr_Occurred(tstate)) { return -1; } /* Can be reached when infinite recursion happens. */ return recursive_issubclass(derived, cls); } int PyObject_IsSubclass(PyObject *derived, PyObject *cls) { PyThreadState *tstate = _PyThreadState_GET(); return object_issubclass(tstate, derived, cls); } int _PyObject_RealIsInstance(PyObject *inst, PyObject *cls) { return object_isinstance(inst, cls); } int _PyObject_RealIsSubclass(PyObject *derived, PyObject *cls) { return recursive_issubclass(derived, cls); } PyObject * PyObject_GetIter(PyObject *o) { PyTypeObject *t = Py_TYPE(o); getiterfunc f; f = t->tp_iter; if (f == NULL) { if (PySequence_Check(o)) return PySeqIter_New(o); return type_error("'%.200s' object is not iterable", o); } else { PyObject *res = (*f)(o); if (res != NULL && !PyIter_Check(res)) { PyErr_Format(PyExc_TypeError, "%T.__iter__() must return an iterator, not %T", o, res); Py_SETREF(res, NULL); } return res; } } PyObject * PyObject_GetAIter(PyObject *o) { PyTypeObject *t = Py_TYPE(o); unaryfunc f; if (t->tp_as_async == NULL || t->tp_as_async->am_aiter == NULL) { return type_error("'%.200s' object is not an async iterable", o); } f = t->tp_as_async->am_aiter; PyObject *it = (*f)(o); if (it != NULL && !PyAIter_Check(it)) { PyErr_Format(PyExc_TypeError, "%T.__aiter__() must return an async iterator, not %T", o, it); Py_SETREF(it, NULL); } return it; } int PyIter_Check(PyObject *obj) { PyTypeObject *tp = Py_TYPE(obj); return (tp->tp_iternext != NULL && tp->tp_iternext != &_PyObject_NextNotImplemented); } int PyAIter_Check(PyObject *obj) { PyTypeObject *tp = Py_TYPE(obj); return (tp->tp_as_async != NULL && tp->tp_as_async->am_anext != NULL && tp->tp_as_async->am_anext != &_PyObject_NextNotImplemented); } static int iternext(PyObject *iter, PyObject **item) { iternextfunc tp_iternext = Py_TYPE(iter)->tp_iternext; if ((*item = tp_iternext(iter))) { return 1; } PyThreadState *tstate = _PyThreadState_GET(); /* When the iterator is exhausted it must return NULL; * a StopIteration exception may or may not be set. */ if (!_PyErr_Occurred(tstate)) { return 0; } if (_PyErr_ExceptionMatches(tstate, PyExc_StopIteration)) { _PyErr_Clear(tstate); return 0; } /* Error case: an exception (different than StopIteration) is set. */ return -1; } /* Return 1 and set 'item' to the next item of 'iter' on success. * Return 0 and set 'item' to NULL when there are no remaining values. * Return -1, set 'item' to NULL and set an exception on error. */ int PyIter_NextItem(PyObject *iter, PyObject **item) { assert(iter != NULL); assert(item != NULL); if (Py_TYPE(iter)->tp_iternext == NULL) { *item = NULL; PyErr_Format(PyExc_TypeError, "expected an iterator, got '%T'", iter); return -1; } return iternext(iter, item); } /* Return next item. * * If an error occurs, return NULL. PyErr_Occurred() will be true. * If the iteration terminates normally, return NULL and clear the * PyExc_StopIteration exception (if it was set). PyErr_Occurred() * will be false. * Else return the next object. PyErr_Occurred() will be false. */ PyObject * PyIter_Next(PyObject *iter) { PyObject *item; (void)iternext(iter, &item); return item; } PySendResult PyIter_Send(PyObject *iter, PyObject *arg, PyObject **result) { assert(arg != NULL); assert(result != NULL); if (Py_TYPE(iter)->tp_as_async && Py_TYPE(iter)->tp_as_async->am_send) { PySendResult res = Py_TYPE(iter)->tp_as_async->am_send(iter, arg, result); assert(_Py_CheckSlotResult(iter, "am_send", res != PYGEN_ERROR)); return res; } if (arg == Py_None && PyIter_Check(iter)) { *result = Py_TYPE(iter)->tp_iternext(iter); } else { *result = PyObject_CallMethodOneArg(iter, &_Py_ID(send), arg); } if (*result != NULL) { return PYGEN_NEXT; } if (_PyGen_FetchStopIterationValue(result) == 0) { return PYGEN_RETURN; } return PYGEN_ERROR; } NOTES ON DICTIONARIES ================================ Principal Use Cases for Dictionaries ------------------------------------ Passing keyword arguments Typically, one read and one write for 1 to 3 elements. Occurs frequently in normal python code. Class method lookup Dictionaries vary in size with 8 to 16 elements being common. Usually written once with many lookups. When base classes are used, there are many failed lookups followed by a lookup in a base class. Instance attribute lookup and Global variables Dictionaries vary in size. 4 to 10 elements are common. Both reads and writes are common. Builtins Frequent reads. Almost never written. About 150 interned strings (as of Py3.3). A few keys are accessed much more frequently than others. Uniquification Dictionaries of any size. Bulk of work is in creation. Repeated writes to a smaller set of keys. Single read of each key. Some use cases have two consecutive accesses to the same key. * Removing duplicates from a sequence. dict.fromkeys(seqn).keys() * Counting elements in a sequence. for e in seqn: d[e] = d.get(e,0) + 1 * Accumulating references in a dictionary of lists: for pagenumber, page in enumerate(pages): for word in page: d.setdefault(word, []).append(pagenumber) Note, the second example is a use case characterized by a get and set to the same key. There are similar use cases with a __contains__ followed by a get, set, or del to the same key. Part of the justification for d.setdefault is combining the two lookups into one. Membership Testing Dictionaries of any size. Created once and then rarely changes. Single write to each key. Many calls to __contains__() or has_key(). Similar access patterns occur with replacement dictionaries such as with the % formatting operator. Dynamic Mappings Characterized by deletions interspersed with adds and replacements. Performance benefits greatly from the re-use of dummy entries. Data Layout ----------- Dictionaries are composed of 3 components: The dictobject struct itself A dict-keys object (keys & hashes) A values array Tunable Dictionary Parameters ----------------------------- See comments for PyDict_MINSIZE, USABLE_FRACTION and GROWTH_RATE in dictobject.c Tune-ups should be measured across a broad range of applications and use cases. A change to any parameter will help in some situations and hurt in others. The key is to find settings that help the most common cases and do the least damage to the less common cases. Results will vary dramatically depending on the exact number of keys, whether the keys are all strings, whether reads or writes dominate, the exact hash values of the keys (some sets of values have fewer collisions than others). Any one test or benchmark is likely to prove misleading. While making a dictionary more sparse reduces collisions, it impairs iteration and key listing. Those methods loop over every potential entry. Doubling the size of dictionary results in twice as many non-overlapping memory accesses for keys(), items(), values(), __iter__(), iterkeys(), iteritems(), itervalues(), and update(). Also, every dictionary iterates at least twice, once for the memset() when it is created and once by dealloc(). Dictionary operations involving only a single key can be O(1) unless resizing is possible. By checking for a resize only when the dictionary can grow (and may *require* resizing), other operations remain O(1), and the odds of resize thrashing or memory fragmentation are reduced. In particular, an algorithm that empties a dictionary by repeatedly invoking .pop will see no resizing, which might not be necessary at all because the dictionary is eventually discarded entirely. The key differences between this implementation and earlier versions are: 1. The table can be split into two parts, the keys and the values. 2. There is an additional key-value combination: (key, NULL). Unlike (, NULL) which represents a deleted value, (key, NULL) represented a yet to be inserted value. This combination can only occur when the table is split. 3. No small table embedded in the dict, as this would make sharing of key-tables impossible. These changes have the following consequences. 1. General dictionaries are slightly larger. 2. All object dictionaries of a single class can share a single key-table, saving about 60% memory for such cases. Results of Cache Locality Experiments -------------------------------------- Experiments on an earlier design of dictionary, in which all tables were combined, showed the following: When an entry is retrieved from memory, several adjacent entries are also retrieved into a cache line. Since accessing items in cache is *much* cheaper than a cache miss, an enticing idea is to probe the adjacent entries as a first step in collision resolution. Unfortunately, the introduction of any regularity into collision searches results in more collisions than the current random chaining approach. Exploiting cache locality at the expense of additional collisions fails to payoff when the entries are already loaded in cache (the expense is paid with no compensating benefit). This occurs in small dictionaries where the whole dictionary fits into a pair of cache lines. It also occurs frequently in large dictionaries which have a common access pattern where some keys are accessed much more frequently than others. The more popular entries *and* their collision chains tend to remain in cache. To exploit cache locality, change the collision resolution section in lookdict() and lookdict_string(). Set i^=1 at the top of the loop and move the i = (i << 2) + i + perturb + 1 to an unrolled version of the loop. For split tables, the above will apply to the keys, but the value will always be in a different cache line from the key. // namespace object implementation #include "Python.h" #include "pycore_modsupport.h" // _PyArg_NoPositional() #include "pycore_namespace.h" // _PyNamespace_Type #include // offsetof() typedef struct { PyObject_HEAD PyObject *ns_dict; } _PyNamespaceObject; #define _PyNamespace_CAST(op) _Py_CAST(_PyNamespaceObject*, (op)) static PyMemberDef namespace_members[] = { {"__dict__", _Py_T_OBJECT, offsetof(_PyNamespaceObject, ns_dict), Py_READONLY}, {NULL} }; // Methods static PyObject * namespace_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *self; assert(type != NULL && type->tp_alloc != NULL); self = type->tp_alloc(type, 0); if (self != NULL) { _PyNamespaceObject *ns = (_PyNamespaceObject *)self; ns->ns_dict = PyDict_New(); if (ns->ns_dict == NULL) { Py_DECREF(ns); return NULL; } } return self; } static int namespace_init(PyObject *op, PyObject *args, PyObject *kwds) { _PyNamespaceObject *ns = _PyNamespace_CAST(op); PyObject *arg = NULL; if (!PyArg_UnpackTuple(args, _PyType_Name(Py_TYPE(ns)), 0, 1, &arg)) { return -1; } if (arg != NULL) { PyObject *dict; if (PyDict_CheckExact(arg)) { dict = Py_NewRef(arg); } else { dict = PyObject_CallOneArg((PyObject *)&PyDict_Type, arg); if (dict == NULL) { return -1; } } int err = (!PyArg_ValidateKeywordArguments(dict) || PyDict_Update(ns->ns_dict, dict) < 0); Py_DECREF(dict); if (err) { return -1; } } if (kwds == NULL) { return 0; } if (!PyArg_ValidateKeywordArguments(kwds)) { return -1; } return PyDict_Update(ns->ns_dict, kwds); } static void namespace_dealloc(PyObject *op) { _PyNamespaceObject *ns = _PyNamespace_CAST(op); PyObject_GC_UnTrack(ns); Py_CLEAR(ns->ns_dict); Py_TYPE(ns)->tp_free((PyObject *)ns); } static PyObject * namespace_repr(PyObject *ns) { int i, loop_error = 0; PyObject *pairs = NULL, *d = NULL, *keys = NULL, *keys_iter = NULL; PyObject *key; PyObject *separator, *pairsrepr, *repr = NULL; const char * name; name = Py_IS_TYPE(ns, &_PyNamespace_Type) ? "namespace" : Py_TYPE(ns)->tp_name; i = Py_ReprEnter(ns); if (i != 0) { return i > 0 ? PyUnicode_FromFormat("%s(...)", name) : NULL; } pairs = PyList_New(0); if (pairs == NULL) goto error; assert(((_PyNamespaceObject *)ns)->ns_dict != NULL); d = Py_NewRef(((_PyNamespaceObject *)ns)->ns_dict); keys = PyDict_Keys(d); if (keys == NULL) goto error; keys_iter = PyObject_GetIter(keys); if (keys_iter == NULL) goto error; while ((key = PyIter_Next(keys_iter)) != NULL) { if (PyUnicode_Check(key) && PyUnicode_GET_LENGTH(key) > 0) { PyObject *value, *item; int has_key = PyDict_GetItemRef(d, key, &value); if (has_key == 1) { item = PyUnicode_FromFormat("%U=%R", key, value); Py_DECREF(value); if (item == NULL) { loop_error = 1; } else { loop_error = PyList_Append(pairs, item); Py_DECREF(item); } } else if (has_key < 0) { loop_error = 1; } } Py_DECREF(key); if (loop_error) goto error; } if (PyErr_Occurred()) { goto error; } separator = PyUnicode_FromString(", "); if (separator == NULL) goto error; pairsrepr = PyUnicode_Join(separator, pairs); Py_DECREF(separator); if (pairsrepr == NULL) goto error; repr = PyUnicode_FromFormat("%s(%S)", name, pairsrepr); Py_DECREF(pairsrepr); error: Py_XDECREF(pairs); Py_XDECREF(d); Py_XDECREF(keys); Py_XDECREF(keys_iter); Py_ReprLeave(ns); return repr; } static int namespace_traverse(PyObject *op, visitproc visit, void *arg) { _PyNamespaceObject *ns = _PyNamespace_CAST(op); Py_VISIT(ns->ns_dict); return 0; } static int namespace_clear(PyObject *op) { _PyNamespaceObject *ns = _PyNamespace_CAST(op); Py_CLEAR(ns->ns_dict); return 0; } static PyObject * namespace_richcompare(PyObject *self, PyObject *other, int op) { if ( (op == Py_EQ || op == Py_NE) && PyObject_TypeCheck(self, &_PyNamespace_Type) && PyObject_TypeCheck(other, &_PyNamespace_Type) ) { return PyObject_RichCompare(((_PyNamespaceObject *)self)->ns_dict, ((_PyNamespaceObject *)other)->ns_dict, op); } Py_RETURN_NOTIMPLEMENTED; } PyDoc_STRVAR(namespace_reduce__doc__, "Return state information for pickling"); static PyObject * namespace_reduce(PyObject *op, PyObject *Py_UNUSED(ignored)) { _PyNamespaceObject *ns = (_PyNamespaceObject*)op; PyObject *result, *args = PyTuple_New(0); if (!args) return NULL; result = PyTuple_Pack(3, (PyObject *)Py_TYPE(ns), args, ns->ns_dict); Py_DECREF(args); return result; } static PyObject * namespace_replace(PyObject *self, PyObject *args, PyObject *kwargs) { if (!_PyArg_NoPositional("__replace__", args)) { return NULL; } PyObject *result = PyObject_CallNoArgs((PyObject *)Py_TYPE(self)); if (!result) { return NULL; } if (PyDict_Update(((_PyNamespaceObject*)result)->ns_dict, ((_PyNamespaceObject*)self)->ns_dict) < 0) { Py_DECREF(result); return NULL; } if (kwargs) { if (PyDict_Update(((_PyNamespaceObject*)result)->ns_dict, kwargs) < 0) { Py_DECREF(result); return NULL; } } return result; } static PyMethodDef namespace_methods[] = { {"__reduce__", namespace_reduce, METH_NOARGS, namespace_reduce__doc__}, {"__replace__", _PyCFunction_CAST(namespace_replace), METH_VARARGS|METH_KEYWORDS, PyDoc_STR("__replace__($self, /, **changes)\n--\n\n" "Return a copy of the namespace object with new values for the specified attributes.")}, {NULL, NULL} // sentinel }; PyDoc_STRVAR(namespace_doc, "SimpleNamespace(mapping_or_iterable=(), /, **kwargs)\n\ --\n\n\ A simple attribute-based namespace."); PyTypeObject _PyNamespace_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "types.SimpleNamespace", /* tp_name */ sizeof(_PyNamespaceObject), /* tp_basicsize */ 0, /* tp_itemsize */ namespace_dealloc, /* tp_dealloc */ 0, /* tp_vectorcall_offset */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ namespace_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ namespace_doc, /* tp_doc */ namespace_traverse, /* tp_traverse */ namespace_clear, /* tp_clear */ namespace_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ namespace_methods, /* tp_methods */ namespace_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(_PyNamespaceObject, ns_dict), /* tp_dictoffset */ namespace_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ namespace_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; PyObject * _PyNamespace_New(PyObject *kwds) { PyObject *ns = namespace_new(&_PyNamespace_Type, NULL, NULL); if (ns == NULL) return NULL; if (kwds == NULL) return ns; if (PyDict_Update(((_PyNamespaceObject *)ns)->ns_dict, kwds) != 0) { Py_DECREF(ns); return NULL; } return (PyObject *)ns; } """