pythoncapi_compat.h 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205
  1. // Header file providing new C API functions to old Python versions.
  2. //
  3. // File distributed under the Zero Clause BSD (0BSD) license.
  4. // Copyright Contributors to the pythoncapi_compat project.
  5. //
  6. // Homepage:
  7. // https://github.com/python/pythoncapi_compat
  8. //
  9. // Latest version:
  10. // https://raw.githubusercontent.com/python/pythoncapi-compat/main/pythoncapi_compat.h
  11. //
  12. // SPDX-License-Identifier: 0BSD
  13. #ifndef PYTHONCAPI_COMPAT
  14. #define PYTHONCAPI_COMPAT
  15. #ifdef __cplusplus
  16. extern "C" {
  17. #endif
  18. #include <Python.h>
  19. #include <stddef.h> // offsetof()
  20. // Python 3.11.0b4 added PyFrame_Back() to Python.h
  21. #if PY_VERSION_HEX < 0x030b00B4 && !defined(PYPY_VERSION)
  22. # include "frameobject.h" // PyFrameObject, PyFrame_GetBack()
  23. #endif
  24. #if PY_VERSION_HEX < 0x030C00A3
  25. # include <structmember.h> // T_SHORT, READONLY
  26. #endif
  27. #ifndef _Py_CAST
  28. # define _Py_CAST(type, expr) ((type)(expr))
  29. #endif
  30. // Static inline functions should use _Py_NULL rather than using directly NULL
  31. // to prevent C++ compiler warnings. On C23 and newer and on C++11 and newer,
  32. // _Py_NULL is defined as nullptr.
  33. #ifndef _Py_NULL
  34. # if (defined (__STDC_VERSION__) && __STDC_VERSION__ > 201710L) \
  35. || (defined(__cplusplus) && __cplusplus >= 201103)
  36. # define _Py_NULL nullptr
  37. # else
  38. # define _Py_NULL NULL
  39. # endif
  40. #endif
  41. // Cast argument to PyObject* type.
  42. #ifndef _PyObject_CAST
  43. # define _PyObject_CAST(op) _Py_CAST(PyObject*, op)
  44. #endif
  45. #ifndef Py_BUILD_ASSERT
  46. # define Py_BUILD_ASSERT(cond) \
  47. do { \
  48. (void)sizeof(char [1 - 2 * !(cond)]); \
  49. } while(0)
  50. #endif
  51. // bpo-42262 added Py_NewRef() to Python 3.10.0a3
  52. #if PY_VERSION_HEX < 0x030A00A3 && !defined(Py_NewRef)
  53. static inline PyObject* _Py_NewRef(PyObject *obj)
  54. {
  55. Py_INCREF(obj);
  56. return obj;
  57. }
  58. #define Py_NewRef(obj) _Py_NewRef(_PyObject_CAST(obj))
  59. #endif
  60. // bpo-42262 added Py_XNewRef() to Python 3.10.0a3
  61. #if PY_VERSION_HEX < 0x030A00A3 && !defined(Py_XNewRef)
  62. static inline PyObject* _Py_XNewRef(PyObject *obj)
  63. {
  64. Py_XINCREF(obj);
  65. return obj;
  66. }
  67. #define Py_XNewRef(obj) _Py_XNewRef(_PyObject_CAST(obj))
  68. #endif
  69. // bpo-39573 added Py_SET_REFCNT() to Python 3.9.0a4
  70. #if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_REFCNT)
  71. static inline void _Py_SET_REFCNT(PyObject *ob, Py_ssize_t refcnt)
  72. {
  73. ob->ob_refcnt = refcnt;
  74. }
  75. #define Py_SET_REFCNT(ob, refcnt) _Py_SET_REFCNT(_PyObject_CAST(ob), refcnt)
  76. #endif
  77. // Py_SETREF() and Py_XSETREF() were added to Python 3.5.2.
  78. // It is excluded from the limited C API.
  79. #if (PY_VERSION_HEX < 0x03050200 && !defined(Py_SETREF)) && !defined(Py_LIMITED_API)
  80. #define Py_SETREF(dst, src) \
  81. do { \
  82. PyObject **_tmp_dst_ptr = _Py_CAST(PyObject**, &(dst)); \
  83. PyObject *_tmp_dst = (*_tmp_dst_ptr); \
  84. *_tmp_dst_ptr = _PyObject_CAST(src); \
  85. Py_DECREF(_tmp_dst); \
  86. } while (0)
  87. #define Py_XSETREF(dst, src) \
  88. do { \
  89. PyObject **_tmp_dst_ptr = _Py_CAST(PyObject**, &(dst)); \
  90. PyObject *_tmp_dst = (*_tmp_dst_ptr); \
  91. *_tmp_dst_ptr = _PyObject_CAST(src); \
  92. Py_XDECREF(_tmp_dst); \
  93. } while (0)
  94. #endif
  95. // bpo-43753 added Py_Is(), Py_IsNone(), Py_IsTrue() and Py_IsFalse()
  96. // to Python 3.10.0b1.
  97. #if PY_VERSION_HEX < 0x030A00B1 && !defined(Py_Is)
  98. # define Py_Is(x, y) ((x) == (y))
  99. #endif
  100. #if PY_VERSION_HEX < 0x030A00B1 && !defined(Py_IsNone)
  101. # define Py_IsNone(x) Py_Is(x, Py_None)
  102. #endif
  103. #if (PY_VERSION_HEX < 0x030A00B1 || defined(PYPY_VERSION)) && !defined(Py_IsTrue)
  104. # define Py_IsTrue(x) Py_Is(x, Py_True)
  105. #endif
  106. #if (PY_VERSION_HEX < 0x030A00B1 || defined(PYPY_VERSION)) && !defined(Py_IsFalse)
  107. # define Py_IsFalse(x) Py_Is(x, Py_False)
  108. #endif
  109. // bpo-39573 added Py_SET_TYPE() to Python 3.9.0a4
  110. #if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_TYPE)
  111. static inline void _Py_SET_TYPE(PyObject *ob, PyTypeObject *type)
  112. {
  113. ob->ob_type = type;
  114. }
  115. #define Py_SET_TYPE(ob, type) _Py_SET_TYPE(_PyObject_CAST(ob), type)
  116. #endif
  117. // bpo-39573 added Py_SET_SIZE() to Python 3.9.0a4
  118. #if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_SIZE)
  119. static inline void _Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size)
  120. {
  121. ob->ob_size = size;
  122. }
  123. #define Py_SET_SIZE(ob, size) _Py_SET_SIZE((PyVarObject*)(ob), size)
  124. #endif
  125. // bpo-40421 added PyFrame_GetCode() to Python 3.9.0b1
  126. #if PY_VERSION_HEX < 0x030900B1 || defined(PYPY_VERSION)
  127. static inline PyCodeObject* PyFrame_GetCode(PyFrameObject *frame)
  128. {
  129. assert(frame != _Py_NULL);
  130. assert(frame->f_code != _Py_NULL);
  131. return _Py_CAST(PyCodeObject*, Py_NewRef(frame->f_code));
  132. }
  133. #endif
  134. static inline PyCodeObject* _PyFrame_GetCodeBorrow(PyFrameObject *frame)
  135. {
  136. PyCodeObject *code = PyFrame_GetCode(frame);
  137. Py_DECREF(code);
  138. return code;
  139. }
  140. // bpo-40421 added PyFrame_GetBack() to Python 3.9.0b1
  141. #if PY_VERSION_HEX < 0x030900B1 && !defined(PYPY_VERSION)
  142. static inline PyFrameObject* PyFrame_GetBack(PyFrameObject *frame)
  143. {
  144. assert(frame != _Py_NULL);
  145. return _Py_CAST(PyFrameObject*, Py_XNewRef(frame->f_back));
  146. }
  147. #endif
  148. #if !defined(PYPY_VERSION)
  149. static inline PyFrameObject* _PyFrame_GetBackBorrow(PyFrameObject *frame)
  150. {
  151. PyFrameObject *back = PyFrame_GetBack(frame);
  152. Py_XDECREF(back);
  153. return back;
  154. }
  155. #endif
  156. // bpo-40421 added PyFrame_GetLocals() to Python 3.11.0a7
  157. #if PY_VERSION_HEX < 0x030B00A7 && !defined(PYPY_VERSION)
  158. static inline PyObject* PyFrame_GetLocals(PyFrameObject *frame)
  159. {
  160. #if PY_VERSION_HEX >= 0x030400B1
  161. if (PyFrame_FastToLocalsWithError(frame) < 0) {
  162. return NULL;
  163. }
  164. #else
  165. PyFrame_FastToLocals(frame);
  166. #endif
  167. return Py_NewRef(frame->f_locals);
  168. }
  169. #endif
  170. // bpo-40421 added PyFrame_GetGlobals() to Python 3.11.0a7
  171. #if PY_VERSION_HEX < 0x030B00A7 && !defined(PYPY_VERSION)
  172. static inline PyObject* PyFrame_GetGlobals(PyFrameObject *frame)
  173. {
  174. return Py_NewRef(frame->f_globals);
  175. }
  176. #endif
  177. // bpo-40421 added PyFrame_GetBuiltins() to Python 3.11.0a7
  178. #if PY_VERSION_HEX < 0x030B00A7 && !defined(PYPY_VERSION)
  179. static inline PyObject* PyFrame_GetBuiltins(PyFrameObject *frame)
  180. {
  181. return Py_NewRef(frame->f_builtins);
  182. }
  183. #endif
  184. // bpo-40421 added PyFrame_GetLasti() to Python 3.11.0b1
  185. #if PY_VERSION_HEX < 0x030B00B1 && !defined(PYPY_VERSION)
  186. static inline int PyFrame_GetLasti(PyFrameObject *frame)
  187. {
  188. #if PY_VERSION_HEX >= 0x030A00A7
  189. // bpo-27129: Since Python 3.10.0a7, f_lasti is an instruction offset,
  190. // not a bytes offset anymore. Python uses 16-bit "wordcode" (2 bytes)
  191. // instructions.
  192. if (frame->f_lasti < 0) {
  193. return -1;
  194. }
  195. return frame->f_lasti * 2;
  196. #else
  197. return frame->f_lasti;
  198. #endif
  199. }
  200. #endif
  201. // gh-91248 added PyFrame_GetVar() to Python 3.12.0a2
  202. #if PY_VERSION_HEX < 0x030C00A2 && !defined(PYPY_VERSION)
  203. static inline PyObject* PyFrame_GetVar(PyFrameObject *frame, PyObject *name)
  204. {
  205. PyObject *locals, *value;
  206. locals = PyFrame_GetLocals(frame);
  207. if (locals == NULL) {
  208. return NULL;
  209. }
  210. #if PY_VERSION_HEX >= 0x03000000
  211. value = PyDict_GetItemWithError(locals, name);
  212. #else
  213. value = _PyDict_GetItemWithError(locals, name);
  214. #endif
  215. Py_DECREF(locals);
  216. if (value == NULL) {
  217. if (PyErr_Occurred()) {
  218. return NULL;
  219. }
  220. #if PY_VERSION_HEX >= 0x03000000
  221. PyErr_Format(PyExc_NameError, "variable %R does not exist", name);
  222. #else
  223. PyErr_SetString(PyExc_NameError, "variable does not exist");
  224. #endif
  225. return NULL;
  226. }
  227. return Py_NewRef(value);
  228. }
  229. #endif
  230. // gh-91248 added PyFrame_GetVarString() to Python 3.12.0a2
  231. #if PY_VERSION_HEX < 0x030C00A2 && !defined(PYPY_VERSION)
  232. static inline PyObject*
  233. PyFrame_GetVarString(PyFrameObject *frame, const char *name)
  234. {
  235. PyObject *name_obj, *value;
  236. #if PY_VERSION_HEX >= 0x03000000
  237. name_obj = PyUnicode_FromString(name);
  238. #else
  239. name_obj = PyString_FromString(name);
  240. #endif
  241. if (name_obj == NULL) {
  242. return NULL;
  243. }
  244. value = PyFrame_GetVar(frame, name_obj);
  245. Py_DECREF(name_obj);
  246. return value;
  247. }
  248. #endif
  249. // bpo-39947 added PyThreadState_GetInterpreter() to Python 3.9.0a5
  250. #if PY_VERSION_HEX < 0x030900A5 || (defined(PYPY_VERSION) && PY_VERSION_HEX < 0x030B0000)
  251. static inline PyInterpreterState *
  252. PyThreadState_GetInterpreter(PyThreadState *tstate)
  253. {
  254. assert(tstate != _Py_NULL);
  255. return tstate->interp;
  256. }
  257. #endif
  258. // bpo-40429 added PyThreadState_GetFrame() to Python 3.9.0b1
  259. #if PY_VERSION_HEX < 0x030900B1 && !defined(PYPY_VERSION)
  260. static inline PyFrameObject* PyThreadState_GetFrame(PyThreadState *tstate)
  261. {
  262. assert(tstate != _Py_NULL);
  263. return _Py_CAST(PyFrameObject *, Py_XNewRef(tstate->frame));
  264. }
  265. #endif
  266. #if !defined(PYPY_VERSION)
  267. static inline PyFrameObject*
  268. _PyThreadState_GetFrameBorrow(PyThreadState *tstate)
  269. {
  270. PyFrameObject *frame = PyThreadState_GetFrame(tstate);
  271. Py_XDECREF(frame);
  272. return frame;
  273. }
  274. #endif
  275. // bpo-39947 added PyInterpreterState_Get() to Python 3.9.0a5
  276. #if PY_VERSION_HEX < 0x030900A5 || defined(PYPY_VERSION)
  277. static inline PyInterpreterState* PyInterpreterState_Get(void)
  278. {
  279. PyThreadState *tstate;
  280. PyInterpreterState *interp;
  281. tstate = PyThreadState_GET();
  282. if (tstate == _Py_NULL) {
  283. Py_FatalError("GIL released (tstate is NULL)");
  284. }
  285. interp = tstate->interp;
  286. if (interp == _Py_NULL) {
  287. Py_FatalError("no current interpreter");
  288. }
  289. return interp;
  290. }
  291. #endif
  292. // bpo-39947 added PyInterpreterState_Get() to Python 3.9.0a6
  293. #if 0x030700A1 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x030900A6 && !defined(PYPY_VERSION)
  294. static inline uint64_t PyThreadState_GetID(PyThreadState *tstate)
  295. {
  296. assert(tstate != _Py_NULL);
  297. return tstate->id;
  298. }
  299. #endif
  300. // bpo-43760 added PyThreadState_EnterTracing() to Python 3.11.0a2
  301. #if PY_VERSION_HEX < 0x030B00A2 && !defined(PYPY_VERSION)
  302. static inline void PyThreadState_EnterTracing(PyThreadState *tstate)
  303. {
  304. tstate->tracing++;
  305. #if PY_VERSION_HEX >= 0x030A00A1
  306. tstate->cframe->use_tracing = 0;
  307. #else
  308. tstate->use_tracing = 0;
  309. #endif
  310. }
  311. #endif
  312. // bpo-43760 added PyThreadState_LeaveTracing() to Python 3.11.0a2
  313. #if PY_VERSION_HEX < 0x030B00A2 && !defined(PYPY_VERSION)
  314. static inline void PyThreadState_LeaveTracing(PyThreadState *tstate)
  315. {
  316. int use_tracing = (tstate->c_tracefunc != _Py_NULL
  317. || tstate->c_profilefunc != _Py_NULL);
  318. tstate->tracing--;
  319. #if PY_VERSION_HEX >= 0x030A00A1
  320. tstate->cframe->use_tracing = use_tracing;
  321. #else
  322. tstate->use_tracing = use_tracing;
  323. #endif
  324. }
  325. #endif
  326. // bpo-37194 added PyObject_CallNoArgs() to Python 3.9.0a1
  327. // PyObject_CallNoArgs() added to PyPy 3.9.16-v7.3.11
  328. #if !defined(PyObject_CallNoArgs) && PY_VERSION_HEX < 0x030900A1
  329. static inline PyObject* PyObject_CallNoArgs(PyObject *func)
  330. {
  331. return PyObject_CallFunctionObjArgs(func, NULL);
  332. }
  333. #endif
  334. // bpo-39245 made PyObject_CallOneArg() public (previously called
  335. // _PyObject_CallOneArg) in Python 3.9.0a4
  336. // PyObject_CallOneArg() added to PyPy 3.9.16-v7.3.11
  337. #if !defined(PyObject_CallOneArg) && PY_VERSION_HEX < 0x030900A4
  338. static inline PyObject* PyObject_CallOneArg(PyObject *func, PyObject *arg)
  339. {
  340. return PyObject_CallFunctionObjArgs(func, arg, NULL);
  341. }
  342. #endif
  343. // bpo-1635741 added PyModule_AddObjectRef() to Python 3.10.0a3
  344. #if PY_VERSION_HEX < 0x030A00A3
  345. static inline int
  346. PyModule_AddObjectRef(PyObject *module, const char *name, PyObject *value)
  347. {
  348. int res;
  349. if (!value && !PyErr_Occurred()) {
  350. // PyModule_AddObject() raises TypeError in this case
  351. PyErr_SetString(PyExc_SystemError,
  352. "PyModule_AddObjectRef() must be called "
  353. "with an exception raised if value is NULL");
  354. return -1;
  355. }
  356. Py_XINCREF(value);
  357. res = PyModule_AddObject(module, name, value);
  358. if (res < 0) {
  359. Py_XDECREF(value);
  360. }
  361. return res;
  362. }
  363. #endif
  364. // bpo-40024 added PyModule_AddType() to Python 3.9.0a5
  365. #if PY_VERSION_HEX < 0x030900A5
  366. static inline int PyModule_AddType(PyObject *module, PyTypeObject *type)
  367. {
  368. const char *name, *dot;
  369. if (PyType_Ready(type) < 0) {
  370. return -1;
  371. }
  372. // inline _PyType_Name()
  373. name = type->tp_name;
  374. assert(name != _Py_NULL);
  375. dot = strrchr(name, '.');
  376. if (dot != _Py_NULL) {
  377. name = dot + 1;
  378. }
  379. return PyModule_AddObjectRef(module, name, _PyObject_CAST(type));
  380. }
  381. #endif
  382. // bpo-40241 added PyObject_GC_IsTracked() to Python 3.9.0a6.
  383. // bpo-4688 added _PyObject_GC_IS_TRACKED() to Python 2.7.0a2.
  384. #if PY_VERSION_HEX < 0x030900A6 && !defined(PYPY_VERSION)
  385. static inline int PyObject_GC_IsTracked(PyObject* obj)
  386. {
  387. return (PyObject_IS_GC(obj) && _PyObject_GC_IS_TRACKED(obj));
  388. }
  389. #endif
  390. // bpo-40241 added PyObject_GC_IsFinalized() to Python 3.9.0a6.
  391. // bpo-18112 added _PyGCHead_FINALIZED() to Python 3.4.0 final.
  392. #if PY_VERSION_HEX < 0x030900A6 && PY_VERSION_HEX >= 0x030400F0 && !defined(PYPY_VERSION)
  393. static inline int PyObject_GC_IsFinalized(PyObject *obj)
  394. {
  395. PyGC_Head *gc = _Py_CAST(PyGC_Head*, obj) - 1;
  396. return (PyObject_IS_GC(obj) && _PyGCHead_FINALIZED(gc));
  397. }
  398. #endif
  399. // bpo-39573 added Py_IS_TYPE() to Python 3.9.0a4
  400. #if PY_VERSION_HEX < 0x030900A4 && !defined(Py_IS_TYPE)
  401. static inline int _Py_IS_TYPE(PyObject *ob, PyTypeObject *type) {
  402. return Py_TYPE(ob) == type;
  403. }
  404. #define Py_IS_TYPE(ob, type) _Py_IS_TYPE(_PyObject_CAST(ob), type)
  405. #endif
  406. // bpo-46906 added PyFloat_Pack2() and PyFloat_Unpack2() to Python 3.11a7.
  407. // bpo-11734 added _PyFloat_Pack2() and _PyFloat_Unpack2() to Python 3.6.0b1.
  408. // Python 3.11a2 moved _PyFloat_Pack2() and _PyFloat_Unpack2() to the internal
  409. // C API: Python 3.11a2-3.11a6 versions are not supported.
  410. #if 0x030600B1 <= PY_VERSION_HEX && PY_VERSION_HEX <= 0x030B00A1 && !defined(PYPY_VERSION)
  411. static inline int PyFloat_Pack2(double x, char *p, int le)
  412. { return _PyFloat_Pack2(x, (unsigned char*)p, le); }
  413. static inline double PyFloat_Unpack2(const char *p, int le)
  414. { return _PyFloat_Unpack2((const unsigned char *)p, le); }
  415. #endif
  416. // bpo-46906 added PyFloat_Pack4(), PyFloat_Pack8(), PyFloat_Unpack4() and
  417. // PyFloat_Unpack8() to Python 3.11a7.
  418. // Python 3.11a2 moved _PyFloat_Pack4(), _PyFloat_Pack8(), _PyFloat_Unpack4()
  419. // and _PyFloat_Unpack8() to the internal C API: Python 3.11a2-3.11a6 versions
  420. // are not supported.
  421. #if PY_VERSION_HEX <= 0x030B00A1 && !defined(PYPY_VERSION)
  422. static inline int PyFloat_Pack4(double x, char *p, int le)
  423. { return _PyFloat_Pack4(x, (unsigned char*)p, le); }
  424. static inline int PyFloat_Pack8(double x, char *p, int le)
  425. { return _PyFloat_Pack8(x, (unsigned char*)p, le); }
  426. static inline double PyFloat_Unpack4(const char *p, int le)
  427. { return _PyFloat_Unpack4((const unsigned char *)p, le); }
  428. static inline double PyFloat_Unpack8(const char *p, int le)
  429. { return _PyFloat_Unpack8((const unsigned char *)p, le); }
  430. #endif
  431. // gh-92154 added PyCode_GetCode() to Python 3.11.0b1
  432. #if PY_VERSION_HEX < 0x030B00B1 && !defined(PYPY_VERSION)
  433. static inline PyObject* PyCode_GetCode(PyCodeObject *code)
  434. {
  435. return Py_NewRef(code->co_code);
  436. }
  437. #endif
  438. // gh-95008 added PyCode_GetVarnames() to Python 3.11.0rc1
  439. #if PY_VERSION_HEX < 0x030B00C1 && !defined(PYPY_VERSION)
  440. static inline PyObject* PyCode_GetVarnames(PyCodeObject *code)
  441. {
  442. return Py_NewRef(code->co_varnames);
  443. }
  444. #endif
  445. // gh-95008 added PyCode_GetFreevars() to Python 3.11.0rc1
  446. #if PY_VERSION_HEX < 0x030B00C1 && !defined(PYPY_VERSION)
  447. static inline PyObject* PyCode_GetFreevars(PyCodeObject *code)
  448. {
  449. return Py_NewRef(code->co_freevars);
  450. }
  451. #endif
  452. // gh-95008 added PyCode_GetCellvars() to Python 3.11.0rc1
  453. #if PY_VERSION_HEX < 0x030B00C1 && !defined(PYPY_VERSION)
  454. static inline PyObject* PyCode_GetCellvars(PyCodeObject *code)
  455. {
  456. return Py_NewRef(code->co_cellvars);
  457. }
  458. #endif
  459. // Py_UNUSED() was added to Python 3.4.0b2.
  460. #if PY_VERSION_HEX < 0x030400B2 && !defined(Py_UNUSED)
  461. # if defined(__GNUC__) || defined(__clang__)
  462. # define Py_UNUSED(name) _unused_ ## name __attribute__((unused))
  463. # else
  464. # define Py_UNUSED(name) _unused_ ## name
  465. # endif
  466. #endif
  467. // gh-105922 added PyImport_AddModuleRef() to Python 3.13.0a1
  468. #if PY_VERSION_HEX < 0x030D00A0
  469. static inline PyObject* PyImport_AddModuleRef(const char *name)
  470. {
  471. return Py_XNewRef(PyImport_AddModule(name));
  472. }
  473. #endif
  474. // gh-105927 added PyWeakref_GetRef() to Python 3.13.0a1
  475. #if PY_VERSION_HEX < 0x030D0000
  476. static inline int PyWeakref_GetRef(PyObject *ref, PyObject **pobj)
  477. {
  478. PyObject *obj;
  479. if (ref != NULL && !PyWeakref_Check(ref)) {
  480. *pobj = NULL;
  481. PyErr_SetString(PyExc_TypeError, "expected a weakref");
  482. return -1;
  483. }
  484. obj = PyWeakref_GetObject(ref);
  485. if (obj == NULL) {
  486. // SystemError if ref is NULL
  487. *pobj = NULL;
  488. return -1;
  489. }
  490. if (obj == Py_None) {
  491. *pobj = NULL;
  492. return 0;
  493. }
  494. *pobj = Py_NewRef(obj);
  495. return 1;
  496. }
  497. #endif
  498. // bpo-36974 added PY_VECTORCALL_ARGUMENTS_OFFSET to Python 3.8b1
  499. #ifndef PY_VECTORCALL_ARGUMENTS_OFFSET
  500. # define PY_VECTORCALL_ARGUMENTS_OFFSET (_Py_CAST(size_t, 1) << (8 * sizeof(size_t) - 1))
  501. #endif
  502. // bpo-36974 added PyVectorcall_NARGS() to Python 3.8b1
  503. #if PY_VERSION_HEX < 0x030800B1
  504. static inline Py_ssize_t PyVectorcall_NARGS(size_t n)
  505. {
  506. return n & ~PY_VECTORCALL_ARGUMENTS_OFFSET;
  507. }
  508. #endif
  509. // gh-105922 added PyObject_Vectorcall() to Python 3.9.0a4
  510. #if PY_VERSION_HEX < 0x030900A4
  511. static inline PyObject*
  512. PyObject_Vectorcall(PyObject *callable, PyObject *const *args,
  513. size_t nargsf, PyObject *kwnames)
  514. {
  515. #if PY_VERSION_HEX >= 0x030800B1 && !defined(PYPY_VERSION)
  516. // bpo-36974 added _PyObject_Vectorcall() to Python 3.8.0b1
  517. return _PyObject_Vectorcall(callable, args, nargsf, kwnames);
  518. #else
  519. PyObject *posargs = NULL, *kwargs = NULL;
  520. PyObject *res;
  521. Py_ssize_t nposargs, nkwargs, i;
  522. if (nargsf != 0 && args == NULL) {
  523. PyErr_BadInternalCall();
  524. goto error;
  525. }
  526. if (kwnames != NULL && !PyTuple_Check(kwnames)) {
  527. PyErr_BadInternalCall();
  528. goto error;
  529. }
  530. nposargs = (Py_ssize_t)PyVectorcall_NARGS(nargsf);
  531. if (kwnames) {
  532. nkwargs = PyTuple_GET_SIZE(kwnames);
  533. }
  534. else {
  535. nkwargs = 0;
  536. }
  537. posargs = PyTuple_New(nposargs);
  538. if (posargs == NULL) {
  539. goto error;
  540. }
  541. if (nposargs) {
  542. for (i=0; i < nposargs; i++) {
  543. PyTuple_SET_ITEM(posargs, i, Py_NewRef(*args));
  544. args++;
  545. }
  546. }
  547. if (nkwargs) {
  548. kwargs = PyDict_New();
  549. if (kwargs == NULL) {
  550. goto error;
  551. }
  552. for (i = 0; i < nkwargs; i++) {
  553. PyObject *key = PyTuple_GET_ITEM(kwnames, i);
  554. PyObject *value = *args;
  555. args++;
  556. if (PyDict_SetItem(kwargs, key, value) < 0) {
  557. goto error;
  558. }
  559. }
  560. }
  561. else {
  562. kwargs = NULL;
  563. }
  564. res = PyObject_Call(callable, posargs, kwargs);
  565. Py_DECREF(posargs);
  566. Py_XDECREF(kwargs);
  567. return res;
  568. error:
  569. Py_DECREF(posargs);
  570. Py_XDECREF(kwargs);
  571. return NULL;
  572. #endif
  573. }
  574. #endif
  575. // gh-106521 added PyObject_GetOptionalAttr() and
  576. // PyObject_GetOptionalAttrString() to Python 3.13.0a1
  577. #if PY_VERSION_HEX < 0x030D00A1
  578. static inline int
  579. PyObject_GetOptionalAttr(PyObject *obj, PyObject *attr_name, PyObject **result)
  580. {
  581. // bpo-32571 added _PyObject_LookupAttr() to Python 3.7.0b1
  582. #if PY_VERSION_HEX >= 0x030700B1 && !defined(PYPY_VERSION)
  583. return _PyObject_LookupAttr(obj, attr_name, result);
  584. #else
  585. *result = PyObject_GetAttr(obj, attr_name);
  586. if (*result != NULL) {
  587. return 1;
  588. }
  589. if (!PyErr_Occurred()) {
  590. return 0;
  591. }
  592. if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
  593. PyErr_Clear();
  594. return 0;
  595. }
  596. return -1;
  597. #endif
  598. }
  599. static inline int
  600. PyObject_GetOptionalAttrString(PyObject *obj, const char *attr_name, PyObject **result)
  601. {
  602. PyObject *name_obj;
  603. int rc;
  604. #if PY_VERSION_HEX >= 0x03000000
  605. name_obj = PyUnicode_FromString(attr_name);
  606. #else
  607. name_obj = PyString_FromString(attr_name);
  608. #endif
  609. if (name_obj == NULL) {
  610. *result = NULL;
  611. return -1;
  612. }
  613. rc = PyObject_GetOptionalAttr(obj, name_obj, result);
  614. Py_DECREF(name_obj);
  615. return rc;
  616. }
  617. #endif
  618. // gh-106307 added PyObject_GetOptionalAttr() and
  619. // PyMapping_GetOptionalItemString() to Python 3.13.0a1
  620. #if PY_VERSION_HEX < 0x030D00A1
  621. static inline int
  622. PyMapping_GetOptionalItem(PyObject *obj, PyObject *key, PyObject **result)
  623. {
  624. *result = PyObject_GetItem(obj, key);
  625. if (*result) {
  626. return 1;
  627. }
  628. if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
  629. return -1;
  630. }
  631. PyErr_Clear();
  632. return 0;
  633. }
  634. static inline int
  635. PyMapping_GetOptionalItemString(PyObject *obj, const char *key, PyObject **result)
  636. {
  637. PyObject *key_obj;
  638. int rc;
  639. #if PY_VERSION_HEX >= 0x03000000
  640. key_obj = PyUnicode_FromString(key);
  641. #else
  642. key_obj = PyString_FromString(key);
  643. #endif
  644. if (key_obj == NULL) {
  645. *result = NULL;
  646. return -1;
  647. }
  648. rc = PyMapping_GetOptionalItem(obj, key_obj, result);
  649. Py_DECREF(key_obj);
  650. return rc;
  651. }
  652. #endif
  653. // gh-108511 added PyMapping_HasKeyWithError() and
  654. // PyMapping_HasKeyStringWithError() to Python 3.13.0a1
  655. #if PY_VERSION_HEX < 0x030D00A1
  656. static inline int
  657. PyMapping_HasKeyWithError(PyObject *obj, PyObject *key)
  658. {
  659. PyObject *res;
  660. int rc = PyMapping_GetOptionalItem(obj, key, &res);
  661. Py_XDECREF(res);
  662. return rc;
  663. }
  664. static inline int
  665. PyMapping_HasKeyStringWithError(PyObject *obj, const char *key)
  666. {
  667. PyObject *res;
  668. int rc = PyMapping_GetOptionalItemString(obj, key, &res);
  669. Py_XDECREF(res);
  670. return rc;
  671. }
  672. #endif
  673. // gh-108511 added PyObject_HasAttrWithError() and
  674. // PyObject_HasAttrStringWithError() to Python 3.13.0a1
  675. #if PY_VERSION_HEX < 0x030D00A1
  676. static inline int
  677. PyObject_HasAttrWithError(PyObject *obj, PyObject *attr)
  678. {
  679. PyObject *res;
  680. int rc = PyObject_GetOptionalAttr(obj, attr, &res);
  681. Py_XDECREF(res);
  682. return rc;
  683. }
  684. static inline int
  685. PyObject_HasAttrStringWithError(PyObject *obj, const char *attr)
  686. {
  687. PyObject *res;
  688. int rc = PyObject_GetOptionalAttrString(obj, attr, &res);
  689. Py_XDECREF(res);
  690. return rc;
  691. }
  692. #endif
  693. // gh-106004 added PyDict_GetItemRef() and PyDict_GetItemStringRef()
  694. // to Python 3.13.0a1
  695. #if PY_VERSION_HEX < 0x030D00A1
  696. static inline int
  697. PyDict_GetItemRef(PyObject *mp, PyObject *key, PyObject **result)
  698. {
  699. #if PY_VERSION_HEX >= 0x03000000
  700. PyObject *item = PyDict_GetItemWithError(mp, key);
  701. #else
  702. PyObject *item = _PyDict_GetItemWithError(mp, key);
  703. #endif
  704. if (item != NULL) {
  705. *result = Py_NewRef(item);
  706. return 1; // found
  707. }
  708. if (!PyErr_Occurred()) {
  709. *result = NULL;
  710. return 0; // not found
  711. }
  712. *result = NULL;
  713. return -1;
  714. }
  715. static inline int
  716. PyDict_GetItemStringRef(PyObject *mp, const char *key, PyObject **result)
  717. {
  718. int res;
  719. #if PY_VERSION_HEX >= 0x03000000
  720. PyObject *key_obj = PyUnicode_FromString(key);
  721. #else
  722. PyObject *key_obj = PyString_FromString(key);
  723. #endif
  724. if (key_obj == NULL) {
  725. *result = NULL;
  726. return -1;
  727. }
  728. res = PyDict_GetItemRef(mp, key_obj, result);
  729. Py_DECREF(key_obj);
  730. return res;
  731. }
  732. #endif
  733. // gh-106307 added PyModule_Add() to Python 3.13.0a1
  734. #if PY_VERSION_HEX < 0x030D00A1
  735. static inline int
  736. PyModule_Add(PyObject *mod, const char *name, PyObject *value)
  737. {
  738. int res = PyModule_AddObjectRef(mod, name, value);
  739. Py_XDECREF(value);
  740. return res;
  741. }
  742. #endif
  743. // gh-108014 added Py_IsFinalizing() to Python 3.13.0a1
  744. // bpo-1856 added _Py_Finalizing to Python 3.2.1b1.
  745. // _Py_IsFinalizing() was added to PyPy 7.3.0.
  746. #if (0x030201B1 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x030D00A1) \
  747. && (!defined(PYPY_VERSION_NUM) || PYPY_VERSION_NUM >= 0x7030000)
  748. static inline int Py_IsFinalizing(void)
  749. {
  750. #if PY_VERSION_HEX >= 0x030700A1
  751. // _Py_IsFinalizing() was added to Python 3.7.0a1.
  752. return _Py_IsFinalizing();
  753. #else
  754. return (_Py_Finalizing != NULL);
  755. #endif
  756. }
  757. #endif
  758. // gh-108323 added PyDict_ContainsString() to Python 3.13.0a1
  759. #if PY_VERSION_HEX < 0x030D00A1
  760. static inline int PyDict_ContainsString(PyObject *op, const char *key)
  761. {
  762. PyObject *key_obj = PyUnicode_FromString(key);
  763. if (key_obj == NULL) {
  764. return -1;
  765. }
  766. int res = PyDict_Contains(op, key_obj);
  767. Py_DECREF(key_obj);
  768. return res;
  769. }
  770. #endif
  771. // gh-108445 added PyLong_AsInt() to Python 3.13.0a1
  772. #if PY_VERSION_HEX < 0x030D00A1
  773. static inline int PyLong_AsInt(PyObject *obj)
  774. {
  775. #ifdef PYPY_VERSION
  776. long value = PyLong_AsLong(obj);
  777. if (value == -1 && PyErr_Occurred()) {
  778. return -1;
  779. }
  780. if (value < (long)INT_MIN || (long)INT_MAX < value) {
  781. PyErr_SetString(PyExc_OverflowError,
  782. "Python int too large to convert to C int");
  783. return -1;
  784. }
  785. return (int)value;
  786. #else
  787. return _PyLong_AsInt(obj);
  788. #endif
  789. }
  790. #endif
  791. // gh-107073 added PyObject_VisitManagedDict() to Python 3.13.0a1
  792. #if PY_VERSION_HEX < 0x030D00A1
  793. static inline int
  794. PyObject_VisitManagedDict(PyObject *obj, visitproc visit, void *arg)
  795. {
  796. PyObject **dict = _PyObject_GetDictPtr(obj);
  797. if (dict == NULL || *dict == NULL) {
  798. return -1;
  799. }
  800. Py_VISIT(*dict);
  801. return 0;
  802. }
  803. static inline void
  804. PyObject_ClearManagedDict(PyObject *obj)
  805. {
  806. PyObject **dict = _PyObject_GetDictPtr(obj);
  807. if (dict == NULL || *dict == NULL) {
  808. return;
  809. }
  810. Py_CLEAR(*dict);
  811. }
  812. #endif
  813. // gh-108867 added PyThreadState_GetUnchecked() to Python 3.13.0a1
  814. // Python 3.5.2 added _PyThreadState_UncheckedGet().
  815. #if PY_VERSION_HEX >= 0x03050200 && PY_VERSION_HEX < 0x030D00A1
  816. static inline PyThreadState*
  817. PyThreadState_GetUnchecked(void)
  818. {
  819. return _PyThreadState_UncheckedGet();
  820. }
  821. #endif
  822. // gh-110289 added PyUnicode_EqualToUTF8() and PyUnicode_EqualToUTF8AndSize()
  823. // to Python 3.13.0a1
  824. #if PY_VERSION_HEX < 0x030D00A1
  825. static inline int
  826. PyUnicode_EqualToUTF8AndSize(PyObject *unicode, const char *str, Py_ssize_t str_len)
  827. {
  828. Py_ssize_t len;
  829. const void *utf8;
  830. PyObject *exc_type, *exc_value, *exc_tb;
  831. int res;
  832. // API cannot report errors so save/restore the exception
  833. PyErr_Fetch(&exc_type, &exc_value, &exc_tb);
  834. // Python 3.3.0a1 added PyUnicode_AsUTF8AndSize()
  835. #if PY_VERSION_HEX >= 0x030300A1
  836. if (PyUnicode_IS_ASCII(unicode)) {
  837. utf8 = PyUnicode_DATA(unicode);
  838. len = PyUnicode_GET_LENGTH(unicode);
  839. }
  840. else {
  841. utf8 = PyUnicode_AsUTF8AndSize(unicode, &len);
  842. if (utf8 == NULL) {
  843. // Memory allocation failure. The API cannot report error,
  844. // so ignore the exception and return 0.
  845. res = 0;
  846. goto done;
  847. }
  848. }
  849. if (len != str_len) {
  850. res = 0;
  851. goto done;
  852. }
  853. res = (memcmp(utf8, str, (size_t)len) == 0);
  854. #else
  855. PyObject *bytes = PyUnicode_AsUTF8String(unicode);
  856. if (bytes == NULL) {
  857. // Memory allocation failure. The API cannot report error,
  858. // so ignore the exception and return 0.
  859. res = 0;
  860. goto done;
  861. }
  862. #if PY_VERSION_HEX >= 0x03000000
  863. len = PyBytes_GET_SIZE(bytes);
  864. utf8 = PyBytes_AS_STRING(bytes);
  865. #else
  866. len = PyString_GET_SIZE(bytes);
  867. utf8 = PyString_AS_STRING(bytes);
  868. #endif
  869. if (len != str_len) {
  870. Py_DECREF(bytes);
  871. res = 0;
  872. goto done;
  873. }
  874. res = (memcmp(utf8, str, (size_t)len) == 0);
  875. Py_DECREF(bytes);
  876. #endif
  877. done:
  878. PyErr_Restore(exc_type, exc_value, exc_tb);
  879. return res;
  880. }
  881. static inline int
  882. PyUnicode_EqualToUTF8(PyObject *unicode, const char *str)
  883. {
  884. return PyUnicode_EqualToUTF8AndSize(unicode, str, (Py_ssize_t)strlen(str));
  885. }
  886. #endif
  887. // gh-111138 added PyList_Extend() and PyList_Clear() to Python 3.13.0a2
  888. #if PY_VERSION_HEX < 0x030D00A2
  889. static inline int
  890. PyList_Extend(PyObject *list, PyObject *iterable)
  891. {
  892. return PyList_SetSlice(list, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, iterable);
  893. }
  894. static inline int
  895. PyList_Clear(PyObject *list)
  896. {
  897. return PyList_SetSlice(list, 0, PY_SSIZE_T_MAX, NULL);
  898. }
  899. #endif
  900. // gh-111262 added PyDict_Pop() and PyDict_PopString() to Python 3.13.0a2
  901. #if PY_VERSION_HEX < 0x030D00A2
  902. static inline int
  903. PyDict_Pop(PyObject *dict, PyObject *key, PyObject **result)
  904. {
  905. PyObject *value;
  906. if (!PyDict_Check(dict)) {
  907. PyErr_BadInternalCall();
  908. if (result) {
  909. *result = NULL;
  910. }
  911. return -1;
  912. }
  913. // bpo-16991 added _PyDict_Pop() to Python 3.5.0b2.
  914. // Python 3.6.0b3 changed _PyDict_Pop() first argument type to PyObject*.
  915. // Python 3.13.0a1 removed _PyDict_Pop().
  916. #if defined(PYPY_VERSION) || PY_VERSION_HEX < 0x030500b2 || PY_VERSION_HEX >= 0x030D0000
  917. value = PyObject_CallMethod(dict, "pop", "O", key);
  918. #elif PY_VERSION_HEX < 0x030600b3
  919. value = _PyDict_Pop(_Py_CAST(PyDictObject*, dict), key, NULL);
  920. #else
  921. value = _PyDict_Pop(dict, key, NULL);
  922. #endif
  923. if (value == NULL) {
  924. if (result) {
  925. *result = NULL;
  926. }
  927. if (PyErr_Occurred() && !PyErr_ExceptionMatches(PyExc_KeyError)) {
  928. return -1;
  929. }
  930. PyErr_Clear();
  931. return 0;
  932. }
  933. if (result) {
  934. *result = value;
  935. }
  936. else {
  937. Py_DECREF(value);
  938. }
  939. return 1;
  940. }
  941. static inline int
  942. PyDict_PopString(PyObject *dict, const char *key, PyObject **result)
  943. {
  944. PyObject *key_obj = PyUnicode_FromString(key);
  945. if (key_obj == NULL) {
  946. if (result != NULL) {
  947. *result = NULL;
  948. }
  949. return -1;
  950. }
  951. int res = PyDict_Pop(dict, key_obj, result);
  952. Py_DECREF(key_obj);
  953. return res;
  954. }
  955. #endif
  956. #if PY_VERSION_HEX < 0x030200A4
  957. // Python 3.2.0a4 added Py_hash_t type
  958. typedef Py_ssize_t Py_hash_t;
  959. #endif
  960. // gh-111545 added Py_HashPointer() to Python 3.13.0a3
  961. #if PY_VERSION_HEX < 0x030D00A3
  962. static inline Py_hash_t Py_HashPointer(const void *ptr)
  963. {
  964. #if PY_VERSION_HEX >= 0x030900A4 && !defined(PYPY_VERSION)
  965. return _Py_HashPointer(ptr);
  966. #else
  967. return _Py_HashPointer(_Py_CAST(void*, ptr));
  968. #endif
  969. }
  970. #endif
  971. // Python 3.13a4 added a PyTime API.
  972. // Use the private API added to Python 3.5.
  973. #if PY_VERSION_HEX < 0x030D00A4 && PY_VERSION_HEX >= 0x03050000
  974. typedef _PyTime_t PyTime_t;
  975. #define PyTime_MIN _PyTime_MIN
  976. #define PyTime_MAX _PyTime_MAX
  977. static inline double PyTime_AsSecondsDouble(PyTime_t t)
  978. { return _PyTime_AsSecondsDouble(t); }
  979. static inline int PyTime_Monotonic(PyTime_t *result)
  980. { return _PyTime_GetMonotonicClockWithInfo(result, NULL); }
  981. static inline int PyTime_Time(PyTime_t *result)
  982. { return _PyTime_GetSystemClockWithInfo(result, NULL); }
  983. static inline int PyTime_PerfCounter(PyTime_t *result)
  984. {
  985. #if PY_VERSION_HEX >= 0x03070000 && !defined(PYPY_VERSION)
  986. return _PyTime_GetPerfCounterWithInfo(result, NULL);
  987. #elif PY_VERSION_HEX >= 0x03070000
  988. // Call time.perf_counter_ns() and convert Python int object to PyTime_t.
  989. // Cache time.perf_counter_ns() function for best performance.
  990. static PyObject *func = NULL;
  991. if (func == NULL) {
  992. PyObject *mod = PyImport_ImportModule("time");
  993. if (mod == NULL) {
  994. return -1;
  995. }
  996. func = PyObject_GetAttrString(mod, "perf_counter_ns");
  997. Py_DECREF(mod);
  998. if (func == NULL) {
  999. return -1;
  1000. }
  1001. }
  1002. PyObject *res = PyObject_CallNoArgs(func);
  1003. if (res == NULL) {
  1004. return -1;
  1005. }
  1006. long long value = PyLong_AsLongLong(res);
  1007. Py_DECREF(res);
  1008. if (value == -1 && PyErr_Occurred()) {
  1009. return -1;
  1010. }
  1011. Py_BUILD_ASSERT(sizeof(value) >= sizeof(PyTime_t));
  1012. *result = (PyTime_t)value;
  1013. return 0;
  1014. #else
  1015. // Call time.perf_counter() and convert C double to PyTime_t.
  1016. // Cache time.perf_counter() function for best performance.
  1017. static PyObject *func = NULL;
  1018. if (func == NULL) {
  1019. PyObject *mod = PyImport_ImportModule("time");
  1020. if (mod == NULL) {
  1021. return -1;
  1022. }
  1023. func = PyObject_GetAttrString(mod, "perf_counter");
  1024. Py_DECREF(mod);
  1025. if (func == NULL) {
  1026. return -1;
  1027. }
  1028. }
  1029. PyObject *res = PyObject_CallNoArgs(func);
  1030. if (res == NULL) {
  1031. return -1;
  1032. }
  1033. double d = PyFloat_AsDouble(res);
  1034. Py_DECREF(res);
  1035. if (d == -1.0 && PyErr_Occurred()) {
  1036. return -1;
  1037. }
  1038. // Avoid floor() to avoid having to link to libm
  1039. *result = (PyTime_t)(d * 1e9);
  1040. return 0;
  1041. #endif
  1042. }
  1043. #endif
  1044. // gh-111389 added hash constants to Python 3.13.0a5. These constants were
  1045. // added first as private macros to Python 3.4.0b1 and PyPy 7.3.8.
  1046. #if (!defined(PyHASH_BITS) \
  1047. && ((!defined(PYPY_VERSION) && PY_VERSION_HEX >= 0x030400B1) \
  1048. || (defined(PYPY_VERSION) && PY_VERSION_HEX >= 0x03070000 \
  1049. && PYPY_VERSION_NUM >= 0x07030800)))
  1050. # define PyHASH_BITS _PyHASH_BITS
  1051. # define PyHASH_MODULUS _PyHASH_MODULUS
  1052. # define PyHASH_INF _PyHASH_INF
  1053. # define PyHASH_IMAG _PyHASH_IMAG
  1054. #endif
  1055. // gh-111545 added Py_GetConstant() and Py_GetConstantBorrowed()
  1056. // to Python 3.13.0a6
  1057. #if PY_VERSION_HEX < 0x030D00A6 && !defined(Py_CONSTANT_NONE)
  1058. #define Py_CONSTANT_NONE 0
  1059. #define Py_CONSTANT_FALSE 1
  1060. #define Py_CONSTANT_TRUE 2
  1061. #define Py_CONSTANT_ELLIPSIS 3
  1062. #define Py_CONSTANT_NOT_IMPLEMENTED 4
  1063. #define Py_CONSTANT_ZERO 5
  1064. #define Py_CONSTANT_ONE 6
  1065. #define Py_CONSTANT_EMPTY_STR 7
  1066. #define Py_CONSTANT_EMPTY_BYTES 8
  1067. #define Py_CONSTANT_EMPTY_TUPLE 9
  1068. static inline PyObject* Py_GetConstant(unsigned int constant_id)
  1069. {
  1070. static PyObject* constants[Py_CONSTANT_EMPTY_TUPLE + 1] = {NULL};
  1071. if (constants[Py_CONSTANT_NONE] == NULL) {
  1072. constants[Py_CONSTANT_NONE] = Py_None;
  1073. constants[Py_CONSTANT_FALSE] = Py_False;
  1074. constants[Py_CONSTANT_TRUE] = Py_True;
  1075. constants[Py_CONSTANT_ELLIPSIS] = Py_Ellipsis;
  1076. constants[Py_CONSTANT_NOT_IMPLEMENTED] = Py_NotImplemented;
  1077. constants[Py_CONSTANT_ZERO] = PyLong_FromLong(0);
  1078. if (constants[Py_CONSTANT_ZERO] == NULL) {
  1079. goto fatal_error;
  1080. }
  1081. constants[Py_CONSTANT_ONE] = PyLong_FromLong(1);
  1082. if (constants[Py_CONSTANT_ONE] == NULL) {
  1083. goto fatal_error;
  1084. }
  1085. constants[Py_CONSTANT_EMPTY_STR] = PyUnicode_FromStringAndSize("", 0);
  1086. if (constants[Py_CONSTANT_EMPTY_STR] == NULL) {
  1087. goto fatal_error;
  1088. }
  1089. constants[Py_CONSTANT_EMPTY_BYTES] = PyBytes_FromStringAndSize("", 0);
  1090. if (constants[Py_CONSTANT_EMPTY_BYTES] == NULL) {
  1091. goto fatal_error;
  1092. }
  1093. constants[Py_CONSTANT_EMPTY_TUPLE] = PyTuple_New(0);
  1094. if (constants[Py_CONSTANT_EMPTY_TUPLE] == NULL) {
  1095. goto fatal_error;
  1096. }
  1097. // goto dance to avoid compiler warnings about Py_FatalError()
  1098. goto init_done;
  1099. fatal_error:
  1100. // This case should never happen
  1101. Py_FatalError("Py_GetConstant() failed to get constants");
  1102. }
  1103. init_done:
  1104. if (constant_id <= Py_CONSTANT_EMPTY_TUPLE) {
  1105. return Py_NewRef(constants[constant_id]);
  1106. }
  1107. else {
  1108. PyErr_BadInternalCall();
  1109. return NULL;
  1110. }
  1111. }
  1112. static inline PyObject* Py_GetConstantBorrowed(unsigned int constant_id)
  1113. {
  1114. PyObject *obj = Py_GetConstant(constant_id);
  1115. Py_XDECREF(obj);
  1116. return obj;
  1117. }
  1118. #endif
  1119. // gh-114329 added PyList_GetItemRef() to Python 3.13.0a4
  1120. #if PY_VERSION_HEX < 0x030D00A4
  1121. static inline PyObject *
  1122. PyList_GetItemRef(PyObject *op, Py_ssize_t index)
  1123. {
  1124. PyObject *item = PyList_GetItem(op, index);
  1125. Py_XINCREF(item);
  1126. return item;
  1127. }
  1128. #endif
  1129. // gh-114329 added PyList_GetItemRef() to Python 3.13.0a4
  1130. #if PY_VERSION_HEX < 0x030D00A4
  1131. static inline int
  1132. PyDict_SetDefaultRef(PyObject *d, PyObject *key, PyObject *default_value,
  1133. PyObject **result)
  1134. {
  1135. PyObject *value;
  1136. if (PyDict_GetItemRef(d, key, &value) < 0) {
  1137. // get error
  1138. if (result) {
  1139. *result = NULL;
  1140. }
  1141. return -1;
  1142. }
  1143. if (value != NULL) {
  1144. // present
  1145. if (result) {
  1146. *result = value;
  1147. }
  1148. else {
  1149. Py_DECREF(value);
  1150. }
  1151. return 1;
  1152. }
  1153. // missing: set the item
  1154. if (PyDict_SetItem(d, key, default_value) < 0) {
  1155. // set error
  1156. if (result) {
  1157. *result = NULL;
  1158. }
  1159. return -1;
  1160. }
  1161. if (result) {
  1162. *result = Py_NewRef(default_value);
  1163. }
  1164. return 0;
  1165. }
  1166. #endif
  1167. #if PY_VERSION_HEX < 0x030D00B3
  1168. # define Py_BEGIN_CRITICAL_SECTION(op) {
  1169. # define Py_END_CRITICAL_SECTION() }
  1170. # define Py_BEGIN_CRITICAL_SECTION2(a, b) {
  1171. # define Py_END_CRITICAL_SECTION2() }
  1172. #endif
  1173. #if PY_VERSION_HEX < 0x030E0000 && PY_VERSION_HEX >= 0x03060000 && !defined(PYPY_VERSION)
  1174. typedef struct PyUnicodeWriter PyUnicodeWriter;
  1175. static inline void PyUnicodeWriter_Discard(PyUnicodeWriter *writer)
  1176. {
  1177. _PyUnicodeWriter_Dealloc((_PyUnicodeWriter*)writer);
  1178. PyMem_Free(writer);
  1179. }
  1180. static inline PyUnicodeWriter* PyUnicodeWriter_Create(Py_ssize_t length)
  1181. {
  1182. if (length < 0) {
  1183. PyErr_SetString(PyExc_ValueError,
  1184. "length must be positive");
  1185. return NULL;
  1186. }
  1187. const size_t size = sizeof(_PyUnicodeWriter);
  1188. PyUnicodeWriter *pub_writer = (PyUnicodeWriter *)PyMem_Malloc(size);
  1189. if (pub_writer == _Py_NULL) {
  1190. PyErr_NoMemory();
  1191. return _Py_NULL;
  1192. }
  1193. _PyUnicodeWriter *writer = (_PyUnicodeWriter *)pub_writer;
  1194. _PyUnicodeWriter_Init(writer);
  1195. if (_PyUnicodeWriter_Prepare(writer, length, 127) < 0) {
  1196. PyUnicodeWriter_Discard(pub_writer);
  1197. return NULL;
  1198. }
  1199. writer->overallocate = 1;
  1200. return pub_writer;
  1201. }
  1202. static inline PyObject* PyUnicodeWriter_Finish(PyUnicodeWriter *writer)
  1203. {
  1204. PyObject *str = _PyUnicodeWriter_Finish((_PyUnicodeWriter*)writer);
  1205. assert(((_PyUnicodeWriter*)writer)->buffer == NULL);
  1206. PyMem_Free(writer);
  1207. return str;
  1208. }
  1209. static inline int
  1210. PyUnicodeWriter_WriteChar(PyUnicodeWriter *writer, Py_UCS4 ch)
  1211. {
  1212. if (ch > 0x10ffff) {
  1213. PyErr_SetString(PyExc_ValueError,
  1214. "character must be in range(0x110000)");
  1215. return -1;
  1216. }
  1217. return _PyUnicodeWriter_WriteChar((_PyUnicodeWriter*)writer, ch);
  1218. }
  1219. static inline int
  1220. PyUnicodeWriter_WriteStr(PyUnicodeWriter *writer, PyObject *obj)
  1221. {
  1222. PyObject *str = PyObject_Str(obj);
  1223. if (str == NULL) {
  1224. return -1;
  1225. }
  1226. int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str);
  1227. Py_DECREF(str);
  1228. return res;
  1229. }
  1230. static inline int
  1231. PyUnicodeWriter_WriteRepr(PyUnicodeWriter *writer, PyObject *obj)
  1232. {
  1233. PyObject *str = PyObject_Repr(obj);
  1234. if (str == NULL) {
  1235. return -1;
  1236. }
  1237. int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str);
  1238. Py_DECREF(str);
  1239. return res;
  1240. }
  1241. static inline int
  1242. PyUnicodeWriter_WriteUTF8(PyUnicodeWriter *writer,
  1243. const char *str, Py_ssize_t size)
  1244. {
  1245. if (size < 0) {
  1246. size = (Py_ssize_t)strlen(str);
  1247. }
  1248. PyObject *str_obj = PyUnicode_FromStringAndSize(str, size);
  1249. if (str_obj == _Py_NULL) {
  1250. return -1;
  1251. }
  1252. int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str_obj);
  1253. Py_DECREF(str_obj);
  1254. return res;
  1255. }
  1256. static inline int
  1257. PyUnicodeWriter_WriteWideChar(PyUnicodeWriter *writer,
  1258. const wchar_t *str, Py_ssize_t size)
  1259. {
  1260. if (size < 0) {
  1261. size = (Py_ssize_t)wcslen(str);
  1262. }
  1263. PyObject *str_obj = PyUnicode_FromWideChar(str, size);
  1264. if (str_obj == _Py_NULL) {
  1265. return -1;
  1266. }
  1267. int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str_obj);
  1268. Py_DECREF(str_obj);
  1269. return res;
  1270. }
  1271. static inline int
  1272. PyUnicodeWriter_WriteSubstring(PyUnicodeWriter *writer, PyObject *str,
  1273. Py_ssize_t start, Py_ssize_t end)
  1274. {
  1275. if (!PyUnicode_Check(str)) {
  1276. PyErr_Format(PyExc_TypeError, "expect str, not %T", str);
  1277. return -1;
  1278. }
  1279. if (start < 0 || start > end) {
  1280. PyErr_Format(PyExc_ValueError, "invalid start argument");
  1281. return -1;
  1282. }
  1283. if (end > PyUnicode_GET_LENGTH(str)) {
  1284. PyErr_Format(PyExc_ValueError, "invalid end argument");
  1285. return -1;
  1286. }
  1287. return _PyUnicodeWriter_WriteSubstring((_PyUnicodeWriter*)writer, str,
  1288. start, end);
  1289. }
  1290. static inline int
  1291. PyUnicodeWriter_Format(PyUnicodeWriter *writer, const char *format, ...)
  1292. {
  1293. va_list vargs;
  1294. va_start(vargs, format);
  1295. PyObject *str = PyUnicode_FromFormatV(format, vargs);
  1296. va_end(vargs);
  1297. if (str == _Py_NULL) {
  1298. return -1;
  1299. }
  1300. int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str);
  1301. Py_DECREF(str);
  1302. return res;
  1303. }
  1304. #endif // PY_VERSION_HEX < 0x030E0000
  1305. // gh-116560 added PyLong_GetSign() to Python 3.14.0a0
  1306. #if PY_VERSION_HEX < 0x030E00A0
  1307. static inline int PyLong_GetSign(PyObject *obj, int *sign)
  1308. {
  1309. if (!PyLong_Check(obj)) {
  1310. PyErr_Format(PyExc_TypeError, "expect int, got %s", Py_TYPE(obj)->tp_name);
  1311. return -1;
  1312. }
  1313. *sign = _PyLong_Sign(obj);
  1314. return 0;
  1315. }
  1316. #endif
  1317. // gh-126061 added PyLong_IsPositive/Negative/Zero() to Python in 3.14.0a2
  1318. #if PY_VERSION_HEX < 0x030E00A2
  1319. static inline int PyLong_IsPositive(PyObject *obj)
  1320. {
  1321. if (!PyLong_Check(obj)) {
  1322. PyErr_Format(PyExc_TypeError, "expected int, got %s", Py_TYPE(obj)->tp_name);
  1323. return -1;
  1324. }
  1325. return _PyLong_Sign(obj) == 1;
  1326. }
  1327. static inline int PyLong_IsNegative(PyObject *obj)
  1328. {
  1329. if (!PyLong_Check(obj)) {
  1330. PyErr_Format(PyExc_TypeError, "expected int, got %s", Py_TYPE(obj)->tp_name);
  1331. return -1;
  1332. }
  1333. return _PyLong_Sign(obj) == -1;
  1334. }
  1335. static inline int PyLong_IsZero(PyObject *obj)
  1336. {
  1337. if (!PyLong_Check(obj)) {
  1338. PyErr_Format(PyExc_TypeError, "expected int, got %s", Py_TYPE(obj)->tp_name);
  1339. return -1;
  1340. }
  1341. return _PyLong_Sign(obj) == 0;
  1342. }
  1343. #endif
  1344. // gh-124502 added PyUnicode_Equal() to Python 3.14.0a0
  1345. #if PY_VERSION_HEX < 0x030E00A0
  1346. static inline int PyUnicode_Equal(PyObject *str1, PyObject *str2)
  1347. {
  1348. if (!PyUnicode_Check(str1)) {
  1349. PyErr_Format(PyExc_TypeError, "first argument must be str, not %s",
  1350. Py_TYPE(str1)->tp_name);
  1351. return -1;
  1352. }
  1353. if (!PyUnicode_Check(str2)) {
  1354. PyErr_Format(PyExc_TypeError, "second argument must be str, not %s",
  1355. Py_TYPE(str2)->tp_name);
  1356. return -1;
  1357. }
  1358. #if PY_VERSION_HEX >= 0x030d0000 && !defined(PYPY_VERSION)
  1359. PyAPI_FUNC(int) _PyUnicode_Equal(PyObject *str1, PyObject *str2);
  1360. return _PyUnicode_Equal(str1, str2);
  1361. #elif PY_VERSION_HEX >= 0x03060000 && !defined(PYPY_VERSION)
  1362. return _PyUnicode_EQ(str1, str2);
  1363. #elif PY_VERSION_HEX >= 0x03090000 && defined(PYPY_VERSION)
  1364. return _PyUnicode_EQ(str1, str2);
  1365. #else
  1366. return (PyUnicode_Compare(str1, str2) == 0);
  1367. #endif
  1368. }
  1369. #endif
  1370. // gh-121645 added PyBytes_Join() to Python 3.14.0a0
  1371. #if PY_VERSION_HEX < 0x030E00A0
  1372. static inline PyObject* PyBytes_Join(PyObject *sep, PyObject *iterable)
  1373. {
  1374. return _PyBytes_Join(sep, iterable);
  1375. }
  1376. #endif
  1377. #if PY_VERSION_HEX < 0x030E00A0
  1378. static inline Py_hash_t Py_HashBuffer(const void *ptr, Py_ssize_t len)
  1379. {
  1380. #if PY_VERSION_HEX >= 0x03000000 && !defined(PYPY_VERSION)
  1381. PyAPI_FUNC(Py_hash_t) _Py_HashBytes(const void *src, Py_ssize_t len);
  1382. return _Py_HashBytes(ptr, len);
  1383. #else
  1384. Py_hash_t hash;
  1385. PyObject *bytes = PyBytes_FromStringAndSize((const char*)ptr, len);
  1386. if (bytes == NULL) {
  1387. return -1;
  1388. }
  1389. hash = PyObject_Hash(bytes);
  1390. Py_DECREF(bytes);
  1391. return hash;
  1392. #endif
  1393. }
  1394. #endif
  1395. #if PY_VERSION_HEX < 0x030E00A0
  1396. static inline int PyIter_NextItem(PyObject *iter, PyObject **item)
  1397. {
  1398. iternextfunc tp_iternext;
  1399. assert(iter != NULL);
  1400. assert(item != NULL);
  1401. tp_iternext = Py_TYPE(iter)->tp_iternext;
  1402. if (tp_iternext == NULL) {
  1403. *item = NULL;
  1404. PyErr_Format(PyExc_TypeError, "expected an iterator, got '%s'",
  1405. Py_TYPE(iter)->tp_name);
  1406. return -1;
  1407. }
  1408. if ((*item = tp_iternext(iter))) {
  1409. return 1;
  1410. }
  1411. if (!PyErr_Occurred()) {
  1412. return 0;
  1413. }
  1414. if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
  1415. PyErr_Clear();
  1416. return 0;
  1417. }
  1418. return -1;
  1419. }
  1420. #endif
  1421. #if PY_VERSION_HEX < 0x030E00A0
  1422. static inline PyObject* PyLong_FromInt32(int32_t value)
  1423. {
  1424. Py_BUILD_ASSERT(sizeof(long) >= 4);
  1425. return PyLong_FromLong(value);
  1426. }
  1427. static inline PyObject* PyLong_FromInt64(int64_t value)
  1428. {
  1429. Py_BUILD_ASSERT(sizeof(long long) >= 8);
  1430. return PyLong_FromLongLong(value);
  1431. }
  1432. static inline PyObject* PyLong_FromUInt32(uint32_t value)
  1433. {
  1434. Py_BUILD_ASSERT(sizeof(unsigned long) >= 4);
  1435. return PyLong_FromUnsignedLong(value);
  1436. }
  1437. static inline PyObject* PyLong_FromUInt64(uint64_t value)
  1438. {
  1439. Py_BUILD_ASSERT(sizeof(unsigned long long) >= 8);
  1440. return PyLong_FromUnsignedLongLong(value);
  1441. }
  1442. static inline int PyLong_AsInt32(PyObject *obj, int32_t *pvalue)
  1443. {
  1444. Py_BUILD_ASSERT(sizeof(int) == 4);
  1445. int value = PyLong_AsInt(obj);
  1446. if (value == -1 && PyErr_Occurred()) {
  1447. return -1;
  1448. }
  1449. *pvalue = (int32_t)value;
  1450. return 0;
  1451. }
  1452. static inline int PyLong_AsInt64(PyObject *obj, int64_t *pvalue)
  1453. {
  1454. Py_BUILD_ASSERT(sizeof(long long) == 8);
  1455. long long value = PyLong_AsLongLong(obj);
  1456. if (value == -1 && PyErr_Occurred()) {
  1457. return -1;
  1458. }
  1459. *pvalue = (int64_t)value;
  1460. return 0;
  1461. }
  1462. static inline int PyLong_AsUInt32(PyObject *obj, uint32_t *pvalue)
  1463. {
  1464. Py_BUILD_ASSERT(sizeof(long) >= 4);
  1465. unsigned long value = PyLong_AsUnsignedLong(obj);
  1466. if (value == (unsigned long)-1 && PyErr_Occurred()) {
  1467. return -1;
  1468. }
  1469. #if SIZEOF_LONG > 4
  1470. if ((unsigned long)UINT32_MAX < value) {
  1471. PyErr_SetString(PyExc_OverflowError,
  1472. "Python int too large to convert to C uint32_t");
  1473. return -1;
  1474. }
  1475. #endif
  1476. *pvalue = (uint32_t)value;
  1477. return 0;
  1478. }
  1479. static inline int PyLong_AsUInt64(PyObject *obj, uint64_t *pvalue)
  1480. {
  1481. Py_BUILD_ASSERT(sizeof(long long) == 8);
  1482. unsigned long long value = PyLong_AsUnsignedLongLong(obj);
  1483. if (value == (unsigned long long)-1 && PyErr_Occurred()) {
  1484. return -1;
  1485. }
  1486. *pvalue = (uint64_t)value;
  1487. return 0;
  1488. }
  1489. #endif
  1490. // gh-102471 added import and export API for integers to 3.14.0a2.
  1491. #if PY_VERSION_HEX < 0x030E00A2 && PY_VERSION_HEX >= 0x03000000 && !defined(PYPY_VERSION)
  1492. // Helpers to access PyLongObject internals.
  1493. static inline void
  1494. _PyLong_SetSignAndDigitCount(PyLongObject *op, int sign, Py_ssize_t size)
  1495. {
  1496. #if PY_VERSION_HEX >= 0x030C0000
  1497. op->long_value.lv_tag = (uintptr_t)(1 - sign) | ((uintptr_t)(size) << 3);
  1498. #elif PY_VERSION_HEX >= 0x030900A4
  1499. Py_SET_SIZE(op, sign * size);
  1500. #else
  1501. Py_SIZE(op) = sign * size;
  1502. #endif
  1503. }
  1504. static inline Py_ssize_t
  1505. _PyLong_DigitCount(const PyLongObject *op)
  1506. {
  1507. #if PY_VERSION_HEX >= 0x030C0000
  1508. return (Py_ssize_t)(op->long_value.lv_tag >> 3);
  1509. #else
  1510. return _PyLong_Sign((PyObject*)op) < 0 ? -Py_SIZE(op) : Py_SIZE(op);
  1511. #endif
  1512. }
  1513. static inline digit*
  1514. _PyLong_GetDigits(const PyLongObject *op)
  1515. {
  1516. #if PY_VERSION_HEX >= 0x030C0000
  1517. return (digit*)(op->long_value.ob_digit);
  1518. #else
  1519. return (digit*)(op->ob_digit);
  1520. #endif
  1521. }
  1522. typedef struct PyLongLayout {
  1523. uint8_t bits_per_digit;
  1524. uint8_t digit_size;
  1525. int8_t digits_order;
  1526. int8_t digit_endianness;
  1527. } PyLongLayout;
  1528. typedef struct PyLongExport {
  1529. int64_t value;
  1530. uint8_t negative;
  1531. Py_ssize_t ndigits;
  1532. const void *digits;
  1533. Py_uintptr_t _reserved;
  1534. } PyLongExport;
  1535. typedef struct PyLongWriter PyLongWriter;
  1536. static inline const PyLongLayout*
  1537. PyLong_GetNativeLayout(void)
  1538. {
  1539. static const PyLongLayout PyLong_LAYOUT = {
  1540. PyLong_SHIFT,
  1541. sizeof(digit),
  1542. -1, // least significant first
  1543. PY_LITTLE_ENDIAN ? -1 : 1,
  1544. };
  1545. return &PyLong_LAYOUT;
  1546. }
  1547. static inline int
  1548. PyLong_Export(PyObject *obj, PyLongExport *export_long)
  1549. {
  1550. if (!PyLong_Check(obj)) {
  1551. memset(export_long, 0, sizeof(*export_long));
  1552. PyErr_Format(PyExc_TypeError, "expected int, got %s",
  1553. Py_TYPE(obj)->tp_name);
  1554. return -1;
  1555. }
  1556. // Fast-path: try to convert to a int64_t
  1557. PyLongObject *self = (PyLongObject*)obj;
  1558. int overflow;
  1559. #if SIZEOF_LONG == 8
  1560. long value = PyLong_AsLongAndOverflow(obj, &overflow);
  1561. #else
  1562. // Windows has 32-bit long, so use 64-bit long long instead
  1563. long long value = PyLong_AsLongLongAndOverflow(obj, &overflow);
  1564. #endif
  1565. Py_BUILD_ASSERT(sizeof(value) == sizeof(int64_t));
  1566. // the function cannot fail since obj is a PyLongObject
  1567. assert(!(value == -1 && PyErr_Occurred()));
  1568. if (!overflow) {
  1569. export_long->value = value;
  1570. export_long->negative = 0;
  1571. export_long->ndigits = 0;
  1572. export_long->digits = 0;
  1573. export_long->_reserved = 0;
  1574. }
  1575. else {
  1576. export_long->value = 0;
  1577. export_long->negative = _PyLong_Sign(obj) < 0;
  1578. export_long->ndigits = _PyLong_DigitCount(self);
  1579. if (export_long->ndigits == 0) {
  1580. export_long->ndigits = 1;
  1581. }
  1582. export_long->digits = _PyLong_GetDigits(self);
  1583. export_long->_reserved = (Py_uintptr_t)Py_NewRef(obj);
  1584. }
  1585. return 0;
  1586. }
  1587. static inline void
  1588. PyLong_FreeExport(PyLongExport *export_long)
  1589. {
  1590. PyObject *obj = (PyObject*)export_long->_reserved;
  1591. if (obj) {
  1592. export_long->_reserved = 0;
  1593. Py_DECREF(obj);
  1594. }
  1595. }
  1596. static inline PyLongWriter*
  1597. PyLongWriter_Create(int negative, Py_ssize_t ndigits, void **digits)
  1598. {
  1599. if (ndigits <= 0) {
  1600. PyErr_SetString(PyExc_ValueError, "ndigits must be positive");
  1601. return NULL;
  1602. }
  1603. assert(digits != NULL);
  1604. PyLongObject *obj = _PyLong_New(ndigits);
  1605. if (obj == NULL) {
  1606. return NULL;
  1607. }
  1608. _PyLong_SetSignAndDigitCount(obj, negative?-1:1, ndigits);
  1609. *digits = _PyLong_GetDigits(obj);
  1610. return (PyLongWriter*)obj;
  1611. }
  1612. static inline void
  1613. PyLongWriter_Discard(PyLongWriter *writer)
  1614. {
  1615. PyLongObject *obj = (PyLongObject *)writer;
  1616. assert(Py_REFCNT(obj) == 1);
  1617. Py_DECREF(obj);
  1618. }
  1619. static inline PyObject*
  1620. PyLongWriter_Finish(PyLongWriter *writer)
  1621. {
  1622. PyObject *obj = (PyObject *)writer;
  1623. PyLongObject *self = (PyLongObject*)obj;
  1624. Py_ssize_t j = _PyLong_DigitCount(self);
  1625. Py_ssize_t i = j;
  1626. int sign = _PyLong_Sign(obj);
  1627. assert(Py_REFCNT(obj) == 1);
  1628. // Normalize and get singleton if possible
  1629. while (i > 0 && _PyLong_GetDigits(self)[i-1] == 0) {
  1630. --i;
  1631. }
  1632. if (i != j) {
  1633. if (i == 0) {
  1634. sign = 0;
  1635. }
  1636. _PyLong_SetSignAndDigitCount(self, sign, i);
  1637. }
  1638. if (i <= 1) {
  1639. long val = sign * (long)(_PyLong_GetDigits(self)[0]);
  1640. Py_DECREF(obj);
  1641. return PyLong_FromLong(val);
  1642. }
  1643. return obj;
  1644. }
  1645. #endif
  1646. #if PY_VERSION_HEX < 0x030C00A3
  1647. # define Py_T_SHORT T_SHORT
  1648. # define Py_T_INT T_INT
  1649. # define Py_T_LONG T_LONG
  1650. # define Py_T_FLOAT T_FLOAT
  1651. # define Py_T_DOUBLE T_DOUBLE
  1652. # define Py_T_STRING T_STRING
  1653. # define _Py_T_OBJECT T_OBJECT
  1654. # define Py_T_CHAR T_CHAR
  1655. # define Py_T_BYTE T_BYTE
  1656. # define Py_T_UBYTE T_UBYTE
  1657. # define Py_T_USHORT T_USHORT
  1658. # define Py_T_UINT T_UINT
  1659. # define Py_T_ULONG T_ULONG
  1660. # define Py_T_STRING_INPLACE T_STRING_INPLACE
  1661. # define Py_T_BOOL T_BOOL
  1662. # define Py_T_OBJECT_EX T_OBJECT_EX
  1663. # define Py_T_LONGLONG T_LONGLONG
  1664. # define Py_T_ULONGLONG T_ULONGLONG
  1665. # define Py_T_PYSSIZET T_PYSSIZET
  1666. # if PY_VERSION_HEX >= 0x03000000 && !defined(PYPY_VERSION)
  1667. # define _Py_T_NONE T_NONE
  1668. # endif
  1669. # define Py_READONLY READONLY
  1670. # define Py_AUDIT_READ READ_RESTRICTED
  1671. # define _Py_WRITE_RESTRICTED PY_WRITE_RESTRICTED
  1672. #endif
  1673. // gh-127350 added Py_fopen() and Py_fclose() to Python 3.14a4
  1674. #if PY_VERSION_HEX < 0x030E00A4
  1675. static inline FILE* Py_fopen(PyObject *path, const char *mode)
  1676. {
  1677. #if 0x030400A2 <= PY_VERSION_HEX && !defined(PYPY_VERSION)
  1678. PyAPI_FUNC(FILE*) _Py_fopen_obj(PyObject *path, const char *mode);
  1679. return _Py_fopen_obj(path, mode);
  1680. #else
  1681. FILE *f;
  1682. PyObject *bytes;
  1683. #if PY_VERSION_HEX >= 0x03000000
  1684. if (!PyUnicode_FSConverter(path, &bytes)) {
  1685. return NULL;
  1686. }
  1687. #else
  1688. if (!PyString_Check(path)) {
  1689. PyErr_SetString(PyExc_TypeError, "except str");
  1690. return NULL;
  1691. }
  1692. bytes = Py_NewRef(path);
  1693. #endif
  1694. const char *path_bytes = PyBytes_AS_STRING(bytes);
  1695. f = fopen(path_bytes, mode);
  1696. Py_DECREF(bytes);
  1697. if (f == NULL) {
  1698. PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
  1699. return NULL;
  1700. }
  1701. return f;
  1702. #endif
  1703. }
  1704. static inline int Py_fclose(FILE *file)
  1705. {
  1706. return fclose(file);
  1707. }
  1708. #endif
  1709. #if 0x03090000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x030E0000 && !defined(PYPY_VERSION)
  1710. static inline PyObject*
  1711. PyConfig_Get(const char *name)
  1712. {
  1713. typedef enum {
  1714. _PyConfig_MEMBER_INT,
  1715. _PyConfig_MEMBER_UINT,
  1716. _PyConfig_MEMBER_ULONG,
  1717. _PyConfig_MEMBER_BOOL,
  1718. _PyConfig_MEMBER_WSTR,
  1719. _PyConfig_MEMBER_WSTR_OPT,
  1720. _PyConfig_MEMBER_WSTR_LIST,
  1721. } PyConfigMemberType;
  1722. typedef struct {
  1723. const char *name;
  1724. size_t offset;
  1725. PyConfigMemberType type;
  1726. const char *sys_attr;
  1727. } PyConfigSpec;
  1728. #define PYTHONCAPI_COMPAT_SPEC(MEMBER, TYPE, sys_attr) \
  1729. {#MEMBER, offsetof(PyConfig, MEMBER), \
  1730. _PyConfig_MEMBER_##TYPE, sys_attr}
  1731. static const PyConfigSpec config_spec[] = {
  1732. PYTHONCAPI_COMPAT_SPEC(argv, WSTR_LIST, "argv"),
  1733. PYTHONCAPI_COMPAT_SPEC(base_exec_prefix, WSTR_OPT, "base_exec_prefix"),
  1734. PYTHONCAPI_COMPAT_SPEC(base_executable, WSTR_OPT, "_base_executable"),
  1735. PYTHONCAPI_COMPAT_SPEC(base_prefix, WSTR_OPT, "base_prefix"),
  1736. PYTHONCAPI_COMPAT_SPEC(bytes_warning, UINT, _Py_NULL),
  1737. PYTHONCAPI_COMPAT_SPEC(exec_prefix, WSTR_OPT, "exec_prefix"),
  1738. PYTHONCAPI_COMPAT_SPEC(executable, WSTR_OPT, "executable"),
  1739. PYTHONCAPI_COMPAT_SPEC(inspect, BOOL, _Py_NULL),
  1740. #if 0x030C0000 <= PY_VERSION_HEX
  1741. PYTHONCAPI_COMPAT_SPEC(int_max_str_digits, UINT, _Py_NULL),
  1742. #endif
  1743. PYTHONCAPI_COMPAT_SPEC(interactive, BOOL, _Py_NULL),
  1744. PYTHONCAPI_COMPAT_SPEC(module_search_paths, WSTR_LIST, "path"),
  1745. PYTHONCAPI_COMPAT_SPEC(optimization_level, UINT, _Py_NULL),
  1746. PYTHONCAPI_COMPAT_SPEC(parser_debug, BOOL, _Py_NULL),
  1747. PYTHONCAPI_COMPAT_SPEC(platlibdir, WSTR, "platlibdir"),
  1748. PYTHONCAPI_COMPAT_SPEC(prefix, WSTR_OPT, "prefix"),
  1749. PYTHONCAPI_COMPAT_SPEC(pycache_prefix, WSTR_OPT, "pycache_prefix"),
  1750. PYTHONCAPI_COMPAT_SPEC(quiet, BOOL, _Py_NULL),
  1751. #if 0x030B0000 <= PY_VERSION_HEX
  1752. PYTHONCAPI_COMPAT_SPEC(stdlib_dir, WSTR_OPT, "_stdlib_dir"),
  1753. #endif
  1754. PYTHONCAPI_COMPAT_SPEC(use_environment, BOOL, _Py_NULL),
  1755. PYTHONCAPI_COMPAT_SPEC(verbose, UINT, _Py_NULL),
  1756. PYTHONCAPI_COMPAT_SPEC(warnoptions, WSTR_LIST, "warnoptions"),
  1757. PYTHONCAPI_COMPAT_SPEC(write_bytecode, BOOL, _Py_NULL),
  1758. PYTHONCAPI_COMPAT_SPEC(xoptions, WSTR_LIST, "_xoptions"),
  1759. PYTHONCAPI_COMPAT_SPEC(buffered_stdio, BOOL, _Py_NULL),
  1760. PYTHONCAPI_COMPAT_SPEC(check_hash_pycs_mode, WSTR, _Py_NULL),
  1761. #if 0x030B0000 <= PY_VERSION_HEX
  1762. PYTHONCAPI_COMPAT_SPEC(code_debug_ranges, BOOL, _Py_NULL),
  1763. #endif
  1764. PYTHONCAPI_COMPAT_SPEC(configure_c_stdio, BOOL, _Py_NULL),
  1765. #if 0x030D0000 <= PY_VERSION_HEX
  1766. PYTHONCAPI_COMPAT_SPEC(cpu_count, INT, _Py_NULL),
  1767. #endif
  1768. PYTHONCAPI_COMPAT_SPEC(dev_mode, BOOL, _Py_NULL),
  1769. PYTHONCAPI_COMPAT_SPEC(dump_refs, BOOL, _Py_NULL),
  1770. #if 0x030B0000 <= PY_VERSION_HEX
  1771. PYTHONCAPI_COMPAT_SPEC(dump_refs_file, WSTR_OPT, _Py_NULL),
  1772. #endif
  1773. #ifdef Py_GIL_DISABLED
  1774. PYTHONCAPI_COMPAT_SPEC(enable_gil, INT, _Py_NULL),
  1775. #endif
  1776. PYTHONCAPI_COMPAT_SPEC(faulthandler, BOOL, _Py_NULL),
  1777. PYTHONCAPI_COMPAT_SPEC(filesystem_encoding, WSTR, _Py_NULL),
  1778. PYTHONCAPI_COMPAT_SPEC(filesystem_errors, WSTR, _Py_NULL),
  1779. PYTHONCAPI_COMPAT_SPEC(hash_seed, ULONG, _Py_NULL),
  1780. PYTHONCAPI_COMPAT_SPEC(home, WSTR_OPT, _Py_NULL),
  1781. PYTHONCAPI_COMPAT_SPEC(import_time, BOOL, _Py_NULL),
  1782. PYTHONCAPI_COMPAT_SPEC(install_signal_handlers, BOOL, _Py_NULL),
  1783. PYTHONCAPI_COMPAT_SPEC(isolated, BOOL, _Py_NULL),
  1784. #ifdef MS_WINDOWS
  1785. PYTHONCAPI_COMPAT_SPEC(legacy_windows_stdio, BOOL, _Py_NULL),
  1786. #endif
  1787. PYTHONCAPI_COMPAT_SPEC(malloc_stats, BOOL, _Py_NULL),
  1788. #if 0x030A0000 <= PY_VERSION_HEX
  1789. PYTHONCAPI_COMPAT_SPEC(orig_argv, WSTR_LIST, "orig_argv"),
  1790. #endif
  1791. PYTHONCAPI_COMPAT_SPEC(parse_argv, BOOL, _Py_NULL),
  1792. PYTHONCAPI_COMPAT_SPEC(pathconfig_warnings, BOOL, _Py_NULL),
  1793. #if 0x030C0000 <= PY_VERSION_HEX
  1794. PYTHONCAPI_COMPAT_SPEC(perf_profiling, UINT, _Py_NULL),
  1795. #endif
  1796. PYTHONCAPI_COMPAT_SPEC(program_name, WSTR, _Py_NULL),
  1797. PYTHONCAPI_COMPAT_SPEC(run_command, WSTR_OPT, _Py_NULL),
  1798. PYTHONCAPI_COMPAT_SPEC(run_filename, WSTR_OPT, _Py_NULL),
  1799. PYTHONCAPI_COMPAT_SPEC(run_module, WSTR_OPT, _Py_NULL),
  1800. #if 0x030B0000 <= PY_VERSION_HEX
  1801. PYTHONCAPI_COMPAT_SPEC(safe_path, BOOL, _Py_NULL),
  1802. #endif
  1803. PYTHONCAPI_COMPAT_SPEC(show_ref_count, BOOL, _Py_NULL),
  1804. PYTHONCAPI_COMPAT_SPEC(site_import, BOOL, _Py_NULL),
  1805. PYTHONCAPI_COMPAT_SPEC(skip_source_first_line, BOOL, _Py_NULL),
  1806. PYTHONCAPI_COMPAT_SPEC(stdio_encoding, WSTR, _Py_NULL),
  1807. PYTHONCAPI_COMPAT_SPEC(stdio_errors, WSTR, _Py_NULL),
  1808. PYTHONCAPI_COMPAT_SPEC(tracemalloc, UINT, _Py_NULL),
  1809. #if 0x030B0000 <= PY_VERSION_HEX
  1810. PYTHONCAPI_COMPAT_SPEC(use_frozen_modules, BOOL, _Py_NULL),
  1811. #endif
  1812. PYTHONCAPI_COMPAT_SPEC(use_hash_seed, BOOL, _Py_NULL),
  1813. PYTHONCAPI_COMPAT_SPEC(user_site_directory, BOOL, _Py_NULL),
  1814. #if 0x030A0000 <= PY_VERSION_HEX
  1815. PYTHONCAPI_COMPAT_SPEC(warn_default_encoding, BOOL, _Py_NULL),
  1816. #endif
  1817. };
  1818. #undef PYTHONCAPI_COMPAT_SPEC
  1819. const PyConfigSpec *spec;
  1820. int found = 0;
  1821. for (size_t i=0; i < sizeof(config_spec) / sizeof(config_spec[0]); i++) {
  1822. spec = &config_spec[i];
  1823. if (strcmp(spec->name, name) == 0) {
  1824. found = 1;
  1825. break;
  1826. }
  1827. }
  1828. if (found) {
  1829. if (spec->sys_attr != NULL) {
  1830. PyObject *value = PySys_GetObject(spec->sys_attr);
  1831. if (value == NULL) {
  1832. PyErr_Format(PyExc_RuntimeError, "lost sys.%s", spec->sys_attr);
  1833. return NULL;
  1834. }
  1835. return Py_NewRef(value);
  1836. }
  1837. PyAPI_FUNC(const PyConfig*) _Py_GetConfig(void);
  1838. const PyConfig *config = _Py_GetConfig();
  1839. void *member = (char *)config + spec->offset;
  1840. switch (spec->type) {
  1841. case _PyConfig_MEMBER_INT:
  1842. case _PyConfig_MEMBER_UINT:
  1843. {
  1844. int value = *(int *)member;
  1845. return PyLong_FromLong(value);
  1846. }
  1847. case _PyConfig_MEMBER_BOOL:
  1848. {
  1849. int value = *(int *)member;
  1850. return PyBool_FromLong(value != 0);
  1851. }
  1852. case _PyConfig_MEMBER_ULONG:
  1853. {
  1854. unsigned long value = *(unsigned long *)member;
  1855. return PyLong_FromUnsignedLong(value);
  1856. }
  1857. case _PyConfig_MEMBER_WSTR:
  1858. case _PyConfig_MEMBER_WSTR_OPT:
  1859. {
  1860. wchar_t *wstr = *(wchar_t **)member;
  1861. if (wstr != NULL) {
  1862. return PyUnicode_FromWideChar(wstr, -1);
  1863. }
  1864. else {
  1865. return Py_NewRef(Py_None);
  1866. }
  1867. }
  1868. case _PyConfig_MEMBER_WSTR_LIST:
  1869. {
  1870. const PyWideStringList *list = (const PyWideStringList *)member;
  1871. PyObject *tuple = PyTuple_New(list->length);
  1872. if (tuple == NULL) {
  1873. return NULL;
  1874. }
  1875. for (Py_ssize_t i = 0; i < list->length; i++) {
  1876. PyObject *item = PyUnicode_FromWideChar(list->items[i], -1);
  1877. if (item == NULL) {
  1878. Py_DECREF(tuple);
  1879. return NULL;
  1880. }
  1881. PyTuple_SET_ITEM(tuple, i, item);
  1882. }
  1883. return tuple;
  1884. }
  1885. default:
  1886. Py_UNREACHABLE();
  1887. }
  1888. }
  1889. PyErr_Format(PyExc_ValueError, "unknown config option name: %s", name);
  1890. return NULL;
  1891. }
  1892. static inline int
  1893. PyConfig_GetInt(const char *name, int *value)
  1894. {
  1895. PyObject *obj = PyConfig_Get(name);
  1896. if (obj == NULL) {
  1897. return -1;
  1898. }
  1899. if (!PyLong_Check(obj)) {
  1900. Py_DECREF(obj);
  1901. PyErr_Format(PyExc_TypeError, "config option %s is not an int", name);
  1902. return -1;
  1903. }
  1904. int as_int = PyLong_AsInt(obj);
  1905. Py_DECREF(obj);
  1906. if (as_int == -1 && PyErr_Occurred()) {
  1907. PyErr_Format(PyExc_OverflowError,
  1908. "config option %s value does not fit into a C int", name);
  1909. return -1;
  1910. }
  1911. *value = as_int;
  1912. return 0;
  1913. }
  1914. #endif // PY_VERSION_HEX > 0x03090000 && !defined(PYPY_VERSION)
  1915. #ifdef __cplusplus
  1916. }
  1917. #endif
  1918. #endif // PYTHONCAPI_COMPAT