abstract.c 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959
  1. /* Abstract Object Interface (many thanks to Jim Fulton) */
  2. #include "Python.h"
  3. #include "pycore_abstract.h" // _PyIndex_Check()
  4. #include "pycore_call.h" // _PyObject_CallNoArgs()
  5. #include "pycore_ceval.h" // _Py_EnterRecursiveCallTstate()
  6. #include "pycore_object.h" // _Py_CheckSlotResult()
  7. #include "pycore_long.h" // _Py_IsNegative
  8. #include "pycore_pyerrors.h" // _PyErr_Occurred()
  9. #include "pycore_pystate.h" // _PyThreadState_GET()
  10. #include "pycore_unionobject.h" // _PyUnion_Check()
  11. #include <ctype.h>
  12. #include <stddef.h> // offsetof()
  13. /* Shorthands to return certain errors */
  14. static PyObject *
  15. type_error(const char *msg, PyObject *obj)
  16. {
  17. PyErr_Format(PyExc_TypeError, msg, Py_TYPE(obj)->tp_name);
  18. return NULL;
  19. }
  20. static PyObject *
  21. null_error(void)
  22. {
  23. PyThreadState *tstate = _PyThreadState_GET();
  24. if (!_PyErr_Occurred(tstate)) {
  25. _PyErr_SetString(tstate, PyExc_SystemError,
  26. "null argument to internal routine");
  27. }
  28. return NULL;
  29. }
  30. /* Operations on any object */
  31. PyObject *
  32. PyObject_Type(PyObject *o)
  33. {
  34. PyObject *v;
  35. if (o == NULL) {
  36. return null_error();
  37. }
  38. v = (PyObject *)Py_TYPE(o);
  39. return Py_NewRef(v);
  40. }
  41. Py_ssize_t
  42. PyObject_Size(PyObject *o)
  43. {
  44. if (o == NULL) {
  45. null_error();
  46. return -1;
  47. }
  48. PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence;
  49. if (m && m->sq_length) {
  50. Py_ssize_t len = m->sq_length(o);
  51. assert(_Py_CheckSlotResult(o, "__len__", len >= 0));
  52. return len;
  53. }
  54. return PyMapping_Size(o);
  55. }
  56. #undef PyObject_Length
  57. Py_ssize_t
  58. PyObject_Length(PyObject *o)
  59. {
  60. return PyObject_Size(o);
  61. }
  62. #define PyObject_Length PyObject_Size
  63. int
  64. _PyObject_HasLen(PyObject *o) {
  65. return (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) ||
  66. (Py_TYPE(o)->tp_as_mapping && Py_TYPE(o)->tp_as_mapping->mp_length);
  67. }
  68. /* The length hint function returns a non-negative value from o.__len__()
  69. or o.__length_hint__(). If those methods aren't found the defaultvalue is
  70. returned. If one of the calls fails with an exception other than TypeError
  71. this function returns -1.
  72. */
  73. Py_ssize_t
  74. PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
  75. {
  76. PyObject *hint, *result;
  77. Py_ssize_t res;
  78. if (_PyObject_HasLen(o)) {
  79. res = PyObject_Length(o);
  80. if (res < 0) {
  81. PyThreadState *tstate = _PyThreadState_GET();
  82. assert(_PyErr_Occurred(tstate));
  83. if (!_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
  84. return -1;
  85. }
  86. _PyErr_Clear(tstate);
  87. }
  88. else {
  89. return res;
  90. }
  91. }
  92. hint = _PyObject_LookupSpecial(o, &_Py_ID(__length_hint__));
  93. if (hint == NULL) {
  94. if (PyErr_Occurred()) {
  95. return -1;
  96. }
  97. return defaultvalue;
  98. }
  99. result = _PyObject_CallNoArgs(hint);
  100. Py_DECREF(hint);
  101. if (result == NULL) {
  102. PyThreadState *tstate = _PyThreadState_GET();
  103. if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
  104. _PyErr_Clear(tstate);
  105. return defaultvalue;
  106. }
  107. return -1;
  108. }
  109. else if (result == Py_NotImplemented) {
  110. Py_DECREF(result);
  111. return defaultvalue;
  112. }
  113. if (!PyLong_Check(result)) {
  114. PyErr_Format(PyExc_TypeError, "__length_hint__ must be an integer, not %.100s",
  115. Py_TYPE(result)->tp_name);
  116. Py_DECREF(result);
  117. return -1;
  118. }
  119. res = PyLong_AsSsize_t(result);
  120. Py_DECREF(result);
  121. if (res < 0 && PyErr_Occurred()) {
  122. return -1;
  123. }
  124. if (res < 0) {
  125. PyErr_Format(PyExc_ValueError, "__length_hint__() should return >= 0");
  126. return -1;
  127. }
  128. return res;
  129. }
  130. PyObject *
  131. PyObject_GetItem(PyObject *o, PyObject *key)
  132. {
  133. if (o == NULL || key == NULL) {
  134. return null_error();
  135. }
  136. PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping;
  137. if (m && m->mp_subscript) {
  138. PyObject *item = m->mp_subscript(o, key);
  139. assert(_Py_CheckSlotResult(o, "__getitem__", item != NULL));
  140. return item;
  141. }
  142. PySequenceMethods *ms = Py_TYPE(o)->tp_as_sequence;
  143. if (ms && ms->sq_item) {
  144. if (_PyIndex_Check(key)) {
  145. Py_ssize_t key_value;
  146. key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
  147. if (key_value == -1 && PyErr_Occurred())
  148. return NULL;
  149. return PySequence_GetItem(o, key_value);
  150. }
  151. else {
  152. return type_error("sequence index must "
  153. "be integer, not '%.200s'", key);
  154. }
  155. }
  156. if (PyType_Check(o)) {
  157. PyObject *meth, *result;
  158. // Special case type[int], but disallow other types so str[int] fails
  159. if ((PyTypeObject*)o == &PyType_Type) {
  160. return Py_GenericAlias(o, key);
  161. }
  162. if (_PyObject_LookupAttr(o, &_Py_ID(__class_getitem__), &meth) < 0) {
  163. return NULL;
  164. }
  165. if (meth && meth != Py_None) {
  166. result = PyObject_CallOneArg(meth, key);
  167. Py_DECREF(meth);
  168. return result;
  169. }
  170. Py_XDECREF(meth);
  171. PyErr_Format(PyExc_TypeError, "type '%.200s' is not subscriptable",
  172. ((PyTypeObject *)o)->tp_name);
  173. return NULL;
  174. }
  175. return type_error("'%.200s' object is not subscriptable", o);
  176. }
  177. int
  178. PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
  179. {
  180. if (o == NULL || key == NULL || value == NULL) {
  181. null_error();
  182. return -1;
  183. }
  184. PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping;
  185. if (m && m->mp_ass_subscript) {
  186. int res = m->mp_ass_subscript(o, key, value);
  187. assert(_Py_CheckSlotResult(o, "__setitem__", res >= 0));
  188. return res;
  189. }
  190. if (Py_TYPE(o)->tp_as_sequence) {
  191. if (_PyIndex_Check(key)) {
  192. Py_ssize_t key_value;
  193. key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
  194. if (key_value == -1 && PyErr_Occurred())
  195. return -1;
  196. return PySequence_SetItem(o, key_value, value);
  197. }
  198. else if (Py_TYPE(o)->tp_as_sequence->sq_ass_item) {
  199. type_error("sequence index must be "
  200. "integer, not '%.200s'", key);
  201. return -1;
  202. }
  203. }
  204. type_error("'%.200s' object does not support item assignment", o);
  205. return -1;
  206. }
  207. int
  208. PyObject_DelItem(PyObject *o, PyObject *key)
  209. {
  210. if (o == NULL || key == NULL) {
  211. null_error();
  212. return -1;
  213. }
  214. PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping;
  215. if (m && m->mp_ass_subscript) {
  216. int res = m->mp_ass_subscript(o, key, (PyObject*)NULL);
  217. assert(_Py_CheckSlotResult(o, "__delitem__", res >= 0));
  218. return res;
  219. }
  220. if (Py_TYPE(o)->tp_as_sequence) {
  221. if (_PyIndex_Check(key)) {
  222. Py_ssize_t key_value;
  223. key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
  224. if (key_value == -1 && PyErr_Occurred())
  225. return -1;
  226. return PySequence_DelItem(o, key_value);
  227. }
  228. else if (Py_TYPE(o)->tp_as_sequence->sq_ass_item) {
  229. type_error("sequence index must be "
  230. "integer, not '%.200s'", key);
  231. return -1;
  232. }
  233. }
  234. type_error("'%.200s' object does not support item deletion", o);
  235. return -1;
  236. }
  237. int
  238. PyObject_DelItemString(PyObject *o, const char *key)
  239. {
  240. PyObject *okey;
  241. int ret;
  242. if (o == NULL || key == NULL) {
  243. null_error();
  244. return -1;
  245. }
  246. okey = PyUnicode_FromString(key);
  247. if (okey == NULL)
  248. return -1;
  249. ret = PyObject_DelItem(o, okey);
  250. Py_DECREF(okey);
  251. return ret;
  252. }
  253. /* Return 1 if the getbuffer function is available, otherwise return 0. */
  254. int
  255. PyObject_CheckBuffer(PyObject *obj)
  256. {
  257. PyBufferProcs *tp_as_buffer = Py_TYPE(obj)->tp_as_buffer;
  258. return (tp_as_buffer != NULL && tp_as_buffer->bf_getbuffer != NULL);
  259. }
  260. /* We release the buffer right after use of this function which could
  261. cause issues later on. Don't use these functions in new code.
  262. */
  263. int
  264. PyObject_CheckReadBuffer(PyObject *obj)
  265. {
  266. PyBufferProcs *pb = Py_TYPE(obj)->tp_as_buffer;
  267. Py_buffer view;
  268. if (pb == NULL ||
  269. pb->bf_getbuffer == NULL)
  270. return 0;
  271. if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE) == -1) {
  272. PyErr_Clear();
  273. return 0;
  274. }
  275. PyBuffer_Release(&view);
  276. return 1;
  277. }
  278. static int
  279. as_read_buffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len)
  280. {
  281. Py_buffer view;
  282. if (obj == NULL || buffer == NULL || buffer_len == NULL) {
  283. null_error();
  284. return -1;
  285. }
  286. if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) != 0)
  287. return -1;
  288. *buffer = view.buf;
  289. *buffer_len = view.len;
  290. PyBuffer_Release(&view);
  291. return 0;
  292. }
  293. int
  294. PyObject_AsCharBuffer(PyObject *obj,
  295. const char **buffer,
  296. Py_ssize_t *buffer_len)
  297. {
  298. return as_read_buffer(obj, (const void **)buffer, buffer_len);
  299. }
  300. int PyObject_AsReadBuffer(PyObject *obj,
  301. const void **buffer,
  302. Py_ssize_t *buffer_len)
  303. {
  304. return as_read_buffer(obj, buffer, buffer_len);
  305. }
  306. int PyObject_AsWriteBuffer(PyObject *obj,
  307. void **buffer,
  308. Py_ssize_t *buffer_len)
  309. {
  310. PyBufferProcs *pb;
  311. Py_buffer view;
  312. if (obj == NULL || buffer == NULL || buffer_len == NULL) {
  313. null_error();
  314. return -1;
  315. }
  316. pb = Py_TYPE(obj)->tp_as_buffer;
  317. if (pb == NULL ||
  318. pb->bf_getbuffer == NULL ||
  319. ((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITABLE) != 0)) {
  320. PyErr_SetString(PyExc_TypeError,
  321. "expected a writable bytes-like object");
  322. return -1;
  323. }
  324. *buffer = view.buf;
  325. *buffer_len = view.len;
  326. PyBuffer_Release(&view);
  327. return 0;
  328. }
  329. /* Buffer C-API for Python 3.0 */
  330. int
  331. PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
  332. {
  333. PyBufferProcs *pb = Py_TYPE(obj)->tp_as_buffer;
  334. if (pb == NULL || pb->bf_getbuffer == NULL) {
  335. PyErr_Format(PyExc_TypeError,
  336. "a bytes-like object is required, not '%.100s'",
  337. Py_TYPE(obj)->tp_name);
  338. return -1;
  339. }
  340. int res = (*pb->bf_getbuffer)(obj, view, flags);
  341. assert(_Py_CheckSlotResult(obj, "getbuffer", res >= 0));
  342. return res;
  343. }
  344. static int
  345. _IsFortranContiguous(const Py_buffer *view)
  346. {
  347. Py_ssize_t sd, dim;
  348. int i;
  349. /* 1) len = product(shape) * itemsize
  350. 2) itemsize > 0
  351. 3) len = 0 <==> exists i: shape[i] = 0 */
  352. if (view->len == 0) return 1;
  353. if (view->strides == NULL) { /* C-contiguous by definition */
  354. /* Trivially F-contiguous */
  355. if (view->ndim <= 1) return 1;
  356. /* ndim > 1 implies shape != NULL */
  357. assert(view->shape != NULL);
  358. /* Effectively 1-d */
  359. sd = 0;
  360. for (i=0; i<view->ndim; i++) {
  361. if (view->shape[i] > 1) sd += 1;
  362. }
  363. return sd <= 1;
  364. }
  365. /* strides != NULL implies both of these */
  366. assert(view->ndim > 0);
  367. assert(view->shape != NULL);
  368. sd = view->itemsize;
  369. for (i=0; i<view->ndim; i++) {
  370. dim = view->shape[i];
  371. if (dim > 1 && view->strides[i] != sd) {
  372. return 0;
  373. }
  374. sd *= dim;
  375. }
  376. return 1;
  377. }
  378. static int
  379. _IsCContiguous(const Py_buffer *view)
  380. {
  381. Py_ssize_t sd, dim;
  382. int i;
  383. /* 1) len = product(shape) * itemsize
  384. 2) itemsize > 0
  385. 3) len = 0 <==> exists i: shape[i] = 0 */
  386. if (view->len == 0) return 1;
  387. if (view->strides == NULL) return 1; /* C-contiguous by definition */
  388. /* strides != NULL implies both of these */
  389. assert(view->ndim > 0);
  390. assert(view->shape != NULL);
  391. sd = view->itemsize;
  392. for (i=view->ndim-1; i>=0; i--) {
  393. dim = view->shape[i];
  394. if (dim > 1 && view->strides[i] != sd) {
  395. return 0;
  396. }
  397. sd *= dim;
  398. }
  399. return 1;
  400. }
  401. int
  402. PyBuffer_IsContiguous(const Py_buffer *view, char order)
  403. {
  404. if (view->suboffsets != NULL) return 0;
  405. if (order == 'C')
  406. return _IsCContiguous(view);
  407. else if (order == 'F')
  408. return _IsFortranContiguous(view);
  409. else if (order == 'A')
  410. return (_IsCContiguous(view) || _IsFortranContiguous(view));
  411. return 0;
  412. }
  413. void*
  414. PyBuffer_GetPointer(const Py_buffer *view, const Py_ssize_t *indices)
  415. {
  416. char* pointer;
  417. int i;
  418. pointer = (char *)view->buf;
  419. for (i = 0; i < view->ndim; i++) {
  420. pointer += view->strides[i]*indices[i];
  421. if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
  422. pointer = *((char**)pointer) + view->suboffsets[i];
  423. }
  424. }
  425. return (void*)pointer;
  426. }
  427. void
  428. _Py_add_one_to_index_F(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
  429. {
  430. int k;
  431. for (k=0; k<nd; k++) {
  432. if (index[k] < shape[k]-1) {
  433. index[k]++;
  434. break;
  435. }
  436. else {
  437. index[k] = 0;
  438. }
  439. }
  440. }
  441. void
  442. _Py_add_one_to_index_C(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
  443. {
  444. int k;
  445. for (k=nd-1; k>=0; k--) {
  446. if (index[k] < shape[k]-1) {
  447. index[k]++;
  448. break;
  449. }
  450. else {
  451. index[k] = 0;
  452. }
  453. }
  454. }
  455. Py_ssize_t
  456. PyBuffer_SizeFromFormat(const char *format)
  457. {
  458. PyObject *calcsize = NULL;
  459. PyObject *res = NULL;
  460. PyObject *fmt = NULL;
  461. Py_ssize_t itemsize = -1;
  462. calcsize = _PyImport_GetModuleAttrString("struct", "calcsize");
  463. if (calcsize == NULL) {
  464. goto done;
  465. }
  466. fmt = PyUnicode_FromString(format);
  467. if (fmt == NULL) {
  468. goto done;
  469. }
  470. res = PyObject_CallFunctionObjArgs(calcsize, fmt, NULL);
  471. if (res == NULL) {
  472. goto done;
  473. }
  474. itemsize = PyLong_AsSsize_t(res);
  475. if (itemsize < 0) {
  476. goto done;
  477. }
  478. done:
  479. Py_XDECREF(calcsize);
  480. Py_XDECREF(fmt);
  481. Py_XDECREF(res);
  482. return itemsize;
  483. }
  484. int
  485. PyBuffer_FromContiguous(const Py_buffer *view, const void *buf, Py_ssize_t len, char fort)
  486. {
  487. int k;
  488. void (*addone)(int, Py_ssize_t *, const Py_ssize_t *);
  489. Py_ssize_t *indices, elements;
  490. char *ptr;
  491. const char *src;
  492. if (len > view->len) {
  493. len = view->len;
  494. }
  495. if (PyBuffer_IsContiguous(view, fort)) {
  496. /* simplest copy is all that is needed */
  497. memcpy(view->buf, buf, len);
  498. return 0;
  499. }
  500. /* Otherwise a more elaborate scheme is needed */
  501. /* view->ndim <= 64 */
  502. indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
  503. if (indices == NULL) {
  504. PyErr_NoMemory();
  505. return -1;
  506. }
  507. for (k=0; k<view->ndim;k++) {
  508. indices[k] = 0;
  509. }
  510. if (fort == 'F') {
  511. addone = _Py_add_one_to_index_F;
  512. }
  513. else {
  514. addone = _Py_add_one_to_index_C;
  515. }
  516. src = buf;
  517. /* XXX : This is not going to be the fastest code in the world
  518. several optimizations are possible.
  519. */
  520. elements = len / view->itemsize;
  521. while (elements--) {
  522. ptr = PyBuffer_GetPointer(view, indices);
  523. memcpy(ptr, src, view->itemsize);
  524. src += view->itemsize;
  525. addone(view->ndim, indices, view->shape);
  526. }
  527. PyMem_Free(indices);
  528. return 0;
  529. }
  530. int PyObject_CopyData(PyObject *dest, PyObject *src)
  531. {
  532. Py_buffer view_dest, view_src;
  533. int k;
  534. Py_ssize_t *indices, elements;
  535. char *dptr, *sptr;
  536. if (!PyObject_CheckBuffer(dest) ||
  537. !PyObject_CheckBuffer(src)) {
  538. PyErr_SetString(PyExc_TypeError,
  539. "both destination and source must be "\
  540. "bytes-like objects");
  541. return -1;
  542. }
  543. if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
  544. if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
  545. PyBuffer_Release(&view_dest);
  546. return -1;
  547. }
  548. if (view_dest.len < view_src.len) {
  549. PyErr_SetString(PyExc_BufferError,
  550. "destination is too small to receive data from source");
  551. PyBuffer_Release(&view_dest);
  552. PyBuffer_Release(&view_src);
  553. return -1;
  554. }
  555. if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
  556. PyBuffer_IsContiguous(&view_src, 'C')) ||
  557. (PyBuffer_IsContiguous(&view_dest, 'F') &&
  558. PyBuffer_IsContiguous(&view_src, 'F'))) {
  559. /* simplest copy is all that is needed */
  560. memcpy(view_dest.buf, view_src.buf, view_src.len);
  561. PyBuffer_Release(&view_dest);
  562. PyBuffer_Release(&view_src);
  563. return 0;
  564. }
  565. /* Otherwise a more elaborate copy scheme is needed */
  566. /* XXX(nnorwitz): need to check for overflow! */
  567. indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
  568. if (indices == NULL) {
  569. PyErr_NoMemory();
  570. PyBuffer_Release(&view_dest);
  571. PyBuffer_Release(&view_src);
  572. return -1;
  573. }
  574. for (k=0; k<view_src.ndim;k++) {
  575. indices[k] = 0;
  576. }
  577. elements = 1;
  578. for (k=0; k<view_src.ndim; k++) {
  579. /* XXX(nnorwitz): can this overflow? */
  580. elements *= view_src.shape[k];
  581. }
  582. while (elements--) {
  583. _Py_add_one_to_index_C(view_src.ndim, indices, view_src.shape);
  584. dptr = PyBuffer_GetPointer(&view_dest, indices);
  585. sptr = PyBuffer_GetPointer(&view_src, indices);
  586. memcpy(dptr, sptr, view_src.itemsize);
  587. }
  588. PyMem_Free(indices);
  589. PyBuffer_Release(&view_dest);
  590. PyBuffer_Release(&view_src);
  591. return 0;
  592. }
  593. void
  594. PyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape,
  595. Py_ssize_t *strides, int itemsize,
  596. char fort)
  597. {
  598. int k;
  599. Py_ssize_t sd;
  600. sd = itemsize;
  601. if (fort == 'F') {
  602. for (k=0; k<nd; k++) {
  603. strides[k] = sd;
  604. sd *= shape[k];
  605. }
  606. }
  607. else {
  608. for (k=nd-1; k>=0; k--) {
  609. strides[k] = sd;
  610. sd *= shape[k];
  611. }
  612. }
  613. return;
  614. }
  615. int
  616. PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len,
  617. int readonly, int flags)
  618. {
  619. if (view == NULL) {
  620. PyErr_SetString(PyExc_BufferError,
  621. "PyBuffer_FillInfo: view==NULL argument is obsolete");
  622. return -1;
  623. }
  624. if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
  625. (readonly == 1)) {
  626. PyErr_SetString(PyExc_BufferError,
  627. "Object is not writable.");
  628. return -1;
  629. }
  630. view->obj = Py_XNewRef(obj);
  631. view->buf = buf;
  632. view->len = len;
  633. view->readonly = readonly;
  634. view->itemsize = 1;
  635. view->format = NULL;
  636. if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
  637. view->format = "B";
  638. view->ndim = 1;
  639. view->shape = NULL;
  640. if ((flags & PyBUF_ND) == PyBUF_ND)
  641. view->shape = &(view->len);
  642. view->strides = NULL;
  643. if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
  644. view->strides = &(view->itemsize);
  645. view->suboffsets = NULL;
  646. view->internal = NULL;
  647. return 0;
  648. }
  649. void
  650. PyBuffer_Release(Py_buffer *view)
  651. {
  652. PyObject *obj = view->obj;
  653. PyBufferProcs *pb;
  654. if (obj == NULL)
  655. return;
  656. pb = Py_TYPE(obj)->tp_as_buffer;
  657. if (pb && pb->bf_releasebuffer) {
  658. pb->bf_releasebuffer(obj, view);
  659. }
  660. view->obj = NULL;
  661. Py_DECREF(obj);
  662. }
  663. PyObject *
  664. PyObject_Format(PyObject *obj, PyObject *format_spec)
  665. {
  666. PyObject *meth;
  667. PyObject *empty = NULL;
  668. PyObject *result = NULL;
  669. if (format_spec != NULL && !PyUnicode_Check(format_spec)) {
  670. PyErr_Format(PyExc_SystemError,
  671. "Format specifier must be a string, not %.200s",
  672. Py_TYPE(format_spec)->tp_name);
  673. return NULL;
  674. }
  675. /* Fast path for common types. */
  676. if (format_spec == NULL || PyUnicode_GET_LENGTH(format_spec) == 0) {
  677. if (PyUnicode_CheckExact(obj)) {
  678. return Py_NewRef(obj);
  679. }
  680. if (PyLong_CheckExact(obj)) {
  681. return PyObject_Str(obj);
  682. }
  683. }
  684. /* If no format_spec is provided, use an empty string */
  685. if (format_spec == NULL) {
  686. empty = PyUnicode_New(0, 0);
  687. format_spec = empty;
  688. }
  689. /* Find the (unbound!) __format__ method */
  690. meth = _PyObject_LookupSpecial(obj, &_Py_ID(__format__));
  691. if (meth == NULL) {
  692. PyThreadState *tstate = _PyThreadState_GET();
  693. if (!_PyErr_Occurred(tstate)) {
  694. _PyErr_Format(tstate, PyExc_TypeError,
  695. "Type %.100s doesn't define __format__",
  696. Py_TYPE(obj)->tp_name);
  697. }
  698. goto done;
  699. }
  700. /* And call it. */
  701. result = PyObject_CallOneArg(meth, format_spec);
  702. Py_DECREF(meth);
  703. if (result && !PyUnicode_Check(result)) {
  704. PyErr_Format(PyExc_TypeError,
  705. "__format__ must return a str, not %.200s",
  706. Py_TYPE(result)->tp_name);
  707. Py_SETREF(result, NULL);
  708. goto done;
  709. }
  710. done:
  711. Py_XDECREF(empty);
  712. return result;
  713. }
  714. /* Operations on numbers */
  715. int
  716. PyNumber_Check(PyObject *o)
  717. {
  718. if (o == NULL)
  719. return 0;
  720. PyNumberMethods *nb = Py_TYPE(o)->tp_as_number;
  721. return nb && (nb->nb_index || nb->nb_int || nb->nb_float || PyComplex_Check(o));
  722. }
  723. /* Binary operators */
  724. #define NB_SLOT(x) offsetof(PyNumberMethods, x)
  725. #define NB_BINOP(nb_methods, slot) \
  726. (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
  727. #define NB_TERNOP(nb_methods, slot) \
  728. (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
  729. /*
  730. Calling scheme used for binary operations:
  731. Order operations are tried until either a valid result or error:
  732. w.op(v,w)[*], v.op(v,w), w.op(v,w)
  733. [*] only when Py_TYPE(v) != Py_TYPE(w) && Py_TYPE(w) is a subclass of
  734. Py_TYPE(v)
  735. */
  736. static PyObject *
  737. binary_op1(PyObject *v, PyObject *w, const int op_slot
  738. #ifndef NDEBUG
  739. , const char *op_name
  740. #endif
  741. )
  742. {
  743. binaryfunc slotv;
  744. if (Py_TYPE(v)->tp_as_number != NULL) {
  745. slotv = NB_BINOP(Py_TYPE(v)->tp_as_number, op_slot);
  746. }
  747. else {
  748. slotv = NULL;
  749. }
  750. binaryfunc slotw;
  751. if (!Py_IS_TYPE(w, Py_TYPE(v)) && Py_TYPE(w)->tp_as_number != NULL) {
  752. slotw = NB_BINOP(Py_TYPE(w)->tp_as_number, op_slot);
  753. if (slotw == slotv) {
  754. slotw = NULL;
  755. }
  756. }
  757. else {
  758. slotw = NULL;
  759. }
  760. if (slotv) {
  761. PyObject *x;
  762. if (slotw && PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v))) {
  763. x = slotw(v, w);
  764. if (x != Py_NotImplemented)
  765. return x;
  766. Py_DECREF(x); /* can't do it */
  767. slotw = NULL;
  768. }
  769. x = slotv(v, w);
  770. assert(_Py_CheckSlotResult(v, op_name, x != NULL));
  771. if (x != Py_NotImplemented) {
  772. return x;
  773. }
  774. Py_DECREF(x); /* can't do it */
  775. }
  776. if (slotw) {
  777. PyObject *x = slotw(v, w);
  778. assert(_Py_CheckSlotResult(w, op_name, x != NULL));
  779. if (x != Py_NotImplemented) {
  780. return x;
  781. }
  782. Py_DECREF(x); /* can't do it */
  783. }
  784. Py_RETURN_NOTIMPLEMENTED;
  785. }
  786. #ifdef NDEBUG
  787. # define BINARY_OP1(v, w, op_slot, op_name) binary_op1(v, w, op_slot)
  788. #else
  789. # define BINARY_OP1(v, w, op_slot, op_name) binary_op1(v, w, op_slot, op_name)
  790. #endif
  791. static PyObject *
  792. binop_type_error(PyObject *v, PyObject *w, const char *op_name)
  793. {
  794. PyErr_Format(PyExc_TypeError,
  795. "unsupported operand type(s) for %.100s: "
  796. "'%.100s' and '%.100s'",
  797. op_name,
  798. Py_TYPE(v)->tp_name,
  799. Py_TYPE(w)->tp_name);
  800. return NULL;
  801. }
  802. static PyObject *
  803. binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
  804. {
  805. PyObject *result = BINARY_OP1(v, w, op_slot, op_name);
  806. if (result == Py_NotImplemented) {
  807. Py_DECREF(result);
  808. if (op_slot == NB_SLOT(nb_rshift) &&
  809. PyCFunction_CheckExact(v) &&
  810. strcmp(((PyCFunctionObject *)v)->m_ml->ml_name, "print") == 0)
  811. {
  812. PyErr_Format(PyExc_TypeError,
  813. "unsupported operand type(s) for %.100s: "
  814. "'%.100s' and '%.100s'. Did you mean \"print(<message>, "
  815. "file=<output_stream>)\"?",
  816. op_name,
  817. Py_TYPE(v)->tp_name,
  818. Py_TYPE(w)->tp_name);
  819. return NULL;
  820. }
  821. return binop_type_error(v, w, op_name);
  822. }
  823. return result;
  824. }
  825. /*
  826. Calling scheme used for ternary operations:
  827. Order operations are tried until either a valid result or error:
  828. v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
  829. */
  830. static PyObject *
  831. ternary_op(PyObject *v,
  832. PyObject *w,
  833. PyObject *z,
  834. const int op_slot,
  835. const char *op_name
  836. )
  837. {
  838. PyNumberMethods *mv = Py_TYPE(v)->tp_as_number;
  839. PyNumberMethods *mw = Py_TYPE(w)->tp_as_number;
  840. ternaryfunc slotv;
  841. if (mv != NULL) {
  842. slotv = NB_TERNOP(mv, op_slot);
  843. }
  844. else {
  845. slotv = NULL;
  846. }
  847. ternaryfunc slotw;
  848. if (!Py_IS_TYPE(w, Py_TYPE(v)) && mw != NULL) {
  849. slotw = NB_TERNOP(mw, op_slot);
  850. if (slotw == slotv) {
  851. slotw = NULL;
  852. }
  853. }
  854. else {
  855. slotw = NULL;
  856. }
  857. if (slotv) {
  858. PyObject *x;
  859. if (slotw && PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v))) {
  860. x = slotw(v, w, z);
  861. if (x != Py_NotImplemented) {
  862. return x;
  863. }
  864. Py_DECREF(x); /* can't do it */
  865. slotw = NULL;
  866. }
  867. x = slotv(v, w, z);
  868. assert(_Py_CheckSlotResult(v, op_name, x != NULL));
  869. if (x != Py_NotImplemented) {
  870. return x;
  871. }
  872. Py_DECREF(x); /* can't do it */
  873. }
  874. if (slotw) {
  875. PyObject *x = slotw(v, w, z);
  876. assert(_Py_CheckSlotResult(w, op_name, x != NULL));
  877. if (x != Py_NotImplemented) {
  878. return x;
  879. }
  880. Py_DECREF(x); /* can't do it */
  881. }
  882. PyNumberMethods *mz = Py_TYPE(z)->tp_as_number;
  883. if (mz != NULL) {
  884. ternaryfunc slotz = NB_TERNOP(mz, op_slot);
  885. if (slotz == slotv || slotz == slotw) {
  886. slotz = NULL;
  887. }
  888. if (slotz) {
  889. PyObject *x = slotz(v, w, z);
  890. assert(_Py_CheckSlotResult(z, op_name, x != NULL));
  891. if (x != Py_NotImplemented) {
  892. return x;
  893. }
  894. Py_DECREF(x); /* can't do it */
  895. }
  896. }
  897. if (z == Py_None) {
  898. PyErr_Format(
  899. PyExc_TypeError,
  900. "unsupported operand type(s) for %.100s: "
  901. "'%.100s' and '%.100s'",
  902. op_name,
  903. Py_TYPE(v)->tp_name,
  904. Py_TYPE(w)->tp_name);
  905. }
  906. else {
  907. PyErr_Format(
  908. PyExc_TypeError,
  909. "unsupported operand type(s) for %.100s: "
  910. "'%.100s', '%.100s', '%.100s'",
  911. op_name,
  912. Py_TYPE(v)->tp_name,
  913. Py_TYPE(w)->tp_name,
  914. Py_TYPE(z)->tp_name);
  915. }
  916. return NULL;
  917. }
  918. #define BINARY_FUNC(func, op, op_name) \
  919. PyObject * \
  920. func(PyObject *v, PyObject *w) { \
  921. return binary_op(v, w, NB_SLOT(op), op_name); \
  922. }
  923. BINARY_FUNC(PyNumber_Or, nb_or, "|")
  924. BINARY_FUNC(PyNumber_Xor, nb_xor, "^")
  925. BINARY_FUNC(PyNumber_And, nb_and, "&")
  926. BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")
  927. BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")
  928. BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")
  929. BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
  930. PyObject *
  931. PyNumber_Add(PyObject *v, PyObject *w)
  932. {
  933. PyObject *result = BINARY_OP1(v, w, NB_SLOT(nb_add), "+");
  934. if (result != Py_NotImplemented) {
  935. return result;
  936. }
  937. Py_DECREF(result);
  938. PySequenceMethods *m = Py_TYPE(v)->tp_as_sequence;
  939. if (m && m->sq_concat) {
  940. result = (*m->sq_concat)(v, w);
  941. assert(_Py_CheckSlotResult(v, "+", result != NULL));
  942. return result;
  943. }
  944. return binop_type_error(v, w, "+");
  945. }
  946. static PyObject *
  947. sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
  948. {
  949. Py_ssize_t count;
  950. if (_PyIndex_Check(n)) {
  951. count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
  952. if (count == -1 && PyErr_Occurred()) {
  953. return NULL;
  954. }
  955. }
  956. else {
  957. return type_error("can't multiply sequence by "
  958. "non-int of type '%.200s'", n);
  959. }
  960. PyObject *res = (*repeatfunc)(seq, count);
  961. assert(_Py_CheckSlotResult(seq, "*", res != NULL));
  962. return res;
  963. }
  964. PyObject *
  965. PyNumber_Multiply(PyObject *v, PyObject *w)
  966. {
  967. PyObject *result = BINARY_OP1(v, w, NB_SLOT(nb_multiply), "*");
  968. if (result == Py_NotImplemented) {
  969. PySequenceMethods *mv = Py_TYPE(v)->tp_as_sequence;
  970. PySequenceMethods *mw = Py_TYPE(w)->tp_as_sequence;
  971. Py_DECREF(result);
  972. if (mv && mv->sq_repeat) {
  973. return sequence_repeat(mv->sq_repeat, v, w);
  974. }
  975. else if (mw && mw->sq_repeat) {
  976. return sequence_repeat(mw->sq_repeat, w, v);
  977. }
  978. result = binop_type_error(v, w, "*");
  979. }
  980. return result;
  981. }
  982. PyObject *
  983. PyNumber_MatrixMultiply(PyObject *v, PyObject *w)
  984. {
  985. return binary_op(v, w, NB_SLOT(nb_matrix_multiply), "@");
  986. }
  987. PyObject *
  988. PyNumber_FloorDivide(PyObject *v, PyObject *w)
  989. {
  990. return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
  991. }
  992. PyObject *
  993. PyNumber_TrueDivide(PyObject *v, PyObject *w)
  994. {
  995. return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
  996. }
  997. PyObject *
  998. PyNumber_Remainder(PyObject *v, PyObject *w)
  999. {
  1000. return binary_op(v, w, NB_SLOT(nb_remainder), "%");
  1001. }
  1002. PyObject *
  1003. PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
  1004. {
  1005. return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
  1006. }
  1007. PyObject *
  1008. _PyNumber_PowerNoMod(PyObject *lhs, PyObject *rhs)
  1009. {
  1010. return PyNumber_Power(lhs, rhs, Py_None);
  1011. }
  1012. /* Binary in-place operators */
  1013. /* The in-place operators are defined to fall back to the 'normal',
  1014. non in-place operations, if the in-place methods are not in place.
  1015. - If the left hand object has the appropriate struct members, and
  1016. they are filled, call the appropriate function and return the
  1017. result. No coercion is done on the arguments; the left-hand object
  1018. is the one the operation is performed on, and it's up to the
  1019. function to deal with the right-hand object.
  1020. - Otherwise, in-place modification is not supported. Handle it exactly as
  1021. a non in-place operation of the same kind.
  1022. */
  1023. static PyObject *
  1024. binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot
  1025. #ifndef NDEBUG
  1026. , const char *op_name
  1027. #endif
  1028. )
  1029. {
  1030. PyNumberMethods *mv = Py_TYPE(v)->tp_as_number;
  1031. if (mv != NULL) {
  1032. binaryfunc slot = NB_BINOP(mv, iop_slot);
  1033. if (slot) {
  1034. PyObject *x = (slot)(v, w);
  1035. assert(_Py_CheckSlotResult(v, op_name, x != NULL));
  1036. if (x != Py_NotImplemented) {
  1037. return x;
  1038. }
  1039. Py_DECREF(x);
  1040. }
  1041. }
  1042. #ifdef NDEBUG
  1043. return binary_op1(v, w, op_slot);
  1044. #else
  1045. return binary_op1(v, w, op_slot, op_name);
  1046. #endif
  1047. }
  1048. #ifdef NDEBUG
  1049. # define BINARY_IOP1(v, w, iop_slot, op_slot, op_name) binary_iop1(v, w, iop_slot, op_slot)
  1050. #else
  1051. # define BINARY_IOP1(v, w, iop_slot, op_slot, op_name) binary_iop1(v, w, iop_slot, op_slot, op_name)
  1052. #endif
  1053. static PyObject *
  1054. binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
  1055. const char *op_name)
  1056. {
  1057. PyObject *result = BINARY_IOP1(v, w, iop_slot, op_slot, op_name);
  1058. if (result == Py_NotImplemented) {
  1059. Py_DECREF(result);
  1060. return binop_type_error(v, w, op_name);
  1061. }
  1062. return result;
  1063. }
  1064. static PyObject *
  1065. ternary_iop(PyObject *v, PyObject *w, PyObject *z, const int iop_slot, const int op_slot,
  1066. const char *op_name)
  1067. {
  1068. PyNumberMethods *mv = Py_TYPE(v)->tp_as_number;
  1069. if (mv != NULL) {
  1070. ternaryfunc slot = NB_TERNOP(mv, iop_slot);
  1071. if (slot) {
  1072. PyObject *x = (slot)(v, w, z);
  1073. if (x != Py_NotImplemented) {
  1074. return x;
  1075. }
  1076. Py_DECREF(x);
  1077. }
  1078. }
  1079. return ternary_op(v, w, z, op_slot, op_name);
  1080. }
  1081. #define INPLACE_BINOP(func, iop, op, op_name) \
  1082. PyObject * \
  1083. func(PyObject *v, PyObject *w) { \
  1084. return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
  1085. }
  1086. INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
  1087. INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
  1088. INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")
  1089. INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")
  1090. INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")
  1091. INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")
  1092. INPLACE_BINOP(PyNumber_InPlaceMatrixMultiply, nb_inplace_matrix_multiply, nb_matrix_multiply, "@=")
  1093. INPLACE_BINOP(PyNumber_InPlaceFloorDivide, nb_inplace_floor_divide, nb_floor_divide, "//=")
  1094. INPLACE_BINOP(PyNumber_InPlaceTrueDivide, nb_inplace_true_divide, nb_true_divide, "/=")
  1095. INPLACE_BINOP(PyNumber_InPlaceRemainder, nb_inplace_remainder, nb_remainder, "%=")
  1096. PyObject *
  1097. PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
  1098. {
  1099. PyObject *result = BINARY_IOP1(v, w, NB_SLOT(nb_inplace_add),
  1100. NB_SLOT(nb_add), "+=");
  1101. if (result == Py_NotImplemented) {
  1102. PySequenceMethods *m = Py_TYPE(v)->tp_as_sequence;
  1103. Py_DECREF(result);
  1104. if (m != NULL) {
  1105. binaryfunc func = m->sq_inplace_concat;
  1106. if (func == NULL)
  1107. func = m->sq_concat;
  1108. if (func != NULL) {
  1109. result = func(v, w);
  1110. assert(_Py_CheckSlotResult(v, "+=", result != NULL));
  1111. return result;
  1112. }
  1113. }
  1114. result = binop_type_error(v, w, "+=");
  1115. }
  1116. return result;
  1117. }
  1118. PyObject *
  1119. PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
  1120. {
  1121. PyObject *result = BINARY_IOP1(v, w, NB_SLOT(nb_inplace_multiply),
  1122. NB_SLOT(nb_multiply), "*=");
  1123. if (result == Py_NotImplemented) {
  1124. ssizeargfunc f = NULL;
  1125. PySequenceMethods *mv = Py_TYPE(v)->tp_as_sequence;
  1126. PySequenceMethods *mw = Py_TYPE(w)->tp_as_sequence;
  1127. Py_DECREF(result);
  1128. if (mv != NULL) {
  1129. f = mv->sq_inplace_repeat;
  1130. if (f == NULL)
  1131. f = mv->sq_repeat;
  1132. if (f != NULL)
  1133. return sequence_repeat(f, v, w);
  1134. }
  1135. else if (mw != NULL) {
  1136. /* Note that the right hand operand should not be
  1137. * mutated in this case so sq_inplace_repeat is not
  1138. * used. */
  1139. if (mw->sq_repeat)
  1140. return sequence_repeat(mw->sq_repeat, w, v);
  1141. }
  1142. result = binop_type_error(v, w, "*=");
  1143. }
  1144. return result;
  1145. }
  1146. PyObject *
  1147. PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
  1148. {
  1149. return ternary_iop(v, w, z, NB_SLOT(nb_inplace_power),
  1150. NB_SLOT(nb_power), "**=");
  1151. }
  1152. PyObject *
  1153. _PyNumber_InPlacePowerNoMod(PyObject *lhs, PyObject *rhs)
  1154. {
  1155. return PyNumber_InPlacePower(lhs, rhs, Py_None);
  1156. }
  1157. /* Unary operators and functions */
  1158. PyObject *
  1159. PyNumber_Negative(PyObject *o)
  1160. {
  1161. if (o == NULL) {
  1162. return null_error();
  1163. }
  1164. PyNumberMethods *m = Py_TYPE(o)->tp_as_number;
  1165. if (m && m->nb_negative) {
  1166. PyObject *res = (*m->nb_negative)(o);
  1167. assert(_Py_CheckSlotResult(o, "__neg__", res != NULL));
  1168. return res;
  1169. }
  1170. return type_error("bad operand type for unary -: '%.200s'", o);
  1171. }
  1172. PyObject *
  1173. PyNumber_Positive(PyObject *o)
  1174. {
  1175. if (o == NULL) {
  1176. return null_error();
  1177. }
  1178. PyNumberMethods *m = Py_TYPE(o)->tp_as_number;
  1179. if (m && m->nb_positive) {
  1180. PyObject *res = (*m->nb_positive)(o);
  1181. assert(_Py_CheckSlotResult(o, "__pos__", res != NULL));
  1182. return res;
  1183. }
  1184. return type_error("bad operand type for unary +: '%.200s'", o);
  1185. }
  1186. PyObject *
  1187. PyNumber_Invert(PyObject *o)
  1188. {
  1189. if (o == NULL) {
  1190. return null_error();
  1191. }
  1192. PyNumberMethods *m = Py_TYPE(o)->tp_as_number;
  1193. if (m && m->nb_invert) {
  1194. PyObject *res = (*m->nb_invert)(o);
  1195. assert(_Py_CheckSlotResult(o, "__invert__", res != NULL));
  1196. return res;
  1197. }
  1198. return type_error("bad operand type for unary ~: '%.200s'", o);
  1199. }
  1200. PyObject *
  1201. PyNumber_Absolute(PyObject *o)
  1202. {
  1203. if (o == NULL) {
  1204. return null_error();
  1205. }
  1206. PyNumberMethods *m = Py_TYPE(o)->tp_as_number;
  1207. if (m && m->nb_absolute) {
  1208. PyObject *res = m->nb_absolute(o);
  1209. assert(_Py_CheckSlotResult(o, "__abs__", res != NULL));
  1210. return res;
  1211. }
  1212. return type_error("bad operand type for abs(): '%.200s'", o);
  1213. }
  1214. int
  1215. PyIndex_Check(PyObject *obj)
  1216. {
  1217. return _PyIndex_Check(obj);
  1218. }
  1219. /* Return a Python int from the object item.
  1220. Can return an instance of int subclass.
  1221. Raise TypeError if the result is not an int
  1222. or if the object cannot be interpreted as an index.
  1223. */
  1224. PyObject *
  1225. _PyNumber_Index(PyObject *item)
  1226. {
  1227. if (item == NULL) {
  1228. return null_error();
  1229. }
  1230. if (PyLong_Check(item)) {
  1231. return Py_NewRef(item);
  1232. }
  1233. if (!_PyIndex_Check(item)) {
  1234. PyErr_Format(PyExc_TypeError,
  1235. "'%.200s' object cannot be interpreted "
  1236. "as an integer", Py_TYPE(item)->tp_name);
  1237. return NULL;
  1238. }
  1239. PyObject *result = Py_TYPE(item)->tp_as_number->nb_index(item);
  1240. assert(_Py_CheckSlotResult(item, "__index__", result != NULL));
  1241. if (!result || PyLong_CheckExact(result)) {
  1242. return result;
  1243. }
  1244. if (!PyLong_Check(result)) {
  1245. PyErr_Format(PyExc_TypeError,
  1246. "__index__ returned non-int (type %.200s)",
  1247. Py_TYPE(result)->tp_name);
  1248. Py_DECREF(result);
  1249. return NULL;
  1250. }
  1251. /* Issue #17576: warn if 'result' not of exact type int. */
  1252. if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
  1253. "__index__ returned non-int (type %.200s). "
  1254. "The ability to return an instance of a strict subclass of int "
  1255. "is deprecated, and may be removed in a future version of Python.",
  1256. Py_TYPE(result)->tp_name)) {
  1257. Py_DECREF(result);
  1258. return NULL;
  1259. }
  1260. return result;
  1261. }
  1262. /* Return an exact Python int from the object item.
  1263. Raise TypeError if the result is not an int
  1264. or if the object cannot be interpreted as an index.
  1265. */
  1266. PyObject *
  1267. PyNumber_Index(PyObject *item)
  1268. {
  1269. PyObject *result = _PyNumber_Index(item);
  1270. if (result != NULL && !PyLong_CheckExact(result)) {
  1271. Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
  1272. }
  1273. return result;
  1274. }
  1275. /* Return an error on Overflow only if err is not NULL*/
  1276. Py_ssize_t
  1277. PyNumber_AsSsize_t(PyObject *item, PyObject *err)
  1278. {
  1279. Py_ssize_t result;
  1280. PyObject *runerr;
  1281. PyObject *value = _PyNumber_Index(item);
  1282. if (value == NULL)
  1283. return -1;
  1284. /* We're done if PyLong_AsSsize_t() returns without error. */
  1285. result = PyLong_AsSsize_t(value);
  1286. if (result != -1)
  1287. goto finish;
  1288. PyThreadState *tstate = _PyThreadState_GET();
  1289. runerr = _PyErr_Occurred(tstate);
  1290. if (!runerr) {
  1291. goto finish;
  1292. }
  1293. /* Error handling code -- only manage OverflowError differently */
  1294. if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) {
  1295. goto finish;
  1296. }
  1297. _PyErr_Clear(tstate);
  1298. /* If no error-handling desired then the default clipping
  1299. is sufficient. */
  1300. if (!err) {
  1301. assert(PyLong_Check(value));
  1302. /* Whether or not it is less than or equal to
  1303. zero is determined by the sign of ob_size
  1304. */
  1305. if (_PyLong_IsNegative((PyLongObject *)value))
  1306. result = PY_SSIZE_T_MIN;
  1307. else
  1308. result = PY_SSIZE_T_MAX;
  1309. }
  1310. else {
  1311. /* Otherwise replace the error with caller's error object. */
  1312. _PyErr_Format(tstate, err,
  1313. "cannot fit '%.200s' into an index-sized integer",
  1314. Py_TYPE(item)->tp_name);
  1315. }
  1316. finish:
  1317. Py_DECREF(value);
  1318. return result;
  1319. }
  1320. PyObject *
  1321. PyNumber_Long(PyObject *o)
  1322. {
  1323. PyObject *result;
  1324. PyNumberMethods *m;
  1325. PyObject *trunc_func;
  1326. Py_buffer view;
  1327. if (o == NULL) {
  1328. return null_error();
  1329. }
  1330. if (PyLong_CheckExact(o)) {
  1331. return Py_NewRef(o);
  1332. }
  1333. m = Py_TYPE(o)->tp_as_number;
  1334. if (m && m->nb_int) { /* This should include subclasses of int */
  1335. /* Convert using the nb_int slot, which should return something
  1336. of exact type int. */
  1337. result = m->nb_int(o);
  1338. assert(_Py_CheckSlotResult(o, "__int__", result != NULL));
  1339. if (!result || PyLong_CheckExact(result)) {
  1340. return result;
  1341. }
  1342. if (!PyLong_Check(result)) {
  1343. PyErr_Format(PyExc_TypeError,
  1344. "__int__ returned non-int (type %.200s)",
  1345. Py_TYPE(result)->tp_name);
  1346. Py_DECREF(result);
  1347. return NULL;
  1348. }
  1349. /* Issue #17576: warn if 'result' not of exact type int. */
  1350. if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
  1351. "__int__ returned non-int (type %.200s). "
  1352. "The ability to return an instance of a strict subclass of int "
  1353. "is deprecated, and may be removed in a future version of Python.",
  1354. Py_TYPE(result)->tp_name)) {
  1355. Py_DECREF(result);
  1356. return NULL;
  1357. }
  1358. Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
  1359. return result;
  1360. }
  1361. if (m && m->nb_index) {
  1362. return PyNumber_Index(o);
  1363. }
  1364. trunc_func = _PyObject_LookupSpecial(o, &_Py_ID(__trunc__));
  1365. if (trunc_func) {
  1366. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  1367. "The delegation of int() to __trunc__ is deprecated.", 1)) {
  1368. Py_DECREF(trunc_func);
  1369. return NULL;
  1370. }
  1371. result = _PyObject_CallNoArgs(trunc_func);
  1372. Py_DECREF(trunc_func);
  1373. if (result == NULL || PyLong_CheckExact(result)) {
  1374. return result;
  1375. }
  1376. if (PyLong_Check(result)) {
  1377. Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
  1378. return result;
  1379. }
  1380. /* __trunc__ is specified to return an Integral type,
  1381. but int() needs to return an int. */
  1382. if (!PyIndex_Check(result)) {
  1383. PyErr_Format(
  1384. PyExc_TypeError,
  1385. "__trunc__ returned non-Integral (type %.200s)",
  1386. Py_TYPE(result)->tp_name);
  1387. Py_DECREF(result);
  1388. return NULL;
  1389. }
  1390. Py_SETREF(result, PyNumber_Index(result));
  1391. return result;
  1392. }
  1393. if (PyErr_Occurred())
  1394. return NULL;
  1395. if (PyUnicode_Check(o))
  1396. /* The below check is done in PyLong_FromUnicodeObject(). */
  1397. return PyLong_FromUnicodeObject(o, 10);
  1398. if (PyBytes_Check(o))
  1399. /* need to do extra error checking that PyLong_FromString()
  1400. * doesn't do. In particular int('9\x005') must raise an
  1401. * exception, not truncate at the null.
  1402. */
  1403. return _PyLong_FromBytes(PyBytes_AS_STRING(o),
  1404. PyBytes_GET_SIZE(o), 10);
  1405. if (PyByteArray_Check(o))
  1406. return _PyLong_FromBytes(PyByteArray_AS_STRING(o),
  1407. PyByteArray_GET_SIZE(o), 10);
  1408. if (PyObject_GetBuffer(o, &view, PyBUF_SIMPLE) == 0) {
  1409. PyObject *bytes;
  1410. /* Copy to NUL-terminated buffer. */
  1411. bytes = PyBytes_FromStringAndSize((const char *)view.buf, view.len);
  1412. if (bytes == NULL) {
  1413. PyBuffer_Release(&view);
  1414. return NULL;
  1415. }
  1416. result = _PyLong_FromBytes(PyBytes_AS_STRING(bytes),
  1417. PyBytes_GET_SIZE(bytes), 10);
  1418. Py_DECREF(bytes);
  1419. PyBuffer_Release(&view);
  1420. return result;
  1421. }
  1422. return type_error("int() argument must be a string, a bytes-like object "
  1423. "or a real number, not '%.200s'", o);
  1424. }
  1425. PyObject *
  1426. PyNumber_Float(PyObject *o)
  1427. {
  1428. if (o == NULL) {
  1429. return null_error();
  1430. }
  1431. if (PyFloat_CheckExact(o)) {
  1432. return Py_NewRef(o);
  1433. }
  1434. PyNumberMethods *m = Py_TYPE(o)->tp_as_number;
  1435. if (m && m->nb_float) { /* This should include subclasses of float */
  1436. PyObject *res = m->nb_float(o);
  1437. assert(_Py_CheckSlotResult(o, "__float__", res != NULL));
  1438. if (!res || PyFloat_CheckExact(res)) {
  1439. return res;
  1440. }
  1441. if (!PyFloat_Check(res)) {
  1442. PyErr_Format(PyExc_TypeError,
  1443. "%.50s.__float__ returned non-float (type %.50s)",
  1444. Py_TYPE(o)->tp_name, Py_TYPE(res)->tp_name);
  1445. Py_DECREF(res);
  1446. return NULL;
  1447. }
  1448. /* Issue #26983: warn if 'res' not of exact type float. */
  1449. if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
  1450. "%.50s.__float__ returned non-float (type %.50s). "
  1451. "The ability to return an instance of a strict subclass of float "
  1452. "is deprecated, and may be removed in a future version of Python.",
  1453. Py_TYPE(o)->tp_name, Py_TYPE(res)->tp_name)) {
  1454. Py_DECREF(res);
  1455. return NULL;
  1456. }
  1457. double val = PyFloat_AS_DOUBLE(res);
  1458. Py_DECREF(res);
  1459. return PyFloat_FromDouble(val);
  1460. }
  1461. if (m && m->nb_index) {
  1462. PyObject *res = _PyNumber_Index(o);
  1463. if (!res) {
  1464. return NULL;
  1465. }
  1466. double val = PyLong_AsDouble(res);
  1467. Py_DECREF(res);
  1468. if (val == -1.0 && PyErr_Occurred()) {
  1469. return NULL;
  1470. }
  1471. return PyFloat_FromDouble(val);
  1472. }
  1473. /* A float subclass with nb_float == NULL */
  1474. if (PyFloat_Check(o)) {
  1475. return PyFloat_FromDouble(PyFloat_AS_DOUBLE(o));
  1476. }
  1477. return PyFloat_FromString(o);
  1478. }
  1479. PyObject *
  1480. PyNumber_ToBase(PyObject *n, int base)
  1481. {
  1482. if (!(base == 2 || base == 8 || base == 10 || base == 16)) {
  1483. PyErr_SetString(PyExc_SystemError,
  1484. "PyNumber_ToBase: base must be 2, 8, 10 or 16");
  1485. return NULL;
  1486. }
  1487. PyObject *index = _PyNumber_Index(n);
  1488. if (!index)
  1489. return NULL;
  1490. PyObject *res = _PyLong_Format(index, base);
  1491. Py_DECREF(index);
  1492. return res;
  1493. }
  1494. /* Operations on sequences */
  1495. int
  1496. PySequence_Check(PyObject *s)
  1497. {
  1498. if (PyDict_Check(s))
  1499. return 0;
  1500. return Py_TYPE(s)->tp_as_sequence &&
  1501. Py_TYPE(s)->tp_as_sequence->sq_item != NULL;
  1502. }
  1503. Py_ssize_t
  1504. PySequence_Size(PyObject *s)
  1505. {
  1506. if (s == NULL) {
  1507. null_error();
  1508. return -1;
  1509. }
  1510. PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
  1511. if (m && m->sq_length) {
  1512. Py_ssize_t len = m->sq_length(s);
  1513. assert(_Py_CheckSlotResult(s, "__len__", len >= 0));
  1514. return len;
  1515. }
  1516. if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_length) {
  1517. type_error("%.200s is not a sequence", s);
  1518. return -1;
  1519. }
  1520. type_error("object of type '%.200s' has no len()", s);
  1521. return -1;
  1522. }
  1523. #undef PySequence_Length
  1524. Py_ssize_t
  1525. PySequence_Length(PyObject *s)
  1526. {
  1527. return PySequence_Size(s);
  1528. }
  1529. #define PySequence_Length PySequence_Size
  1530. PyObject *
  1531. PySequence_Concat(PyObject *s, PyObject *o)
  1532. {
  1533. if (s == NULL || o == NULL) {
  1534. return null_error();
  1535. }
  1536. PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
  1537. if (m && m->sq_concat) {
  1538. PyObject *res = m->sq_concat(s, o);
  1539. assert(_Py_CheckSlotResult(s, "+", res != NULL));
  1540. return res;
  1541. }
  1542. /* Instances of user classes defining an __add__() method only
  1543. have an nb_add slot, not an sq_concat slot. So we fall back
  1544. to nb_add if both arguments appear to be sequences. */
  1545. if (PySequence_Check(s) && PySequence_Check(o)) {
  1546. PyObject *result = BINARY_OP1(s, o, NB_SLOT(nb_add), "+");
  1547. if (result != Py_NotImplemented)
  1548. return result;
  1549. Py_DECREF(result);
  1550. }
  1551. return type_error("'%.200s' object can't be concatenated", s);
  1552. }
  1553. PyObject *
  1554. PySequence_Repeat(PyObject *o, Py_ssize_t count)
  1555. {
  1556. if (o == NULL) {
  1557. return null_error();
  1558. }
  1559. PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence;
  1560. if (m && m->sq_repeat) {
  1561. PyObject *res = m->sq_repeat(o, count);
  1562. assert(_Py_CheckSlotResult(o, "*", res != NULL));
  1563. return res;
  1564. }
  1565. /* Instances of user classes defining a __mul__() method only
  1566. have an nb_multiply slot, not an sq_repeat slot. so we fall back
  1567. to nb_multiply if o appears to be a sequence. */
  1568. if (PySequence_Check(o)) {
  1569. PyObject *n, *result;
  1570. n = PyLong_FromSsize_t(count);
  1571. if (n == NULL)
  1572. return NULL;
  1573. result = BINARY_OP1(o, n, NB_SLOT(nb_multiply), "*");
  1574. Py_DECREF(n);
  1575. if (result != Py_NotImplemented)
  1576. return result;
  1577. Py_DECREF(result);
  1578. }
  1579. return type_error("'%.200s' object can't be repeated", o);
  1580. }
  1581. PyObject *
  1582. PySequence_InPlaceConcat(PyObject *s, PyObject *o)
  1583. {
  1584. if (s == NULL || o == NULL) {
  1585. return null_error();
  1586. }
  1587. PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
  1588. if (m && m->sq_inplace_concat) {
  1589. PyObject *res = m->sq_inplace_concat(s, o);
  1590. assert(_Py_CheckSlotResult(s, "+=", res != NULL));
  1591. return res;
  1592. }
  1593. if (m && m->sq_concat) {
  1594. PyObject *res = m->sq_concat(s, o);
  1595. assert(_Py_CheckSlotResult(s, "+", res != NULL));
  1596. return res;
  1597. }
  1598. if (PySequence_Check(s) && PySequence_Check(o)) {
  1599. PyObject *result = BINARY_IOP1(s, o, NB_SLOT(nb_inplace_add),
  1600. NB_SLOT(nb_add), "+=");
  1601. if (result != Py_NotImplemented)
  1602. return result;
  1603. Py_DECREF(result);
  1604. }
  1605. return type_error("'%.200s' object can't be concatenated", s);
  1606. }
  1607. PyObject *
  1608. PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
  1609. {
  1610. if (o == NULL) {
  1611. return null_error();
  1612. }
  1613. PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence;
  1614. if (m && m->sq_inplace_repeat) {
  1615. PyObject *res = m->sq_inplace_repeat(o, count);
  1616. assert(_Py_CheckSlotResult(o, "*=", res != NULL));
  1617. return res;
  1618. }
  1619. if (m && m->sq_repeat) {
  1620. PyObject *res = m->sq_repeat(o, count);
  1621. assert(_Py_CheckSlotResult(o, "*", res != NULL));
  1622. return res;
  1623. }
  1624. if (PySequence_Check(o)) {
  1625. PyObject *n, *result;
  1626. n = PyLong_FromSsize_t(count);
  1627. if (n == NULL)
  1628. return NULL;
  1629. result = BINARY_IOP1(o, n, NB_SLOT(nb_inplace_multiply),
  1630. NB_SLOT(nb_multiply), "*=");
  1631. Py_DECREF(n);
  1632. if (result != Py_NotImplemented)
  1633. return result;
  1634. Py_DECREF(result);
  1635. }
  1636. return type_error("'%.200s' object can't be repeated", o);
  1637. }
  1638. PyObject *
  1639. PySequence_GetItem(PyObject *s, Py_ssize_t i)
  1640. {
  1641. if (s == NULL) {
  1642. return null_error();
  1643. }
  1644. PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
  1645. if (m && m->sq_item) {
  1646. if (i < 0) {
  1647. if (m->sq_length) {
  1648. Py_ssize_t l = (*m->sq_length)(s);
  1649. assert(_Py_CheckSlotResult(s, "__len__", l >= 0));
  1650. if (l < 0) {
  1651. return NULL;
  1652. }
  1653. i += l;
  1654. }
  1655. }
  1656. PyObject *res = m->sq_item(s, i);
  1657. assert(_Py_CheckSlotResult(s, "__getitem__", res != NULL));
  1658. return res;
  1659. }
  1660. if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_subscript) {
  1661. return type_error("%.200s is not a sequence", s);
  1662. }
  1663. return type_error("'%.200s' object does not support indexing", s);
  1664. }
  1665. PyObject *
  1666. PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
  1667. {
  1668. if (!s) {
  1669. return null_error();
  1670. }
  1671. PyMappingMethods *mp = Py_TYPE(s)->tp_as_mapping;
  1672. if (mp && mp->mp_subscript) {
  1673. PyObject *slice = _PySlice_FromIndices(i1, i2);
  1674. if (!slice) {
  1675. return NULL;
  1676. }
  1677. PyObject *res = mp->mp_subscript(s, slice);
  1678. assert(_Py_CheckSlotResult(s, "__getitem__", res != NULL));
  1679. Py_DECREF(slice);
  1680. return res;
  1681. }
  1682. return type_error("'%.200s' object is unsliceable", s);
  1683. }
  1684. int
  1685. PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
  1686. {
  1687. if (s == NULL) {
  1688. null_error();
  1689. return -1;
  1690. }
  1691. PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
  1692. if (m && m->sq_ass_item) {
  1693. if (i < 0) {
  1694. if (m->sq_length) {
  1695. Py_ssize_t l = (*m->sq_length)(s);
  1696. assert(_Py_CheckSlotResult(s, "__len__", l >= 0));
  1697. if (l < 0) {
  1698. return -1;
  1699. }
  1700. i += l;
  1701. }
  1702. }
  1703. int res = m->sq_ass_item(s, i, o);
  1704. assert(_Py_CheckSlotResult(s, "__setitem__", res >= 0));
  1705. return res;
  1706. }
  1707. if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) {
  1708. type_error("%.200s is not a sequence", s);
  1709. return -1;
  1710. }
  1711. type_error("'%.200s' object does not support item assignment", s);
  1712. return -1;
  1713. }
  1714. int
  1715. PySequence_DelItem(PyObject *s, Py_ssize_t i)
  1716. {
  1717. if (s == NULL) {
  1718. null_error();
  1719. return -1;
  1720. }
  1721. PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
  1722. if (m && m->sq_ass_item) {
  1723. if (i < 0) {
  1724. if (m->sq_length) {
  1725. Py_ssize_t l = (*m->sq_length)(s);
  1726. assert(_Py_CheckSlotResult(s, "__len__", l >= 0));
  1727. if (l < 0) {
  1728. return -1;
  1729. }
  1730. i += l;
  1731. }
  1732. }
  1733. int res = m->sq_ass_item(s, i, (PyObject *)NULL);
  1734. assert(_Py_CheckSlotResult(s, "__delitem__", res >= 0));
  1735. return res;
  1736. }
  1737. if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) {
  1738. type_error("%.200s is not a sequence", s);
  1739. return -1;
  1740. }
  1741. type_error("'%.200s' object doesn't support item deletion", s);
  1742. return -1;
  1743. }
  1744. int
  1745. PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
  1746. {
  1747. if (s == NULL) {
  1748. null_error();
  1749. return -1;
  1750. }
  1751. PyMappingMethods *mp = Py_TYPE(s)->tp_as_mapping;
  1752. if (mp && mp->mp_ass_subscript) {
  1753. PyObject *slice = _PySlice_FromIndices(i1, i2);
  1754. if (!slice)
  1755. return -1;
  1756. int res = mp->mp_ass_subscript(s, slice, o);
  1757. assert(_Py_CheckSlotResult(s, "__setitem__", res >= 0));
  1758. Py_DECREF(slice);
  1759. return res;
  1760. }
  1761. type_error("'%.200s' object doesn't support slice assignment", s);
  1762. return -1;
  1763. }
  1764. int
  1765. PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
  1766. {
  1767. if (s == NULL) {
  1768. null_error();
  1769. return -1;
  1770. }
  1771. PyMappingMethods *mp = Py_TYPE(s)->tp_as_mapping;
  1772. if (mp && mp->mp_ass_subscript) {
  1773. PyObject *slice = _PySlice_FromIndices(i1, i2);
  1774. if (!slice) {
  1775. return -1;
  1776. }
  1777. int res = mp->mp_ass_subscript(s, slice, NULL);
  1778. assert(_Py_CheckSlotResult(s, "__delitem__", res >= 0));
  1779. Py_DECREF(slice);
  1780. return res;
  1781. }
  1782. type_error("'%.200s' object doesn't support slice deletion", s);
  1783. return -1;
  1784. }
  1785. PyObject *
  1786. PySequence_Tuple(PyObject *v)
  1787. {
  1788. PyObject *it; /* iter(v) */
  1789. Py_ssize_t n; /* guess for result tuple size */
  1790. PyObject *result = NULL;
  1791. Py_ssize_t j;
  1792. if (v == NULL) {
  1793. return null_error();
  1794. }
  1795. /* Special-case the common tuple and list cases, for efficiency. */
  1796. if (PyTuple_CheckExact(v)) {
  1797. /* Note that we can't know whether it's safe to return
  1798. a tuple *subclass* instance as-is, hence the restriction
  1799. to exact tuples here. In contrast, lists always make
  1800. a copy, so there's no need for exactness below. */
  1801. return Py_NewRef(v);
  1802. }
  1803. if (PyList_CheckExact(v))
  1804. return PyList_AsTuple(v);
  1805. /* Get iterator. */
  1806. it = PyObject_GetIter(v);
  1807. if (it == NULL)
  1808. return NULL;
  1809. /* Guess result size and allocate space. */
  1810. n = PyObject_LengthHint(v, 10);
  1811. if (n == -1)
  1812. goto Fail;
  1813. result = PyTuple_New(n);
  1814. if (result == NULL)
  1815. goto Fail;
  1816. /* Fill the tuple. */
  1817. for (j = 0; ; ++j) {
  1818. PyObject *item = PyIter_Next(it);
  1819. if (item == NULL) {
  1820. if (PyErr_Occurred())
  1821. goto Fail;
  1822. break;
  1823. }
  1824. if (j >= n) {
  1825. size_t newn = (size_t)n;
  1826. /* The over-allocation strategy can grow a bit faster
  1827. than for lists because unlike lists the
  1828. over-allocation isn't permanent -- we reclaim
  1829. the excess before the end of this routine.
  1830. So, grow by ten and then add 25%.
  1831. */
  1832. newn += 10u;
  1833. newn += newn >> 2;
  1834. if (newn > PY_SSIZE_T_MAX) {
  1835. /* Check for overflow */
  1836. PyErr_NoMemory();
  1837. Py_DECREF(item);
  1838. goto Fail;
  1839. }
  1840. n = (Py_ssize_t)newn;
  1841. if (_PyTuple_Resize(&result, n) != 0) {
  1842. Py_DECREF(item);
  1843. goto Fail;
  1844. }
  1845. }
  1846. PyTuple_SET_ITEM(result, j, item);
  1847. }
  1848. /* Cut tuple back if guess was too large. */
  1849. if (j < n &&
  1850. _PyTuple_Resize(&result, j) != 0)
  1851. goto Fail;
  1852. Py_DECREF(it);
  1853. return result;
  1854. Fail:
  1855. Py_XDECREF(result);
  1856. Py_DECREF(it);
  1857. return NULL;
  1858. }
  1859. PyObject *
  1860. PySequence_List(PyObject *v)
  1861. {
  1862. PyObject *result; /* result list */
  1863. PyObject *rv; /* return value from PyList_Extend */
  1864. if (v == NULL) {
  1865. return null_error();
  1866. }
  1867. result = PyList_New(0);
  1868. if (result == NULL)
  1869. return NULL;
  1870. rv = _PyList_Extend((PyListObject *)result, v);
  1871. if (rv == NULL) {
  1872. Py_DECREF(result);
  1873. return NULL;
  1874. }
  1875. Py_DECREF(rv);
  1876. return result;
  1877. }
  1878. PyObject *
  1879. PySequence_Fast(PyObject *v, const char *m)
  1880. {
  1881. PyObject *it;
  1882. if (v == NULL) {
  1883. return null_error();
  1884. }
  1885. if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
  1886. return Py_NewRef(v);
  1887. }
  1888. it = PyObject_GetIter(v);
  1889. if (it == NULL) {
  1890. PyThreadState *tstate = _PyThreadState_GET();
  1891. if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
  1892. _PyErr_SetString(tstate, PyExc_TypeError, m);
  1893. }
  1894. return NULL;
  1895. }
  1896. v = PySequence_List(it);
  1897. Py_DECREF(it);
  1898. return v;
  1899. }
  1900. /* Iterate over seq. Result depends on the operation:
  1901. PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
  1902. PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;
  1903. set ValueError and return -1 if none found; also return -1 on error.
  1904. Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
  1905. */
  1906. Py_ssize_t
  1907. _PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
  1908. {
  1909. Py_ssize_t n;
  1910. int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
  1911. PyObject *it; /* iter(seq) */
  1912. if (seq == NULL || obj == NULL) {
  1913. null_error();
  1914. return -1;
  1915. }
  1916. it = PyObject_GetIter(seq);
  1917. if (it == NULL) {
  1918. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  1919. type_error("argument of type '%.200s' is not iterable", seq);
  1920. }
  1921. return -1;
  1922. }
  1923. n = wrapped = 0;
  1924. for (;;) {
  1925. int cmp;
  1926. PyObject *item = PyIter_Next(it);
  1927. if (item == NULL) {
  1928. if (PyErr_Occurred())
  1929. goto Fail;
  1930. break;
  1931. }
  1932. cmp = PyObject_RichCompareBool(item, obj, Py_EQ);
  1933. Py_DECREF(item);
  1934. if (cmp < 0)
  1935. goto Fail;
  1936. if (cmp > 0) {
  1937. switch (operation) {
  1938. case PY_ITERSEARCH_COUNT:
  1939. if (n == PY_SSIZE_T_MAX) {
  1940. PyErr_SetString(PyExc_OverflowError,
  1941. "count exceeds C integer size");
  1942. goto Fail;
  1943. }
  1944. ++n;
  1945. break;
  1946. case PY_ITERSEARCH_INDEX:
  1947. if (wrapped) {
  1948. PyErr_SetString(PyExc_OverflowError,
  1949. "index exceeds C integer size");
  1950. goto Fail;
  1951. }
  1952. goto Done;
  1953. case PY_ITERSEARCH_CONTAINS:
  1954. n = 1;
  1955. goto Done;
  1956. default:
  1957. Py_UNREACHABLE();
  1958. }
  1959. }
  1960. if (operation == PY_ITERSEARCH_INDEX) {
  1961. if (n == PY_SSIZE_T_MAX)
  1962. wrapped = 1;
  1963. ++n;
  1964. }
  1965. }
  1966. if (operation != PY_ITERSEARCH_INDEX)
  1967. goto Done;
  1968. PyErr_SetString(PyExc_ValueError,
  1969. "sequence.index(x): x not in sequence");
  1970. /* fall into failure code */
  1971. Fail:
  1972. n = -1;
  1973. /* fall through */
  1974. Done:
  1975. Py_DECREF(it);
  1976. return n;
  1977. }
  1978. /* Return # of times o appears in s. */
  1979. Py_ssize_t
  1980. PySequence_Count(PyObject *s, PyObject *o)
  1981. {
  1982. return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
  1983. }
  1984. /* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
  1985. * Use sq_contains if possible, else defer to _PySequence_IterSearch().
  1986. */
  1987. int
  1988. PySequence_Contains(PyObject *seq, PyObject *ob)
  1989. {
  1990. PySequenceMethods *sqm = Py_TYPE(seq)->tp_as_sequence;
  1991. if (sqm != NULL && sqm->sq_contains != NULL) {
  1992. int res = (*sqm->sq_contains)(seq, ob);
  1993. assert(_Py_CheckSlotResult(seq, "__contains__", res >= 0));
  1994. return res;
  1995. }
  1996. Py_ssize_t result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
  1997. return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
  1998. }
  1999. /* Backwards compatibility */
  2000. #undef PySequence_In
  2001. int
  2002. PySequence_In(PyObject *w, PyObject *v)
  2003. {
  2004. return PySequence_Contains(w, v);
  2005. }
  2006. Py_ssize_t
  2007. PySequence_Index(PyObject *s, PyObject *o)
  2008. {
  2009. return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
  2010. }
  2011. /* Operations on mappings */
  2012. int
  2013. PyMapping_Check(PyObject *o)
  2014. {
  2015. return o && Py_TYPE(o)->tp_as_mapping &&
  2016. Py_TYPE(o)->tp_as_mapping->mp_subscript;
  2017. }
  2018. Py_ssize_t
  2019. PyMapping_Size(PyObject *o)
  2020. {
  2021. if (o == NULL) {
  2022. null_error();
  2023. return -1;
  2024. }
  2025. PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping;
  2026. if (m && m->mp_length) {
  2027. Py_ssize_t len = m->mp_length(o);
  2028. assert(_Py_CheckSlotResult(o, "__len__", len >= 0));
  2029. return len;
  2030. }
  2031. if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) {
  2032. type_error("%.200s is not a mapping", o);
  2033. return -1;
  2034. }
  2035. /* PyMapping_Size() can be called from PyObject_Size(). */
  2036. type_error("object of type '%.200s' has no len()", o);
  2037. return -1;
  2038. }
  2039. #undef PyMapping_Length
  2040. Py_ssize_t
  2041. PyMapping_Length(PyObject *o)
  2042. {
  2043. return PyMapping_Size(o);
  2044. }
  2045. #define PyMapping_Length PyMapping_Size
  2046. PyObject *
  2047. PyMapping_GetItemString(PyObject *o, const char *key)
  2048. {
  2049. PyObject *okey, *r;
  2050. if (key == NULL) {
  2051. return null_error();
  2052. }
  2053. okey = PyUnicode_FromString(key);
  2054. if (okey == NULL)
  2055. return NULL;
  2056. r = PyObject_GetItem(o, okey);
  2057. Py_DECREF(okey);
  2058. return r;
  2059. }
  2060. int
  2061. PyMapping_SetItemString(PyObject *o, const char *key, PyObject *value)
  2062. {
  2063. PyObject *okey;
  2064. int r;
  2065. if (key == NULL) {
  2066. null_error();
  2067. return -1;
  2068. }
  2069. okey = PyUnicode_FromString(key);
  2070. if (okey == NULL)
  2071. return -1;
  2072. r = PyObject_SetItem(o, okey, value);
  2073. Py_DECREF(okey);
  2074. return r;
  2075. }
  2076. int
  2077. PyMapping_HasKeyString(PyObject *o, const char *key)
  2078. {
  2079. PyObject *v;
  2080. v = PyMapping_GetItemString(o, key);
  2081. if (v) {
  2082. Py_DECREF(v);
  2083. return 1;
  2084. }
  2085. PyErr_Clear();
  2086. return 0;
  2087. }
  2088. int
  2089. PyMapping_HasKey(PyObject *o, PyObject *key)
  2090. {
  2091. PyObject *v;
  2092. v = PyObject_GetItem(o, key);
  2093. if (v) {
  2094. Py_DECREF(v);
  2095. return 1;
  2096. }
  2097. PyErr_Clear();
  2098. return 0;
  2099. }
  2100. /* This function is quite similar to PySequence_Fast(), but specialized to be
  2101. a helper for PyMapping_Keys(), PyMapping_Items() and PyMapping_Values().
  2102. */
  2103. static PyObject *
  2104. method_output_as_list(PyObject *o, PyObject *meth)
  2105. {
  2106. PyObject *it, *result, *meth_output;
  2107. assert(o != NULL);
  2108. meth_output = PyObject_CallMethodNoArgs(o, meth);
  2109. if (meth_output == NULL || PyList_CheckExact(meth_output)) {
  2110. return meth_output;
  2111. }
  2112. it = PyObject_GetIter(meth_output);
  2113. if (it == NULL) {
  2114. PyThreadState *tstate = _PyThreadState_GET();
  2115. if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
  2116. _PyErr_Format(tstate, PyExc_TypeError,
  2117. "%.200s.%U() returned a non-iterable (type %.200s)",
  2118. Py_TYPE(o)->tp_name,
  2119. meth,
  2120. Py_TYPE(meth_output)->tp_name);
  2121. }
  2122. Py_DECREF(meth_output);
  2123. return NULL;
  2124. }
  2125. Py_DECREF(meth_output);
  2126. result = PySequence_List(it);
  2127. Py_DECREF(it);
  2128. return result;
  2129. }
  2130. PyObject *
  2131. PyMapping_Keys(PyObject *o)
  2132. {
  2133. if (o == NULL) {
  2134. return null_error();
  2135. }
  2136. if (PyDict_CheckExact(o)) {
  2137. return PyDict_Keys(o);
  2138. }
  2139. return method_output_as_list(o, &_Py_ID(keys));
  2140. }
  2141. PyObject *
  2142. PyMapping_Items(PyObject *o)
  2143. {
  2144. if (o == NULL) {
  2145. return null_error();
  2146. }
  2147. if (PyDict_CheckExact(o)) {
  2148. return PyDict_Items(o);
  2149. }
  2150. return method_output_as_list(o, &_Py_ID(items));
  2151. }
  2152. PyObject *
  2153. PyMapping_Values(PyObject *o)
  2154. {
  2155. if (o == NULL) {
  2156. return null_error();
  2157. }
  2158. if (PyDict_CheckExact(o)) {
  2159. return PyDict_Values(o);
  2160. }
  2161. return method_output_as_list(o, &_Py_ID(values));
  2162. }
  2163. /* isinstance(), issubclass() */
  2164. /* abstract_get_bases() has logically 4 return states:
  2165. *
  2166. * 1. getattr(cls, '__bases__') could raise an AttributeError
  2167. * 2. getattr(cls, '__bases__') could raise some other exception
  2168. * 3. getattr(cls, '__bases__') could return a tuple
  2169. * 4. getattr(cls, '__bases__') could return something other than a tuple
  2170. *
  2171. * Only state #3 is a non-error state and only it returns a non-NULL object
  2172. * (it returns the retrieved tuple).
  2173. *
  2174. * Any raised AttributeErrors are masked by clearing the exception and
  2175. * returning NULL. If an object other than a tuple comes out of __bases__,
  2176. * then again, the return value is NULL. So yes, these two situations
  2177. * produce exactly the same results: NULL is returned and no error is set.
  2178. *
  2179. * If some exception other than AttributeError is raised, then NULL is also
  2180. * returned, but the exception is not cleared. That's because we want the
  2181. * exception to be propagated along.
  2182. *
  2183. * Callers are expected to test for PyErr_Occurred() when the return value
  2184. * is NULL to decide whether a valid exception should be propagated or not.
  2185. * When there's no exception to propagate, it's customary for the caller to
  2186. * set a TypeError.
  2187. */
  2188. static PyObject *
  2189. abstract_get_bases(PyObject *cls)
  2190. {
  2191. PyObject *bases;
  2192. (void)_PyObject_LookupAttr(cls, &_Py_ID(__bases__), &bases);
  2193. if (bases != NULL && !PyTuple_Check(bases)) {
  2194. Py_DECREF(bases);
  2195. return NULL;
  2196. }
  2197. return bases;
  2198. }
  2199. static int
  2200. abstract_issubclass(PyObject *derived, PyObject *cls)
  2201. {
  2202. PyObject *bases = NULL;
  2203. Py_ssize_t i, n;
  2204. int r = 0;
  2205. while (1) {
  2206. if (derived == cls) {
  2207. Py_XDECREF(bases); /* See below comment */
  2208. return 1;
  2209. }
  2210. /* Use XSETREF to drop bases reference *after* finishing with
  2211. derived; bases might be the only reference to it.
  2212. XSETREF is used instead of SETREF, because bases is NULL on the
  2213. first iteration of the loop.
  2214. */
  2215. Py_XSETREF(bases, abstract_get_bases(derived));
  2216. if (bases == NULL) {
  2217. if (PyErr_Occurred())
  2218. return -1;
  2219. return 0;
  2220. }
  2221. n = PyTuple_GET_SIZE(bases);
  2222. if (n == 0) {
  2223. Py_DECREF(bases);
  2224. return 0;
  2225. }
  2226. /* Avoid recursivity in the single inheritance case */
  2227. if (n == 1) {
  2228. derived = PyTuple_GET_ITEM(bases, 0);
  2229. continue;
  2230. }
  2231. break;
  2232. }
  2233. assert(n >= 2);
  2234. if (_Py_EnterRecursiveCall(" in __issubclass__")) {
  2235. Py_DECREF(bases);
  2236. return -1;
  2237. }
  2238. for (i = 0; i < n; i++) {
  2239. r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
  2240. if (r != 0) {
  2241. break;
  2242. }
  2243. }
  2244. _Py_LeaveRecursiveCall();
  2245. Py_DECREF(bases);
  2246. return r;
  2247. }
  2248. static int
  2249. check_class(PyObject *cls, const char *error)
  2250. {
  2251. PyObject *bases = abstract_get_bases(cls);
  2252. if (bases == NULL) {
  2253. /* Do not mask errors. */
  2254. PyThreadState *tstate = _PyThreadState_GET();
  2255. if (!_PyErr_Occurred(tstate)) {
  2256. _PyErr_SetString(tstate, PyExc_TypeError, error);
  2257. }
  2258. return 0;
  2259. }
  2260. Py_DECREF(bases);
  2261. return -1;
  2262. }
  2263. static int
  2264. object_isinstance(PyObject *inst, PyObject *cls)
  2265. {
  2266. PyObject *icls;
  2267. int retval;
  2268. if (PyType_Check(cls)) {
  2269. retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
  2270. if (retval == 0) {
  2271. retval = _PyObject_LookupAttr(inst, &_Py_ID(__class__), &icls);
  2272. if (icls != NULL) {
  2273. if (icls != (PyObject *)(Py_TYPE(inst)) && PyType_Check(icls)) {
  2274. retval = PyType_IsSubtype(
  2275. (PyTypeObject *)icls,
  2276. (PyTypeObject *)cls);
  2277. }
  2278. else {
  2279. retval = 0;
  2280. }
  2281. Py_DECREF(icls);
  2282. }
  2283. }
  2284. }
  2285. else {
  2286. if (!check_class(cls,
  2287. "isinstance() arg 2 must be a type, a tuple of types, or a union"))
  2288. return -1;
  2289. retval = _PyObject_LookupAttr(inst, &_Py_ID(__class__), &icls);
  2290. if (icls != NULL) {
  2291. retval = abstract_issubclass(icls, cls);
  2292. Py_DECREF(icls);
  2293. }
  2294. }
  2295. return retval;
  2296. }
  2297. static int
  2298. object_recursive_isinstance(PyThreadState *tstate, PyObject *inst, PyObject *cls)
  2299. {
  2300. /* Quick test for an exact match */
  2301. if (Py_IS_TYPE(inst, (PyTypeObject *)cls)) {
  2302. return 1;
  2303. }
  2304. /* We know what type's __instancecheck__ does. */
  2305. if (PyType_CheckExact(cls)) {
  2306. return object_isinstance(inst, cls);
  2307. }
  2308. if (_PyUnion_Check(cls)) {
  2309. cls = _Py_union_args(cls);
  2310. }
  2311. if (PyTuple_Check(cls)) {
  2312. /* Not a general sequence -- that opens up the road to
  2313. recursion and stack overflow. */
  2314. if (_Py_EnterRecursiveCallTstate(tstate, " in __instancecheck__")) {
  2315. return -1;
  2316. }
  2317. Py_ssize_t n = PyTuple_GET_SIZE(cls);
  2318. int r = 0;
  2319. for (Py_ssize_t i = 0; i < n; ++i) {
  2320. PyObject *item = PyTuple_GET_ITEM(cls, i);
  2321. r = object_recursive_isinstance(tstate, inst, item);
  2322. if (r != 0) {
  2323. /* either found it, or got an error */
  2324. break;
  2325. }
  2326. }
  2327. _Py_LeaveRecursiveCallTstate(tstate);
  2328. return r;
  2329. }
  2330. PyObject *checker = _PyObject_LookupSpecial(cls, &_Py_ID(__instancecheck__));
  2331. if (checker != NULL) {
  2332. if (_Py_EnterRecursiveCallTstate(tstate, " in __instancecheck__")) {
  2333. Py_DECREF(checker);
  2334. return -1;
  2335. }
  2336. PyObject *res = PyObject_CallOneArg(checker, inst);
  2337. _Py_LeaveRecursiveCallTstate(tstate);
  2338. Py_DECREF(checker);
  2339. if (res == NULL) {
  2340. return -1;
  2341. }
  2342. int ok = PyObject_IsTrue(res);
  2343. Py_DECREF(res);
  2344. return ok;
  2345. }
  2346. else if (_PyErr_Occurred(tstate)) {
  2347. return -1;
  2348. }
  2349. /* cls has no __instancecheck__() method */
  2350. return object_isinstance(inst, cls);
  2351. }
  2352. int
  2353. PyObject_IsInstance(PyObject *inst, PyObject *cls)
  2354. {
  2355. PyThreadState *tstate = _PyThreadState_GET();
  2356. return object_recursive_isinstance(tstate, inst, cls);
  2357. }
  2358. static int
  2359. recursive_issubclass(PyObject *derived, PyObject *cls)
  2360. {
  2361. if (PyType_Check(cls) && PyType_Check(derived)) {
  2362. /* Fast path (non-recursive) */
  2363. return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls);
  2364. }
  2365. if (!check_class(derived,
  2366. "issubclass() arg 1 must be a class"))
  2367. return -1;
  2368. if (!_PyUnion_Check(cls) && !check_class(cls,
  2369. "issubclass() arg 2 must be a class,"
  2370. " a tuple of classes, or a union")) {
  2371. return -1;
  2372. }
  2373. return abstract_issubclass(derived, cls);
  2374. }
  2375. static int
  2376. object_issubclass(PyThreadState *tstate, PyObject *derived, PyObject *cls)
  2377. {
  2378. PyObject *checker;
  2379. /* We know what type's __subclasscheck__ does. */
  2380. if (PyType_CheckExact(cls)) {
  2381. /* Quick test for an exact match */
  2382. if (derived == cls)
  2383. return 1;
  2384. return recursive_issubclass(derived, cls);
  2385. }
  2386. if (_PyUnion_Check(cls)) {
  2387. cls = _Py_union_args(cls);
  2388. }
  2389. if (PyTuple_Check(cls)) {
  2390. if (_Py_EnterRecursiveCallTstate(tstate, " in __subclasscheck__")) {
  2391. return -1;
  2392. }
  2393. Py_ssize_t n = PyTuple_GET_SIZE(cls);
  2394. int r = 0;
  2395. for (Py_ssize_t i = 0; i < n; ++i) {
  2396. PyObject *item = PyTuple_GET_ITEM(cls, i);
  2397. r = object_issubclass(tstate, derived, item);
  2398. if (r != 0)
  2399. /* either found it, or got an error */
  2400. break;
  2401. }
  2402. _Py_LeaveRecursiveCallTstate(tstate);
  2403. return r;
  2404. }
  2405. checker = _PyObject_LookupSpecial(cls, &_Py_ID(__subclasscheck__));
  2406. if (checker != NULL) {
  2407. int ok = -1;
  2408. if (_Py_EnterRecursiveCallTstate(tstate, " in __subclasscheck__")) {
  2409. Py_DECREF(checker);
  2410. return ok;
  2411. }
  2412. PyObject *res = PyObject_CallOneArg(checker, derived);
  2413. _Py_LeaveRecursiveCallTstate(tstate);
  2414. Py_DECREF(checker);
  2415. if (res != NULL) {
  2416. ok = PyObject_IsTrue(res);
  2417. Py_DECREF(res);
  2418. }
  2419. return ok;
  2420. }
  2421. else if (_PyErr_Occurred(tstate)) {
  2422. return -1;
  2423. }
  2424. /* Probably never reached anymore. */
  2425. return recursive_issubclass(derived, cls);
  2426. }
  2427. int
  2428. PyObject_IsSubclass(PyObject *derived, PyObject *cls)
  2429. {
  2430. PyThreadState *tstate = _PyThreadState_GET();
  2431. return object_issubclass(tstate, derived, cls);
  2432. }
  2433. int
  2434. _PyObject_RealIsInstance(PyObject *inst, PyObject *cls)
  2435. {
  2436. return object_isinstance(inst, cls);
  2437. }
  2438. int
  2439. _PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)
  2440. {
  2441. return recursive_issubclass(derived, cls);
  2442. }
  2443. PyObject *
  2444. PyObject_GetIter(PyObject *o)
  2445. {
  2446. PyTypeObject *t = Py_TYPE(o);
  2447. getiterfunc f;
  2448. f = t->tp_iter;
  2449. if (f == NULL) {
  2450. if (PySequence_Check(o))
  2451. return PySeqIter_New(o);
  2452. return type_error("'%.200s' object is not iterable", o);
  2453. }
  2454. else {
  2455. PyObject *res = (*f)(o);
  2456. if (res != NULL && !PyIter_Check(res)) {
  2457. PyErr_Format(PyExc_TypeError,
  2458. "iter() returned non-iterator "
  2459. "of type '%.100s'",
  2460. Py_TYPE(res)->tp_name);
  2461. Py_SETREF(res, NULL);
  2462. }
  2463. return res;
  2464. }
  2465. }
  2466. PyObject *
  2467. PyObject_GetAIter(PyObject *o) {
  2468. PyTypeObject *t = Py_TYPE(o);
  2469. unaryfunc f;
  2470. if (t->tp_as_async == NULL || t->tp_as_async->am_aiter == NULL) {
  2471. return type_error("'%.200s' object is not an async iterable", o);
  2472. }
  2473. f = t->tp_as_async->am_aiter;
  2474. PyObject *it = (*f)(o);
  2475. if (it != NULL && !PyAIter_Check(it)) {
  2476. PyErr_Format(PyExc_TypeError,
  2477. "aiter() returned not an async iterator of type '%.100s'",
  2478. Py_TYPE(it)->tp_name);
  2479. Py_SETREF(it, NULL);
  2480. }
  2481. return it;
  2482. }
  2483. int
  2484. PyIter_Check(PyObject *obj)
  2485. {
  2486. PyTypeObject *tp = Py_TYPE(obj);
  2487. return (tp->tp_iternext != NULL &&
  2488. tp->tp_iternext != &_PyObject_NextNotImplemented);
  2489. }
  2490. int
  2491. PyAIter_Check(PyObject *obj)
  2492. {
  2493. PyTypeObject *tp = Py_TYPE(obj);
  2494. return (tp->tp_as_async != NULL &&
  2495. tp->tp_as_async->am_anext != NULL &&
  2496. tp->tp_as_async->am_anext != &_PyObject_NextNotImplemented);
  2497. }
  2498. /* Return next item.
  2499. * If an error occurs, return NULL. PyErr_Occurred() will be true.
  2500. * If the iteration terminates normally, return NULL and clear the
  2501. * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
  2502. * will be false.
  2503. * Else return the next object. PyErr_Occurred() will be false.
  2504. */
  2505. PyObject *
  2506. PyIter_Next(PyObject *iter)
  2507. {
  2508. PyObject *result;
  2509. result = (*Py_TYPE(iter)->tp_iternext)(iter);
  2510. if (result == NULL) {
  2511. PyThreadState *tstate = _PyThreadState_GET();
  2512. if (_PyErr_Occurred(tstate)
  2513. && _PyErr_ExceptionMatches(tstate, PyExc_StopIteration))
  2514. {
  2515. _PyErr_Clear(tstate);
  2516. }
  2517. }
  2518. return result;
  2519. }
  2520. PySendResult
  2521. PyIter_Send(PyObject *iter, PyObject *arg, PyObject **result)
  2522. {
  2523. assert(arg != NULL);
  2524. assert(result != NULL);
  2525. if (Py_TYPE(iter)->tp_as_async && Py_TYPE(iter)->tp_as_async->am_send) {
  2526. PySendResult res = Py_TYPE(iter)->tp_as_async->am_send(iter, arg, result);
  2527. assert(_Py_CheckSlotResult(iter, "am_send", res != PYGEN_ERROR));
  2528. return res;
  2529. }
  2530. if (arg == Py_None && PyIter_Check(iter)) {
  2531. *result = Py_TYPE(iter)->tp_iternext(iter);
  2532. }
  2533. else {
  2534. *result = PyObject_CallMethodOneArg(iter, &_Py_ID(send), arg);
  2535. }
  2536. if (*result != NULL) {
  2537. return PYGEN_NEXT;
  2538. }
  2539. if (_PyGen_FetchStopIterationValue(result) == 0) {
  2540. return PYGEN_RETURN;
  2541. }
  2542. return PYGEN_ERROR;
  2543. }
  2544. /*
  2545. * Flatten a sequence of bytes() objects into a C array of
  2546. * NULL terminated string pointers with a NULL char* terminating the array.
  2547. * (ie: an argv or env list)
  2548. *
  2549. * Memory allocated for the returned list is allocated using PyMem_Malloc()
  2550. * and MUST be freed by _Py_FreeCharPArray().
  2551. */
  2552. char *const *
  2553. _PySequence_BytesToCharpArray(PyObject* self)
  2554. {
  2555. char **array;
  2556. Py_ssize_t i, argc;
  2557. PyObject *item = NULL;
  2558. Py_ssize_t size;
  2559. argc = PySequence_Size(self);
  2560. if (argc == -1)
  2561. return NULL;
  2562. assert(argc >= 0);
  2563. if ((size_t)argc > (PY_SSIZE_T_MAX-sizeof(char *)) / sizeof(char *)) {
  2564. PyErr_NoMemory();
  2565. return NULL;
  2566. }
  2567. array = PyMem_Malloc((argc + 1) * sizeof(char *));
  2568. if (array == NULL) {
  2569. PyErr_NoMemory();
  2570. return NULL;
  2571. }
  2572. for (i = 0; i < argc; ++i) {
  2573. char *data;
  2574. item = PySequence_GetItem(self, i);
  2575. if (item == NULL) {
  2576. /* NULL terminate before freeing. */
  2577. array[i] = NULL;
  2578. goto fail;
  2579. }
  2580. /* check for embedded null bytes */
  2581. if (PyBytes_AsStringAndSize(item, &data, NULL) < 0) {
  2582. /* NULL terminate before freeing. */
  2583. array[i] = NULL;
  2584. goto fail;
  2585. }
  2586. size = PyBytes_GET_SIZE(item) + 1;
  2587. array[i] = PyMem_Malloc(size);
  2588. if (!array[i]) {
  2589. PyErr_NoMemory();
  2590. goto fail;
  2591. }
  2592. memcpy(array[i], data, size);
  2593. Py_DECREF(item);
  2594. }
  2595. array[argc] = NULL;
  2596. return array;
  2597. fail:
  2598. Py_XDECREF(item);
  2599. _Py_FreeCharPArray(array);
  2600. return NULL;
  2601. }
  2602. /* Free's a NULL terminated char** array of C strings. */
  2603. void
  2604. _Py_FreeCharPArray(char *const array[])
  2605. {
  2606. Py_ssize_t i;
  2607. for (i = 0; array[i] != NULL; ++i) {
  2608. PyMem_Free(array[i]);
  2609. }
  2610. PyMem_Free((void*)array);
  2611. }