Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes15kdownloads
object.h829 linesDownload Raw Back to include
1#ifndef Py_OBJECT_H2#define Py_OBJECT_H3#ifdef __cplusplus4extern "C" {5#endif6 7 8/* Object and type object interface */9 10/*11Objects are structures allocated on the heap.  Special rules apply to12the use of objects to ensure they are properly garbage-collected.13Objects are never allocated statically or on the stack; they must be14accessed through special macros and functions only.  (Type objects are15exceptions to the first rule; the standard types are represented by16statically initialized type objects, although work on type/class unification17for Python 2.2 made it possible to have heap-allocated type objects too).18 19An object has a 'reference count' that is increased or decreased when a20pointer to the object is copied or deleted; when the reference count21reaches zero there are no references to the object left and it can be22removed from the heap.23 24An object has a 'type' that determines what it represents and what kind25of data it contains.  An object's type is fixed when it is created.26Types themselves are represented as objects; an object contains a27pointer to the corresponding type object.  The type itself has a type28pointer pointing to the object representing the type 'type', which29contains a pointer to itself!.30 31Objects do not float around in memory; once allocated an object keeps32the same size and address.  Objects that must hold variable-size data33can contain pointers to variable-size parts of the object.  Not all34objects of the same type have the same size; but the size cannot change35after allocation.  (These restrictions are made so a reference to an36object can be simply a pointer -- moving an object would require37updating all the pointers, and changing an object's size would require38moving it if there was another object right next to it.)39 40Objects are always accessed through pointers of the type 'PyObject *'.41The type 'PyObject' is a structure that only contains the reference count42and the type pointer.  The actual memory allocated for an object43contains other data that can only be accessed after casting the pointer44to a pointer to a longer structure type.  This longer type must start45with the reference count and type fields; the macro PyObject_HEAD should be46used for this (to accommodate for future changes).  The implementation47of a particular object type can cast the object pointer to the proper48type and back.49 50A standard interface exists for objects that contain an array of items51whose size is determined when the object is allocated.52*/53 54/* Py_DEBUG implies Py_REF_DEBUG. */55#if defined(Py_DEBUG) && !defined(Py_REF_DEBUG)56#  define Py_REF_DEBUG57#endif58 59/* PyObject_HEAD defines the initial segment of every PyObject. */60#define PyObject_HEAD                   PyObject ob_base;61 62// Kept for backward compatibility. It was needed by Py_TRACE_REFS build.63#define _PyObject_EXTRA_INIT64 65/* Make all uses of PyObject_HEAD_INIT immortal.66 *67 * Statically allocated objects might be shared between68 * interpreters, so must be marked as immortal.69 */70#if defined(Py_GIL_DISABLED)71#define PyObject_HEAD_INIT(type)    \72    {                               \73        0,                          \74        _Py_STATICALLY_ALLOCATED_FLAG, \75        { 0 },                      \76        0,                          \77        _Py_IMMORTAL_REFCNT_LOCAL,  \78        0,                          \79        (type),                     \80    },81#else82#define PyObject_HEAD_INIT(type)    \83    {                               \84        { _Py_STATIC_IMMORTAL_INITIAL_REFCNT },    \85        (type)                      \86    },87#endif88 89#define PyVarObject_HEAD_INIT(type, size) \90    {                                     \91        PyObject_HEAD_INIT(type)          \92        (size)                            \93    },94 95/* PyObject_VAR_HEAD defines the initial segment of all variable-size96 * container objects.  These end with a declaration of an array with 197 * element, but enough space is malloc'ed so that the array actually98 * has room for ob_size elements.  Note that ob_size is an element count,99 * not necessarily a byte count.100 */101#define PyObject_VAR_HEAD      PyVarObject ob_base;102#define Py_INVALID_SIZE (Py_ssize_t)-1103 104/* Nothing is actually declared to be a PyObject, but every pointer to105 * a Python object can be cast to a PyObject*.  This is inheritance built106 * by hand.  Similarly every pointer to a variable-size Python object can,107 * in addition, be cast to PyVarObject*.108 */109#ifndef Py_GIL_DISABLED110struct _object {111#if (defined(__GNUC__) || defined(__clang__)) \112        && !(defined __STDC_VERSION__ && __STDC_VERSION__ >= 201112L)113    // On C99 and older, anonymous union is a GCC and clang extension114    __extension__115#endif116#ifdef _MSC_VER117    // Ignore MSC warning C4201: "nonstandard extension used:118    // nameless struct/union"119    __pragma(warning(push))120    __pragma(warning(disable: 4201))121#endif122    union {123#if SIZEOF_VOID_P > 4124        PY_INT64_T ob_refcnt_full; /* This field is needed for efficient initialization with Clang on ARM */125        struct {126#  if PY_BIG_ENDIAN127            uint16_t ob_flags;128            uint16_t ob_overflow;129            uint32_t ob_refcnt;130#  else131            uint32_t ob_refcnt;132            uint16_t ob_overflow;133            uint16_t ob_flags;134#  endif135        };136#else137        Py_ssize_t ob_refcnt;138#endif139    };140#ifdef _MSC_VER141    __pragma(warning(pop))142#endif143 144    PyTypeObject *ob_type;145};146#else147// Objects that are not owned by any thread use a thread id (tid) of zero.148// This includes both immortal objects and objects whose reference count149// fields have been merged.150#define _Py_UNOWNED_TID             0151 152struct _object {153    // ob_tid stores the thread id (or zero). It is also used by the GC and the154    // trashcan mechanism as a linked list pointer and by the GC to store the155    // computed "gc_refs" refcount.156    uintptr_t ob_tid;157    uint16_t ob_flags;158    PyMutex ob_mutex;           // per-object lock159    uint8_t ob_gc_bits;         // gc-related state160    uint32_t ob_ref_local;      // local reference count161    Py_ssize_t ob_ref_shared;   // shared (atomic) reference count162    PyTypeObject *ob_type;163};164#endif165 166/* Cast argument to PyObject* type. */167#define _PyObject_CAST(op) _Py_CAST(PyObject*, (op))168 169typedef struct {170    PyObject ob_base;171    Py_ssize_t ob_size; /* Number of items in variable part */172} PyVarObject;173 174/* Cast argument to PyVarObject* type. */175#define _PyVarObject_CAST(op) _Py_CAST(PyVarObject*, (op))176 177 178// Test if the 'x' object is the 'y' object, the same as "x is y" in Python.179PyAPI_FUNC(int) Py_Is(PyObject *x, PyObject *y);180#define Py_Is(x, y) ((x) == (y))181 182#if defined(Py_GIL_DISABLED) && !defined(Py_LIMITED_API)183PyAPI_FUNC(uintptr_t) _Py_GetThreadLocal_Addr(void);184 185static inline uintptr_t186_Py_ThreadId(void)187{188    uintptr_t tid;189#if defined(_MSC_VER) && defined(_M_X64)190    tid = __readgsqword(48);191#elif defined(_MSC_VER) && defined(_M_IX86)192    tid = __readfsdword(24);193#elif defined(_MSC_VER) && defined(_M_ARM64)194    tid = __getReg(18);195#elif defined(__MINGW32__) && defined(_M_X64)196    tid = __readgsqword(48);197#elif defined(__MINGW32__) && defined(_M_IX86)198    tid = __readfsdword(24);199#elif defined(__MINGW32__) && defined(_M_ARM64)200    tid = __getReg(18);201#elif defined(__i386__)202    __asm__("{movl %%gs:0, %0|mov %0, dword ptr gs:[0]}" : "=r" (tid));  // 32-bit always uses GS203#elif defined(__MACH__) && defined(__x86_64__)204    __asm__("{movq %%gs:0, %0|mov %0, qword ptr gs:[0]}" : "=r" (tid));  // x86_64 macOSX uses GS205#elif defined(__x86_64__)206    __asm__("{movq %%fs:0, %0|mov %0, qword ptr fs:[0]}" : "=r" (tid));  // x86_64 Linux, BSD uses FS207#elif defined(__arm__) && __ARM_ARCH >= 7208    __asm__ ("mrc p15, 0, %0, c13, c0, 3\nbic %0, %0, #3" : "=r" (tid));209#elif defined(__aarch64__) && defined(__APPLE__)210    __asm__ ("mrs %0, tpidrro_el0" : "=r" (tid));211#elif defined(__aarch64__)212    __asm__ ("mrs %0, tpidr_el0" : "=r" (tid));213#elif defined(__powerpc64__)214    #if defined(__clang__) && _Py__has_builtin(__builtin_thread_pointer)215    tid = (uintptr_t)__builtin_thread_pointer();216    #else217    // r13 is reserved for use as system thread ID by the Power 64-bit ABI.218    register uintptr_t tp __asm__ ("r13");219    __asm__("" : "=r" (tp));220    tid = tp;221    #endif222#elif defined(__powerpc__)223    #if defined(__clang__) && _Py__has_builtin(__builtin_thread_pointer)224    tid = (uintptr_t)__builtin_thread_pointer();225    #else226    // r2 is reserved for use as system thread ID by the Power 32-bit ABI.227    register uintptr_t tp __asm__ ("r2");228    __asm__ ("" : "=r" (tp));229    tid = tp;230    #endif231#elif defined(__s390__) && defined(__GNUC__)232    // Both GCC and Clang have supported __builtin_thread_pointer233    // for s390 from long time ago.234    tid = (uintptr_t)__builtin_thread_pointer();235#elif defined(__riscv)236    #if defined(__clang__) && _Py__has_builtin(__builtin_thread_pointer)237    tid = (uintptr_t)__builtin_thread_pointer();238    #else239    // tp is Thread Pointer provided by the RISC-V ABI.240    __asm__ ("mv %0, tp" : "=r" (tid));241    #endif242#else243    // Fallback to a portable implementation if we do not have a faster244    // platform-specific implementation.245    tid = _Py_GetThreadLocal_Addr();246#endif247  return tid;248}249 250static inline Py_ALWAYS_INLINE int251_Py_IsOwnedByCurrentThread(PyObject *ob)252{253#ifdef _Py_THREAD_SANITIZER254    return _Py_atomic_load_uintptr_relaxed(&ob->ob_tid) == _Py_ThreadId();255#else256    return ob->ob_tid == _Py_ThreadId();257#endif258}259#endif260 261// Py_TYPE() implementation for the stable ABI262PyAPI_FUNC(PyTypeObject*) Py_TYPE(PyObject *ob);263 264#if defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030e0000265    // Stable ABI implements Py_TYPE() as a function call266    // on limited C API version 3.14 and newer.267#else268    static inline PyTypeObject* _Py_TYPE(PyObject *ob)269    {270        return ob->ob_type;271    }272    #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000273    #   define Py_TYPE(ob) _Py_TYPE(_PyObject_CAST(ob))274    #else275    #   define Py_TYPE(ob) _Py_TYPE(ob)276    #endif277#endif278 279PyAPI_DATA(PyTypeObject) PyLong_Type;280PyAPI_DATA(PyTypeObject) PyBool_Type;281 282// bpo-39573: The Py_SET_SIZE() function must be used to set an object size.283static inline Py_ssize_t Py_SIZE(PyObject *ob) {284    assert(Py_TYPE(ob) != &PyLong_Type);285    assert(Py_TYPE(ob) != &PyBool_Type);286    return  _PyVarObject_CAST(ob)->ob_size;287}288#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000289#  define Py_SIZE(ob) Py_SIZE(_PyObject_CAST(ob))290#endif291 292static inline int Py_IS_TYPE(PyObject *ob, PyTypeObject *type) {293    return Py_TYPE(ob) == type;294}295#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000296#  define Py_IS_TYPE(ob, type) Py_IS_TYPE(_PyObject_CAST(ob), (type))297#endif298 299 300static inline void Py_SET_TYPE(PyObject *ob, PyTypeObject *type) {301    ob->ob_type = type;302}303#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000304#  define Py_SET_TYPE(ob, type) Py_SET_TYPE(_PyObject_CAST(ob), type)305#endif306 307static inline void Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size) {308    assert(Py_TYPE(_PyObject_CAST(ob)) != &PyLong_Type);309    assert(Py_TYPE(_PyObject_CAST(ob)) != &PyBool_Type);310#ifdef Py_GIL_DISABLED311    _Py_atomic_store_ssize_relaxed(&ob->ob_size, size);312#else313    ob->ob_size = size;314#endif315}316#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000317#  define Py_SET_SIZE(ob, size) Py_SET_SIZE(_PyVarObject_CAST(ob), (size))318#endif319 320 321/*322Type objects contain a string containing the type name (to help somewhat323in debugging), the allocation parameters (see PyObject_New() and324PyObject_NewVar()),325and methods for accessing objects of the type.  Methods are optional, a326nil pointer meaning that particular kind of access is not available for327this type.  The Py_DECREF() macro uses the tp_dealloc method without328checking for a nil pointer; it should always be implemented except if329the implementation can guarantee that the reference count will never330reach zero (e.g., for statically allocated type objects).331 332NB: the methods for certain type groups are now contained in separate333method blocks.334*/335 336typedef PyObject * (*unaryfunc)(PyObject *);337typedef PyObject * (*binaryfunc)(PyObject *, PyObject *);338typedef PyObject * (*ternaryfunc)(PyObject *, PyObject *, PyObject *);339typedef int (*inquiry)(PyObject *);340typedef Py_ssize_t (*lenfunc)(PyObject *);341typedef PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t);342typedef PyObject *(*ssizessizeargfunc)(PyObject *, Py_ssize_t, Py_ssize_t);343typedef int(*ssizeobjargproc)(PyObject *, Py_ssize_t, PyObject *);344typedef int(*ssizessizeobjargproc)(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);345typedef int(*objobjargproc)(PyObject *, PyObject *, PyObject *);346 347typedef int (*objobjproc)(PyObject *, PyObject *);348typedef int (*visitproc)(PyObject *, void *);349typedef int (*traverseproc)(PyObject *, visitproc, void *);350 351 352typedef void (*freefunc)(void *);353typedef void (*destructor)(PyObject *);354typedef PyObject *(*getattrfunc)(PyObject *, char *);355typedef PyObject *(*getattrofunc)(PyObject *, PyObject *);356typedef int (*setattrfunc)(PyObject *, char *, PyObject *);357typedef int (*setattrofunc)(PyObject *, PyObject *, PyObject *);358typedef PyObject *(*reprfunc)(PyObject *);359typedef Py_hash_t (*hashfunc)(PyObject *);360typedef PyObject *(*richcmpfunc) (PyObject *, PyObject *, int);361typedef PyObject *(*getiterfunc) (PyObject *);362typedef PyObject *(*iternextfunc) (PyObject *);363typedef PyObject *(*descrgetfunc) (PyObject *, PyObject *, PyObject *);364typedef int (*descrsetfunc) (PyObject *, PyObject *, PyObject *);365typedef int (*initproc)(PyObject *, PyObject *, PyObject *);366typedef PyObject *(*newfunc)(PyTypeObject *, PyObject *, PyObject *);367typedef PyObject *(*allocfunc)(PyTypeObject *, Py_ssize_t);368 369#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030c0000 // 3.12370typedef PyObject *(*vectorcallfunc)(PyObject *callable, PyObject *const *args,371                                    size_t nargsf, PyObject *kwnames);372#endif373 374typedef struct{375    int slot;    /* slot id, see below */376    void *pfunc; /* function pointer */377} PyType_Slot;378 379typedef struct{380    const char* name;381    int basicsize;382    int itemsize;383    unsigned int flags;384    PyType_Slot *slots; /* terminated by slot==0. */385} PyType_Spec;386 387PyAPI_FUNC(PyObject*) PyType_FromSpec(PyType_Spec*);388#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000389PyAPI_FUNC(PyObject*) PyType_FromSpecWithBases(PyType_Spec*, PyObject*);390#endif391#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000392PyAPI_FUNC(void*) PyType_GetSlot(PyTypeObject*, int);393#endif394#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03090000395PyAPI_FUNC(PyObject*) PyType_FromModuleAndSpec(PyObject *, PyType_Spec *, PyObject *);396PyAPI_FUNC(PyObject *) PyType_GetModule(PyTypeObject *);397PyAPI_FUNC(void *) PyType_GetModuleState(PyTypeObject *);398#endif399#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030B0000400PyAPI_FUNC(PyObject *) PyType_GetName(PyTypeObject *);401PyAPI_FUNC(PyObject *) PyType_GetQualName(PyTypeObject *);402#endif403#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030D0000404PyAPI_FUNC(PyObject *) PyType_GetFullyQualifiedName(PyTypeObject *type);405PyAPI_FUNC(PyObject *) PyType_GetModuleName(PyTypeObject *type);406#endif407#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030C0000408PyAPI_FUNC(PyObject *) PyType_FromMetaclass(PyTypeObject*, PyObject*, PyType_Spec*, PyObject*);409PyAPI_FUNC(void *) PyObject_GetTypeData(PyObject *obj, PyTypeObject *cls);410PyAPI_FUNC(Py_ssize_t) PyType_GetTypeDataSize(PyTypeObject *cls);411#endif412#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030E0000413PyAPI_FUNC(int) PyType_GetBaseByToken(PyTypeObject *, void *, PyTypeObject **);414#define Py_TP_USE_SPEC NULL415#endif416 417/* Generic type check */418PyAPI_FUNC(int) PyType_IsSubtype(PyTypeObject *, PyTypeObject *);419 420static inline int PyObject_TypeCheck(PyObject *ob, PyTypeObject *type) {421    return Py_IS_TYPE(ob, type) || PyType_IsSubtype(Py_TYPE(ob), type);422}423#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000424#  define PyObject_TypeCheck(ob, type) PyObject_TypeCheck(_PyObject_CAST(ob), (type))425#endif426 427PyAPI_DATA(PyTypeObject) PyType_Type; /* built-in 'type' */428PyAPI_DATA(PyTypeObject) PyBaseObject_Type; /* built-in 'object' */429PyAPI_DATA(PyTypeObject) PySuper_Type; /* built-in 'super' */430 431PyAPI_FUNC(unsigned long) PyType_GetFlags(PyTypeObject*);432 433PyAPI_FUNC(int) PyType_Ready(PyTypeObject *);434PyAPI_FUNC(PyObject *) PyType_GenericAlloc(PyTypeObject *, Py_ssize_t);435PyAPI_FUNC(PyObject *) PyType_GenericNew(PyTypeObject *,436                                               PyObject *, PyObject *);437PyAPI_FUNC(unsigned int) PyType_ClearCache(void);438PyAPI_FUNC(void) PyType_Modified(PyTypeObject *);439 440/* Generic operations on objects */441PyAPI_FUNC(PyObject *) PyObject_Repr(PyObject *);442PyAPI_FUNC(PyObject *) PyObject_Str(PyObject *);443PyAPI_FUNC(PyObject *) PyObject_ASCII(PyObject *);444PyAPI_FUNC(PyObject *) PyObject_Bytes(PyObject *);445PyAPI_FUNC(PyObject *) PyObject_RichCompare(PyObject *, PyObject *, int);446PyAPI_FUNC(int) PyObject_RichCompareBool(PyObject *, PyObject *, int);447PyAPI_FUNC(PyObject *) PyObject_GetAttrString(PyObject *, const char *);448PyAPI_FUNC(int) PyObject_SetAttrString(PyObject *, const char *, PyObject *);449PyAPI_FUNC(int) PyObject_DelAttrString(PyObject *v, const char *name);450PyAPI_FUNC(int) PyObject_HasAttrString(PyObject *, const char *);451PyAPI_FUNC(PyObject *) PyObject_GetAttr(PyObject *, PyObject *);452#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030d0000453PyAPI_FUNC(int) PyObject_GetOptionalAttr(PyObject *, PyObject *, PyObject **);454PyAPI_FUNC(int) PyObject_GetOptionalAttrString(PyObject *, const char *, PyObject **);455#endif456PyAPI_FUNC(int) PyObject_SetAttr(PyObject *, PyObject *, PyObject *);457PyAPI_FUNC(int) PyObject_DelAttr(PyObject *v, PyObject *name);458PyAPI_FUNC(int) PyObject_HasAttr(PyObject *, PyObject *);459#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030d0000460PyAPI_FUNC(int) PyObject_HasAttrWithError(PyObject *, PyObject *);461PyAPI_FUNC(int) PyObject_HasAttrStringWithError(PyObject *, const char *);462#endif463PyAPI_FUNC(PyObject *) PyObject_SelfIter(PyObject *);464PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *);465PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *, PyObject *, PyObject *);466#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000467PyAPI_FUNC(int) PyObject_GenericSetDict(PyObject *, PyObject *, void *);468#endif469PyAPI_FUNC(Py_hash_t) PyObject_Hash(PyObject *);470PyAPI_FUNC(Py_hash_t) PyObject_HashNotImplemented(PyObject *);471PyAPI_FUNC(int) PyObject_IsTrue(PyObject *);472PyAPI_FUNC(int) PyObject_Not(PyObject *);473PyAPI_FUNC(int) PyCallable_Check(PyObject *);474PyAPI_FUNC(void) PyObject_ClearWeakRefs(PyObject *);475 476/* PyObject_Dir(obj) acts like Python builtins.dir(obj), returning a477   list of strings.  PyObject_Dir(NULL) is like builtins.dir(),478   returning the names of the current locals.  In this case, if there are479   no current locals, NULL is returned, and PyErr_Occurred() is false.480*/481PyAPI_FUNC(PyObject *) PyObject_Dir(PyObject *);482 483/* Helpers for printing recursive container types */484PyAPI_FUNC(int) Py_ReprEnter(PyObject *);485PyAPI_FUNC(void) Py_ReprLeave(PyObject *);486 487/* Flag bits for printing: */488#define Py_PRINT_RAW    1       /* No string quotes etc. */489 490/*491Type flags (tp_flags)492 493These flags are used to change expected features and behavior for a494particular type.495 496Arbitration of the flag bit positions will need to be coordinated among497all extension writers who publicly release their extensions (this will498be fewer than you might expect!).499 500Most flags were removed as of Python 3.0 to make room for new flags.  (Some501flags are not for backwards compatibility but to indicate the presence of an502optional feature; these flags remain of course.)503 504Type definitions should use Py_TPFLAGS_DEFAULT for their tp_flags value.505 506Code can use PyType_HasFeature(type_ob, flag_value) to test whether the507given type object has a specified feature.508*/509 510#ifndef Py_LIMITED_API511 512/* Track types initialized using _PyStaticType_InitBuiltin(). */513#define _Py_TPFLAGS_STATIC_BUILTIN (1 << 1)514 515/* The values array is placed inline directly after the rest of516 * the object. Implies Py_TPFLAGS_HAVE_GC.517 */518#define Py_TPFLAGS_INLINE_VALUES (1 << 2)519 520/* Placement of weakref pointers are managed by the VM, not by the type.521 * The VM will automatically set tp_weaklistoffset.522 */523#define Py_TPFLAGS_MANAGED_WEAKREF (1 << 3)524 525/* Placement of dict (and values) pointers are managed by the VM, not by the type.526 * The VM will automatically set tp_dictoffset. Implies Py_TPFLAGS_HAVE_GC.527 */528#define Py_TPFLAGS_MANAGED_DICT (1 << 4)529 530#define Py_TPFLAGS_PREHEADER (Py_TPFLAGS_MANAGED_WEAKREF | Py_TPFLAGS_MANAGED_DICT)531 532/* Set if instances of the type object are treated as sequences for pattern matching */533#define Py_TPFLAGS_SEQUENCE (1 << 5)534/* Set if instances of the type object are treated as mappings for pattern matching */535#define Py_TPFLAGS_MAPPING (1 << 6)536#endif537 538/* Disallow creating instances of the type: set tp_new to NULL and don't create539 * the "__new__" key in the type dictionary. */540#define Py_TPFLAGS_DISALLOW_INSTANTIATION (1UL << 7)541 542/* Set if the type object is immutable: type attributes cannot be set nor deleted */543#define Py_TPFLAGS_IMMUTABLETYPE (1UL << 8)544 545/* Set if the type object is dynamically allocated */546#define Py_TPFLAGS_HEAPTYPE (1UL << 9)547 548/* Set if the type allows subclassing */549#define Py_TPFLAGS_BASETYPE (1UL << 10)550 551/* Set if the type implements the vectorcall protocol (PEP 590) */552#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030C0000553#define Py_TPFLAGS_HAVE_VECTORCALL (1UL << 11)554#ifndef Py_LIMITED_API555// Backwards compatibility alias for API that was provisional in Python 3.8556#define _Py_TPFLAGS_HAVE_VECTORCALL Py_TPFLAGS_HAVE_VECTORCALL557#endif558#endif559 560/* Set if the type is 'ready' -- fully initialized */561#define Py_TPFLAGS_READY (1UL << 12)562 563/* Set while the type is being 'readied', to prevent recursive ready calls */564#define Py_TPFLAGS_READYING (1UL << 13)565 566/* Objects support garbage collection (see objimpl.h) */567#define Py_TPFLAGS_HAVE_GC (1UL << 14)568 569/* These two bits are preserved for Stackless Python, next after this is 17 */570#ifdef STACKLESS571#define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION (3UL << 15)572#else573#define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION 0574#endif575 576/* Objects behave like an unbound method */577#define Py_TPFLAGS_METHOD_DESCRIPTOR (1UL << 17)578 579/* Unused. Legacy flag */580#define Py_TPFLAGS_VALID_VERSION_TAG  (1UL << 19)581 582/* Type is abstract and cannot be instantiated */583#define Py_TPFLAGS_IS_ABSTRACT (1UL << 20)584 585// This undocumented flag gives certain built-ins their unique pattern-matching586// behavior, which allows a single positional subpattern to match against the587// subject itself (rather than a mapped attribute on it):588#define _Py_TPFLAGS_MATCH_SELF (1UL << 22)589 590/* Items (ob_size*tp_itemsize) are found at the end of an instance's memory */591#define Py_TPFLAGS_ITEMS_AT_END (1UL << 23)592 593/* These flags are used to determine if a type is a subclass. */594#define Py_TPFLAGS_LONG_SUBCLASS        (1UL << 24)595#define Py_TPFLAGS_LIST_SUBCLASS        (1UL << 25)596#define Py_TPFLAGS_TUPLE_SUBCLASS       (1UL << 26)597#define Py_TPFLAGS_BYTES_SUBCLASS       (1UL << 27)598#define Py_TPFLAGS_UNICODE_SUBCLASS     (1UL << 28)599#define Py_TPFLAGS_DICT_SUBCLASS        (1UL << 29)600#define Py_TPFLAGS_BASE_EXC_SUBCLASS    (1UL << 30)601#define Py_TPFLAGS_TYPE_SUBCLASS        (1UL << 31)602 603#define Py_TPFLAGS_DEFAULT  ( \604                 Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \605                0)606 607/* NOTE: Some of the following flags reuse lower bits (removed as part of the608 * Python 3.0 transition). */609 610/* The following flags are kept for compatibility; in previous611 * versions they indicated presence of newer tp_* fields on the612 * type struct.613 * Starting with 3.8, binary compatibility of C extensions across614 * feature releases of Python is not supported anymore (except when615 * using the stable ABI, in which all classes are created dynamically,616 * using the interpreter's memory layout.)617 * Note that older extensions using the stable ABI set these flags,618 * so the bits must not be repurposed.619 */620#define Py_TPFLAGS_HAVE_FINALIZE (1UL << 0)621#define Py_TPFLAGS_HAVE_VERSION_TAG   (1UL << 18)622 623 624#define Py_CONSTANT_NONE 0625#define Py_CONSTANT_FALSE 1626#define Py_CONSTANT_TRUE 2627#define Py_CONSTANT_ELLIPSIS 3628#define Py_CONSTANT_NOT_IMPLEMENTED 4629#define Py_CONSTANT_ZERO 5630#define Py_CONSTANT_ONE 6631#define Py_CONSTANT_EMPTY_STR 7632#define Py_CONSTANT_EMPTY_BYTES 8633#define Py_CONSTANT_EMPTY_TUPLE 9634 635#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030d0000636PyAPI_FUNC(PyObject*) Py_GetConstant(unsigned int constant_id);637PyAPI_FUNC(PyObject*) Py_GetConstantBorrowed(unsigned int constant_id);638#endif639 640 641/*642_Py_NoneStruct is an object of undefined type which can be used in contexts643where NULL (nil) is not suitable (since NULL often means 'error').644*/645PyAPI_DATA(PyObject) _Py_NoneStruct; /* Don't use this directly */646 647#if defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030D0000648#  define Py_None Py_GetConstantBorrowed(Py_CONSTANT_NONE)649#else650#  define Py_None (&_Py_NoneStruct)651#endif652 653// Test if an object is the None singleton, the same as "x is None" in Python.654PyAPI_FUNC(int) Py_IsNone(PyObject *x);655#define Py_IsNone(x) Py_Is((x), Py_None)656 657/* Macro for returning Py_None from a function.658 * Only treat Py_None as immortal in the limited C API 3.12 and newer. */659#if defined(Py_LIMITED_API) && Py_LIMITED_API+0 < 0x030c0000660#  define Py_RETURN_NONE return Py_NewRef(Py_None)661#else662#  define Py_RETURN_NONE return Py_None663#endif664 665/*666Py_NotImplemented is a singleton used to signal that an operation is667not implemented for a given type combination.668*/669PyAPI_DATA(PyObject) _Py_NotImplementedStruct; /* Don't use this directly */670 671#if defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030D0000672#  define Py_NotImplemented Py_GetConstantBorrowed(Py_CONSTANT_NOT_IMPLEMENTED)673#else674#  define Py_NotImplemented (&_Py_NotImplementedStruct)675#endif676 677/* Macro for returning Py_NotImplemented from a function. Only treat678 * Py_NotImplemented as immortal in the limited C API 3.12 and newer. */679#if defined(Py_LIMITED_API) && Py_LIMITED_API+0 < 0x030c0000680#  define Py_RETURN_NOTIMPLEMENTED return Py_NewRef(Py_NotImplemented)681#else682#  define Py_RETURN_NOTIMPLEMENTED return Py_NotImplemented683#endif684 685/* Rich comparison opcodes */686#define Py_LT 0687#define Py_LE 1688#define Py_EQ 2689#define Py_NE 3690#define Py_GT 4691#define Py_GE 5692 693#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000694/* Result of calling PyIter_Send */695typedef enum {696    PYGEN_RETURN = 0,697    PYGEN_ERROR = -1,698    PYGEN_NEXT = 1699} PySendResult;700#endif701 702/*703 * Macro for implementing rich comparisons704 *705 * Needs to be a macro because any C-comparable type can be used.706 */707#define Py_RETURN_RICHCOMPARE(val1, val2, op)                               \708    do {                                                                    \709        switch (op) {                                                       \710        case Py_EQ: if ((val1) == (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE;  \711        case Py_NE: if ((val1) != (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE;  \712        case Py_LT: if ((val1) < (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE;   \713        case Py_GT: if ((val1) > (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE;   \714        case Py_LE: if ((val1) <= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE;  \715        case Py_GE: if ((val1) >= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE;  \716        default:                                                            \717            Py_UNREACHABLE();                                               \718        }                                                                   \719    } while (0)720 721 722/*723More conventions724================725 726Argument Checking727-----------------728 729Functions that take objects as arguments normally don't check for nil730arguments, but they do check the type of the argument, and return an731error if the function doesn't apply to the type.732 733Failure Modes734-------------735 736Functions may fail for a variety of reasons, including running out of737memory.  This is communicated to the caller in two ways: an error string738is set (see errors.h), and the function result differs: functions that739normally return a pointer return NULL for failure, functions returning740an integer return -1 (which could be a legal return value too!), and741other functions return 0 for success and -1 for failure.742Callers should always check for errors before using the result.  If743an error was set, the caller must either explicitly clear it, or pass744the error on to its caller.745 746Reference Counts747----------------748 749It takes a while to get used to the proper usage of reference counts.750 751Functions that create an object set the reference count to 1; such new752objects must be stored somewhere or destroyed again with Py_DECREF().753Some functions that 'store' objects, such as PyTuple_SetItem() and754PyList_SetItem(),755don't increment the reference count of the object, since the most756frequent use is to store a fresh object.  Functions that 'retrieve'757objects, such as PyTuple_GetItem() and PyDict_GetItemString(), also758don't increment759the reference count, since most frequently the object is only looked at760quickly.  Thus, to retrieve an object and store it again, the caller761must call Py_INCREF() explicitly.762 763NOTE: functions that 'consume' a reference count, like764PyList_SetItem(), consume the reference even if the object wasn't765successfully stored, to simplify error handling.766 767It seems attractive to make other functions that take an object as768argument consume a reference count; however, this may quickly get769confusing (even the current practice is already confusing).  Consider770it carefully, it may save lots of calls to Py_INCREF() and Py_DECREF() at771times.772*/773 774#ifndef Py_LIMITED_API775#  define Py_CPYTHON_OBJECT_H776#  include "cpython/object.h"777#  undef Py_CPYTHON_OBJECT_H778#endif779 780 781static inline int782PyType_HasFeature(PyTypeObject *type, unsigned long feature)783{784    unsigned long flags;785#ifdef Py_LIMITED_API786    // PyTypeObject is opaque in the limited C API787    flags = PyType_GetFlags(type);788#else789#   ifdef Py_GIL_DISABLED790        flags = _Py_atomic_load_ulong_relaxed(&type->tp_flags);791#   else792        flags = type->tp_flags;793#   endif794#endif795    return ((flags & feature) != 0);796}797 798#define PyType_FastSubclass(type, flag) PyType_HasFeature((type), (flag))799 800static inline int PyType_Check(PyObject *op) {801    return PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS);802}803#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000804#  define PyType_Check(op) PyType_Check(_PyObject_CAST(op))805#endif806 807#define _PyType_CAST(op) \808    (assert(PyType_Check(op)), _Py_CAST(PyTypeObject*, (op)))809 810static inline int PyType_CheckExact(PyObject *op) {811    return Py_IS_TYPE(op, &PyType_Type);812}813#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000814#  define PyType_CheckExact(op) PyType_CheckExact(_PyObject_CAST(op))815#endif816 817#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030d0000818PyAPI_FUNC(PyObject *) PyType_GetModuleByDef(PyTypeObject *, PyModuleDef *);819#endif820 821#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030e0000822PyAPI_FUNC(int) PyType_Freeze(PyTypeObject *type);823#endif824 825#ifdef __cplusplus826}827#endif828#endif   // !Py_OBJECT_H829 
codekingpro/portable-devtools · Team Ai