object.h 28 KB

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