1#ifndef Py_OBJECT_H
2#define Py_OBJECT_H
3
4#ifdef __cplusplus
5extern "C" {
6#endif
7
8
9/* Object and type object interface */
10
11/*
12Objects are structures allocated on the heap. Special rules apply to
13the use of objects to ensure they are properly garbage-collected.
14Objects are never allocated statically or on the stack; they must be
15accessed through special macros and functions only. (Type objects are
16exceptions to the first rule; the standard types are represented by
17statically initialized type objects, although work on type/class unification
18for Python 2.2 made it possible to have heap-allocated type objects too).
19
20An object has a 'reference count' that is increased or decreased when a
21pointer to the object is copied or deleted; when the reference count
22reaches zero there are no references to the object left and it can be
23removed from the heap.
24
25An object has a 'type' that determines what it represents and what kind
26of data it contains. An object's type is fixed when it is created.
27Types themselves are represented as objects; an object contains a
28pointer to the corresponding type object. The type itself has a type
29pointer pointing to the object representing the type 'type', which
30contains a pointer to itself!.
31
32Objects do not float around in memory; once allocated an object keeps
33the same size and address. Objects that must hold variable-size data
34can contain pointers to variable-size parts of the object. Not all
35objects of the same type have the same size; but the size cannot change
36after allocation. (These restrictions are made so a reference to an
37object can be simply a pointer -- moving an object would require
38updating all the pointers, and changing an object's size would require
39moving it if there was another object right next to it.)
40
41Objects are always accessed through pointers of the type 'PyObject *'.
42The type 'PyObject' is a structure that only contains the reference count
43and the type pointer. The actual memory allocated for an object
44contains other data that can only be accessed after casting the pointer
45to a pointer to a longer structure type. This longer type must start
46with the reference count and type fields; the macro PyObject_HEAD should be
47used for this (to accommodate for future changes). The implementation
48of a particular object type can cast the object pointer to the proper
49type and back.
50
51A standard interface exists for objects that contain an array of items
52whose size is determined when the object is allocated.
53*/
54
55/* Py_DEBUG implies Py_REF_DEBUG. */
56#if defined(Py_DEBUG) && !defined(Py_REF_DEBUG)
57# define Py_REF_DEBUG
58#endif
59
60#if defined(Py_LIMITED_API) && defined(Py_TRACE_REFS)
61# error Py_LIMITED_API is incompatible with Py_TRACE_REFS
62#endif
63
64/* PyTypeObject structure is defined in cpython/object.h.
65 In Py_LIMITED_API, PyTypeObject is an opaque structure. */
66typedef struct _typeobject PyTypeObject;
67
68#ifdef Py_TRACE_REFS
69/* Define pointers to support a doubly-linked list of all live heap objects. */
70#define _PyObject_HEAD_EXTRA \
71 struct _object *_ob_next; \
72 struct _object *_ob_prev;
73
74#define _PyObject_EXTRA_INIT 0, 0,
75
76#else
77# define _PyObject_HEAD_EXTRA
78# define _PyObject_EXTRA_INIT
79#endif
80
81/* PyObject_HEAD defines the initial segment of every PyObject. */
82#define PyObject_HEAD PyObject ob_base;
83
84#define PyObject_HEAD_INIT(type) \
85 { _PyObject_EXTRA_INIT \
86 1, type },
87
88#define PyVarObject_HEAD_INIT(type, size) \
89 { PyObject_HEAD_INIT(type) size },
90
91/* PyObject_VAR_HEAD defines the initial segment of all variable-size
92 * container objects. These end with a declaration of an array with 1
93 * element, but enough space is malloc'ed so that the array actually
94 * has room for ob_size elements. Note that ob_size is an element count,
95 * not necessarily a byte count.
96 */
97#define PyObject_VAR_HEAD PyVarObject ob_base;
98#define Py_INVALID_SIZE (Py_ssize_t)-1
99
100/* Nothing is actually declared to be a PyObject, but every pointer to
101 * a Python object can be cast to a PyObject*. This is inheritance built
102 * by hand. Similarly every pointer to a variable-size Python object can,
103 * in addition, be cast to PyVarObject*.
104 */
105typedef struct _object {
106 _PyObject_HEAD_EXTRA
107 Py_ssize_t ob_refcnt;
108 PyTypeObject *ob_type;
109} PyObject;
110
111/* Cast argument to PyObject* type. */
112#define _PyObject_CAST(op) ((PyObject*)(op))
113#define _PyObject_CAST_CONST(op) ((const PyObject*)(op))
114
115typedef struct {
116 PyObject ob_base;
117 Py_ssize_t ob_size; /* Number of items in variable part */
118} PyVarObject;
119
120/* Cast argument to PyVarObject* type. */
121#define _PyVarObject_CAST(op) ((PyVarObject*)(op))
122#define _PyVarObject_CAST_CONST(op) ((const PyVarObject*)(op))
123
124
125// Test if the 'x' object is the 'y' object, the same as "x is y" in Python.
126PyAPI_FUNC(int) Py_Is(PyObject *x, PyObject *y);
127#define Py_Is(x, y) ((x) == (y))
128
129
130static inline Py_ssize_t _Py_REFCNT(const PyObject *ob) {
131 return ob->ob_refcnt;
132}
133#define Py_REFCNT(ob) _Py_REFCNT(_PyObject_CAST_CONST(ob))
134
135
136// bpo-39573: The Py_SET_TYPE() function must be used to set an object type.
137#define Py_TYPE(ob) (_PyObject_CAST(ob)->ob_type)
138
139// bpo-39573: The Py_SET_SIZE() function must be used to set an object size.
140#define Py_SIZE(ob) (_PyVarObject_CAST(ob)->ob_size)
141
142
143static inline int _Py_IS_TYPE(const PyObject *ob, const PyTypeObject *type) {
144 // bpo-44378: Don't use Py_TYPE() since Py_TYPE() requires a non-const
145 // object.
146 return ob->ob_type == type;
147}
148#define Py_IS_TYPE(ob, type) _Py_IS_TYPE(_PyObject_CAST_CONST(ob), type)
149
150
151static inline void _Py_SET_REFCNT(PyObject *ob, Py_ssize_t refcnt) {
152 ob->ob_refcnt = refcnt;
153}
154#define Py_SET_REFCNT(ob, refcnt) _Py_SET_REFCNT(_PyObject_CAST(ob), refcnt)
155
156
157static inline void _Py_SET_TYPE(PyObject *ob, PyTypeObject *type) {
158 ob->ob_type = type;
159}
160#define Py_SET_TYPE(ob, type) _Py_SET_TYPE(_PyObject_CAST(ob), type)
161
162
163static inline void _Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size) {
164 ob->ob_size = size;
165}
166#define Py_SET_SIZE(ob, size) _Py_SET_SIZE(_PyVarObject_CAST(ob), size)
167
168
169/*
170Type objects contain a string containing the type name (to help somewhat
171in debugging), the allocation parameters (see PyObject_New() and
172PyObject_NewVar()),
173and methods for accessing objects of the type. Methods are optional, a
174nil pointer meaning that particular kind of access is not available for
175this type. The Py_DECREF() macro uses the tp_dealloc method without
176checking for a nil pointer; it should always be implemented except if
177the implementation can guarantee that the reference count will never
178reach zero (e.g., for statically allocated type objects).
179
180NB: the methods for certain type groups are now contained in separate
181method blocks.
182*/
183
184typedef PyObject * (*unaryfunc)(PyObject *);
185typedef PyObject * (*binaryfunc)(PyObject *, PyObject *);
186typedef PyObject * (*ternaryfunc)(PyObject *, PyObject *, PyObject *);
187typedef int (*inquiry)(PyObject *);
188typedef Py_ssize_t (*lenfunc)(PyObject *);
189typedef PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t);
190typedef PyObject *(*ssizessizeargfunc)(PyObject *, Py_ssize_t, Py_ssize_t);
191typedef int(*ssizeobjargproc)(PyObject *, Py_ssize_t, PyObject *);
192typedef int(*ssizessizeobjargproc)(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);
193typedef int(*objobjargproc)(PyObject *, PyObject *, PyObject *);
194
195typedef int (*objobjproc)(PyObject *, PyObject *);
196typedef int (*visitproc)(PyObject *, void *);
197typedef int (*traverseproc)(PyObject *, visitproc, void *);
198
199
200typedef void (*freefunc)(void *);
201typedef void (*destructor)(PyObject *);
202typedef PyObject *(*getattrfunc)(PyObject *, char *);
203typedef PyObject *(*getattrofunc)(PyObject *, PyObject *);
204typedef int (*setattrfunc)(PyObject *, char *, PyObject *);
205typedef int (*setattrofunc)(PyObject *, PyObject *, PyObject *);
206typedef PyObject *(*reprfunc)(PyObject *);
207typedef Py_hash_t (*hashfunc)(PyObject *);
208typedef PyObject *(*richcmpfunc) (PyObject *, PyObject *, int);
209typedef PyObject *(*getiterfunc) (PyObject *);
210typedef PyObject *(*iternextfunc) (PyObject *);
211typedef PyObject *(*descrgetfunc) (PyObject *, PyObject *, PyObject *);
212typedef int (*descrsetfunc) (PyObject *, PyObject *, PyObject *);
213typedef int (*initproc)(PyObject *, PyObject *, PyObject *);
214typedef PyObject *(*newfunc)(PyTypeObject *, PyObject *, PyObject *);
215typedef PyObject *(*allocfunc)(PyTypeObject *, Py_ssize_t);
216
217typedef struct{
218 int slot; /* slot id, see below */
219 void *pfunc; /* function pointer */
220} PyType_Slot;
221
222typedef struct{
223 const char* name;
224 int basicsize;
225 int itemsize;
226 unsigned int flags;
227 PyType_Slot *slots; /* terminated by slot==0. */
228} PyType_Spec;
229
230PyAPI_FUNC(PyObject*) PyType_FromSpec(PyType_Spec*);
231#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
232PyAPI_FUNC(PyObject*) PyType_FromSpecWithBases(PyType_Spec*, PyObject*);
233#endif
234#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000
235PyAPI_FUNC(void*) PyType_GetSlot(PyTypeObject*, int);
236#endif
237#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03090000
238PyAPI_FUNC(PyObject*) PyType_FromModuleAndSpec(PyObject *, PyType_Spec *, PyObject *);
239PyAPI_FUNC(PyObject *) PyType_GetModule(struct _typeobject *);
240PyAPI_FUNC(void *) PyType_GetModuleState(struct _typeobject *);
241#endif
242
243/* Generic type check */
244PyAPI_FUNC(int) PyType_IsSubtype(PyTypeObject *, PyTypeObject *);
245
246static inline int _PyObject_TypeCheck(PyObject *ob, PyTypeObject *type) {
247 return Py_IS_TYPE(ob, type) || PyType_IsSubtype(Py_TYPE(ob), type);
248}
249#define PyObject_TypeCheck(ob, type) _PyObject_TypeCheck(_PyObject_CAST(ob), type)
250
251PyAPI_DATA(PyTypeObject) PyType_Type; /* built-in 'type' */
252PyAPI_DATA(PyTypeObject) PyBaseObject_Type; /* built-in 'object' */
253PyAPI_DATA(PyTypeObject) PySuper_Type; /* built-in 'super' */
254
255PyAPI_FUNC(unsigned long) PyType_GetFlags(PyTypeObject*);
256
257PyAPI_FUNC(int) PyType_Ready(PyTypeObject *);
258PyAPI_FUNC(PyObject *) PyType_GenericAlloc(PyTypeObject *, Py_ssize_t);
259PyAPI_FUNC(PyObject *) PyType_GenericNew(PyTypeObject *,
260 PyObject *, PyObject *);
261PyAPI_FUNC(unsigned int) PyType_ClearCache(void);
262PyAPI_FUNC(void) PyType_Modified(PyTypeObject *);
263
264/* Generic operations on objects */
265PyAPI_FUNC(PyObject *) PyObject_Repr(PyObject *);
266PyAPI_FUNC(PyObject *) PyObject_Str(PyObject *);
267PyAPI_FUNC(PyObject *) PyObject_ASCII(PyObject *);
268PyAPI_FUNC(PyObject *) PyObject_Bytes(PyObject *);
269PyAPI_FUNC(PyObject *) PyObject_RichCompare(PyObject *, PyObject *, int);
270PyAPI_FUNC(int) PyObject_RichCompareBool(PyObject *, PyObject *, int);
271PyAPI_FUNC(PyObject *) PyObject_GetAttrString(PyObject *, const char *);
272PyAPI_FUNC(int) PyObject_SetAttrString(PyObject *, const char *, PyObject *);
273PyAPI_FUNC(int) PyObject_HasAttrString(PyObject *, const char *);
274PyAPI_FUNC(PyObject *) PyObject_GetAttr(PyObject *, PyObject *);
275PyAPI_FUNC(int) PyObject_SetAttr(PyObject *, PyObject *, PyObject *);
276PyAPI_FUNC(int) PyObject_HasAttr(PyObject *, PyObject *);
277PyAPI_FUNC(PyObject *) PyObject_SelfIter(PyObject *);
278PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *);
279PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *, PyObject *, PyObject *);
280#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
281PyAPI_FUNC(int) PyObject_GenericSetDict(PyObject *, PyObject *, void *);
282#endif
283PyAPI_FUNC(Py_hash_t) PyObject_Hash(PyObject *);
284PyAPI_FUNC(Py_hash_t) PyObject_HashNotImplemented(PyObject *);
285PyAPI_FUNC(int) PyObject_IsTrue(PyObject *);
286PyAPI_FUNC(int) PyObject_Not(PyObject *);
287PyAPI_FUNC(int) PyCallable_Check(PyObject *);
288PyAPI_FUNC(void) PyObject_ClearWeakRefs(PyObject *);
289
290/* PyObject_Dir(obj) acts like Python builtins.dir(obj), returning a
291 list of strings. PyObject_Dir(NULL) is like builtins.dir(),
292 returning the names of the current locals. In this case, if there are
293 no current locals, NULL is returned, and PyErr_Occurred() is false.
294*/
295PyAPI_FUNC(PyObject *) PyObject_Dir(PyObject *);
296
297
298/* Helpers for printing recursive container types */
299PyAPI_FUNC(int) Py_ReprEnter(PyObject *);
300PyAPI_FUNC(void) Py_ReprLeave(PyObject *);
301
302/* Flag bits for printing: */
303#define Py_PRINT_RAW 1 /* No string quotes etc. */
304
305/*
306Type flags (tp_flags)
307
308These flags are used to change expected features and behavior for a
309particular type.
310
311Arbitration of the flag bit positions will need to be coordinated among
312all extension writers who publicly release their extensions (this will
313be fewer than you might expect!).
314
315Most flags were removed as of Python 3.0 to make room for new flags. (Some
316flags are not for backwards compatibility but to indicate the presence of an
317optional feature; these flags remain of course.)
318
319Type definitions should use Py_TPFLAGS_DEFAULT for their tp_flags value.
320
321Code can use PyType_HasFeature(type_ob, flag_value) to test whether the
322given type object has a specified feature.
323*/
324
325#ifndef Py_LIMITED_API
326/* Set if instances of the type object are treated as sequences for pattern matching */
327#define Py_TPFLAGS_SEQUENCE (1 << 5)
328/* Set if instances of the type object are treated as mappings for pattern matching */
329#define Py_TPFLAGS_MAPPING (1 << 6)
330#endif
331
332/* Disallow creating instances of the type: set tp_new to NULL and don't create
333 * the "__new__" key in the type dictionary. */
334#define Py_TPFLAGS_DISALLOW_INSTANTIATION (1UL << 7)
335
336/* Set if the type object is immutable: type attributes cannot be set nor deleted */
337#define Py_TPFLAGS_IMMUTABLETYPE (1UL << 8)
338
339/* Set if the type object is dynamically allocated */
340#define Py_TPFLAGS_HEAPTYPE (1UL << 9)
341
342/* Set if the type allows subclassing */
343#define Py_TPFLAGS_BASETYPE (1UL << 10)
344
345/* Set if the type implements the vectorcall protocol (PEP 590) */
346#ifndef Py_LIMITED_API
347#define Py_TPFLAGS_HAVE_VECTORCALL (1UL << 11)
348// Backwards compatibility alias for API that was provisional in Python 3.8
349#define _Py_TPFLAGS_HAVE_VECTORCALL Py_TPFLAGS_HAVE_VECTORCALL
350#endif
351
352/* Set if the type is 'ready' -- fully initialized */
353#define Py_TPFLAGS_READY (1UL << 12)
354
355/* Set while the type is being 'readied', to prevent recursive ready calls */
356#define Py_TPFLAGS_READYING (1UL << 13)
357
358/* Objects support garbage collection (see objimpl.h) */
359#define Py_TPFLAGS_HAVE_GC (1UL << 14)
360
361/* These two bits are preserved for Stackless Python, next after this is 17 */
362#ifdef STACKLESS
363#define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION (3UL << 15)
364#else
365#define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION 0
366#endif
367
368/* Objects behave like an unbound method */
369#define Py_TPFLAGS_METHOD_DESCRIPTOR (1UL << 17)
370
371/* Object has up-to-date type attribute cache */
372#define Py_TPFLAGS_VALID_VERSION_TAG (1UL << 19)
373
374/* Type is abstract and cannot be instantiated */
375#define Py_TPFLAGS_IS_ABSTRACT (1UL << 20)
376
377// This undocumented flag gives certain built-ins their unique pattern-matching
378// behavior, which allows a single positional subpattern to match against the
379// subject itself (rather than a mapped attribute on it):
380#define _Py_TPFLAGS_MATCH_SELF (1UL << 22)
381
382/* These flags are used to determine if a type is a subclass. */
383#define Py_TPFLAGS_LONG_SUBCLASS (1UL << 24)
384#define Py_TPFLAGS_LIST_SUBCLASS (1UL << 25)
385#define Py_TPFLAGS_TUPLE_SUBCLASS (1UL << 26)
386#define Py_TPFLAGS_BYTES_SUBCLASS (1UL << 27)
387#define Py_TPFLAGS_UNICODE_SUBCLASS (1UL << 28)
388#define Py_TPFLAGS_DICT_SUBCLASS (1UL << 29)
389#define Py_TPFLAGS_BASE_EXC_SUBCLASS (1UL << 30)
390#define Py_TPFLAGS_TYPE_SUBCLASS (1UL << 31)
391
392#define Py_TPFLAGS_DEFAULT ( \
393 Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \
394 0)
395
396/* NOTE: Some of the following flags reuse lower bits (removed as part of the
397 * Python 3.0 transition). */
398
399/* The following flags are kept for compatibility; in previous
400 * versions they indicated presence of newer tp_* fields on the
401 * type struct.
402 * Starting with 3.8, binary compatibility of C extensions across
403 * feature releases of Python is not supported anymore (except when
404 * using the stable ABI, in which all classes are created dynamically,
405 * using the interpreter's memory layout.)
406 * Note that older extensions using the stable ABI set these flags,
407 * so the bits must not be repurposed.
408 */
409#define Py_TPFLAGS_HAVE_FINALIZE (1UL << 0)
410#define Py_TPFLAGS_HAVE_VERSION_TAG (1UL << 18)
411
412
413/*
414The macros Py_INCREF(op) and Py_DECREF(op) are used to increment or decrement
415reference counts. Py_DECREF calls the object's deallocator function when
416the refcount falls to 0; for
417objects that don't contain references to other objects or heap memory
418this can be the standard function free(). Both macros can be used
419wherever a void expression is allowed. The argument must not be a
420NULL pointer. If it may be NULL, use Py_XINCREF/Py_XDECREF instead.
421The macro _Py_NewReference(op) initialize reference counts to 1, and
422in special builds (Py_REF_DEBUG, Py_TRACE_REFS) performs additional
423bookkeeping appropriate to the special build.
424
425We assume that the reference count field can never overflow; this can
426be proven when the size of the field is the same as the pointer size, so
427we ignore the possibility. Provided a C int is at least 32 bits (which
428is implicitly assumed in many parts of this code), that's enough for
429about 2**31 references to an object.
430
431XXX The following became out of date in Python 2.2, but I'm not sure
432XXX what the full truth is now. Certainly, heap-allocated type objects
433XXX can and should be deallocated.
434Type objects should never be deallocated; the type pointer in an object
435is not considered to be a reference to the type object, to save
436complications in the deallocation function. (This is actually a
437decision that's up to the implementer of each new type so if you want,
438you can count such references to the type object.)
439*/
440
441#ifdef Py_REF_DEBUG
442PyAPI_DATA(Py_ssize_t) _Py_RefTotal;
443PyAPI_FUNC(void) _Py_NegativeRefcount(const char *filename, int lineno,
444 PyObject *op);
445#endif /* Py_REF_DEBUG */
446
447PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
448
449/*
450These are provided as conveniences to Python runtime embedders, so that
451they can have object code that is not dependent on Python compilation flags.
452*/
453PyAPI_FUNC(void) Py_IncRef(PyObject *);
454PyAPI_FUNC(void) Py_DecRef(PyObject *);
455
456// Similar to Py_IncRef() and Py_DecRef() but the argument must be non-NULL.
457// Private functions used by Py_INCREF() and Py_DECREF().
458PyAPI_FUNC(void) _Py_IncRef(PyObject *);
459PyAPI_FUNC(void) _Py_DecRef(PyObject *);
460
461static inline void _Py_INCREF(PyObject *op)
462{
463#if defined(Py_REF_DEBUG) && defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030A0000
464 // Stable ABI for Python 3.10 built in debug mode.
465 _Py_IncRef(op);
466#else
467 // Non-limited C API and limited C API for Python 3.9 and older access
468 // directly PyObject.ob_refcnt.
469#ifdef Py_REF_DEBUG
470 _Py_RefTotal++;
471#endif
472 op->ob_refcnt++;
473#endif
474}
475#define Py_INCREF(op) _Py_INCREF(_PyObject_CAST(op))
476
477static inline void _Py_DECREF(
478#if defined(Py_REF_DEBUG) && !(defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030A0000)
479 const char *filename, int lineno,
480#endif
481 PyObject *op)
482{
483#if defined(Py_REF_DEBUG) && defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030A0000
484 // Stable ABI for Python 3.10 built in debug mode.
485 _Py_DecRef(op);
486#else
487 // Non-limited C API and limited C API for Python 3.9 and older access
488 // directly PyObject.ob_refcnt.
489#ifdef Py_REF_DEBUG
490 _Py_RefTotal--;
491#endif
492 if (--op->ob_refcnt != 0) {
493#ifdef Py_REF_DEBUG
494 if (op->ob_refcnt < 0) {
495 _Py_NegativeRefcount(filename, lineno, op);
496 }
497#endif
498 }
499 else {
500 _Py_Dealloc(op);
501 }
502#endif
503}
504#if defined(Py_REF_DEBUG) && !(defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030A0000)
505# define Py_DECREF(op) _Py_DECREF(__FILE__, __LINE__, _PyObject_CAST(op))
506#else
507# define Py_DECREF(op) _Py_DECREF(_PyObject_CAST(op))
508#endif
509
510
511/* Safely decref `op` and set `op` to NULL, especially useful in tp_clear
512 * and tp_dealloc implementations.
513 *
514 * Note that "the obvious" code can be deadly:
515 *
516 * Py_XDECREF(op);
517 * op = NULL;
518 *
519 * Typically, `op` is something like self->containee, and `self` is done
520 * using its `containee` member. In the code sequence above, suppose
521 * `containee` is non-NULL with a refcount of 1. Its refcount falls to
522 * 0 on the first line, which can trigger an arbitrary amount of code,
523 * possibly including finalizers (like __del__ methods or weakref callbacks)
524 * coded in Python, which in turn can release the GIL and allow other threads
525 * to run, etc. Such code may even invoke methods of `self` again, or cause
526 * cyclic gc to trigger, but-- oops! --self->containee still points to the
527 * object being torn down, and it may be in an insane state while being torn
528 * down. This has in fact been a rich historic source of miserable (rare &
529 * hard-to-diagnose) segfaulting (and other) bugs.
530 *
531 * The safe way is:
532 *
533 * Py_CLEAR(op);
534 *
535 * That arranges to set `op` to NULL _before_ decref'ing, so that any code
536 * triggered as a side-effect of `op` getting torn down no longer believes
537 * `op` points to a valid object.
538 *
539 * There are cases where it's safe to use the naive code, but they're brittle.
540 * For example, if `op` points to a Python integer, you know that destroying
541 * one of those can't cause problems -- but in part that relies on that
542 * Python integers aren't currently weakly referencable. Best practice is
543 * to use Py_CLEAR() even if you can't think of a reason for why you need to.
544 */
545#define Py_CLEAR(op) \
546 do { \
547 PyObject *_py_tmp = _PyObject_CAST(op); \
548 if (_py_tmp != NULL) { \
549 (op) = NULL; \
550 Py_DECREF(_py_tmp); \
551 } \
552 } while (0)
553
554/* Function to use in case the object pointer can be NULL: */
555static inline void _Py_XINCREF(PyObject *op)
556{
557 if (op != NULL) {
558 Py_INCREF(op);
559 }
560}
561
562#define Py_XINCREF(op) _Py_XINCREF(_PyObject_CAST(op))
563
564static inline void _Py_XDECREF(PyObject *op)
565{
566 if (op != NULL) {
567 Py_DECREF(op);
568 }
569}
570
571#define Py_XDECREF(op) _Py_XDECREF(_PyObject_CAST(op))
572
573// Create a new strong reference to an object:
574// increment the reference count of the object and return the object.
575PyAPI_FUNC(PyObject*) Py_NewRef(PyObject *obj);
576
577// Similar to Py_NewRef(), but the object can be NULL.
578PyAPI_FUNC(PyObject*) Py_XNewRef(PyObject *obj);
579
580static inline PyObject* _Py_NewRef(PyObject *obj)
581{
582 Py_INCREF(obj);
583 return obj;
584}
585
586static inline PyObject* _Py_XNewRef(PyObject *obj)
587{
588 Py_XINCREF(obj);
589 return obj;
590}
591
592// Py_NewRef() and Py_XNewRef() are exported as functions for the stable ABI.
593// Names overridden with macros by static inline functions for best
594// performances.
595#define Py_NewRef(obj) _Py_NewRef(_PyObject_CAST(obj))
596#define Py_XNewRef(obj) _Py_XNewRef(_PyObject_CAST(obj))
597
598
599/*
600_Py_NoneStruct is an object of undefined type which can be used in contexts
601where NULL (nil) is not suitable (since NULL often means 'error').
602
603Don't forget to apply Py_INCREF() when returning this value!!!
604*/
605PyAPI_DATA(PyObject) _Py_NoneStruct; /* Don't use this directly */
606#define Py_None (&_Py_NoneStruct)
607
608// Test if an object is the None singleton, the same as "x is None" in Python.
609PyAPI_FUNC(int) Py_IsNone(PyObject *x);
610#define Py_IsNone(x) Py_Is((x), Py_None)
611
612/* Macro for returning Py_None from a function */
613#define Py_RETURN_NONE return Py_NewRef(Py_None)
614
615/*
616Py_NotImplemented is a singleton used to signal that an operation is
617not implemented for a given type combination.
618*/
619PyAPI_DATA(PyObject) _Py_NotImplementedStruct; /* Don't use this directly */
620#define Py_NotImplemented (&_Py_NotImplementedStruct)
621
622/* Macro for returning Py_NotImplemented from a function */
623#define Py_RETURN_NOTIMPLEMENTED return Py_NewRef(Py_NotImplemented)
624
625/* Rich comparison opcodes */
626#define Py_LT 0
627#define Py_LE 1
628#define Py_EQ 2
629#define Py_NE 3
630#define Py_GT 4
631#define Py_GE 5
632
633#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000
634/* Result of calling PyIter_Send */
635typedef enum {
636 PYGEN_RETURN = 0,
637 PYGEN_ERROR = -1,
638 PYGEN_NEXT = 1,
639} PySendResult;
640#endif
641
642/*
643 * Macro for implementing rich comparisons
644 *
645 * Needs to be a macro because any C-comparable type can be used.
646 */
647#define Py_RETURN_RICHCOMPARE(val1, val2, op) \
648 do { \
649 switch (op) { \
650 case Py_EQ: if ((val1) == (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
651 case Py_NE: if ((val1) != (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
652 case Py_LT: if ((val1) < (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
653 case Py_GT: if ((val1) > (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
654 case Py_LE: if ((val1) <= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
655 case Py_GE: if ((val1) >= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
656 default: \
657 Py_UNREACHABLE(); \
658 } \
659 } while (0)
660
661
662/*
663More conventions
664================
665
666Argument Checking
667-----------------
668
669Functions that take objects as arguments normally don't check for nil
670arguments, but they do check the type of the argument, and return an
671error if the function doesn't apply to the type.
672
673Failure Modes
674-------------
675
676Functions may fail for a variety of reasons, including running out of
677memory. This is communicated to the caller in two ways: an error string
678is set (see errors.h), and the function result differs: functions that
679normally return a pointer return NULL for failure, functions returning
680an integer return -1 (which could be a legal return value too!), and
681other functions return 0 for success and -1 for failure.
682Callers should always check for errors before using the result. If
683an error was set, the caller must either explicitly clear it, or pass
684the error on to its caller.
685
686Reference Counts
687----------------
688
689It takes a while to get used to the proper usage of reference counts.
690
691Functions that create an object set the reference count to 1; such new
692objects must be stored somewhere or destroyed again with Py_DECREF().
693Some functions that 'store' objects, such as PyTuple_SetItem() and
694PyList_SetItem(),
695don't increment the reference count of the object, since the most
696frequent use is to store a fresh object. Functions that 'retrieve'
697objects, such as PyTuple_GetItem() and PyDict_GetItemString(), also
698don't increment
699the reference count, since most frequently the object is only looked at
700quickly. Thus, to retrieve an object and store it again, the caller
701must call Py_INCREF() explicitly.
702
703NOTE: functions that 'consume' a reference count, like
704PyList_SetItem(), consume the reference even if the object wasn't
705successfully stored, to simplify error handling.
706
707It seems attractive to make other functions that take an object as
708argument consume a reference count; however, this may quickly get
709confusing (even the current practice is already confusing). Consider
710it carefully, it may save lots of calls to Py_INCREF() and Py_DECREF() at
711times.
712*/
713
714#ifndef Py_LIMITED_API
715# define Py_CPYTHON_OBJECT_H
716# include "cpython/object.h"
717# undef Py_CPYTHON_OBJECT_H
718#endif
719
720
721static inline int
722PyType_HasFeature(PyTypeObject *type, unsigned long feature)
723{
724 unsigned long flags;
725#ifdef Py_LIMITED_API
726 // PyTypeObject is opaque in the limited C API
727 flags = PyType_GetFlags(type);
728#else
729 flags = type->tp_flags;
730#endif
731 return ((flags & feature) != 0);
732}
733
734#define PyType_FastSubclass(type, flag) PyType_HasFeature(type, flag)
735
736static inline int _PyType_Check(PyObject *op) {
737 return PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS);
738}
739#define PyType_Check(op) _PyType_Check(_PyObject_CAST(op))
740
741static inline int _PyType_CheckExact(PyObject *op) {
742 return Py_IS_TYPE(op, &PyType_Type);
743}
744#define PyType_CheckExact(op) _PyType_CheckExact(_PyObject_CAST(op))
745
746#ifdef __cplusplus
747}
748#endif
749#endif /* !Py_OBJECT_H */
750