object.h 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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_REF_DEBUG)
  50. #error Py_LIMITED_API is incompatible with Py_DEBUG, Py_TRACE_REFS, and Py_REF_DEBUG
  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 Py_REFCNT(ob) (_PyObject_CAST(ob)->ob_refcnt)
  100. #define Py_TYPE(ob) (_PyObject_CAST(ob)->ob_type)
  101. #define Py_SIZE(ob) (_PyVarObject_CAST(ob)->ob_size)
  102. static inline int _Py_IS_TYPE(const PyObject *ob, const PyTypeObject *type) {
  103. return ob->ob_type == type;
  104. }
  105. #define Py_IS_TYPE(ob, type) _Py_IS_TYPE(_PyObject_CAST_CONST(ob), type)
  106. static inline void _Py_SET_REFCNT(PyObject *ob, Py_ssize_t refcnt) {
  107. ob->ob_refcnt = refcnt;
  108. }
  109. #define Py_SET_REFCNT(ob, refcnt) _Py_SET_REFCNT(_PyObject_CAST(ob), refcnt)
  110. static inline void _Py_SET_TYPE(PyObject *ob, PyTypeObject *type) {
  111. ob->ob_type = type;
  112. }
  113. #define Py_SET_TYPE(ob, type) _Py_SET_TYPE(_PyObject_CAST(ob), type)
  114. static inline void _Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size) {
  115. ob->ob_size = size;
  116. }
  117. #define Py_SET_SIZE(ob, size) _Py_SET_SIZE(_PyVarObject_CAST(ob), size)
  118. /*
  119. Type objects contain a string containing the type name (to help somewhat
  120. in debugging), the allocation parameters (see PyObject_New() and
  121. PyObject_NewVar()),
  122. and methods for accessing objects of the type. Methods are optional, a
  123. nil pointer meaning that particular kind of access is not available for
  124. this type. The Py_DECREF() macro uses the tp_dealloc method without
  125. checking for a nil pointer; it should always be implemented except if
  126. the implementation can guarantee that the reference count will never
  127. reach zero (e.g., for statically allocated type objects).
  128. NB: the methods for certain type groups are now contained in separate
  129. method blocks.
  130. */
  131. typedef PyObject * (*unaryfunc)(PyObject *);
  132. typedef PyObject * (*binaryfunc)(PyObject *, PyObject *);
  133. typedef PyObject * (*ternaryfunc)(PyObject *, PyObject *, PyObject *);
  134. typedef int (*inquiry)(PyObject *);
  135. typedef Py_ssize_t (*lenfunc)(PyObject *);
  136. typedef PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t);
  137. typedef PyObject *(*ssizessizeargfunc)(PyObject *, Py_ssize_t, Py_ssize_t);
  138. typedef int(*ssizeobjargproc)(PyObject *, Py_ssize_t, PyObject *);
  139. typedef int(*ssizessizeobjargproc)(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);
  140. typedef int(*objobjargproc)(PyObject *, PyObject *, PyObject *);
  141. typedef int (*objobjproc)(PyObject *, PyObject *);
  142. typedef int (*visitproc)(PyObject *, void *);
  143. typedef int (*traverseproc)(PyObject *, visitproc, void *);
  144. typedef void (*freefunc)(void *);
  145. typedef void (*destructor)(PyObject *);
  146. typedef PyObject *(*getattrfunc)(PyObject *, char *);
  147. typedef PyObject *(*getattrofunc)(PyObject *, PyObject *);
  148. typedef int (*setattrfunc)(PyObject *, char *, PyObject *);
  149. typedef int (*setattrofunc)(PyObject *, PyObject *, PyObject *);
  150. typedef PyObject *(*reprfunc)(PyObject *);
  151. typedef Py_hash_t (*hashfunc)(PyObject *);
  152. typedef PyObject *(*richcmpfunc) (PyObject *, PyObject *, int);
  153. typedef PyObject *(*getiterfunc) (PyObject *);
  154. typedef PyObject *(*iternextfunc) (PyObject *);
  155. typedef PyObject *(*descrgetfunc) (PyObject *, PyObject *, PyObject *);
  156. typedef int (*descrsetfunc) (PyObject *, PyObject *, PyObject *);
  157. typedef int (*initproc)(PyObject *, PyObject *, PyObject *);
  158. typedef PyObject *(*newfunc)(PyTypeObject *, PyObject *, PyObject *);
  159. typedef PyObject *(*allocfunc)(PyTypeObject *, Py_ssize_t);
  160. typedef struct{
  161. int slot; /* slot id, see below */
  162. void *pfunc; /* function pointer */
  163. } PyType_Slot;
  164. typedef struct{
  165. const char* name;
  166. int basicsize;
  167. int itemsize;
  168. unsigned int flags;
  169. PyType_Slot *slots; /* terminated by slot==0. */
  170. } PyType_Spec;
  171. PyAPI_FUNC(PyObject*) PyType_FromSpec(PyType_Spec*);
  172. #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
  173. PyAPI_FUNC(PyObject*) PyType_FromSpecWithBases(PyType_Spec*, PyObject*);
  174. #endif
  175. #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000
  176. PyAPI_FUNC(void*) PyType_GetSlot(PyTypeObject*, int);
  177. #endif
  178. #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03090000
  179. PyAPI_FUNC(PyObject*) PyType_FromModuleAndSpec(PyObject *, PyType_Spec *, PyObject *);
  180. PyAPI_FUNC(PyObject *) PyType_GetModule(struct _typeobject *);
  181. PyAPI_FUNC(void *) PyType_GetModuleState(struct _typeobject *);
  182. #endif
  183. /* Generic type check */
  184. PyAPI_FUNC(int) PyType_IsSubtype(PyTypeObject *, PyTypeObject *);
  185. #define PyObject_TypeCheck(ob, tp) \
  186. (Py_IS_TYPE(ob, tp) || PyType_IsSubtype(Py_TYPE(ob), (tp)))
  187. PyAPI_DATA(PyTypeObject) PyType_Type; /* built-in 'type' */
  188. PyAPI_DATA(PyTypeObject) PyBaseObject_Type; /* built-in 'object' */
  189. PyAPI_DATA(PyTypeObject) PySuper_Type; /* built-in 'super' */
  190. PyAPI_FUNC(unsigned long) PyType_GetFlags(PyTypeObject*);
  191. PyAPI_FUNC(int) PyType_Ready(PyTypeObject *);
  192. PyAPI_FUNC(PyObject *) PyType_GenericAlloc(PyTypeObject *, Py_ssize_t);
  193. PyAPI_FUNC(PyObject *) PyType_GenericNew(PyTypeObject *,
  194. PyObject *, PyObject *);
  195. PyAPI_FUNC(unsigned int) PyType_ClearCache(void);
  196. PyAPI_FUNC(void) PyType_Modified(PyTypeObject *);
  197. /* Generic operations on objects */
  198. PyAPI_FUNC(PyObject *) PyObject_Repr(PyObject *);
  199. PyAPI_FUNC(PyObject *) PyObject_Str(PyObject *);
  200. PyAPI_FUNC(PyObject *) PyObject_ASCII(PyObject *);
  201. PyAPI_FUNC(PyObject *) PyObject_Bytes(PyObject *);
  202. PyAPI_FUNC(PyObject *) PyObject_RichCompare(PyObject *, PyObject *, int);
  203. PyAPI_FUNC(int) PyObject_RichCompareBool(PyObject *, PyObject *, int);
  204. PyAPI_FUNC(PyObject *) PyObject_GetAttrString(PyObject *, const char *);
  205. PyAPI_FUNC(int) PyObject_SetAttrString(PyObject *, const char *, PyObject *);
  206. PyAPI_FUNC(int) PyObject_HasAttrString(PyObject *, const char *);
  207. PyAPI_FUNC(PyObject *) PyObject_GetAttr(PyObject *, PyObject *);
  208. PyAPI_FUNC(int) PyObject_SetAttr(PyObject *, PyObject *, PyObject *);
  209. PyAPI_FUNC(int) PyObject_HasAttr(PyObject *, PyObject *);
  210. PyAPI_FUNC(PyObject *) PyObject_SelfIter(PyObject *);
  211. PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *);
  212. PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *, PyObject *, PyObject *);
  213. #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
  214. PyAPI_FUNC(int) PyObject_GenericSetDict(PyObject *, PyObject *, void *);
  215. #endif
  216. PyAPI_FUNC(Py_hash_t) PyObject_Hash(PyObject *);
  217. PyAPI_FUNC(Py_hash_t) PyObject_HashNotImplemented(PyObject *);
  218. PyAPI_FUNC(int) PyObject_IsTrue(PyObject *);
  219. PyAPI_FUNC(int) PyObject_Not(PyObject *);
  220. PyAPI_FUNC(int) PyCallable_Check(PyObject *);
  221. PyAPI_FUNC(void) PyObject_ClearWeakRefs(PyObject *);
  222. /* PyObject_Dir(obj) acts like Python builtins.dir(obj), returning a
  223. list of strings. PyObject_Dir(NULL) is like builtins.dir(),
  224. returning the names of the current locals. In this case, if there are
  225. no current locals, NULL is returned, and PyErr_Occurred() is false.
  226. */
  227. PyAPI_FUNC(PyObject *) PyObject_Dir(PyObject *);
  228. /* Helpers for printing recursive container types */
  229. PyAPI_FUNC(int) Py_ReprEnter(PyObject *);
  230. PyAPI_FUNC(void) Py_ReprLeave(PyObject *);
  231. /* Flag bits for printing: */
  232. #define Py_PRINT_RAW 1 /* No string quotes etc. */
  233. /*
  234. Type flags (tp_flags)
  235. These flags are used to change expected features and behavior for a
  236. particular type.
  237. Arbitration of the flag bit positions will need to be coordinated among
  238. all extension writers who publicly release their extensions (this will
  239. be fewer than you might expect!).
  240. Most flags were removed as of Python 3.0 to make room for new flags. (Some
  241. flags are not for backwards compatibility but to indicate the presence of an
  242. optional feature; these flags remain of course.)
  243. Type definitions should use Py_TPFLAGS_DEFAULT for their tp_flags value.
  244. Code can use PyType_HasFeature(type_ob, flag_value) to test whether the
  245. given type object has a specified feature.
  246. */
  247. /* Set if the type object is dynamically allocated */
  248. #define Py_TPFLAGS_HEAPTYPE (1UL << 9)
  249. /* Set if the type allows subclassing */
  250. #define Py_TPFLAGS_BASETYPE (1UL << 10)
  251. /* Set if the type implements the vectorcall protocol (PEP 590) */
  252. #ifndef Py_LIMITED_API
  253. #define Py_TPFLAGS_HAVE_VECTORCALL (1UL << 11)
  254. // Backwards compatibility alias for API that was provisional in Python 3.8
  255. #define _Py_TPFLAGS_HAVE_VECTORCALL Py_TPFLAGS_HAVE_VECTORCALL
  256. #endif
  257. /* Set if the type is 'ready' -- fully initialized */
  258. #define Py_TPFLAGS_READY (1UL << 12)
  259. /* Set while the type is being 'readied', to prevent recursive ready calls */
  260. #define Py_TPFLAGS_READYING (1UL << 13)
  261. /* Objects support garbage collection (see objimpl.h) */
  262. #define Py_TPFLAGS_HAVE_GC (1UL << 14)
  263. /* These two bits are preserved for Stackless Python, next after this is 17 */
  264. #ifdef STACKLESS
  265. #define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION (3UL << 15)
  266. #else
  267. #define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION 0
  268. #endif
  269. /* Objects behave like an unbound method */
  270. #define Py_TPFLAGS_METHOD_DESCRIPTOR (1UL << 17)
  271. /* Objects support type attribute cache */
  272. #define Py_TPFLAGS_HAVE_VERSION_TAG (1UL << 18)
  273. #define Py_TPFLAGS_VALID_VERSION_TAG (1UL << 19)
  274. /* Type is abstract and cannot be instantiated */
  275. #define Py_TPFLAGS_IS_ABSTRACT (1UL << 20)
  276. /* These flags are used to determine if a type is a subclass. */
  277. #define Py_TPFLAGS_LONG_SUBCLASS (1UL << 24)
  278. #define Py_TPFLAGS_LIST_SUBCLASS (1UL << 25)
  279. #define Py_TPFLAGS_TUPLE_SUBCLASS (1UL << 26)
  280. #define Py_TPFLAGS_BYTES_SUBCLASS (1UL << 27)
  281. #define Py_TPFLAGS_UNICODE_SUBCLASS (1UL << 28)
  282. #define Py_TPFLAGS_DICT_SUBCLASS (1UL << 29)
  283. #define Py_TPFLAGS_BASE_EXC_SUBCLASS (1UL << 30)
  284. #define Py_TPFLAGS_TYPE_SUBCLASS (1UL << 31)
  285. #define Py_TPFLAGS_DEFAULT ( \
  286. Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \
  287. Py_TPFLAGS_HAVE_VERSION_TAG | \
  288. 0)
  289. /* NOTE: The following flags reuse lower bits (removed as part of the
  290. * Python 3.0 transition). */
  291. /* The following flag is kept for compatibility. Starting with 3.8,
  292. * binary compatibility of C extensions across feature releases of
  293. * Python is not supported anymore, except when using the stable ABI.
  294. */
  295. /* Type structure has tp_finalize member (3.4) */
  296. #define Py_TPFLAGS_HAVE_FINALIZE (1UL << 0)
  297. /*
  298. The macros Py_INCREF(op) and Py_DECREF(op) are used to increment or decrement
  299. reference counts. Py_DECREF calls the object's deallocator function when
  300. the refcount falls to 0; for
  301. objects that don't contain references to other objects or heap memory
  302. this can be the standard function free(). Both macros can be used
  303. wherever a void expression is allowed. The argument must not be a
  304. NULL pointer. If it may be NULL, use Py_XINCREF/Py_XDECREF instead.
  305. The macro _Py_NewReference(op) initialize reference counts to 1, and
  306. in special builds (Py_REF_DEBUG, Py_TRACE_REFS) performs additional
  307. bookkeeping appropriate to the special build.
  308. We assume that the reference count field can never overflow; this can
  309. be proven when the size of the field is the same as the pointer size, so
  310. we ignore the possibility. Provided a C int is at least 32 bits (which
  311. is implicitly assumed in many parts of this code), that's enough for
  312. about 2**31 references to an object.
  313. XXX The following became out of date in Python 2.2, but I'm not sure
  314. XXX what the full truth is now. Certainly, heap-allocated type objects
  315. XXX can and should be deallocated.
  316. Type objects should never be deallocated; the type pointer in an object
  317. is not considered to be a reference to the type object, to save
  318. complications in the deallocation function. (This is actually a
  319. decision that's up to the implementer of each new type so if you want,
  320. you can count such references to the type object.)
  321. */
  322. #ifdef Py_REF_DEBUG
  323. PyAPI_DATA(Py_ssize_t) _Py_RefTotal;
  324. PyAPI_FUNC(void) _Py_NegativeRefcount(const char *filename, int lineno,
  325. PyObject *op);
  326. #endif /* Py_REF_DEBUG */
  327. PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
  328. static inline void _Py_INCREF(PyObject *op)
  329. {
  330. #ifdef Py_REF_DEBUG
  331. _Py_RefTotal++;
  332. #endif
  333. op->ob_refcnt++;
  334. }
  335. #define Py_INCREF(op) _Py_INCREF(_PyObject_CAST(op))
  336. static inline void _Py_DECREF(
  337. #ifdef Py_REF_DEBUG
  338. const char *filename, int lineno,
  339. #endif
  340. PyObject *op)
  341. {
  342. #ifdef Py_REF_DEBUG
  343. _Py_RefTotal--;
  344. #endif
  345. if (--op->ob_refcnt != 0) {
  346. #ifdef Py_REF_DEBUG
  347. if (op->ob_refcnt < 0) {
  348. _Py_NegativeRefcount(filename, lineno, op);
  349. }
  350. #endif
  351. }
  352. else {
  353. _Py_Dealloc(op);
  354. }
  355. }
  356. #ifdef Py_REF_DEBUG
  357. # define Py_DECREF(op) _Py_DECREF(__FILE__, __LINE__, _PyObject_CAST(op))
  358. #else
  359. # define Py_DECREF(op) _Py_DECREF(_PyObject_CAST(op))
  360. #endif
  361. /* Safely decref `op` and set `op` to NULL, especially useful in tp_clear
  362. * and tp_dealloc implementations.
  363. *
  364. * Note that "the obvious" code can be deadly:
  365. *
  366. * Py_XDECREF(op);
  367. * op = NULL;
  368. *
  369. * Typically, `op` is something like self->containee, and `self` is done
  370. * using its `containee` member. In the code sequence above, suppose
  371. * `containee` is non-NULL with a refcount of 1. Its refcount falls to
  372. * 0 on the first line, which can trigger an arbitrary amount of code,
  373. * possibly including finalizers (like __del__ methods or weakref callbacks)
  374. * coded in Python, which in turn can release the GIL and allow other threads
  375. * to run, etc. Such code may even invoke methods of `self` again, or cause
  376. * cyclic gc to trigger, but-- oops! --self->containee still points to the
  377. * object being torn down, and it may be in an insane state while being torn
  378. * down. This has in fact been a rich historic source of miserable (rare &
  379. * hard-to-diagnose) segfaulting (and other) bugs.
  380. *
  381. * The safe way is:
  382. *
  383. * Py_CLEAR(op);
  384. *
  385. * That arranges to set `op` to NULL _before_ decref'ing, so that any code
  386. * triggered as a side-effect of `op` getting torn down no longer believes
  387. * `op` points to a valid object.
  388. *
  389. * There are cases where it's safe to use the naive code, but they're brittle.
  390. * For example, if `op` points to a Python integer, you know that destroying
  391. * one of those can't cause problems -- but in part that relies on that
  392. * Python integers aren't currently weakly referencable. Best practice is
  393. * to use Py_CLEAR() even if you can't think of a reason for why you need to.
  394. */
  395. #define Py_CLEAR(op) \
  396. do { \
  397. PyObject *_py_tmp = _PyObject_CAST(op); \
  398. if (_py_tmp != NULL) { \
  399. (op) = NULL; \
  400. Py_DECREF(_py_tmp); \
  401. } \
  402. } while (0)
  403. /* Function to use in case the object pointer can be NULL: */
  404. static inline void _Py_XINCREF(PyObject *op)
  405. {
  406. if (op != NULL) {
  407. Py_INCREF(op);
  408. }
  409. }
  410. #define Py_XINCREF(op) _Py_XINCREF(_PyObject_CAST(op))
  411. static inline void _Py_XDECREF(PyObject *op)
  412. {
  413. if (op != NULL) {
  414. Py_DECREF(op);
  415. }
  416. }
  417. #define Py_XDECREF(op) _Py_XDECREF(_PyObject_CAST(op))
  418. /*
  419. These are provided as conveniences to Python runtime embedders, so that
  420. they can have object code that is not dependent on Python compilation flags.
  421. */
  422. PyAPI_FUNC(void) Py_IncRef(PyObject *);
  423. PyAPI_FUNC(void) Py_DecRef(PyObject *);
  424. /*
  425. _Py_NoneStruct is an object of undefined type which can be used in contexts
  426. where NULL (nil) is not suitable (since NULL often means 'error').
  427. Don't forget to apply Py_INCREF() when returning this value!!!
  428. */
  429. PyAPI_DATA(PyObject) _Py_NoneStruct; /* Don't use this directly */
  430. #define Py_None (&_Py_NoneStruct)
  431. /* Macro for returning Py_None from a function */
  432. #define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None
  433. /*
  434. Py_NotImplemented is a singleton used to signal that an operation is
  435. not implemented for a given type combination.
  436. */
  437. PyAPI_DATA(PyObject) _Py_NotImplementedStruct; /* Don't use this directly */
  438. #define Py_NotImplemented (&_Py_NotImplementedStruct)
  439. /* Macro for returning Py_NotImplemented from a function */
  440. #define Py_RETURN_NOTIMPLEMENTED \
  441. return Py_INCREF(Py_NotImplemented), Py_NotImplemented
  442. /* Rich comparison opcodes */
  443. #define Py_LT 0
  444. #define Py_LE 1
  445. #define Py_EQ 2
  446. #define Py_NE 3
  447. #define Py_GT 4
  448. #define Py_GE 5
  449. /*
  450. * Macro for implementing rich comparisons
  451. *
  452. * Needs to be a macro because any C-comparable type can be used.
  453. */
  454. #define Py_RETURN_RICHCOMPARE(val1, val2, op) \
  455. do { \
  456. switch (op) { \
  457. case Py_EQ: if ((val1) == (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
  458. case Py_NE: if ((val1) != (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
  459. case Py_LT: if ((val1) < (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
  460. case Py_GT: if ((val1) > (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
  461. case Py_LE: if ((val1) <= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
  462. case Py_GE: if ((val1) >= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
  463. default: \
  464. Py_UNREACHABLE(); \
  465. } \
  466. } while (0)
  467. /*
  468. More conventions
  469. ================
  470. Argument Checking
  471. -----------------
  472. Functions that take objects as arguments normally don't check for nil
  473. arguments, but they do check the type of the argument, and return an
  474. error if the function doesn't apply to the type.
  475. Failure Modes
  476. -------------
  477. Functions may fail for a variety of reasons, including running out of
  478. memory. This is communicated to the caller in two ways: an error string
  479. is set (see errors.h), and the function result differs: functions that
  480. normally return a pointer return NULL for failure, functions returning
  481. an integer return -1 (which could be a legal return value too!), and
  482. other functions return 0 for success and -1 for failure.
  483. Callers should always check for errors before using the result. If
  484. an error was set, the caller must either explicitly clear it, or pass
  485. the error on to its caller.
  486. Reference Counts
  487. ----------------
  488. It takes a while to get used to the proper usage of reference counts.
  489. Functions that create an object set the reference count to 1; such new
  490. objects must be stored somewhere or destroyed again with Py_DECREF().
  491. Some functions that 'store' objects, such as PyTuple_SetItem() and
  492. PyList_SetItem(),
  493. don't increment the reference count of the object, since the most
  494. frequent use is to store a fresh object. Functions that 'retrieve'
  495. objects, such as PyTuple_GetItem() and PyDict_GetItemString(), also
  496. don't increment
  497. the reference count, since most frequently the object is only looked at
  498. quickly. Thus, to retrieve an object and store it again, the caller
  499. must call Py_INCREF() explicitly.
  500. NOTE: functions that 'consume' a reference count, like
  501. PyList_SetItem(), consume the reference even if the object wasn't
  502. successfully stored, to simplify error handling.
  503. It seems attractive to make other functions that take an object as
  504. argument consume a reference count; however, this may quickly get
  505. confusing (even the current practice is already confusing). Consider
  506. it carefully, it may save lots of calls to Py_INCREF() and Py_DECREF() at
  507. times.
  508. */
  509. #ifndef Py_LIMITED_API
  510. # define Py_CPYTHON_OBJECT_H
  511. # include "cpython/object.h"
  512. # undef Py_CPYTHON_OBJECT_H
  513. #endif
  514. static inline int
  515. PyType_HasFeature(PyTypeObject *type, unsigned long feature)
  516. {
  517. unsigned long flags;
  518. #ifdef Py_LIMITED_API
  519. // PyTypeObject is opaque in the limited C API
  520. flags = PyType_GetFlags(type);
  521. #else
  522. flags = type->tp_flags;
  523. #endif
  524. return ((flags & feature) != 0);
  525. }
  526. #define PyType_FastSubclass(type, flag) PyType_HasFeature(type, flag)
  527. static inline int _PyType_Check(PyObject *op) {
  528. return PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS);
  529. }
  530. #define PyType_Check(op) _PyType_Check(_PyObject_CAST(op))
  531. static inline int _PyType_CheckExact(PyObject *op) {
  532. return Py_IS_TYPE(op, &PyType_Type);
  533. }
  534. #define PyType_CheckExact(op) _PyType_CheckExact(_PyObject_CAST(op))
  535. #ifdef __cplusplus
  536. }
  537. #endif
  538. #endif /* !Py_OBJECT_H */