Debian Codegraph @

pypy/module/cpyext/include/object.h

raw symbols SCIP
1 #ifndef Py_OBJECT_H
2 #define Py_OBJECT_H
3
4 #ifdef __cplusplus
5 extern "C" {
6 #endif
7
8 #include "cpyext_object.h"
9 /* Object and type object interface */
10
11 /*
12 Objects are structures allocated on the heap. Special rules apply to
13 the use of objects to ensure they are properly garbage-collected.
14 Objects are never allocated statically or on the stack; they must be
15 accessed through special macros and functions only. (Type objects are
16 exceptions to the first rule; the standard types are represented by
17 statically initialized type objects, although work on type/class unification
18 for Python 2.2 made it possible to have heap-allocated type objects too).
19
20 An object has a 'reference count' that is increased or decreased when a
21 pointer to the object is copied or deleted; when the reference count
22 reaches zero there are no references to the object left and it can be
23 removed from the heap.
24
25 An object has a 'type' that determines what it represents and what kind
26 of data it contains. An object's type is fixed when it is created.
27 Types themselves are represented as objects; an object contains a
28 pointer to the corresponding type object. The type itself has a type
29 pointer pointing to the object representing the type 'type', which
30 contains a pointer to itself!.
31
32 Objects do not float around in memory; once allocated an object keeps
33 the same size and address. Objects that must hold variable-size data
34 can contain pointers to variable-size parts of the object. Not all
35 objects of the same type have the same size; but the size cannot change
36 after allocation. (These restrictions are made so a reference to an
37 object can be simply a pointer -- moving an object would require
38 updating all the pointers, and changing an object's size would require
39 moving it if there was another object right next to it.)
40
41 Objects are always accessed through pointers of the type 'PyObject *'.
42 The type 'PyObject' is a structure that only contains the reference count
43 and the type pointer. The actual memory allocated for an object
44 contains other data that can only be accessed after casting the pointer
45 to a pointer to a longer structure type. This longer type must start
46 with the reference count and type fields; the macro PyObject_HEAD should be
47 used for this (to accommodate for future changes). The implementation
48 of a particular object type can cast the object pointer to the proper
49 type and back.
50
51 A standard interface exists for objects that contain an array of items
52 whose 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. */
66 typedef 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 PyObject *_ob_next; \
72 PyObject *_ob_prev;
73
74 #define _PyObject_EXTRA_INIT _Py_NULL, _Py_NULL,
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 /* PyPy adds an extra field here */
85 #define PyObject_HEAD_INIT(type) \
86 { _PyObject_EXTRA_INIT \
87 1, 0, type },
88
89 #define PyVarObject_HEAD_INIT(type, size) \
90 { PyObject_HEAD_INIT(type) size },
91
92 /* PyObject_VAR_HEAD defines the initial segment of all variable-size
93 * container objects. These end with a declaration of an array with 1
94 * element, but enough space is malloc'ed so that the array actually
95 * has room for ob_size elements. Note that ob_size is an element count,
96 * not necessarily a byte count.
97 */
98 #define PyObject_VAR_HEAD PyVarObject ob_base;
99 #define Py_INVALID_SIZE (Py_ssize_t)-1
100
101 #ifndef PYPY_VERSION
102 /* Nothing is actually declared to be a PyObject, but every pointer to
103 * a Python object can be cast to a PyObject*. This is inheritance built
104 * by hand. Similarly every pointer to a variable-size Python object can,
105 * in addition, be cast to PyVarObject*.
106 */
107 struct _object {
108 _PyObject_HEAD_EXTRA
109 Py_ssize_t ob_refcnt;
110 PyTypeObject *ob_type;
111 };
112 #endif
113
114 /* Cast argument to PyObject* type. */
115 #define _PyObject_CAST(op) _Py_CAST(PyObject*, (op))
116
117 /* Cast argument to PyVarObject* type. */
118 #define _PyVarObject_CAST(op) _Py_CAST(PyVarObject*, (op))
119
120 static inline Py_ssize_t Py_REFCNT(PyObject *ob) {
121 return ob->ob_refcnt;
122 }
123 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
124 # define Py_REFCNT(ob) Py_REFCNT(_PyObject_CAST(ob))
125 #endif
126
127
128 // bpo-39573: The Py_SET_TYPE() function must be used to set an object type.
129 static inline PyTypeObject* Py_TYPE(PyObject *ob) {
130 return ob->ob_type;
131 }
132 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
133 # define Py_TYPE(ob) Py_TYPE(_PyObject_CAST(ob))
134 #endif
135
136 // bpo-39573: The Py_SET_SIZE() function must be used to set an object size.
137 static inline Py_ssize_t Py_SIZE(PyObject *ob) {
138 PyVarObject *var_ob = _PyVarObject_CAST(ob);
139 return var_ob->ob_size;
140 }
141 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
142 # define Py_SIZE(ob) Py_SIZE(_PyObject_CAST(ob))
143 #endif
144
145
146 static inline int Py_IS_TYPE(PyObject *ob, PyTypeObject *type) {
147 return Py_TYPE(ob) == type;
148 }
149 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
150 # define Py_IS_TYPE(ob, type) Py_IS_TYPE(_PyObject_CAST(ob), type)
151 #endif
152
153
154 static inline void Py_SET_REFCNT(PyObject *ob, Py_ssize_t refcnt) {
155 ob->ob_refcnt = refcnt;
156 }
157 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
158 # define Py_SET_REFCNT(ob, refcnt) Py_SET_REFCNT(_PyObject_CAST(ob), refcnt)
159 #endif
160
161
162 static inline void Py_SET_TYPE(PyObject *ob, PyTypeObject *type) {
163 ob->ob_type = type;
164 }
165 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
166 # define Py_SET_TYPE(ob, type) Py_SET_TYPE(_PyObject_CAST(ob), type)
167 #endif
168
169
170 static inline void Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size) {
171 ob->ob_size = size;
172 }
173 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
174 # define Py_SET_SIZE(ob, size) Py_SET_SIZE(_PyVarObject_CAST(ob), size)
175 #endif
176
177 #ifndef PYPY_VERSION
178 /* Moved to cpyext_object.h so they can be parsed */
179
180 /*
181 Type objects contain a string containing the type name (to help somewhat
182 in debugging), the allocation parameters (see PyObject_New() and
183 PyObject_NewVar()),
184 and methods for accessing objects of the type. Methods are optional, a
185 nil pointer meaning that particular kind of access is not available for
186 this type. The Py_DECREF() macro uses the tp_dealloc method without
187 checking for a nil pointer; it should always be implemented except if
188 the implementation can guarantee that the reference count will never
189 reach zero (e.g., for statically allocated type objects).
190
191 NB: the methods for certain type groups are now contained in separate
192 method blocks.
193 */
194
195 typedef PyObject * (*unaryfunc)(PyObject *);
196 typedef PyObject * (*binaryfunc)(PyObject *, PyObject *);
197 typedef PyObject * (*ternaryfunc)(PyObject *, PyObject *, PyObject *);
198 typedef int (*inquiry)(PyObject *);
199 typedef Py_ssize_t (*lenfunc)(PyObject *);
200 typedef PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t);
201 typedef PyObject *(*ssizessizeargfunc)(PyObject *, Py_ssize_t, Py_ssize_t);
202 typedef int(*ssizeobjargproc)(PyObject *, Py_ssize_t, PyObject *);
203 typedef int(*ssizessizeobjargproc)(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);
204 typedef int(*objobjargproc)(PyObject *, PyObject *, PyObject *);
205
206 typedef int (*objobjproc)(PyObject *, PyObject *);
207 typedef int (*visitproc)(PyObject *, void *);
208 typedef int (*traverseproc)(PyObject *, visitproc, void *);
209
210
211 typedef void (*freefunc)(void *);
212 typedef void (*destructor)(PyObject *);
213 typedef PyObject *(*getattrfunc)(PyObject *, char *);
214 typedef PyObject *(*getattrofunc)(PyObject *, PyObject *);
215 typedef int (*setattrfunc)(PyObject *, char *, PyObject *);
216 typedef int (*setattrofunc)(PyObject *, PyObject *, PyObject *);
217 typedef PyObject *(*reprfunc)(PyObject *);
218 typedef Py_hash_t (*hashfunc)(PyObject *);
219 typedef PyObject *(*richcmpfunc) (PyObject *, PyObject *, int);
220 typedef PyObject *(*getiterfunc) (PyObject *);
221 typedef PyObject *(*iternextfunc) (PyObject *);
222 typedef PyObject *(*descrgetfunc) (PyObject *, PyObject *, PyObject *);
223 typedef int (*descrsetfunc) (PyObject *, PyObject *, PyObject *);
224 typedef int (*initproc)(PyObject *, PyObject *, PyObject *);
225 typedef PyObject *(*newfunc)(PyTypeObject *, PyObject *, PyObject *);
226 typedef PyObject *(*allocfunc)(PyTypeObject *, Py_ssize_t);
227
228 typedef struct{
229 int slot; /* slot id, see below */
230 void *pfunc; /* function pointer */
231 } PyType_Slot;
232
233 typedef struct{
234 const char* name;
235 int basicsize;
236 int itemsize;
237 unsigned int flags;
238 PyType_Slot *slots; /* terminated by slot==0. */
239 } PyType_Spec;
240 #endif
241
242 PyAPI_FUNC(PyObject*) PyType_FromSpec(PyType_Spec*);
243 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
244 PyAPI_FUNC(PyObject*) PyType_FromSpecWithBases(PyType_Spec*, PyObject*);
245 #endif
246 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000
247 PyAPI_FUNC(void*) PyType_GetSlot(PyTypeObject*, int);
248 #endif
249 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03090000
250 PyAPI_FUNC(PyObject*) PyType_FromModuleAndSpec(PyObject *, PyType_Spec *, PyObject *);
251 PyAPI_FUNC(PyObject *) PyType_GetModule(PyTypeObject *);
252 PyAPI_FUNC(void *) PyType_GetModuleState(PyTypeObject *);
253 #endif
254 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030B0000
255 PyAPI_FUNC(PyObject *) PyType_GetName(PyTypeObject *);
256 PyAPI_FUNC(PyObject *) PyType_GetQualName(PyTypeObject *);
257 #endif
258
259 /* Generic type check */
260 PyAPI_FUNC(int) PyType_IsSubtype(PyTypeObject *, PyTypeObject *);
261
262 static inline int PyObject_TypeCheck(PyObject *ob, PyTypeObject *type) {
263 return Py_IS_TYPE(ob, type) || PyType_IsSubtype(Py_TYPE(ob), type);
264 }
265 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
266 # define PyObject_TypeCheck(ob, type) PyObject_TypeCheck(_PyObject_CAST(ob), type)
267 #endif
268
269 PyAPI_DATA(PyTypeObject) PyType_Type; /* built-in 'type' */
270 PyAPI_DATA(PyTypeObject) PyBaseObject_Type; /* built-in 'object' */
271 PyAPI_DATA(PyTypeObject) PySuper_Type; /* built-in 'super' */
272
273 PyAPI_FUNC(unsigned long) PyType_GetFlags(PyTypeObject*);
274
275 PyAPI_FUNC(int) PyType_Ready(PyTypeObject *);
276 PyAPI_FUNC(PyObject *) PyType_GenericAlloc(PyTypeObject *, Py_ssize_t);
277 PyAPI_FUNC(PyObject *) PyType_GenericNew(PyTypeObject *,
278 PyObject *, PyObject *);
279 PyAPI_FUNC(unsigned int) PyType_ClearCache(void);
280 PyAPI_FUNC(void) PyType_Modified(PyTypeObject *);
281
282 /* Generic operations on objects */
283 PyAPI_FUNC(PyObject *) PyObject_Repr(PyObject *);
284 PyAPI_FUNC(PyObject *) PyObject_Str(PyObject *);
285 PyAPI_FUNC(PyObject *) PyObject_ASCII(PyObject *);
286 PyAPI_FUNC(PyObject *) PyObject_Bytes(PyObject *);
287 PyAPI_FUNC(PyObject *) PyObject_RichCompare(PyObject *, PyObject *, int);
288 PyAPI_FUNC(int) PyObject_RichCompareBool(PyObject *, PyObject *, int);
289 PyAPI_FUNC(PyObject *) PyObject_GetAttrString(PyObject *, const char *);
290 PyAPI_FUNC(int) PyObject_SetAttrString(PyObject *, const char *, PyObject *);
291 PyAPI_FUNC(int) PyObject_HasAttrString(PyObject *, const char *);
292 PyAPI_FUNC(PyObject *) PyObject_GetAttr(PyObject *, PyObject *);
293 PyAPI_FUNC(int) PyObject_SetAttr(PyObject *, PyObject *, PyObject *);
294 PyAPI_FUNC(int) PyObject_HasAttr(PyObject *, PyObject *);
295 PyAPI_FUNC(PyObject *) PyObject_SelfIter(PyObject *);
296 PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *);
297 PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *, PyObject *, PyObject *);
298 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
299 PyAPI_FUNC(int) PyObject_GenericSetDict(PyObject *, PyObject *, void *);
300 #endif
301 PyAPI_FUNC(Py_hash_t) PyObject_Hash(PyObject *);
302 PyAPI_FUNC(Py_hash_t) PyObject_HashNotImplemented(PyObject *);
303 PyAPI_FUNC(int) PyObject_IsTrue(PyObject *);
304 PyAPI_FUNC(int) PyObject_Not(PyObject *);
305 PyAPI_FUNC(int) PyCallable_Check(PyObject *);
306 PyAPI_FUNC(void) PyObject_ClearWeakRefs(PyObject *);
307
308 /* PyObject_Dir(obj) acts like Python builtins.dir(obj), returning a
309 list of strings. PyObject_Dir(NULL) is like builtins.dir(),
310 returning the names of the current locals. In this case, if there are
311 no current locals, NULL is returned, and PyErr_Occurred() is false.
312 */
313 PyAPI_FUNC(PyObject *) PyObject_Dir(PyObject *);
314
315
316 /* Helpers for printing recursive container types */
317 PyAPI_FUNC(int) Py_ReprEnter(PyObject *);
318 PyAPI_FUNC(void) Py_ReprLeave(PyObject *);
319
320 /* Flag bits for printing: */
321 #define Py_PRINT_RAW 1 /* No string quotes etc. */
322
323 /*
324 Type flags (tp_flags)
325
326 These flags are used to change expected features and behavior for a
327 particular type.
328
329 Arbitration of the flag bit positions will need to be coordinated among
330 all extension writers who publicly release their extensions (this will
331 be fewer than you might expect!).
332
333 Most flags were removed as of Python 3.0 to make room for new flags. (Some
334 flags are not for backwards compatibility but to indicate the presence of an
335 optional feature; these flags remain of course.)
336
337 Type definitions should use Py_TPFLAGS_DEFAULT for their tp_flags value.
338
339 Code can use PyType_HasFeature(type_ob, flag_value) to test whether the
340 given type object has a specified feature.
341 */
342
343 #ifndef Py_LIMITED_API
344
345 /* Track types initialized using _PyStaticType_InitBuiltin(). */
346 #define _Py_TPFLAGS_STATIC_BUILTIN (1 << 1)
347
348 /* The values array is placed inline directly after the rest of
349 * the object. Implies Py_TPFLAGS_HAVE_GC.
350 */
351 #define Py_TPFLAGS_INLINE_VALUES (1 << 2)
352
353 /* Placement of weakref pointers are managed by the VM, not by the type.
354 * The VM will automatically set tp_weaklistoffset.
355 */
356 #define Py_TPFLAGS_MANAGED_WEAKREF (1 << 3)
357
358 /* Placement of dict (and values) pointers are managed by the VM, not by the type.
359 * The VM will automatically set tp_dictoffset. Should not be used for variable sized
360 * classes, such as classes that extend tuple.
361 */
362 #define Py_TPFLAGS_MANAGED_DICT (1 << 4)
363
364 /* Set if instances of the type object are treated as sequences for pattern matching */
365 #define Py_TPFLAGS_SEQUENCE (1 << 5)
366 /* Set if instances of the type object are treated as mappings for pattern matching */
367 #define Py_TPFLAGS_MAPPING (1 << 6)
368 #endif
369
370 /* Disallow creating instances of the type: set tp_new to NULL and don't create
371 * the "__new__" key in the type dictionary. */
372 #define Py_TPFLAGS_DISALLOW_INSTANTIATION (1UL << 7)
373
374 /* Set if the type object is immutable: type attributes cannot be set nor deleted */
375 #define Py_TPFLAGS_IMMUTABLETYPE (1UL << 8)
376
377 /* Set if the type object is dynamically allocated */
378 #define Py_TPFLAGS_HEAPTYPE (1UL << 9)
379
380 /* Set if the type allows subclassing */
381 #define Py_TPFLAGS_BASETYPE (1UL << 10)
382
383 /* Set if the type implements the vectorcall protocol (PEP 590) */
384 #ifndef Py_LIMITED_API
385 #define Py_TPFLAGS_HAVE_VECTORCALL (1UL << 11)
386 // Backwards compatibility alias for API that was provisional in Python 3.8
387 #define _Py_TPFLAGS_HAVE_VECTORCALL Py_TPFLAGS_HAVE_VECTORCALL
388 #endif
389
390 /* Set if the type is 'ready' -- fully initialized */
391 #define Py_TPFLAGS_READY (1UL << 12)
392
393 /* Set while the type is being 'readied', to prevent recursive ready calls */
394 #define Py_TPFLAGS_READYING (1UL << 13)
395
396 /* Objects support garbage collection (see objimpl.h) */
397 #define Py_TPFLAGS_HAVE_GC (1UL << 14)
398
399 /* These two bits are preserved for Stackless Python, next after this is 17 */
400 #ifdef STACKLESS
401 #define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION (3UL << 15)
402 #else
403 #define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION 0
404 #endif
405
406 /* Objects behave like an unbound method */
407 #define Py_TPFLAGS_METHOD_DESCRIPTOR (1UL << 17)
408
409 /* Object has up-to-date type attribute cache */
410 #define Py_TPFLAGS_VALID_VERSION_TAG (1UL << 19)
411
412 /* Type is abstract and cannot be instantiated */
413 #define Py_TPFLAGS_IS_ABSTRACT (1UL << 20)
414
415 // This undocumented flag gives certain built-ins their unique pattern-matching
416 // behavior, which allows a single positional subpattern to match against the
417 // subject itself (rather than a mapped attribute on it):
418 #define _Py_TPFLAGS_MATCH_SELF (1UL << 22)
419
420 /* These flags are used to determine if a type is a subclass. */
421 #define Py_TPFLAGS_LONG_SUBCLASS (1UL << 24)
422 #define Py_TPFLAGS_LIST_SUBCLASS (1UL << 25)
423 #define Py_TPFLAGS_TUPLE_SUBCLASS (1UL << 26)
424 #define Py_TPFLAGS_BYTES_SUBCLASS (1UL << 27)
425 #define Py_TPFLAGS_UNICODE_SUBCLASS (1UL << 28)
426 #define Py_TPFLAGS_DICT_SUBCLASS (1UL << 29)
427 #define Py_TPFLAGS_BASE_EXC_SUBCLASS (1UL << 30)
428 #define Py_TPFLAGS_TYPE_SUBCLASS (1UL << 31)
429
430 #define Py_TPFLAGS_DEFAULT ( \
431 Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \
432 0)
433
434 /* NOTE: Some of the following flags reuse lower bits (removed as part of the
435 * Python 3.0 transition). */
436
437 /* The following flags are kept for compatibility; in previous
438 * versions they indicated presence of newer tp_* fields on the
439 * type struct.
440 * Starting with 3.8, binary compatibility of C extensions across
441 * feature releases of Python is not supported anymore (except when
442 * using the stable ABI, in which all classes are created dynamically,
443 * using the interpreter's memory layout.)
444 * Note that older extensions using the stable ABI set these flags,
445 * so the bits must not be repurposed.
446 */
447 #define Py_TPFLAGS_HAVE_FINALIZE (1UL << 0)
448 #define Py_TPFLAGS_HAVE_VERSION_TAG (1UL << 18)
449
450
451 /*
452 The macros Py_INCREF(op) and Py_DECREF(op) are used to increment or decrement
453 reference counts. Py_DECREF calls the object's deallocator function when
454 the refcount falls to 0; for
455 objects that don't contain references to other objects or heap memory
456 this can be the standard function free(). Both macros can be used
457 wherever a void expression is allowed. The argument must not be a
458 NULL pointer. If it may be NULL, use Py_XINCREF/Py_XDECREF instead.
459 The macro _Py_NewReference(op) initialize reference counts to 1, and
460 in special builds (Py_REF_DEBUG, Py_TRACE_REFS) performs additional
461 bookkeeping appropriate to the special build.
462
463 We assume that the reference count field can never overflow; this can
464 be proven when the size of the field is the same as the pointer size, so
465 we ignore the possibility. Provided a C int is at least 32 bits (which
466 is implicitly assumed in many parts of this code), that's enough for
467 about 2**31 references to an object.
468
469 XXX The following became out of date in Python 2.2, but I'm not sure
470 XXX what the full truth is now. Certainly, heap-allocated type objects
471 XXX can and should be deallocated.
472 Type objects should never be deallocated; the type pointer in an object
473 is not considered to be a reference to the type object, to save
474 complications in the deallocation function. (This is actually a
475 decision that's up to the implementer of each new type so if you want,
476 you can count such references to the type object.)
477 */
478
479 #ifdef Py_REF_DEBUG
480 PyAPI_DATA(Py_ssize_t) _Py_RefTotal;
481 PyAPI_FUNC(void) _Py_NegativeRefcount(const char *filename, int lineno,
482 PyObject *op);
483 #endif /* Py_REF_DEBUG */
484
485 PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
486
487 /*
488 These are provided as conveniences to Python runtime embedders, so that
489 they can have object code that is not dependent on Python compilation flags.
490 */
491 PyAPI_FUNC(void) Py_IncRef(PyObject *);
492 PyAPI_FUNC(void) Py_DecRef(PyObject *);
493
494 // Similar to Py_IncRef() and Py_DecRef() but the argument must be non-NULL.
495 // Private functions used by Py_INCREF() and Py_DECREF().
496 PyAPI_FUNC(void) _Py_IncRef(PyObject *);
497 PyAPI_FUNC(void) _Py_DecRef(PyObject *);
498
499 static inline void Py_INCREF(PyObject *op)
500 {
501 #if defined(Py_REF_DEBUG) && defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030A0000
502 // Stable ABI for Python 3.10 built in debug mode.
503 _Py_IncRef(op);
504 #else
505 // Non-limited C API and limited C API for Python 3.9 and older access
506 // directly PyObject.ob_refcnt.
507 #ifdef Py_REF_DEBUG
508 _Py_RefTotal++;
509 #endif
510 op->ob_refcnt++;
511 #endif
512 }
513 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
514 # define Py_INCREF(op) Py_INCREF(_PyObject_CAST(op))
515 #endif
516
517
518 #if defined(Py_REF_DEBUG) && defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030A0000
519 // Stable ABI for limited C API version 3.10 of Python debug build
520 static inline void Py_DECREF(PyObject *op) {
521 _Py_DecRef(op);
522 }
523 #define Py_DECREF(op) Py_DECREF(_PyObject_CAST(op))
524
525 #elif defined(Py_REF_DEBUG)
526 static inline void Py_DECREF(const char *filename, int lineno, PyObject *op)
527 {
528 _Py_RefTotal--;
529 if (--op->ob_refcnt != 0) {
530 if (op->ob_refcnt < 0) {
531 _Py_NegativeRefcount(filename, lineno, op);
532 }
533 }
534 else {
535 _Py_Dealloc(op);
536 }
537 }
538 #define Py_DECREF(op) Py_DECREF(__FILE__, __LINE__, _PyObject_CAST(op))
539
540 #else
541 static inline void Py_DECREF(PyObject *op)
542 {
543 // Non-limited C API and limited C API for Python 3.9 and older access
544 // directly PyObject.ob_refcnt.
545 if (--op->ob_refcnt == 0) {
546 _Py_Dealloc(op);
547 }
548 }
549 #define Py_DECREF(op) Py_DECREF(_PyObject_CAST(op))
550 #endif
551
552
553 /* Safely decref `op` and set `op` to NULL, especially useful in tp_clear
554 * and tp_dealloc implementations.
555 *
556 * Note that "the obvious" code can be deadly:
557 *
558 * Py_XDECREF(op);
559 * op = NULL;
560 *
561 * Typically, `op` is something like self->containee, and `self` is done
562 * using its `containee` member. In the code sequence above, suppose
563 * `containee` is non-NULL with a refcount of 1. Its refcount falls to
564 * 0 on the first line, which can trigger an arbitrary amount of code,
565 * possibly including finalizers (like __del__ methods or weakref callbacks)
566 * coded in Python, which in turn can release the GIL and allow other threads
567 * to run, etc. Such code may even invoke methods of `self` again, or cause
568 * cyclic gc to trigger, but-- oops! --self->containee still points to the
569 * object being torn down, and it may be in an insane state while being torn
570 * down. This has in fact been a rich historic source of miserable (rare &
571 * hard-to-diagnose) segfaulting (and other) bugs.
572 *
573 * The safe way is:
574 *
575 * Py_CLEAR(op);
576 *
577 * That arranges to set `op` to NULL _before_ decref'ing, so that any code
578 * triggered as a side-effect of `op` getting torn down no longer believes
579 * `op` points to a valid object.
580 *
581 * There are cases where it's safe to use the naive code, but they're brittle.
582 * For example, if `op` points to a Python integer, you know that destroying
583 * one of those can't cause problems -- but in part that relies on that
584 * Python integers aren't currently weakly referencable. Best practice is
585 * to use Py_CLEAR() even if you can't think of a reason for why you need to.
586 */
587 #define Py_CLEAR(op) \
588 do { \
589 PyObject *_py_tmp = _PyObject_CAST(op); \
590 if (_py_tmp != NULL) { \
591 (op) = NULL; \
592 Py_DECREF(_py_tmp); \
593 } \
594 } while (0)
595
596 /* Function to use in case the object pointer can be NULL: */
597 static inline void Py_XINCREF(PyObject *op)
598 {
599 if (op != _Py_NULL) {
600 Py_INCREF(op);
601 }
602 }
603 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
604 # define Py_XINCREF(op) Py_XINCREF(_PyObject_CAST(op))
605 #endif
606
607 static inline void Py_XDECREF(PyObject *op)
608 {
609 if (op != _Py_NULL) {
610 Py_DECREF(op);
611 }
612 }
613 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
614 # define Py_XDECREF(op) Py_XDECREF(_PyObject_CAST(op))
615 #endif
616
617 // Create a new strong reference to an object:
618 // increment the reference count of the object and return the object.
619 PyAPI_FUNC(PyObject*) Py_NewRef(PyObject *obj);
620
621 // Similar to Py_NewRef(), but the object can be NULL.
622 PyAPI_FUNC(PyObject*) Py_XNewRef(PyObject *obj);
623
624 static inline PyObject* _Py_NewRef(PyObject *obj)
625 {
626 Py_INCREF(obj);
627 return obj;
628 }
629
630 static inline PyObject* _Py_XNewRef(PyObject *obj)
631 {
632 Py_XINCREF(obj);
633 return obj;
634 }
635
636 // Py_NewRef() and Py_XNewRef() are exported as functions for the stable ABI.
637 // Names overridden with macros by static inline functions for best
638 // performances.
639 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
640 # define Py_NewRef(obj) _Py_NewRef(_PyObject_CAST(obj))
641 # define Py_XNewRef(obj) _Py_XNewRef(_PyObject_CAST(obj))
642 #else
643 # define Py_NewRef(obj) _Py_NewRef(obj)
644 # define Py_XNewRef(obj) _Py_XNewRef(obj)
645 #endif
646
647
648 /*
649 _Py_NoneStruct is an object of undefined type which can be used in contexts
650 where NULL (nil) is not suitable (since NULL often means 'error').
651
652 Don't forget to apply Py_INCREF() when returning this value!!!
653 */
654 PyAPI_DATA(PyObject) _Py_NoneStruct; /* Don't use this directly */
655 #define Py_None (&_Py_NoneStruct)
656
657 // Test if an object is the None singleton, the same as "x is None" in Python.
658 PyAPI_FUNC(int) Py_IsNone(PyObject *x);
659 #define Py_IsNone(x) ((x) == Py_None)
660
661 /* Macro for returning Py_None from a function */
662 #define Py_RETURN_NONE return Py_NewRef(Py_None)
663
664 /*
665 Py_NotImplemented is a singleton used to signal that an operation is
666 not implemented for a given type combination.
667 */
668 PyAPI_DATA(PyObject) _Py_NotImplementedStruct; /* Don't use this directly */
669 #define Py_NotImplemented (&_Py_NotImplementedStruct)
670
671 /* Macro for returning Py_NotImplemented from a function */
672 #define Py_RETURN_NOTIMPLEMENTED return Py_NewRef(Py_NotImplemented)
673
674 /* Rich comparison opcodes */
675 /*
676 XXX: Also defined in slotdefs.py
677 */
678 #define Py_LT 0
679 #define Py_LE 1
680 #define Py_EQ 2
681 #define Py_NE 3
682 #define Py_GT 4
683 #define Py_GE 5
684
685
686 /*
687 * Macro for implementing rich comparisons
688 *
689 * Needs to be a macro because any C-comparable type can be used.
690 */
691 #define Py_RETURN_RICHCOMPARE(val1, val2, op) \
692 do { \
693 switch (op) { \
694 case Py_EQ: if ((val1) == (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
695 case Py_NE: if ((val1) != (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
696 case Py_LT: if ((val1) < (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
697 case Py_GT: if ((val1) > (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
698 case Py_LE: if ((val1) <= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
699 case Py_GE: if ((val1) >= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
700 default: \
701 Py_UNREACHABLE(); \
702 } \
703 } while (0)
704
705
706 /*
707 More conventions
708 ================
709
710 Argument Checking
711 -----------------
712
713 Functions that take objects as arguments normally don't check for nil
714 arguments, but they do check the type of the argument, and return an
715 error if the function doesn't apply to the type.
716
717 Failure Modes
718 -------------
719
720 Functions may fail for a variety of reasons, including running out of
721 memory. This is communicated to the caller in two ways: an error string
722 is set (see errors.h), and the function result differs: functions that
723 normally return a pointer return NULL for failure, functions returning
724 an integer return -1 (which could be a legal return value too!), and
725 other functions return 0 for success and -1 for failure.
726 Callers should always check for errors before using the result. If
727 an error was set, the caller must either explicitly clear it, or pass
728 the error on to its caller.
729
730 Reference Counts
731 ----------------
732
733 It takes a while to get used to the proper usage of reference counts.
734
735 Functions that create an object set the reference count to 1; such new
736 objects must be stored somewhere or destroyed again with Py_DECREF().
737 Some functions that 'store' objects, such as PyTuple_SetItem() and
738 PyList_SetItem(),
739 don't increment the reference count of the object, since the most
740 frequent use is to store a fresh object. Functions that 'retrieve'
741 objects, such as PyTuple_GetItem() and PyDict_GetItemString(), also
742 don't increment
743 the reference count, since most frequently the object is only looked at
744 quickly. Thus, to retrieve an object and store it again, the caller
745 must call Py_INCREF() explicitly.
746
747 NOTE: functions that 'consume' a reference count, like
748 PyList_SetItem(), consume the reference even if the object wasn't
749 successfully stored, to simplify error handling.
750
751 It seems attractive to make other functions that take an object as
752 argument consume a reference count; however, this may quickly get
753 confusing (even the current practice is already confusing). Consider
754 it carefully, it may save lots of calls to Py_INCREF() and Py_DECREF() at
755 times.
756 */
757
758 /* CPython has an internal cpython/object.h with the following code */
759
760 /* Py3k buffer interface, adapted for PyPy */
761 /* Flags for getting buffers */
762 #define PyBUF_SIMPLE 0
763 #define PyBUF_WRITABLE 0x0001
764 /* we used to include an E, backwards compatible alias */
765 #define PyBUF_WRITEABLE PyBUF_WRITABLE
766 #define PyBUF_FORMAT 0x0004
767 #define PyBUF_ND 0x0008
768 #define PyBUF_STRIDES (0x0010 | PyBUF_ND)
769 #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES)
770 #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES)
771 #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES)
772 #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES)
773
774 #define PyBUF_CONTIG (PyBUF_ND | PyBUF_WRITABLE)
775 #define PyBUF_CONTIG_RO (PyBUF_ND)
776
777 #define PyBUF_STRIDED (PyBUF_STRIDES | PyBUF_WRITABLE)
778 #define PyBUF_STRIDED_RO (PyBUF_STRIDES)
779
780 #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_WRITABLE | PyBUF_FORMAT)
781 #define PyBUF_RECORDS_RO (PyBUF_STRIDES | PyBUF_FORMAT)
782
783 #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_WRITABLE | PyBUF_FORMAT)
784 #define PyBUF_FULL_RO (PyBUF_INDIRECT | PyBUF_FORMAT)
785
786
787 #define PyBUF_READ 0x100
788 #define PyBUF_WRITE 0x200
789 #define PyBUF_SHADOW 0x400
790 /* end Py3k buffer interface */
791
792 PyAPI_FUNC(const char *) _PyType_Name(PyTypeObject *);
793
794 struct PyModuleDef;
795 PyAPI_FUNC(PyObject *) PyType_GetModuleByDef(PyTypeObject *, struct PyModuleDef *);
796
797 /* Safely decref `op` and set `op` to `op2`.
798 *
799 * As in case of Py_CLEAR "the obvious" code can be deadly:
800 *
801 * Py_DECREF(op);
802 * op = op2;
803 *
804 * The safe way is:
805 *
806 * Py_SETREF(op, op2);
807 *
808 * That arranges to set `op` to `op2` _before_ decref'ing, so that any code
809 * triggered as a side-effect of `op` getting torn down no longer believes
810 * `op` points to a valid object.
811 *
812 * Py_XSETREF is a variant of Py_SETREF that uses Py_XDECREF instead of
813 * Py_DECREF.
814 */
815
816 #define Py_SETREF(op, op2) \
817 do { \
818 PyObject *_py_tmp = _PyObject_CAST(op); \
819 (op) = (op2); \
820 Py_DECREF(_py_tmp); \
821 } while (0)
822
823 /* Generic type check */
824 PyAPI_FUNC(int) PyType_IsSubtype(PyTypeObject *, PyTypeObject *);
825
826 #define Py_XSETREF(op, op2) \
827 do { \
828 PyObject *_py_tmp = _PyObject_CAST(op); \
829 (op) = (op2); \
830 Py_XDECREF(_py_tmp); \
831 } while (0)
832
833 #define Py_TRASHCAN_BEGIN(op, cond) do {
834 #define Py_TRASHCAN_END ; } while(0);
835
836 Py_DEPRECATED(3.11) typedef int UsingDeprecatedTrashcanMacro;
837 #define Py_TRASHCAN_SAFE_BEGIN(pyObj) do {
838 #define Py_TRASHCAN_SAFE_END(pyObj) ; } while(0);
839 /* note: the ";" at the start of Py_TRASHCAN_SAFE_END is needed
840 if the code has a label in front of the macro call */
841
842 /* Copied from CPython ----------------------------- */
843 PyAPI_FUNC(int) PyObject_AsReadBuffer(PyObject *, const void **, Py_ssize_t *);
844 PyAPI_FUNC(int) PyObject_AsWriteBuffer(PyObject *, void **, Py_ssize_t *);
845 PyAPI_FUNC(int) PyObject_CheckReadBuffer(PyObject *);
846 PyAPI_FUNC(void *) PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices);
847 /* Get the memory area pointed to by the indices for the buffer given.
848 Note that view->ndim is the assumed size of indices
849 */
850
851 PyAPI_FUNC(int) PyBuffer_ToContiguous(void *buf, Py_buffer *view,
852 Py_ssize_t len, char fort);
853 PyAPI_FUNC(int) PyBuffer_FromContiguous(Py_buffer *view, void *buf,
854 Py_ssize_t len, char fort);
855 /* Copy len bytes of data from the contiguous chunk of memory
856 pointed to by buf into the buffer exported by obj. Return
857 0 on success and return -1 and raise a PyBuffer_Error on
858 error (i.e. the object does not have a buffer interface or
859 it is not working).
860
861 If fort is 'F' and the object is multi-dimensional,
862 then the data will be copied into the array in
863 Fortran-style (first dimension varies the fastest). If
864 fort is 'C', then the data will be copied into the array
865 in C-style (last dimension varies the fastest). If fort
866 is 'A', then it does not matter and the copy will be made
867 in whatever way is more efficient.
868
869 */
870
871
872 PyAPI_FUNC(int) PyObject_CallFinalizerFromDealloc(PyObject *);
873
874 /*
875 * On CPython with Py_REF_DEBUG these use _PyRefTotal, _Py_NegativeRefcount,
876 * _Py_GetRefTotal, ...
877 * So far we ignore Py_REF_DEBUG
878 */
879
880 #define _Py_INC_REFTOTAL
881 #define _Py_DEC_REFTOTAL
882 #define _Py_REF_DEBUG_COMMA
883 #define _Py_CHECK_REFCNT(OP) /* a semicolon */;
884
885 PyAPI_FUNC(void) _Py_NewReference(PyObject *op);
886
887 #ifdef Py_TRACE_REFS
888 /* Py_TRACE_REFS is such major surgery that we call external routines. */
889 PyAPI_FUNC(void) _Py_ForgetReference(PyObject *);
890 #endif
891
892 #ifdef Py_REF_DEBUG
893 PyAPI_FUNC(Py_ssize_t) _Py_GetRefTotal(void);
894 #endif
895
896 /* ---- cpython/object.h */
897
898 static inline int
899 PyType_HasFeature(PyTypeObject *type, unsigned long feature)
900 {
901 unsigned long flags;
902 #ifdef Py_LIMITED_API
903 // PyTypeObject is opaque in the limited C API
904 flags = PyType_GetFlags(type);
905 #else
906 flags = type->tp_flags;
907 #endif
908 return ((flags & feature) != 0);
909 }
910
911 #define PyType_FastSubclass(type, flag) PyType_HasFeature(type, flag)
912
913 static inline int _PyType_Check(PyObject *op) {
914 return PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS);
915 }
916 #define PyType_Check(op) _PyType_Check(_PyObject_CAST(op))
917
918 static inline int _PyType_CheckExact(PyObject *op) {
919 return Py_IS_TYPE(op, &PyType_Type);
920 }
921 #define PyType_CheckExact(op) _PyType_CheckExact(_PyObject_CAST(op))
922
923
924 /* PyPy internal ----------------------------------- */
925 PyAPI_FUNC(int) PyPyType_Register(PyTypeObject *);
926 #define _PyObject_GC_Del PyObject_GC_Del
927 PyAPI_FUNC(void) _PyPy_subtype_dealloc(PyObject *);
928 PyAPI_FUNC(void) _PyPy_object_dealloc(PyObject *);
929
930
931 #ifdef __cplusplus
932 }
933 #endif
934 #endif /* !Py_OBJECT_H */