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