bltinmodule.c 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157
  1. /* Built-in functions */
  2. #include "Python.h"
  3. #include <ctype.h>
  4. #include "pycore_ast.h" // _PyAST_Validate()
  5. #include "pycore_call.h" // _PyObject_CallNoArgs()
  6. #include "pycore_compile.h" // _PyAST_Compile()
  7. #include "pycore_long.h" // _PyLong_CompactValue
  8. #include "pycore_object.h" // _Py_AddToAllObjects()
  9. #include "pycore_pyerrors.h" // _PyErr_NoMemory()
  10. #include "pycore_pystate.h" // _PyThreadState_GET()
  11. #include "pycore_tuple.h" // _PyTuple_FromArray()
  12. #include "pycore_ceval.h" // _PyEval_Vector()
  13. #include "clinic/bltinmodule.c.h"
  14. static PyObject*
  15. update_bases(PyObject *bases, PyObject *const *args, Py_ssize_t nargs)
  16. {
  17. Py_ssize_t i, j;
  18. PyObject *base, *meth, *new_base, *result, *new_bases = NULL;
  19. assert(PyTuple_Check(bases));
  20. for (i = 0; i < nargs; i++) {
  21. base = args[i];
  22. if (PyType_Check(base)) {
  23. if (new_bases) {
  24. /* If we already have made a replacement, then we append every normal base,
  25. otherwise just skip it. */
  26. if (PyList_Append(new_bases, base) < 0) {
  27. goto error;
  28. }
  29. }
  30. continue;
  31. }
  32. if (_PyObject_LookupAttr(base, &_Py_ID(__mro_entries__), &meth) < 0) {
  33. goto error;
  34. }
  35. if (!meth) {
  36. if (new_bases) {
  37. if (PyList_Append(new_bases, base) < 0) {
  38. goto error;
  39. }
  40. }
  41. continue;
  42. }
  43. new_base = PyObject_CallOneArg(meth, bases);
  44. Py_DECREF(meth);
  45. if (!new_base) {
  46. goto error;
  47. }
  48. if (!PyTuple_Check(new_base)) {
  49. PyErr_SetString(PyExc_TypeError,
  50. "__mro_entries__ must return a tuple");
  51. Py_DECREF(new_base);
  52. goto error;
  53. }
  54. if (!new_bases) {
  55. /* If this is a first successful replacement, create new_bases list and
  56. copy previously encountered bases. */
  57. if (!(new_bases = PyList_New(i))) {
  58. Py_DECREF(new_base);
  59. goto error;
  60. }
  61. for (j = 0; j < i; j++) {
  62. base = args[j];
  63. PyList_SET_ITEM(new_bases, j, Py_NewRef(base));
  64. }
  65. }
  66. j = PyList_GET_SIZE(new_bases);
  67. if (PyList_SetSlice(new_bases, j, j, new_base) < 0) {
  68. Py_DECREF(new_base);
  69. goto error;
  70. }
  71. Py_DECREF(new_base);
  72. }
  73. if (!new_bases) {
  74. return bases;
  75. }
  76. result = PyList_AsTuple(new_bases);
  77. Py_DECREF(new_bases);
  78. return result;
  79. error:
  80. Py_XDECREF(new_bases);
  81. return NULL;
  82. }
  83. /* AC: cannot convert yet, waiting for *args support */
  84. static PyObject *
  85. builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
  86. PyObject *kwnames)
  87. {
  88. PyObject *func, *name, *winner, *prep;
  89. PyObject *cls = NULL, *cell = NULL, *ns = NULL, *meta = NULL, *orig_bases = NULL;
  90. PyObject *mkw = NULL, *bases = NULL;
  91. int isclass = 0; /* initialize to prevent gcc warning */
  92. if (nargs < 2) {
  93. PyErr_SetString(PyExc_TypeError,
  94. "__build_class__: not enough arguments");
  95. return NULL;
  96. }
  97. func = args[0]; /* Better be callable */
  98. if (!PyFunction_Check(func)) {
  99. PyErr_SetString(PyExc_TypeError,
  100. "__build_class__: func must be a function");
  101. return NULL;
  102. }
  103. name = args[1];
  104. if (!PyUnicode_Check(name)) {
  105. PyErr_SetString(PyExc_TypeError,
  106. "__build_class__: name is not a string");
  107. return NULL;
  108. }
  109. orig_bases = _PyTuple_FromArray(args + 2, nargs - 2);
  110. if (orig_bases == NULL)
  111. return NULL;
  112. bases = update_bases(orig_bases, args + 2, nargs - 2);
  113. if (bases == NULL) {
  114. Py_DECREF(orig_bases);
  115. return NULL;
  116. }
  117. if (kwnames == NULL) {
  118. meta = NULL;
  119. mkw = NULL;
  120. }
  121. else {
  122. mkw = _PyStack_AsDict(args + nargs, kwnames);
  123. if (mkw == NULL) {
  124. goto error;
  125. }
  126. meta = _PyDict_GetItemWithError(mkw, &_Py_ID(metaclass));
  127. if (meta != NULL) {
  128. Py_INCREF(meta);
  129. if (PyDict_DelItem(mkw, &_Py_ID(metaclass)) < 0) {
  130. goto error;
  131. }
  132. /* metaclass is explicitly given, check if it's indeed a class */
  133. isclass = PyType_Check(meta);
  134. }
  135. else if (PyErr_Occurred()) {
  136. goto error;
  137. }
  138. }
  139. if (meta == NULL) {
  140. /* if there are no bases, use type: */
  141. if (PyTuple_GET_SIZE(bases) == 0) {
  142. meta = (PyObject *) (&PyType_Type);
  143. }
  144. /* else get the type of the first base */
  145. else {
  146. PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
  147. meta = (PyObject *)Py_TYPE(base0);
  148. }
  149. Py_INCREF(meta);
  150. isclass = 1; /* meta is really a class */
  151. }
  152. if (isclass) {
  153. /* meta is really a class, so check for a more derived
  154. metaclass, or possible metaclass conflicts: */
  155. winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
  156. bases);
  157. if (winner == NULL) {
  158. goto error;
  159. }
  160. if (winner != meta) {
  161. Py_SETREF(meta, Py_NewRef(winner));
  162. }
  163. }
  164. /* else: meta is not a class, so we cannot do the metaclass
  165. calculation, so we will use the explicitly given object as it is */
  166. if (_PyObject_LookupAttr(meta, &_Py_ID(__prepare__), &prep) < 0) {
  167. ns = NULL;
  168. }
  169. else if (prep == NULL) {
  170. ns = PyDict_New();
  171. }
  172. else {
  173. PyObject *pargs[2] = {name, bases};
  174. ns = PyObject_VectorcallDict(prep, pargs, 2, mkw);
  175. Py_DECREF(prep);
  176. }
  177. if (ns == NULL) {
  178. goto error;
  179. }
  180. if (!PyMapping_Check(ns)) {
  181. PyErr_Format(PyExc_TypeError,
  182. "%.200s.__prepare__() must return a mapping, not %.200s",
  183. isclass ? ((PyTypeObject *)meta)->tp_name : "<metaclass>",
  184. Py_TYPE(ns)->tp_name);
  185. goto error;
  186. }
  187. PyThreadState *tstate = _PyThreadState_GET();
  188. EVAL_CALL_STAT_INC(EVAL_CALL_BUILD_CLASS);
  189. cell = _PyEval_Vector(tstate, (PyFunctionObject *)func, ns, NULL, 0, NULL);
  190. if (cell != NULL) {
  191. if (bases != orig_bases) {
  192. if (PyMapping_SetItemString(ns, "__orig_bases__", orig_bases) < 0) {
  193. goto error;
  194. }
  195. }
  196. PyObject *margs[3] = {name, bases, ns};
  197. cls = PyObject_VectorcallDict(meta, margs, 3, mkw);
  198. if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
  199. PyObject *cell_cls = PyCell_GET(cell);
  200. if (cell_cls != cls) {
  201. if (cell_cls == NULL) {
  202. const char *msg =
  203. "__class__ not set defining %.200R as %.200R. "
  204. "Was __classcell__ propagated to type.__new__?";
  205. PyErr_Format(PyExc_RuntimeError, msg, name, cls);
  206. } else {
  207. const char *msg =
  208. "__class__ set to %.200R defining %.200R as %.200R";
  209. PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
  210. }
  211. Py_SETREF(cls, NULL);
  212. goto error;
  213. }
  214. }
  215. }
  216. error:
  217. Py_XDECREF(cell);
  218. Py_XDECREF(ns);
  219. Py_XDECREF(meta);
  220. Py_XDECREF(mkw);
  221. if (bases != orig_bases) {
  222. Py_DECREF(orig_bases);
  223. }
  224. Py_DECREF(bases);
  225. return cls;
  226. }
  227. PyDoc_STRVAR(build_class_doc,
  228. "__build_class__(func, name, /, *bases, [metaclass], **kwds) -> class\n\
  229. \n\
  230. Internal helper function used by the class statement.");
  231. /*[clinic input]
  232. __import__ as builtin___import__
  233. name: object
  234. globals: object(c_default="NULL") = None
  235. locals: object(c_default="NULL") = None
  236. fromlist: object(c_default="NULL") = ()
  237. level: int = 0
  238. Import a module.
  239. Because this function is meant for use by the Python
  240. interpreter and not for general use, it is better to use
  241. importlib.import_module() to programmatically import a module.
  242. The globals argument is only used to determine the context;
  243. they are not modified. The locals argument is unused. The fromlist
  244. should be a list of names to emulate ``from name import ...``, or an
  245. empty list to emulate ``import name``.
  246. When importing a module from a package, note that __import__('A.B', ...)
  247. returns package A when fromlist is empty, but its submodule B when
  248. fromlist is not empty. The level argument is used to determine whether to
  249. perform absolute or relative imports: 0 is absolute, while a positive number
  250. is the number of parent directories to search relative to the current module.
  251. [clinic start generated code]*/
  252. static PyObject *
  253. builtin___import___impl(PyObject *module, PyObject *name, PyObject *globals,
  254. PyObject *locals, PyObject *fromlist, int level)
  255. /*[clinic end generated code: output=4febeda88a0cd245 input=73f4b960ea5b9dd6]*/
  256. {
  257. return PyImport_ImportModuleLevelObject(name, globals, locals,
  258. fromlist, level);
  259. }
  260. /*[clinic input]
  261. abs as builtin_abs
  262. x: object
  263. /
  264. Return the absolute value of the argument.
  265. [clinic start generated code]*/
  266. static PyObject *
  267. builtin_abs(PyObject *module, PyObject *x)
  268. /*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
  269. {
  270. return PyNumber_Absolute(x);
  271. }
  272. /*[clinic input]
  273. all as builtin_all
  274. iterable: object
  275. /
  276. Return True if bool(x) is True for all values x in the iterable.
  277. If the iterable is empty, return True.
  278. [clinic start generated code]*/
  279. static PyObject *
  280. builtin_all(PyObject *module, PyObject *iterable)
  281. /*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
  282. {
  283. PyObject *it, *item;
  284. PyObject *(*iternext)(PyObject *);
  285. int cmp;
  286. it = PyObject_GetIter(iterable);
  287. if (it == NULL)
  288. return NULL;
  289. iternext = *Py_TYPE(it)->tp_iternext;
  290. for (;;) {
  291. item = iternext(it);
  292. if (item == NULL)
  293. break;
  294. cmp = PyObject_IsTrue(item);
  295. Py_DECREF(item);
  296. if (cmp < 0) {
  297. Py_DECREF(it);
  298. return NULL;
  299. }
  300. if (cmp == 0) {
  301. Py_DECREF(it);
  302. Py_RETURN_FALSE;
  303. }
  304. }
  305. Py_DECREF(it);
  306. if (PyErr_Occurred()) {
  307. if (PyErr_ExceptionMatches(PyExc_StopIteration))
  308. PyErr_Clear();
  309. else
  310. return NULL;
  311. }
  312. Py_RETURN_TRUE;
  313. }
  314. /*[clinic input]
  315. any as builtin_any
  316. iterable: object
  317. /
  318. Return True if bool(x) is True for any x in the iterable.
  319. If the iterable is empty, return False.
  320. [clinic start generated code]*/
  321. static PyObject *
  322. builtin_any(PyObject *module, PyObject *iterable)
  323. /*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
  324. {
  325. PyObject *it, *item;
  326. PyObject *(*iternext)(PyObject *);
  327. int cmp;
  328. it = PyObject_GetIter(iterable);
  329. if (it == NULL)
  330. return NULL;
  331. iternext = *Py_TYPE(it)->tp_iternext;
  332. for (;;) {
  333. item = iternext(it);
  334. if (item == NULL)
  335. break;
  336. cmp = PyObject_IsTrue(item);
  337. Py_DECREF(item);
  338. if (cmp < 0) {
  339. Py_DECREF(it);
  340. return NULL;
  341. }
  342. if (cmp > 0) {
  343. Py_DECREF(it);
  344. Py_RETURN_TRUE;
  345. }
  346. }
  347. Py_DECREF(it);
  348. if (PyErr_Occurred()) {
  349. if (PyErr_ExceptionMatches(PyExc_StopIteration))
  350. PyErr_Clear();
  351. else
  352. return NULL;
  353. }
  354. Py_RETURN_FALSE;
  355. }
  356. /*[clinic input]
  357. ascii as builtin_ascii
  358. obj: object
  359. /
  360. Return an ASCII-only representation of an object.
  361. As repr(), return a string containing a printable representation of an
  362. object, but escape the non-ASCII characters in the string returned by
  363. repr() using \\x, \\u or \\U escapes. This generates a string similar
  364. to that returned by repr() in Python 2.
  365. [clinic start generated code]*/
  366. static PyObject *
  367. builtin_ascii(PyObject *module, PyObject *obj)
  368. /*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
  369. {
  370. return PyObject_ASCII(obj);
  371. }
  372. /*[clinic input]
  373. bin as builtin_bin
  374. number: object
  375. /
  376. Return the binary representation of an integer.
  377. >>> bin(2796202)
  378. '0b1010101010101010101010'
  379. [clinic start generated code]*/
  380. static PyObject *
  381. builtin_bin(PyObject *module, PyObject *number)
  382. /*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
  383. {
  384. return PyNumber_ToBase(number, 2);
  385. }
  386. /*[clinic input]
  387. callable as builtin_callable
  388. obj: object
  389. /
  390. Return whether the object is callable (i.e., some kind of function).
  391. Note that classes are callable, as are instances of classes with a
  392. __call__() method.
  393. [clinic start generated code]*/
  394. static PyObject *
  395. builtin_callable(PyObject *module, PyObject *obj)
  396. /*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
  397. {
  398. return PyBool_FromLong((long)PyCallable_Check(obj));
  399. }
  400. static PyObject *
  401. builtin_breakpoint(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
  402. {
  403. PyObject *hook = PySys_GetObject("breakpointhook");
  404. if (hook == NULL) {
  405. PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook");
  406. return NULL;
  407. }
  408. if (PySys_Audit("builtins.breakpoint", "O", hook) < 0) {
  409. return NULL;
  410. }
  411. Py_INCREF(hook);
  412. PyObject *retval = PyObject_Vectorcall(hook, args, nargs, keywords);
  413. Py_DECREF(hook);
  414. return retval;
  415. }
  416. PyDoc_STRVAR(breakpoint_doc,
  417. "breakpoint(*args, **kws)\n\
  418. \n\
  419. Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept\n\
  420. whatever arguments are passed.\n\
  421. \n\
  422. By default, this drops you into the pdb debugger.");
  423. typedef struct {
  424. PyObject_HEAD
  425. PyObject *func;
  426. PyObject *it;
  427. } filterobject;
  428. static PyObject *
  429. filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  430. {
  431. PyObject *func, *seq;
  432. PyObject *it;
  433. filterobject *lz;
  434. if ((type == &PyFilter_Type || type->tp_init == PyFilter_Type.tp_init) &&
  435. !_PyArg_NoKeywords("filter", kwds))
  436. return NULL;
  437. if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
  438. return NULL;
  439. /* Get iterator. */
  440. it = PyObject_GetIter(seq);
  441. if (it == NULL)
  442. return NULL;
  443. /* create filterobject structure */
  444. lz = (filterobject *)type->tp_alloc(type, 0);
  445. if (lz == NULL) {
  446. Py_DECREF(it);
  447. return NULL;
  448. }
  449. lz->func = Py_NewRef(func);
  450. lz->it = it;
  451. return (PyObject *)lz;
  452. }
  453. static PyObject *
  454. filter_vectorcall(PyObject *type, PyObject * const*args,
  455. size_t nargsf, PyObject *kwnames)
  456. {
  457. PyTypeObject *tp = _PyType_CAST(type);
  458. if (tp == &PyFilter_Type && !_PyArg_NoKwnames("filter", kwnames)) {
  459. return NULL;
  460. }
  461. Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
  462. if (!_PyArg_CheckPositional("filter", nargs, 2, 2)) {
  463. return NULL;
  464. }
  465. PyObject *it = PyObject_GetIter(args[1]);
  466. if (it == NULL) {
  467. return NULL;
  468. }
  469. filterobject *lz = (filterobject *)tp->tp_alloc(tp, 0);
  470. if (lz == NULL) {
  471. Py_DECREF(it);
  472. return NULL;
  473. }
  474. lz->func = Py_NewRef(args[0]);
  475. lz->it = it;
  476. return (PyObject *)lz;
  477. }
  478. static void
  479. filter_dealloc(filterobject *lz)
  480. {
  481. PyObject_GC_UnTrack(lz);
  482. Py_TRASHCAN_BEGIN(lz, filter_dealloc)
  483. Py_XDECREF(lz->func);
  484. Py_XDECREF(lz->it);
  485. Py_TYPE(lz)->tp_free(lz);
  486. Py_TRASHCAN_END
  487. }
  488. static int
  489. filter_traverse(filterobject *lz, visitproc visit, void *arg)
  490. {
  491. Py_VISIT(lz->it);
  492. Py_VISIT(lz->func);
  493. return 0;
  494. }
  495. static PyObject *
  496. filter_next(filterobject *lz)
  497. {
  498. PyObject *item;
  499. PyObject *it = lz->it;
  500. long ok;
  501. PyObject *(*iternext)(PyObject *);
  502. int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
  503. iternext = *Py_TYPE(it)->tp_iternext;
  504. for (;;) {
  505. item = iternext(it);
  506. if (item == NULL)
  507. return NULL;
  508. if (checktrue) {
  509. ok = PyObject_IsTrue(item);
  510. } else {
  511. PyObject *good;
  512. good = PyObject_CallOneArg(lz->func, item);
  513. if (good == NULL) {
  514. Py_DECREF(item);
  515. return NULL;
  516. }
  517. ok = PyObject_IsTrue(good);
  518. Py_DECREF(good);
  519. }
  520. if (ok > 0)
  521. return item;
  522. Py_DECREF(item);
  523. if (ok < 0)
  524. return NULL;
  525. }
  526. }
  527. static PyObject *
  528. filter_reduce(filterobject *lz, PyObject *Py_UNUSED(ignored))
  529. {
  530. return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
  531. }
  532. PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
  533. static PyMethodDef filter_methods[] = {
  534. {"__reduce__", _PyCFunction_CAST(filter_reduce), METH_NOARGS, reduce_doc},
  535. {NULL, NULL} /* sentinel */
  536. };
  537. PyDoc_STRVAR(filter_doc,
  538. "filter(function or None, iterable) --> filter object\n\
  539. \n\
  540. Return an iterator yielding those items of iterable for which function(item)\n\
  541. is true. If function is None, return the items that are true.");
  542. PyTypeObject PyFilter_Type = {
  543. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  544. "filter", /* tp_name */
  545. sizeof(filterobject), /* tp_basicsize */
  546. 0, /* tp_itemsize */
  547. /* methods */
  548. (destructor)filter_dealloc, /* tp_dealloc */
  549. 0, /* tp_vectorcall_offset */
  550. 0, /* tp_getattr */
  551. 0, /* tp_setattr */
  552. 0, /* tp_as_async */
  553. 0, /* tp_repr */
  554. 0, /* tp_as_number */
  555. 0, /* tp_as_sequence */
  556. 0, /* tp_as_mapping */
  557. 0, /* tp_hash */
  558. 0, /* tp_call */
  559. 0, /* tp_str */
  560. PyObject_GenericGetAttr, /* tp_getattro */
  561. 0, /* tp_setattro */
  562. 0, /* tp_as_buffer */
  563. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  564. Py_TPFLAGS_BASETYPE, /* tp_flags */
  565. filter_doc, /* tp_doc */
  566. (traverseproc)filter_traverse, /* tp_traverse */
  567. 0, /* tp_clear */
  568. 0, /* tp_richcompare */
  569. 0, /* tp_weaklistoffset */
  570. PyObject_SelfIter, /* tp_iter */
  571. (iternextfunc)filter_next, /* tp_iternext */
  572. filter_methods, /* tp_methods */
  573. 0, /* tp_members */
  574. 0, /* tp_getset */
  575. 0, /* tp_base */
  576. 0, /* tp_dict */
  577. 0, /* tp_descr_get */
  578. 0, /* tp_descr_set */
  579. 0, /* tp_dictoffset */
  580. 0, /* tp_init */
  581. PyType_GenericAlloc, /* tp_alloc */
  582. filter_new, /* tp_new */
  583. PyObject_GC_Del, /* tp_free */
  584. .tp_vectorcall = (vectorcallfunc)filter_vectorcall
  585. };
  586. /*[clinic input]
  587. format as builtin_format
  588. value: object
  589. format_spec: unicode(c_default="NULL") = ''
  590. /
  591. Return type(value).__format__(value, format_spec)
  592. Many built-in types implement format_spec according to the
  593. Format Specification Mini-language. See help('FORMATTING').
  594. If type(value) does not supply a method named __format__
  595. and format_spec is empty, then str(value) is returned.
  596. See also help('SPECIALMETHODS').
  597. [clinic start generated code]*/
  598. static PyObject *
  599. builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
  600. /*[clinic end generated code: output=2f40bdfa4954b077 input=45ef3934b86d5624]*/
  601. {
  602. return PyObject_Format(value, format_spec);
  603. }
  604. /*[clinic input]
  605. chr as builtin_chr
  606. i: int
  607. /
  608. Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
  609. [clinic start generated code]*/
  610. static PyObject *
  611. builtin_chr_impl(PyObject *module, int i)
  612. /*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
  613. {
  614. return PyUnicode_FromOrdinal(i);
  615. }
  616. /*[clinic input]
  617. compile as builtin_compile
  618. source: object
  619. filename: object(converter="PyUnicode_FSDecoder")
  620. mode: str
  621. flags: int = 0
  622. dont_inherit: bool = False
  623. optimize: int = -1
  624. *
  625. _feature_version as feature_version: int = -1
  626. Compile source into a code object that can be executed by exec() or eval().
  627. The source code may represent a Python module, statement or expression.
  628. The filename will be used for run-time error messages.
  629. The mode must be 'exec' to compile a module, 'single' to compile a
  630. single (interactive) statement, or 'eval' to compile an expression.
  631. The flags argument, if present, controls which future statements influence
  632. the compilation of the code.
  633. The dont_inherit argument, if true, stops the compilation inheriting
  634. the effects of any future statements in effect in the code calling
  635. compile; if absent or false these statements do influence the compilation,
  636. in addition to any features explicitly specified.
  637. [clinic start generated code]*/
  638. static PyObject *
  639. builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
  640. const char *mode, int flags, int dont_inherit,
  641. int optimize, int feature_version)
  642. /*[clinic end generated code: output=b0c09c84f116d3d7 input=cc78e20e7c7682ba]*/
  643. {
  644. PyObject *source_copy;
  645. const char *str;
  646. int compile_mode = -1;
  647. int is_ast;
  648. int start[] = {Py_file_input, Py_eval_input, Py_single_input, Py_func_type_input};
  649. PyObject *result;
  650. PyCompilerFlags cf = _PyCompilerFlags_INIT;
  651. cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
  652. if (feature_version >= 0 && (flags & PyCF_ONLY_AST)) {
  653. cf.cf_feature_version = feature_version;
  654. }
  655. if (flags &
  656. ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_COMPILE_MASK))
  657. {
  658. PyErr_SetString(PyExc_ValueError,
  659. "compile(): unrecognised flags");
  660. goto error;
  661. }
  662. /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
  663. if (optimize < -1 || optimize > 2) {
  664. PyErr_SetString(PyExc_ValueError,
  665. "compile(): invalid optimize value");
  666. goto error;
  667. }
  668. if (!dont_inherit) {
  669. PyEval_MergeCompilerFlags(&cf);
  670. }
  671. if (strcmp(mode, "exec") == 0)
  672. compile_mode = 0;
  673. else if (strcmp(mode, "eval") == 0)
  674. compile_mode = 1;
  675. else if (strcmp(mode, "single") == 0)
  676. compile_mode = 2;
  677. else if (strcmp(mode, "func_type") == 0) {
  678. if (!(flags & PyCF_ONLY_AST)) {
  679. PyErr_SetString(PyExc_ValueError,
  680. "compile() mode 'func_type' requires flag PyCF_ONLY_AST");
  681. goto error;
  682. }
  683. compile_mode = 3;
  684. }
  685. else {
  686. const char *msg;
  687. if (flags & PyCF_ONLY_AST)
  688. msg = "compile() mode must be 'exec', 'eval', 'single' or 'func_type'";
  689. else
  690. msg = "compile() mode must be 'exec', 'eval' or 'single'";
  691. PyErr_SetString(PyExc_ValueError, msg);
  692. goto error;
  693. }
  694. is_ast = PyAST_Check(source);
  695. if (is_ast == -1)
  696. goto error;
  697. if (is_ast) {
  698. if (flags & PyCF_ONLY_AST) {
  699. result = Py_NewRef(source);
  700. }
  701. else {
  702. PyArena *arena;
  703. mod_ty mod;
  704. arena = _PyArena_New();
  705. if (arena == NULL)
  706. goto error;
  707. mod = PyAST_obj2mod(source, arena, compile_mode);
  708. if (mod == NULL || !_PyAST_Validate(mod)) {
  709. _PyArena_Free(arena);
  710. goto error;
  711. }
  712. result = (PyObject*)_PyAST_Compile(mod, filename,
  713. &cf, optimize, arena);
  714. _PyArena_Free(arena);
  715. }
  716. goto finally;
  717. }
  718. str = _Py_SourceAsString(source, "compile", "string, bytes or AST", &cf, &source_copy);
  719. if (str == NULL)
  720. goto error;
  721. result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
  722. Py_XDECREF(source_copy);
  723. goto finally;
  724. error:
  725. result = NULL;
  726. finally:
  727. Py_DECREF(filename);
  728. return result;
  729. }
  730. /*[clinic input]
  731. dir as builtin_dir
  732. arg: object = NULL
  733. /
  734. Show attributes of an object.
  735. If called without an argument, return the names in the current scope.
  736. Else, return an alphabetized list of names comprising (some of) the attributes
  737. of the given object, and of attributes reachable from it.
  738. If the object supplies a method named __dir__, it will be used; otherwise
  739. the default dir() logic is used and returns:
  740. for a module object: the module's attributes.
  741. for a class object: its attributes, and recursively the attributes
  742. of its bases.
  743. for any other object: its attributes, its class's attributes, and
  744. recursively the attributes of its class's base classes.
  745. [clinic start generated code]*/
  746. static PyObject *
  747. builtin_dir_impl(PyObject *module, PyObject *arg)
  748. /*[clinic end generated code: output=24f2c7a52c1e3b08 input=ed6d6ccb13d52251]*/
  749. {
  750. return PyObject_Dir(arg);
  751. }
  752. /*[clinic input]
  753. divmod as builtin_divmod
  754. x: object
  755. y: object
  756. /
  757. Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
  758. [clinic start generated code]*/
  759. static PyObject *
  760. builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
  761. /*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
  762. {
  763. return PyNumber_Divmod(x, y);
  764. }
  765. /*[clinic input]
  766. eval as builtin_eval
  767. source: object
  768. globals: object = None
  769. locals: object = None
  770. /
  771. Evaluate the given source in the context of globals and locals.
  772. The source may be a string representing a Python expression
  773. or a code object as returned by compile().
  774. The globals must be a dictionary and locals can be any mapping,
  775. defaulting to the current globals and locals.
  776. If only globals is given, locals defaults to it.
  777. [clinic start generated code]*/
  778. static PyObject *
  779. builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
  780. PyObject *locals)
  781. /*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
  782. {
  783. PyObject *result = NULL, *source_copy;
  784. const char *str;
  785. if (locals != Py_None && !PyMapping_Check(locals)) {
  786. PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
  787. return NULL;
  788. }
  789. if (globals != Py_None && !PyDict_Check(globals)) {
  790. PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
  791. "globals must be a real dict; try eval(expr, {}, mapping)"
  792. : "globals must be a dict");
  793. return NULL;
  794. }
  795. if (globals == Py_None) {
  796. globals = PyEval_GetGlobals();
  797. if (locals == Py_None) {
  798. locals = _PyEval_GetFrameLocals();
  799. if (locals == NULL)
  800. return NULL;
  801. }
  802. else {
  803. Py_INCREF(locals);
  804. }
  805. }
  806. else if (locals == Py_None)
  807. locals = Py_NewRef(globals);
  808. else {
  809. Py_INCREF(locals);
  810. }
  811. if (globals == NULL || locals == NULL) {
  812. PyErr_SetString(PyExc_TypeError,
  813. "eval must be given globals and locals "
  814. "when called without a frame");
  815. goto error;
  816. }
  817. int r = PyDict_Contains(globals, &_Py_ID(__builtins__));
  818. if (r == 0) {
  819. r = PyDict_SetItem(globals, &_Py_ID(__builtins__), PyEval_GetBuiltins());
  820. }
  821. if (r < 0) {
  822. goto error;
  823. }
  824. if (PyCode_Check(source)) {
  825. if (PySys_Audit("exec", "O", source) < 0) {
  826. goto error;
  827. }
  828. if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
  829. PyErr_SetString(PyExc_TypeError,
  830. "code object passed to eval() may not contain free variables");
  831. goto error;
  832. }
  833. result = PyEval_EvalCode(source, globals, locals);
  834. }
  835. else {
  836. PyCompilerFlags cf = _PyCompilerFlags_INIT;
  837. cf.cf_flags = PyCF_SOURCE_IS_UTF8;
  838. str = _Py_SourceAsString(source, "eval", "string, bytes or code", &cf, &source_copy);
  839. if (str == NULL)
  840. goto error;
  841. while (*str == ' ' || *str == '\t')
  842. str++;
  843. (void)PyEval_MergeCompilerFlags(&cf);
  844. result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
  845. Py_XDECREF(source_copy);
  846. }
  847. error:
  848. Py_XDECREF(locals);
  849. return result;
  850. }
  851. /*[clinic input]
  852. exec as builtin_exec
  853. source: object
  854. globals: object = None
  855. locals: object = None
  856. /
  857. *
  858. closure: object(c_default="NULL") = None
  859. Execute the given source in the context of globals and locals.
  860. The source may be a string representing one or more Python statements
  861. or a code object as returned by compile().
  862. The globals must be a dictionary and locals can be any mapping,
  863. defaulting to the current globals and locals.
  864. If only globals is given, locals defaults to it.
  865. The closure must be a tuple of cellvars, and can only be used
  866. when source is a code object requiring exactly that many cellvars.
  867. [clinic start generated code]*/
  868. static PyObject *
  869. builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
  870. PyObject *locals, PyObject *closure)
  871. /*[clinic end generated code: output=7579eb4e7646743d input=f13a7e2b503d1d9a]*/
  872. {
  873. PyObject *v;
  874. if (globals == Py_None) {
  875. globals = PyEval_GetGlobals();
  876. if (locals == Py_None) {
  877. locals = _PyEval_GetFrameLocals();
  878. if (locals == NULL)
  879. return NULL;
  880. }
  881. else {
  882. Py_INCREF(locals);
  883. }
  884. if (!globals || !locals) {
  885. PyErr_SetString(PyExc_SystemError,
  886. "globals and locals cannot be NULL");
  887. return NULL;
  888. }
  889. }
  890. else if (locals == Py_None) {
  891. locals = Py_NewRef(globals);
  892. }
  893. else {
  894. Py_INCREF(locals);
  895. }
  896. if (!PyDict_Check(globals)) {
  897. PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
  898. Py_TYPE(globals)->tp_name);
  899. goto error;
  900. }
  901. if (!PyMapping_Check(locals)) {
  902. PyErr_Format(PyExc_TypeError,
  903. "locals must be a mapping or None, not %.100s",
  904. Py_TYPE(locals)->tp_name);
  905. goto error;
  906. }
  907. int r = PyDict_Contains(globals, &_Py_ID(__builtins__));
  908. if (r == 0) {
  909. r = PyDict_SetItem(globals, &_Py_ID(__builtins__), PyEval_GetBuiltins());
  910. }
  911. if (r < 0) {
  912. goto error;
  913. }
  914. if (closure == Py_None) {
  915. closure = NULL;
  916. }
  917. if (PyCode_Check(source)) {
  918. Py_ssize_t num_free = PyCode_GetNumFree((PyCodeObject *)source);
  919. if (num_free == 0) {
  920. if (closure) {
  921. PyErr_SetString(PyExc_TypeError,
  922. "cannot use a closure with this code object");
  923. goto error;
  924. }
  925. } else {
  926. int closure_is_ok =
  927. closure
  928. && PyTuple_CheckExact(closure)
  929. && (PyTuple_GET_SIZE(closure) == num_free);
  930. if (closure_is_ok) {
  931. for (Py_ssize_t i = 0; i < num_free; i++) {
  932. PyObject *cell = PyTuple_GET_ITEM(closure, i);
  933. if (!PyCell_Check(cell)) {
  934. closure_is_ok = 0;
  935. break;
  936. }
  937. }
  938. }
  939. if (!closure_is_ok) {
  940. PyErr_Format(PyExc_TypeError,
  941. "code object requires a closure of exactly length %zd",
  942. num_free);
  943. goto error;
  944. }
  945. }
  946. if (PySys_Audit("exec", "O", source) < 0) {
  947. goto error;
  948. }
  949. if (!closure) {
  950. v = PyEval_EvalCode(source, globals, locals);
  951. } else {
  952. v = PyEval_EvalCodeEx(source, globals, locals,
  953. NULL, 0,
  954. NULL, 0,
  955. NULL, 0,
  956. NULL,
  957. closure);
  958. }
  959. }
  960. else {
  961. if (closure != NULL) {
  962. PyErr_SetString(PyExc_TypeError,
  963. "closure can only be used when source is a code object");
  964. }
  965. PyObject *source_copy;
  966. const char *str;
  967. PyCompilerFlags cf = _PyCompilerFlags_INIT;
  968. cf.cf_flags = PyCF_SOURCE_IS_UTF8;
  969. str = _Py_SourceAsString(source, "exec",
  970. "string, bytes or code", &cf,
  971. &source_copy);
  972. if (str == NULL)
  973. goto error;
  974. if (PyEval_MergeCompilerFlags(&cf))
  975. v = PyRun_StringFlags(str, Py_file_input, globals,
  976. locals, &cf);
  977. else
  978. v = PyRun_String(str, Py_file_input, globals, locals);
  979. Py_XDECREF(source_copy);
  980. }
  981. if (v == NULL)
  982. goto error;
  983. Py_DECREF(locals);
  984. Py_DECREF(v);
  985. Py_RETURN_NONE;
  986. error:
  987. Py_XDECREF(locals);
  988. return NULL;
  989. }
  990. /*[clinic input]
  991. getattr as builtin_getattr
  992. object: object
  993. name: object
  994. default: object = NULL
  995. /
  996. Get a named attribute from an object.
  997. getattr(x, 'y') is equivalent to x.y
  998. When a default argument is given, it is returned when the attribute doesn't
  999. exist; without it, an exception is raised in that case.
  1000. [clinic start generated code]*/
  1001. static PyObject *
  1002. builtin_getattr_impl(PyObject *module, PyObject *object, PyObject *name,
  1003. PyObject *default_value)
  1004. /*[clinic end generated code: output=74ad0e225e3f701c input=d7562cd4c3556171]*/
  1005. {
  1006. PyObject *result;
  1007. if (default_value != NULL) {
  1008. if (_PyObject_LookupAttr(object, name, &result) == 0) {
  1009. return Py_NewRef(default_value);
  1010. }
  1011. }
  1012. else {
  1013. result = PyObject_GetAttr(object, name);
  1014. }
  1015. return result;
  1016. }
  1017. /*[clinic input]
  1018. globals as builtin_globals
  1019. Return the dictionary containing the current scope's global variables.
  1020. NOTE: Updates to this dictionary *will* affect name lookups in the current
  1021. global scope and vice-versa.
  1022. [clinic start generated code]*/
  1023. static PyObject *
  1024. builtin_globals_impl(PyObject *module)
  1025. /*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
  1026. {
  1027. PyObject *d;
  1028. d = PyEval_GetGlobals();
  1029. return Py_XNewRef(d);
  1030. }
  1031. /*[clinic input]
  1032. hasattr as builtin_hasattr
  1033. obj: object
  1034. name: object
  1035. /
  1036. Return whether the object has an attribute with the given name.
  1037. This is done by calling getattr(obj, name) and catching AttributeError.
  1038. [clinic start generated code]*/
  1039. static PyObject *
  1040. builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
  1041. /*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
  1042. {
  1043. PyObject *v;
  1044. if (_PyObject_LookupAttr(obj, name, &v) < 0) {
  1045. return NULL;
  1046. }
  1047. if (v == NULL) {
  1048. Py_RETURN_FALSE;
  1049. }
  1050. Py_DECREF(v);
  1051. Py_RETURN_TRUE;
  1052. }
  1053. /* AC: gdb's integration with CPython relies on builtin_id having
  1054. * the *exact* parameter names of "self" and "v", so we ensure we
  1055. * preserve those name rather than using the AC defaults.
  1056. */
  1057. /*[clinic input]
  1058. id as builtin_id
  1059. self: self(type="PyModuleDef *")
  1060. obj as v: object
  1061. /
  1062. Return the identity of an object.
  1063. This is guaranteed to be unique among simultaneously existing objects.
  1064. (CPython uses the object's memory address.)
  1065. [clinic start generated code]*/
  1066. static PyObject *
  1067. builtin_id(PyModuleDef *self, PyObject *v)
  1068. /*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
  1069. {
  1070. PyObject *id = PyLong_FromVoidPtr(v);
  1071. if (id && PySys_Audit("builtins.id", "O", id) < 0) {
  1072. Py_DECREF(id);
  1073. return NULL;
  1074. }
  1075. return id;
  1076. }
  1077. /* map object ************************************************************/
  1078. typedef struct {
  1079. PyObject_HEAD
  1080. PyObject *iters;
  1081. PyObject *func;
  1082. } mapobject;
  1083. static PyObject *
  1084. map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  1085. {
  1086. PyObject *it, *iters, *func;
  1087. mapobject *lz;
  1088. Py_ssize_t numargs, i;
  1089. if ((type == &PyMap_Type || type->tp_init == PyMap_Type.tp_init) &&
  1090. !_PyArg_NoKeywords("map", kwds))
  1091. return NULL;
  1092. numargs = PyTuple_Size(args);
  1093. if (numargs < 2) {
  1094. PyErr_SetString(PyExc_TypeError,
  1095. "map() must have at least two arguments.");
  1096. return NULL;
  1097. }
  1098. iters = PyTuple_New(numargs-1);
  1099. if (iters == NULL)
  1100. return NULL;
  1101. for (i=1 ; i<numargs ; i++) {
  1102. /* Get iterator. */
  1103. it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
  1104. if (it == NULL) {
  1105. Py_DECREF(iters);
  1106. return NULL;
  1107. }
  1108. PyTuple_SET_ITEM(iters, i-1, it);
  1109. }
  1110. /* create mapobject structure */
  1111. lz = (mapobject *)type->tp_alloc(type, 0);
  1112. if (lz == NULL) {
  1113. Py_DECREF(iters);
  1114. return NULL;
  1115. }
  1116. lz->iters = iters;
  1117. func = PyTuple_GET_ITEM(args, 0);
  1118. lz->func = Py_NewRef(func);
  1119. return (PyObject *)lz;
  1120. }
  1121. static PyObject *
  1122. map_vectorcall(PyObject *type, PyObject * const*args,
  1123. size_t nargsf, PyObject *kwnames)
  1124. {
  1125. PyTypeObject *tp = _PyType_CAST(type);
  1126. if (tp == &PyMap_Type && !_PyArg_NoKwnames("map", kwnames)) {
  1127. return NULL;
  1128. }
  1129. Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
  1130. if (nargs < 2) {
  1131. PyErr_SetString(PyExc_TypeError,
  1132. "map() must have at least two arguments.");
  1133. return NULL;
  1134. }
  1135. PyObject *iters = PyTuple_New(nargs-1);
  1136. if (iters == NULL) {
  1137. return NULL;
  1138. }
  1139. for (int i=1; i<nargs; i++) {
  1140. PyObject *it = PyObject_GetIter(args[i]);
  1141. if (it == NULL) {
  1142. Py_DECREF(iters);
  1143. return NULL;
  1144. }
  1145. PyTuple_SET_ITEM(iters, i-1, it);
  1146. }
  1147. mapobject *lz = (mapobject *)tp->tp_alloc(tp, 0);
  1148. if (lz == NULL) {
  1149. Py_DECREF(iters);
  1150. return NULL;
  1151. }
  1152. lz->iters = iters;
  1153. lz->func = Py_NewRef(args[0]);
  1154. return (PyObject *)lz;
  1155. }
  1156. static void
  1157. map_dealloc(mapobject *lz)
  1158. {
  1159. PyObject_GC_UnTrack(lz);
  1160. Py_XDECREF(lz->iters);
  1161. Py_XDECREF(lz->func);
  1162. Py_TYPE(lz)->tp_free(lz);
  1163. }
  1164. static int
  1165. map_traverse(mapobject *lz, visitproc visit, void *arg)
  1166. {
  1167. Py_VISIT(lz->iters);
  1168. Py_VISIT(lz->func);
  1169. return 0;
  1170. }
  1171. static PyObject *
  1172. map_next(mapobject *lz)
  1173. {
  1174. PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
  1175. PyObject **stack;
  1176. PyObject *result = NULL;
  1177. PyThreadState *tstate = _PyThreadState_GET();
  1178. const Py_ssize_t niters = PyTuple_GET_SIZE(lz->iters);
  1179. if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
  1180. stack = small_stack;
  1181. }
  1182. else {
  1183. stack = PyMem_Malloc(niters * sizeof(stack[0]));
  1184. if (stack == NULL) {
  1185. _PyErr_NoMemory(tstate);
  1186. return NULL;
  1187. }
  1188. }
  1189. Py_ssize_t nargs = 0;
  1190. for (Py_ssize_t i=0; i < niters; i++) {
  1191. PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
  1192. PyObject *val = Py_TYPE(it)->tp_iternext(it);
  1193. if (val == NULL) {
  1194. goto exit;
  1195. }
  1196. stack[i] = val;
  1197. nargs++;
  1198. }
  1199. result = _PyObject_VectorcallTstate(tstate, lz->func, stack, nargs, NULL);
  1200. exit:
  1201. for (Py_ssize_t i=0; i < nargs; i++) {
  1202. Py_DECREF(stack[i]);
  1203. }
  1204. if (stack != small_stack) {
  1205. PyMem_Free(stack);
  1206. }
  1207. return result;
  1208. }
  1209. static PyObject *
  1210. map_reduce(mapobject *lz, PyObject *Py_UNUSED(ignored))
  1211. {
  1212. Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
  1213. PyObject *args = PyTuple_New(numargs+1);
  1214. Py_ssize_t i;
  1215. if (args == NULL)
  1216. return NULL;
  1217. PyTuple_SET_ITEM(args, 0, Py_NewRef(lz->func));
  1218. for (i = 0; i<numargs; i++){
  1219. PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
  1220. PyTuple_SET_ITEM(args, i+1, Py_NewRef(it));
  1221. }
  1222. return Py_BuildValue("ON", Py_TYPE(lz), args);
  1223. }
  1224. static PyMethodDef map_methods[] = {
  1225. {"__reduce__", _PyCFunction_CAST(map_reduce), METH_NOARGS, reduce_doc},
  1226. {NULL, NULL} /* sentinel */
  1227. };
  1228. PyDoc_STRVAR(map_doc,
  1229. "map(func, *iterables) --> map object\n\
  1230. \n\
  1231. Make an iterator that computes the function using arguments from\n\
  1232. each of the iterables. Stops when the shortest iterable is exhausted.");
  1233. PyTypeObject PyMap_Type = {
  1234. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1235. "map", /* tp_name */
  1236. sizeof(mapobject), /* tp_basicsize */
  1237. 0, /* tp_itemsize */
  1238. /* methods */
  1239. (destructor)map_dealloc, /* tp_dealloc */
  1240. 0, /* tp_vectorcall_offset */
  1241. 0, /* tp_getattr */
  1242. 0, /* tp_setattr */
  1243. 0, /* tp_as_async */
  1244. 0, /* tp_repr */
  1245. 0, /* tp_as_number */
  1246. 0, /* tp_as_sequence */
  1247. 0, /* tp_as_mapping */
  1248. 0, /* tp_hash */
  1249. 0, /* tp_call */
  1250. 0, /* tp_str */
  1251. PyObject_GenericGetAttr, /* tp_getattro */
  1252. 0, /* tp_setattro */
  1253. 0, /* tp_as_buffer */
  1254. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  1255. Py_TPFLAGS_BASETYPE, /* tp_flags */
  1256. map_doc, /* tp_doc */
  1257. (traverseproc)map_traverse, /* tp_traverse */
  1258. 0, /* tp_clear */
  1259. 0, /* tp_richcompare */
  1260. 0, /* tp_weaklistoffset */
  1261. PyObject_SelfIter, /* tp_iter */
  1262. (iternextfunc)map_next, /* tp_iternext */
  1263. map_methods, /* tp_methods */
  1264. 0, /* tp_members */
  1265. 0, /* tp_getset */
  1266. 0, /* tp_base */
  1267. 0, /* tp_dict */
  1268. 0, /* tp_descr_get */
  1269. 0, /* tp_descr_set */
  1270. 0, /* tp_dictoffset */
  1271. 0, /* tp_init */
  1272. PyType_GenericAlloc, /* tp_alloc */
  1273. map_new, /* tp_new */
  1274. PyObject_GC_Del, /* tp_free */
  1275. .tp_vectorcall = (vectorcallfunc)map_vectorcall
  1276. };
  1277. /*[clinic input]
  1278. next as builtin_next
  1279. iterator: object
  1280. default: object = NULL
  1281. /
  1282. Return the next item from the iterator.
  1283. If default is given and the iterator is exhausted,
  1284. it is returned instead of raising StopIteration.
  1285. [clinic start generated code]*/
  1286. static PyObject *
  1287. builtin_next_impl(PyObject *module, PyObject *iterator,
  1288. PyObject *default_value)
  1289. /*[clinic end generated code: output=a38a94eeb447fef9 input=180f9984f182020f]*/
  1290. {
  1291. PyObject *res;
  1292. if (!PyIter_Check(iterator)) {
  1293. PyErr_Format(PyExc_TypeError,
  1294. "'%.200s' object is not an iterator",
  1295. Py_TYPE(iterator)->tp_name);
  1296. return NULL;
  1297. }
  1298. res = (*Py_TYPE(iterator)->tp_iternext)(iterator);
  1299. if (res != NULL) {
  1300. return res;
  1301. } else if (default_value != NULL) {
  1302. if (PyErr_Occurred()) {
  1303. if(!PyErr_ExceptionMatches(PyExc_StopIteration))
  1304. return NULL;
  1305. PyErr_Clear();
  1306. }
  1307. return Py_NewRef(default_value);
  1308. } else if (PyErr_Occurred()) {
  1309. return NULL;
  1310. } else {
  1311. PyErr_SetNone(PyExc_StopIteration);
  1312. return NULL;
  1313. }
  1314. }
  1315. /*[clinic input]
  1316. setattr as builtin_setattr
  1317. obj: object
  1318. name: object
  1319. value: object
  1320. /
  1321. Sets the named attribute on the given object to the specified value.
  1322. setattr(x, 'y', v) is equivalent to ``x.y = v``
  1323. [clinic start generated code]*/
  1324. static PyObject *
  1325. builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
  1326. PyObject *value)
  1327. /*[clinic end generated code: output=dc2ce1d1add9acb4 input=5e26417f2e8598d4]*/
  1328. {
  1329. if (PyObject_SetAttr(obj, name, value) != 0)
  1330. return NULL;
  1331. Py_RETURN_NONE;
  1332. }
  1333. /*[clinic input]
  1334. delattr as builtin_delattr
  1335. obj: object
  1336. name: object
  1337. /
  1338. Deletes the named attribute from the given object.
  1339. delattr(x, 'y') is equivalent to ``del x.y``
  1340. [clinic start generated code]*/
  1341. static PyObject *
  1342. builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
  1343. /*[clinic end generated code: output=85134bc58dff79fa input=164865623abe7216]*/
  1344. {
  1345. if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
  1346. return NULL;
  1347. Py_RETURN_NONE;
  1348. }
  1349. /*[clinic input]
  1350. hash as builtin_hash
  1351. obj: object
  1352. /
  1353. Return the hash value for the given object.
  1354. Two objects that compare equal must also have the same hash value, but the
  1355. reverse is not necessarily true.
  1356. [clinic start generated code]*/
  1357. static PyObject *
  1358. builtin_hash(PyObject *module, PyObject *obj)
  1359. /*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
  1360. {
  1361. Py_hash_t x;
  1362. x = PyObject_Hash(obj);
  1363. if (x == -1)
  1364. return NULL;
  1365. return PyLong_FromSsize_t(x);
  1366. }
  1367. /*[clinic input]
  1368. hex as builtin_hex
  1369. number: object
  1370. /
  1371. Return the hexadecimal representation of an integer.
  1372. >>> hex(12648430)
  1373. '0xc0ffee'
  1374. [clinic start generated code]*/
  1375. static PyObject *
  1376. builtin_hex(PyObject *module, PyObject *number)
  1377. /*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
  1378. {
  1379. return PyNumber_ToBase(number, 16);
  1380. }
  1381. /*[clinic input]
  1382. iter as builtin_iter
  1383. object: object
  1384. sentinel: object = NULL
  1385. /
  1386. Get an iterator from an object.
  1387. In the first form, the argument must supply its own iterator, or be a sequence.
  1388. In the second form, the callable is called until it returns the sentinel.
  1389. [clinic start generated code]*/
  1390. static PyObject *
  1391. builtin_iter_impl(PyObject *module, PyObject *object, PyObject *sentinel)
  1392. /*[clinic end generated code: output=12cf64203c195a94 input=a5d64d9d81880ba6]*/
  1393. {
  1394. if (sentinel == NULL)
  1395. return PyObject_GetIter(object);
  1396. if (!PyCallable_Check(object)) {
  1397. PyErr_SetString(PyExc_TypeError,
  1398. "iter(object, sentinel): object must be callable");
  1399. return NULL;
  1400. }
  1401. return PyCallIter_New(object, sentinel);
  1402. }
  1403. /*[clinic input]
  1404. aiter as builtin_aiter
  1405. async_iterable: object
  1406. /
  1407. Return an AsyncIterator for an AsyncIterable object.
  1408. [clinic start generated code]*/
  1409. static PyObject *
  1410. builtin_aiter(PyObject *module, PyObject *async_iterable)
  1411. /*[clinic end generated code: output=1bae108d86f7960e input=473993d0cacc7d23]*/
  1412. {
  1413. return PyObject_GetAIter(async_iterable);
  1414. }
  1415. PyObject *PyAnextAwaitable_New(PyObject *, PyObject *);
  1416. /*[clinic input]
  1417. anext as builtin_anext
  1418. aiterator: object
  1419. default: object = NULL
  1420. /
  1421. async anext(aiterator[, default])
  1422. Return the next item from the async iterator. If default is given and the async
  1423. iterator is exhausted, it is returned instead of raising StopAsyncIteration.
  1424. [clinic start generated code]*/
  1425. static PyObject *
  1426. builtin_anext_impl(PyObject *module, PyObject *aiterator,
  1427. PyObject *default_value)
  1428. /*[clinic end generated code: output=f02c060c163a81fa input=8f63f4f78590bb4c]*/
  1429. {
  1430. PyTypeObject *t;
  1431. PyObject *awaitable;
  1432. t = Py_TYPE(aiterator);
  1433. if (t->tp_as_async == NULL || t->tp_as_async->am_anext == NULL) {
  1434. PyErr_Format(PyExc_TypeError,
  1435. "'%.200s' object is not an async iterator",
  1436. t->tp_name);
  1437. return NULL;
  1438. }
  1439. awaitable = (*t->tp_as_async->am_anext)(aiterator);
  1440. if (default_value == NULL) {
  1441. return awaitable;
  1442. }
  1443. PyObject* new_awaitable = PyAnextAwaitable_New(
  1444. awaitable, default_value);
  1445. Py_DECREF(awaitable);
  1446. return new_awaitable;
  1447. }
  1448. /*[clinic input]
  1449. len as builtin_len
  1450. obj: object
  1451. /
  1452. Return the number of items in a container.
  1453. [clinic start generated code]*/
  1454. static PyObject *
  1455. builtin_len(PyObject *module, PyObject *obj)
  1456. /*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
  1457. {
  1458. Py_ssize_t res;
  1459. res = PyObject_Size(obj);
  1460. if (res < 0) {
  1461. assert(PyErr_Occurred());
  1462. return NULL;
  1463. }
  1464. return PyLong_FromSsize_t(res);
  1465. }
  1466. /*[clinic input]
  1467. locals as builtin_locals
  1468. Return a dictionary containing the current scope's local variables.
  1469. NOTE: Whether or not updates to this dictionary will affect name lookups in
  1470. the local scope and vice-versa is *implementation dependent* and not
  1471. covered by any backwards compatibility guarantees.
  1472. [clinic start generated code]*/
  1473. static PyObject *
  1474. builtin_locals_impl(PyObject *module)
  1475. /*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
  1476. {
  1477. return _PyEval_GetFrameLocals();
  1478. }
  1479. static PyObject *
  1480. min_max(PyObject *args, PyObject *kwds, int op)
  1481. {
  1482. PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
  1483. PyObject *emptytuple, *defaultval = NULL;
  1484. static char *kwlist[] = {"key", "default", NULL};
  1485. const char *name = op == Py_LT ? "min" : "max";
  1486. const int positional = PyTuple_Size(args) > 1;
  1487. int ret;
  1488. if (positional) {
  1489. v = args;
  1490. }
  1491. else if (!PyArg_UnpackTuple(args, name, 1, 1, &v)) {
  1492. if (PyExceptionClass_Check(PyExc_TypeError)) {
  1493. PyErr_Format(PyExc_TypeError, "%s expected at least 1 argument, got 0", name);
  1494. }
  1495. return NULL;
  1496. }
  1497. emptytuple = PyTuple_New(0);
  1498. if (emptytuple == NULL)
  1499. return NULL;
  1500. ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
  1501. (op == Py_LT) ? "|$OO:min" : "|$OO:max",
  1502. kwlist, &keyfunc, &defaultval);
  1503. Py_DECREF(emptytuple);
  1504. if (!ret)
  1505. return NULL;
  1506. if (positional && defaultval != NULL) {
  1507. PyErr_Format(PyExc_TypeError,
  1508. "Cannot specify a default for %s() with multiple "
  1509. "positional arguments", name);
  1510. return NULL;
  1511. }
  1512. it = PyObject_GetIter(v);
  1513. if (it == NULL) {
  1514. return NULL;
  1515. }
  1516. if (keyfunc == Py_None) {
  1517. keyfunc = NULL;
  1518. }
  1519. maxitem = NULL; /* the result */
  1520. maxval = NULL; /* the value associated with the result */
  1521. while (( item = PyIter_Next(it) )) {
  1522. /* get the value from the key function */
  1523. if (keyfunc != NULL) {
  1524. val = PyObject_CallOneArg(keyfunc, item);
  1525. if (val == NULL)
  1526. goto Fail_it_item;
  1527. }
  1528. /* no key function; the value is the item */
  1529. else {
  1530. val = Py_NewRef(item);
  1531. }
  1532. /* maximum value and item are unset; set them */
  1533. if (maxval == NULL) {
  1534. maxitem = item;
  1535. maxval = val;
  1536. }
  1537. /* maximum value and item are set; update them as necessary */
  1538. else {
  1539. int cmp = PyObject_RichCompareBool(val, maxval, op);
  1540. if (cmp < 0)
  1541. goto Fail_it_item_and_val;
  1542. else if (cmp > 0) {
  1543. Py_DECREF(maxval);
  1544. Py_DECREF(maxitem);
  1545. maxval = val;
  1546. maxitem = item;
  1547. }
  1548. else {
  1549. Py_DECREF(item);
  1550. Py_DECREF(val);
  1551. }
  1552. }
  1553. }
  1554. if (PyErr_Occurred())
  1555. goto Fail_it;
  1556. if (maxval == NULL) {
  1557. assert(maxitem == NULL);
  1558. if (defaultval != NULL) {
  1559. maxitem = Py_NewRef(defaultval);
  1560. } else {
  1561. PyErr_Format(PyExc_ValueError,
  1562. "%s() iterable argument is empty", name);
  1563. }
  1564. }
  1565. else
  1566. Py_DECREF(maxval);
  1567. Py_DECREF(it);
  1568. return maxitem;
  1569. Fail_it_item_and_val:
  1570. Py_DECREF(val);
  1571. Fail_it_item:
  1572. Py_DECREF(item);
  1573. Fail_it:
  1574. Py_XDECREF(maxval);
  1575. Py_XDECREF(maxitem);
  1576. Py_DECREF(it);
  1577. return NULL;
  1578. }
  1579. /* AC: cannot convert yet, waiting for *args support */
  1580. static PyObject *
  1581. builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
  1582. {
  1583. return min_max(args, kwds, Py_LT);
  1584. }
  1585. PyDoc_STRVAR(min_doc,
  1586. "min(iterable, *[, default=obj, key=func]) -> value\n\
  1587. min(arg1, arg2, *args, *[, key=func]) -> value\n\
  1588. \n\
  1589. With a single iterable argument, return its smallest item. The\n\
  1590. default keyword-only argument specifies an object to return if\n\
  1591. the provided iterable is empty.\n\
  1592. With two or more arguments, return the smallest argument.");
  1593. /* AC: cannot convert yet, waiting for *args support */
  1594. static PyObject *
  1595. builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
  1596. {
  1597. return min_max(args, kwds, Py_GT);
  1598. }
  1599. PyDoc_STRVAR(max_doc,
  1600. "max(iterable, *[, default=obj, key=func]) -> value\n\
  1601. max(arg1, arg2, *args, *[, key=func]) -> value\n\
  1602. \n\
  1603. With a single iterable argument, return its biggest item. The\n\
  1604. default keyword-only argument specifies an object to return if\n\
  1605. the provided iterable is empty.\n\
  1606. With two or more arguments, return the largest argument.");
  1607. /*[clinic input]
  1608. oct as builtin_oct
  1609. number: object
  1610. /
  1611. Return the octal representation of an integer.
  1612. >>> oct(342391)
  1613. '0o1234567'
  1614. [clinic start generated code]*/
  1615. static PyObject *
  1616. builtin_oct(PyObject *module, PyObject *number)
  1617. /*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
  1618. {
  1619. return PyNumber_ToBase(number, 8);
  1620. }
  1621. /*[clinic input]
  1622. ord as builtin_ord
  1623. c: object
  1624. /
  1625. Return the Unicode code point for a one-character string.
  1626. [clinic start generated code]*/
  1627. static PyObject *
  1628. builtin_ord(PyObject *module, PyObject *c)
  1629. /*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
  1630. {
  1631. long ord;
  1632. Py_ssize_t size;
  1633. if (PyBytes_Check(c)) {
  1634. size = PyBytes_GET_SIZE(c);
  1635. if (size == 1) {
  1636. ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
  1637. return PyLong_FromLong(ord);
  1638. }
  1639. }
  1640. else if (PyUnicode_Check(c)) {
  1641. if (PyUnicode_READY(c) == -1)
  1642. return NULL;
  1643. size = PyUnicode_GET_LENGTH(c);
  1644. if (size == 1) {
  1645. ord = (long)PyUnicode_READ_CHAR(c, 0);
  1646. return PyLong_FromLong(ord);
  1647. }
  1648. }
  1649. else if (PyByteArray_Check(c)) {
  1650. /* XXX Hopefully this is temporary */
  1651. size = PyByteArray_GET_SIZE(c);
  1652. if (size == 1) {
  1653. ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
  1654. return PyLong_FromLong(ord);
  1655. }
  1656. }
  1657. else {
  1658. PyErr_Format(PyExc_TypeError,
  1659. "ord() expected string of length 1, but " \
  1660. "%.200s found", Py_TYPE(c)->tp_name);
  1661. return NULL;
  1662. }
  1663. PyErr_Format(PyExc_TypeError,
  1664. "ord() expected a character, "
  1665. "but string of length %zd found",
  1666. size);
  1667. return NULL;
  1668. }
  1669. /*[clinic input]
  1670. pow as builtin_pow
  1671. base: object
  1672. exp: object
  1673. mod: object = None
  1674. Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
  1675. Some types, such as ints, are able to use a more efficient algorithm when
  1676. invoked using the three argument form.
  1677. [clinic start generated code]*/
  1678. static PyObject *
  1679. builtin_pow_impl(PyObject *module, PyObject *base, PyObject *exp,
  1680. PyObject *mod)
  1681. /*[clinic end generated code: output=3ca1538221bbf15f input=435dbd48a12efb23]*/
  1682. {
  1683. return PyNumber_Power(base, exp, mod);
  1684. }
  1685. /*[clinic input]
  1686. print as builtin_print
  1687. *args: object
  1688. sep: object(c_default="Py_None") = ' '
  1689. string inserted between values, default a space.
  1690. end: object(c_default="Py_None") = '\n'
  1691. string appended after the last value, default a newline.
  1692. file: object = None
  1693. a file-like object (stream); defaults to the current sys.stdout.
  1694. flush: bool = False
  1695. whether to forcibly flush the stream.
  1696. Prints the values to a stream, or to sys.stdout by default.
  1697. [clinic start generated code]*/
  1698. static PyObject *
  1699. builtin_print_impl(PyObject *module, PyObject *args, PyObject *sep,
  1700. PyObject *end, PyObject *file, int flush)
  1701. /*[clinic end generated code: output=3cfc0940f5bc237b input=c143c575d24fe665]*/
  1702. {
  1703. int i, err;
  1704. if (file == Py_None) {
  1705. PyThreadState *tstate = _PyThreadState_GET();
  1706. file = _PySys_GetAttr(tstate, &_Py_ID(stdout));
  1707. if (file == NULL) {
  1708. PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
  1709. return NULL;
  1710. }
  1711. /* sys.stdout may be None when FILE* stdout isn't connected */
  1712. if (file == Py_None) {
  1713. Py_RETURN_NONE;
  1714. }
  1715. }
  1716. if (sep == Py_None) {
  1717. sep = NULL;
  1718. }
  1719. else if (sep && !PyUnicode_Check(sep)) {
  1720. PyErr_Format(PyExc_TypeError,
  1721. "sep must be None or a string, not %.200s",
  1722. Py_TYPE(sep)->tp_name);
  1723. return NULL;
  1724. }
  1725. if (end == Py_None) {
  1726. end = NULL;
  1727. }
  1728. else if (end && !PyUnicode_Check(end)) {
  1729. PyErr_Format(PyExc_TypeError,
  1730. "end must be None or a string, not %.200s",
  1731. Py_TYPE(end)->tp_name);
  1732. return NULL;
  1733. }
  1734. for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
  1735. if (i > 0) {
  1736. if (sep == NULL) {
  1737. err = PyFile_WriteString(" ", file);
  1738. }
  1739. else {
  1740. err = PyFile_WriteObject(sep, file, Py_PRINT_RAW);
  1741. }
  1742. if (err) {
  1743. return NULL;
  1744. }
  1745. }
  1746. err = PyFile_WriteObject(PyTuple_GET_ITEM(args, i), file, Py_PRINT_RAW);
  1747. if (err) {
  1748. return NULL;
  1749. }
  1750. }
  1751. if (end == NULL) {
  1752. err = PyFile_WriteString("\n", file);
  1753. }
  1754. else {
  1755. err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
  1756. }
  1757. if (err) {
  1758. return NULL;
  1759. }
  1760. if (flush) {
  1761. PyObject *tmp = PyObject_CallMethodNoArgs(file, &_Py_ID(flush));
  1762. if (tmp == NULL) {
  1763. return NULL;
  1764. }
  1765. Py_DECREF(tmp);
  1766. }
  1767. Py_RETURN_NONE;
  1768. }
  1769. /*[clinic input]
  1770. input as builtin_input
  1771. prompt: object(c_default="NULL") = ""
  1772. /
  1773. Read a string from standard input. The trailing newline is stripped.
  1774. The prompt string, if given, is printed to standard output without a
  1775. trailing newline before reading input.
  1776. If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
  1777. On *nix systems, readline is used if available.
  1778. [clinic start generated code]*/
  1779. static PyObject *
  1780. builtin_input_impl(PyObject *module, PyObject *prompt)
  1781. /*[clinic end generated code: output=83db5a191e7a0d60 input=159c46d4ae40977e]*/
  1782. {
  1783. PyThreadState *tstate = _PyThreadState_GET();
  1784. PyObject *fin = _PySys_GetAttr(
  1785. tstate, &_Py_ID(stdin));
  1786. PyObject *fout = _PySys_GetAttr(
  1787. tstate, &_Py_ID(stdout));
  1788. PyObject *ferr = _PySys_GetAttr(
  1789. tstate, &_Py_ID(stderr));
  1790. PyObject *tmp;
  1791. long fd;
  1792. int tty;
  1793. /* Check that stdin/out/err are intact */
  1794. if (fin == NULL || fin == Py_None) {
  1795. PyErr_SetString(PyExc_RuntimeError,
  1796. "input(): lost sys.stdin");
  1797. return NULL;
  1798. }
  1799. if (fout == NULL || fout == Py_None) {
  1800. PyErr_SetString(PyExc_RuntimeError,
  1801. "input(): lost sys.stdout");
  1802. return NULL;
  1803. }
  1804. if (ferr == NULL || ferr == Py_None) {
  1805. PyErr_SetString(PyExc_RuntimeError,
  1806. "input(): lost sys.stderr");
  1807. return NULL;
  1808. }
  1809. if (PySys_Audit("builtins.input", "O", prompt ? prompt : Py_None) < 0) {
  1810. return NULL;
  1811. }
  1812. /* First of all, flush stderr */
  1813. tmp = PyObject_CallMethodNoArgs(ferr, &_Py_ID(flush));
  1814. if (tmp == NULL)
  1815. PyErr_Clear();
  1816. else
  1817. Py_DECREF(tmp);
  1818. /* We should only use (GNU) readline if Python's sys.stdin and
  1819. sys.stdout are the same as C's stdin and stdout, because we
  1820. need to pass it those. */
  1821. tmp = PyObject_CallMethodNoArgs(fin, &_Py_ID(fileno));
  1822. if (tmp == NULL) {
  1823. PyErr_Clear();
  1824. tty = 0;
  1825. }
  1826. else {
  1827. fd = PyLong_AsLong(tmp);
  1828. Py_DECREF(tmp);
  1829. if (fd < 0 && PyErr_Occurred())
  1830. return NULL;
  1831. tty = fd == fileno(stdin) && isatty(fd);
  1832. }
  1833. if (tty) {
  1834. tmp = PyObject_CallMethodNoArgs(fout, &_Py_ID(fileno));
  1835. if (tmp == NULL) {
  1836. PyErr_Clear();
  1837. tty = 0;
  1838. }
  1839. else {
  1840. fd = PyLong_AsLong(tmp);
  1841. Py_DECREF(tmp);
  1842. if (fd < 0 && PyErr_Occurred())
  1843. return NULL;
  1844. tty = fd == fileno(stdout) && isatty(fd);
  1845. }
  1846. }
  1847. /* If we're interactive, use (GNU) readline */
  1848. if (tty) {
  1849. PyObject *po = NULL;
  1850. const char *promptstr;
  1851. char *s = NULL;
  1852. PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
  1853. PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
  1854. const char *stdin_encoding_str, *stdin_errors_str;
  1855. PyObject *result;
  1856. size_t len;
  1857. /* stdin is a text stream, so it must have an encoding. */
  1858. stdin_encoding = PyObject_GetAttr(fin, &_Py_ID(encoding));
  1859. if (stdin_encoding == NULL) {
  1860. tty = 0;
  1861. goto _readline_errors;
  1862. }
  1863. stdin_errors = PyObject_GetAttr(fin, &_Py_ID(errors));
  1864. if (stdin_errors == NULL) {
  1865. tty = 0;
  1866. goto _readline_errors;
  1867. }
  1868. if (!PyUnicode_Check(stdin_encoding) ||
  1869. !PyUnicode_Check(stdin_errors))
  1870. {
  1871. tty = 0;
  1872. goto _readline_errors;
  1873. }
  1874. stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
  1875. if (stdin_encoding_str == NULL) {
  1876. goto _readline_errors;
  1877. }
  1878. stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
  1879. if (stdin_errors_str == NULL) {
  1880. goto _readline_errors;
  1881. }
  1882. tmp = PyObject_CallMethodNoArgs(fout, &_Py_ID(flush));
  1883. if (tmp == NULL)
  1884. PyErr_Clear();
  1885. else
  1886. Py_DECREF(tmp);
  1887. if (prompt != NULL) {
  1888. /* We have a prompt, encode it as stdout would */
  1889. const char *stdout_encoding_str, *stdout_errors_str;
  1890. PyObject *stringpo;
  1891. stdout_encoding = PyObject_GetAttr(fout, &_Py_ID(encoding));
  1892. if (stdout_encoding == NULL) {
  1893. tty = 0;
  1894. goto _readline_errors;
  1895. }
  1896. stdout_errors = PyObject_GetAttr(fout, &_Py_ID(errors));
  1897. if (stdout_errors == NULL) {
  1898. tty = 0;
  1899. goto _readline_errors;
  1900. }
  1901. if (!PyUnicode_Check(stdout_encoding) ||
  1902. !PyUnicode_Check(stdout_errors))
  1903. {
  1904. tty = 0;
  1905. goto _readline_errors;
  1906. }
  1907. stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
  1908. if (stdout_encoding_str == NULL) {
  1909. goto _readline_errors;
  1910. }
  1911. stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
  1912. if (stdout_errors_str == NULL) {
  1913. goto _readline_errors;
  1914. }
  1915. stringpo = PyObject_Str(prompt);
  1916. if (stringpo == NULL)
  1917. goto _readline_errors;
  1918. po = PyUnicode_AsEncodedString(stringpo,
  1919. stdout_encoding_str, stdout_errors_str);
  1920. Py_CLEAR(stdout_encoding);
  1921. Py_CLEAR(stdout_errors);
  1922. Py_CLEAR(stringpo);
  1923. if (po == NULL)
  1924. goto _readline_errors;
  1925. assert(PyBytes_Check(po));
  1926. promptstr = PyBytes_AS_STRING(po);
  1927. }
  1928. else {
  1929. po = NULL;
  1930. promptstr = "";
  1931. }
  1932. s = PyOS_Readline(stdin, stdout, promptstr);
  1933. if (s == NULL) {
  1934. PyErr_CheckSignals();
  1935. if (!PyErr_Occurred())
  1936. PyErr_SetNone(PyExc_KeyboardInterrupt);
  1937. goto _readline_errors;
  1938. }
  1939. len = strlen(s);
  1940. if (len == 0) {
  1941. PyErr_SetNone(PyExc_EOFError);
  1942. result = NULL;
  1943. }
  1944. else {
  1945. if (len > PY_SSIZE_T_MAX) {
  1946. PyErr_SetString(PyExc_OverflowError,
  1947. "input: input too long");
  1948. result = NULL;
  1949. }
  1950. else {
  1951. len--; /* strip trailing '\n' */
  1952. if (len != 0 && s[len-1] == '\r')
  1953. len--; /* strip trailing '\r' */
  1954. result = PyUnicode_Decode(s, len, stdin_encoding_str,
  1955. stdin_errors_str);
  1956. }
  1957. }
  1958. Py_DECREF(stdin_encoding);
  1959. Py_DECREF(stdin_errors);
  1960. Py_XDECREF(po);
  1961. PyMem_Free(s);
  1962. if (result != NULL) {
  1963. if (PySys_Audit("builtins.input/result", "O", result) < 0) {
  1964. return NULL;
  1965. }
  1966. }
  1967. return result;
  1968. _readline_errors:
  1969. Py_XDECREF(stdin_encoding);
  1970. Py_XDECREF(stdout_encoding);
  1971. Py_XDECREF(stdin_errors);
  1972. Py_XDECREF(stdout_errors);
  1973. Py_XDECREF(po);
  1974. if (tty)
  1975. return NULL;
  1976. PyErr_Clear();
  1977. }
  1978. /* Fallback if we're not interactive */
  1979. if (prompt != NULL) {
  1980. if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
  1981. return NULL;
  1982. }
  1983. tmp = PyObject_CallMethodNoArgs(fout, &_Py_ID(flush));
  1984. if (tmp == NULL)
  1985. PyErr_Clear();
  1986. else
  1987. Py_DECREF(tmp);
  1988. return PyFile_GetLine(fin, -1);
  1989. }
  1990. /*[clinic input]
  1991. repr as builtin_repr
  1992. obj: object
  1993. /
  1994. Return the canonical string representation of the object.
  1995. For many object types, including most builtins, eval(repr(obj)) == obj.
  1996. [clinic start generated code]*/
  1997. static PyObject *
  1998. builtin_repr(PyObject *module, PyObject *obj)
  1999. /*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
  2000. {
  2001. return PyObject_Repr(obj);
  2002. }
  2003. /*[clinic input]
  2004. round as builtin_round
  2005. number: object
  2006. ndigits: object = None
  2007. Round a number to a given precision in decimal digits.
  2008. The return value is an integer if ndigits is omitted or None. Otherwise
  2009. the return value has the same type as the number. ndigits may be negative.
  2010. [clinic start generated code]*/
  2011. static PyObject *
  2012. builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
  2013. /*[clinic end generated code: output=ff0d9dd176c02ede input=275678471d7aca15]*/
  2014. {
  2015. PyObject *round, *result;
  2016. if (!_PyType_IsReady(Py_TYPE(number))) {
  2017. if (PyType_Ready(Py_TYPE(number)) < 0)
  2018. return NULL;
  2019. }
  2020. round = _PyObject_LookupSpecial(number, &_Py_ID(__round__));
  2021. if (round == NULL) {
  2022. if (!PyErr_Occurred())
  2023. PyErr_Format(PyExc_TypeError,
  2024. "type %.100s doesn't define __round__ method",
  2025. Py_TYPE(number)->tp_name);
  2026. return NULL;
  2027. }
  2028. if (ndigits == Py_None)
  2029. result = _PyObject_CallNoArgs(round);
  2030. else
  2031. result = PyObject_CallOneArg(round, ndigits);
  2032. Py_DECREF(round);
  2033. return result;
  2034. }
  2035. /*AC: we need to keep the kwds dict intact to easily call into the
  2036. * list.sort method, which isn't currently supported in AC. So we just use
  2037. * the initially generated signature with a custom implementation.
  2038. */
  2039. /* [disabled clinic input]
  2040. sorted as builtin_sorted
  2041. iterable as seq: object
  2042. key as keyfunc: object = None
  2043. reverse: object = False
  2044. Return a new list containing all items from the iterable in ascending order.
  2045. A custom key function can be supplied to customize the sort order, and the
  2046. reverse flag can be set to request the result in descending order.
  2047. [end disabled clinic input]*/
  2048. PyDoc_STRVAR(builtin_sorted__doc__,
  2049. "sorted($module, iterable, /, *, key=None, reverse=False)\n"
  2050. "--\n"
  2051. "\n"
  2052. "Return a new list containing all items from the iterable in ascending order.\n"
  2053. "\n"
  2054. "A custom key function can be supplied to customize the sort order, and the\n"
  2055. "reverse flag can be set to request the result in descending order.");
  2056. #define BUILTIN_SORTED_METHODDEF \
  2057. {"sorted", _PyCFunction_CAST(builtin_sorted), METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
  2058. static PyObject *
  2059. builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
  2060. {
  2061. PyObject *newlist, *v, *seq, *callable;
  2062. /* Keyword arguments are passed through list.sort() which will check
  2063. them. */
  2064. if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
  2065. return NULL;
  2066. newlist = PySequence_List(seq);
  2067. if (newlist == NULL)
  2068. return NULL;
  2069. callable = PyObject_GetAttr(newlist, &_Py_ID(sort));
  2070. if (callable == NULL) {
  2071. Py_DECREF(newlist);
  2072. return NULL;
  2073. }
  2074. assert(nargs >= 1);
  2075. v = PyObject_Vectorcall(callable, args + 1, nargs - 1, kwnames);
  2076. Py_DECREF(callable);
  2077. if (v == NULL) {
  2078. Py_DECREF(newlist);
  2079. return NULL;
  2080. }
  2081. Py_DECREF(v);
  2082. return newlist;
  2083. }
  2084. /*[clinic input]
  2085. vars as builtin_vars
  2086. object: object = NULL
  2087. /
  2088. Show vars.
  2089. Without arguments, equivalent to locals().
  2090. With an argument, equivalent to object.__dict__.
  2091. [clinic start generated code]*/
  2092. static PyObject *
  2093. builtin_vars_impl(PyObject *module, PyObject *object)
  2094. /*[clinic end generated code: output=840a7f64007a3e0a input=80cbdef9182c4ba3]*/
  2095. {
  2096. PyObject *d;
  2097. if (object == NULL) {
  2098. d = _PyEval_GetFrameLocals();
  2099. }
  2100. else {
  2101. if (_PyObject_LookupAttr(object, &_Py_ID(__dict__), &d) == 0) {
  2102. PyErr_SetString(PyExc_TypeError,
  2103. "vars() argument must have __dict__ attribute");
  2104. }
  2105. }
  2106. return d;
  2107. }
  2108. /*[clinic input]
  2109. sum as builtin_sum
  2110. iterable: object
  2111. /
  2112. start: object(c_default="NULL") = 0
  2113. Return the sum of a 'start' value (default: 0) plus an iterable of numbers
  2114. When the iterable is empty, return the start value.
  2115. This function is intended specifically for use with numeric values and may
  2116. reject non-numeric types.
  2117. [clinic start generated code]*/
  2118. static PyObject *
  2119. builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
  2120. /*[clinic end generated code: output=df758cec7d1d302f input=162b50765250d222]*/
  2121. {
  2122. PyObject *result = start;
  2123. PyObject *temp, *item, *iter;
  2124. iter = PyObject_GetIter(iterable);
  2125. if (iter == NULL)
  2126. return NULL;
  2127. if (result == NULL) {
  2128. result = PyLong_FromLong(0);
  2129. if (result == NULL) {
  2130. Py_DECREF(iter);
  2131. return NULL;
  2132. }
  2133. } else {
  2134. /* reject string values for 'start' parameter */
  2135. if (PyUnicode_Check(result)) {
  2136. PyErr_SetString(PyExc_TypeError,
  2137. "sum() can't sum strings [use ''.join(seq) instead]");
  2138. Py_DECREF(iter);
  2139. return NULL;
  2140. }
  2141. if (PyBytes_Check(result)) {
  2142. PyErr_SetString(PyExc_TypeError,
  2143. "sum() can't sum bytes [use b''.join(seq) instead]");
  2144. Py_DECREF(iter);
  2145. return NULL;
  2146. }
  2147. if (PyByteArray_Check(result)) {
  2148. PyErr_SetString(PyExc_TypeError,
  2149. "sum() can't sum bytearray [use b''.join(seq) instead]");
  2150. Py_DECREF(iter);
  2151. return NULL;
  2152. }
  2153. Py_INCREF(result);
  2154. }
  2155. #ifndef SLOW_SUM
  2156. /* Fast addition by keeping temporary sums in C instead of new Python objects.
  2157. Assumes all inputs are the same type. If the assumption fails, default
  2158. to the more general routine.
  2159. */
  2160. if (PyLong_CheckExact(result)) {
  2161. int overflow;
  2162. Py_ssize_t i_result = PyLong_AsLongAndOverflow(result, &overflow);
  2163. /* If this already overflowed, don't even enter the loop. */
  2164. if (overflow == 0) {
  2165. Py_SETREF(result, NULL);
  2166. }
  2167. while(result == NULL) {
  2168. item = PyIter_Next(iter);
  2169. if (item == NULL) {
  2170. Py_DECREF(iter);
  2171. if (PyErr_Occurred())
  2172. return NULL;
  2173. return PyLong_FromSsize_t(i_result);
  2174. }
  2175. if (PyLong_CheckExact(item) || PyBool_Check(item)) {
  2176. Py_ssize_t b;
  2177. overflow = 0;
  2178. /* Single digits are common, fast, and cannot overflow on unpacking. */
  2179. if (_PyLong_IsCompact((PyLongObject *)item)) {
  2180. b = _PyLong_CompactValue((PyLongObject *)item);
  2181. }
  2182. else {
  2183. b = PyLong_AsLongAndOverflow(item, &overflow);
  2184. }
  2185. if (overflow == 0 &&
  2186. (i_result >= 0 ? (b <= LONG_MAX - i_result)
  2187. : (b >= LONG_MIN - i_result)))
  2188. {
  2189. i_result += b;
  2190. Py_DECREF(item);
  2191. continue;
  2192. }
  2193. }
  2194. /* Either overflowed or is not an int. Restore real objects and process normally */
  2195. result = PyLong_FromSsize_t(i_result);
  2196. if (result == NULL) {
  2197. Py_DECREF(item);
  2198. Py_DECREF(iter);
  2199. return NULL;
  2200. }
  2201. temp = PyNumber_Add(result, item);
  2202. Py_DECREF(result);
  2203. Py_DECREF(item);
  2204. result = temp;
  2205. if (result == NULL) {
  2206. Py_DECREF(iter);
  2207. return NULL;
  2208. }
  2209. }
  2210. }
  2211. if (PyFloat_CheckExact(result)) {
  2212. double f_result = PyFloat_AS_DOUBLE(result);
  2213. double c = 0.0;
  2214. Py_SETREF(result, NULL);
  2215. while(result == NULL) {
  2216. item = PyIter_Next(iter);
  2217. if (item == NULL) {
  2218. Py_DECREF(iter);
  2219. if (PyErr_Occurred())
  2220. return NULL;
  2221. /* Avoid losing the sign on a negative result,
  2222. and don't let adding the compensation convert
  2223. an infinite or overflowed sum to a NaN. */
  2224. if (c && Py_IS_FINITE(c)) {
  2225. f_result += c;
  2226. }
  2227. return PyFloat_FromDouble(f_result);
  2228. }
  2229. if (PyFloat_CheckExact(item)) {
  2230. // Improved Kahan–Babuška algorithm by Arnold Neumaier
  2231. // Neumaier, A. (1974), Rundungsfehleranalyse einiger Verfahren
  2232. // zur Summation endlicher Summen. Z. angew. Math. Mech.,
  2233. // 54: 39-51. https://doi.org/10.1002/zamm.19740540106
  2234. // https://en.wikipedia.org/wiki/Kahan_summation_algorithm#Further_enhancements
  2235. double x = PyFloat_AS_DOUBLE(item);
  2236. double t = f_result + x;
  2237. if (fabs(f_result) >= fabs(x)) {
  2238. c += (f_result - t) + x;
  2239. } else {
  2240. c += (x - t) + f_result;
  2241. }
  2242. f_result = t;
  2243. _Py_DECREF_SPECIALIZED(item, _PyFloat_ExactDealloc);
  2244. continue;
  2245. }
  2246. if (PyLong_Check(item)) {
  2247. long value;
  2248. int overflow;
  2249. value = PyLong_AsLongAndOverflow(item, &overflow);
  2250. if (!overflow) {
  2251. f_result += (double)value;
  2252. Py_DECREF(item);
  2253. continue;
  2254. }
  2255. }
  2256. if (c && Py_IS_FINITE(c)) {
  2257. f_result += c;
  2258. }
  2259. result = PyFloat_FromDouble(f_result);
  2260. if (result == NULL) {
  2261. Py_DECREF(item);
  2262. Py_DECREF(iter);
  2263. return NULL;
  2264. }
  2265. temp = PyNumber_Add(result, item);
  2266. Py_DECREF(result);
  2267. Py_DECREF(item);
  2268. result = temp;
  2269. if (result == NULL) {
  2270. Py_DECREF(iter);
  2271. return NULL;
  2272. }
  2273. }
  2274. }
  2275. #endif
  2276. for(;;) {
  2277. item = PyIter_Next(iter);
  2278. if (item == NULL) {
  2279. /* error, or end-of-sequence */
  2280. if (PyErr_Occurred()) {
  2281. Py_SETREF(result, NULL);
  2282. }
  2283. break;
  2284. }
  2285. /* It's tempting to use PyNumber_InPlaceAdd instead of
  2286. PyNumber_Add here, to avoid quadratic running time
  2287. when doing 'sum(list_of_lists, [])'. However, this
  2288. would produce a change in behaviour: a snippet like
  2289. empty = []
  2290. sum([[x] for x in range(10)], empty)
  2291. would change the value of empty. In fact, using
  2292. in-place addition rather that binary addition for
  2293. any of the steps introduces subtle behavior changes:
  2294. https://bugs.python.org/issue18305 */
  2295. temp = PyNumber_Add(result, item);
  2296. Py_DECREF(result);
  2297. Py_DECREF(item);
  2298. result = temp;
  2299. if (result == NULL)
  2300. break;
  2301. }
  2302. Py_DECREF(iter);
  2303. return result;
  2304. }
  2305. /*[clinic input]
  2306. isinstance as builtin_isinstance
  2307. obj: object
  2308. class_or_tuple: object
  2309. /
  2310. Return whether an object is an instance of a class or of a subclass thereof.
  2311. A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
  2312. check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
  2313. or ...`` etc.
  2314. [clinic start generated code]*/
  2315. static PyObject *
  2316. builtin_isinstance_impl(PyObject *module, PyObject *obj,
  2317. PyObject *class_or_tuple)
  2318. /*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
  2319. {
  2320. int retval;
  2321. retval = PyObject_IsInstance(obj, class_or_tuple);
  2322. if (retval < 0)
  2323. return NULL;
  2324. return PyBool_FromLong(retval);
  2325. }
  2326. /*[clinic input]
  2327. issubclass as builtin_issubclass
  2328. cls: object
  2329. class_or_tuple: object
  2330. /
  2331. Return whether 'cls' is derived from another class or is the same class.
  2332. A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
  2333. check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
  2334. or ...``.
  2335. [clinic start generated code]*/
  2336. static PyObject *
  2337. builtin_issubclass_impl(PyObject *module, PyObject *cls,
  2338. PyObject *class_or_tuple)
  2339. /*[clinic end generated code: output=358412410cd7a250 input=a24b9f3d58c370d6]*/
  2340. {
  2341. int retval;
  2342. retval = PyObject_IsSubclass(cls, class_or_tuple);
  2343. if (retval < 0)
  2344. return NULL;
  2345. return PyBool_FromLong(retval);
  2346. }
  2347. typedef struct {
  2348. PyObject_HEAD
  2349. Py_ssize_t tuplesize;
  2350. PyObject *ittuple; /* tuple of iterators */
  2351. PyObject *result;
  2352. int strict;
  2353. } zipobject;
  2354. static PyObject *
  2355. zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  2356. {
  2357. zipobject *lz;
  2358. Py_ssize_t i;
  2359. PyObject *ittuple; /* tuple of iterators */
  2360. PyObject *result;
  2361. Py_ssize_t tuplesize;
  2362. int strict = 0;
  2363. if (kwds) {
  2364. PyObject *empty = PyTuple_New(0);
  2365. if (empty == NULL) {
  2366. return NULL;
  2367. }
  2368. static char *kwlist[] = {"strict", NULL};
  2369. int parsed = PyArg_ParseTupleAndKeywords(
  2370. empty, kwds, "|$p:zip", kwlist, &strict);
  2371. Py_DECREF(empty);
  2372. if (!parsed) {
  2373. return NULL;
  2374. }
  2375. }
  2376. /* args must be a tuple */
  2377. assert(PyTuple_Check(args));
  2378. tuplesize = PyTuple_GET_SIZE(args);
  2379. /* obtain iterators */
  2380. ittuple = PyTuple_New(tuplesize);
  2381. if (ittuple == NULL)
  2382. return NULL;
  2383. for (i=0; i < tuplesize; ++i) {
  2384. PyObject *item = PyTuple_GET_ITEM(args, i);
  2385. PyObject *it = PyObject_GetIter(item);
  2386. if (it == NULL) {
  2387. Py_DECREF(ittuple);
  2388. return NULL;
  2389. }
  2390. PyTuple_SET_ITEM(ittuple, i, it);
  2391. }
  2392. /* create a result holder */
  2393. result = PyTuple_New(tuplesize);
  2394. if (result == NULL) {
  2395. Py_DECREF(ittuple);
  2396. return NULL;
  2397. }
  2398. for (i=0 ; i < tuplesize ; i++) {
  2399. PyTuple_SET_ITEM(result, i, Py_NewRef(Py_None));
  2400. }
  2401. /* create zipobject structure */
  2402. lz = (zipobject *)type->tp_alloc(type, 0);
  2403. if (lz == NULL) {
  2404. Py_DECREF(ittuple);
  2405. Py_DECREF(result);
  2406. return NULL;
  2407. }
  2408. lz->ittuple = ittuple;
  2409. lz->tuplesize = tuplesize;
  2410. lz->result = result;
  2411. lz->strict = strict;
  2412. return (PyObject *)lz;
  2413. }
  2414. static void
  2415. zip_dealloc(zipobject *lz)
  2416. {
  2417. PyObject_GC_UnTrack(lz);
  2418. Py_XDECREF(lz->ittuple);
  2419. Py_XDECREF(lz->result);
  2420. Py_TYPE(lz)->tp_free(lz);
  2421. }
  2422. static int
  2423. zip_traverse(zipobject *lz, visitproc visit, void *arg)
  2424. {
  2425. Py_VISIT(lz->ittuple);
  2426. Py_VISIT(lz->result);
  2427. return 0;
  2428. }
  2429. static PyObject *
  2430. zip_next(zipobject *lz)
  2431. {
  2432. Py_ssize_t i;
  2433. Py_ssize_t tuplesize = lz->tuplesize;
  2434. PyObject *result = lz->result;
  2435. PyObject *it;
  2436. PyObject *item;
  2437. PyObject *olditem;
  2438. if (tuplesize == 0)
  2439. return NULL;
  2440. if (Py_REFCNT(result) == 1) {
  2441. Py_INCREF(result);
  2442. for (i=0 ; i < tuplesize ; i++) {
  2443. it = PyTuple_GET_ITEM(lz->ittuple, i);
  2444. item = (*Py_TYPE(it)->tp_iternext)(it);
  2445. if (item == NULL) {
  2446. Py_DECREF(result);
  2447. if (lz->strict) {
  2448. goto check;
  2449. }
  2450. return NULL;
  2451. }
  2452. olditem = PyTuple_GET_ITEM(result, i);
  2453. PyTuple_SET_ITEM(result, i, item);
  2454. Py_DECREF(olditem);
  2455. }
  2456. // bpo-42536: The GC may have untracked this result tuple. Since we're
  2457. // recycling it, make sure it's tracked again:
  2458. if (!_PyObject_GC_IS_TRACKED(result)) {
  2459. _PyObject_GC_TRACK(result);
  2460. }
  2461. } else {
  2462. result = PyTuple_New(tuplesize);
  2463. if (result == NULL)
  2464. return NULL;
  2465. for (i=0 ; i < tuplesize ; i++) {
  2466. it = PyTuple_GET_ITEM(lz->ittuple, i);
  2467. item = (*Py_TYPE(it)->tp_iternext)(it);
  2468. if (item == NULL) {
  2469. Py_DECREF(result);
  2470. if (lz->strict) {
  2471. goto check;
  2472. }
  2473. return NULL;
  2474. }
  2475. PyTuple_SET_ITEM(result, i, item);
  2476. }
  2477. }
  2478. return result;
  2479. check:
  2480. if (PyErr_Occurred()) {
  2481. if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
  2482. // next() on argument i raised an exception (not StopIteration)
  2483. return NULL;
  2484. }
  2485. PyErr_Clear();
  2486. }
  2487. if (i) {
  2488. // ValueError: zip() argument 2 is shorter than argument 1
  2489. // ValueError: zip() argument 3 is shorter than arguments 1-2
  2490. const char* plural = i == 1 ? " " : "s 1-";
  2491. return PyErr_Format(PyExc_ValueError,
  2492. "zip() argument %d is shorter than argument%s%d",
  2493. i + 1, plural, i);
  2494. }
  2495. for (i = 1; i < tuplesize; i++) {
  2496. it = PyTuple_GET_ITEM(lz->ittuple, i);
  2497. item = (*Py_TYPE(it)->tp_iternext)(it);
  2498. if (item) {
  2499. Py_DECREF(item);
  2500. const char* plural = i == 1 ? " " : "s 1-";
  2501. return PyErr_Format(PyExc_ValueError,
  2502. "zip() argument %d is longer than argument%s%d",
  2503. i + 1, plural, i);
  2504. }
  2505. if (PyErr_Occurred()) {
  2506. if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
  2507. // next() on argument i raised an exception (not StopIteration)
  2508. return NULL;
  2509. }
  2510. PyErr_Clear();
  2511. }
  2512. // Argument i is exhausted. So far so good...
  2513. }
  2514. // All arguments are exhausted. Success!
  2515. return NULL;
  2516. }
  2517. static PyObject *
  2518. zip_reduce(zipobject *lz, PyObject *Py_UNUSED(ignored))
  2519. {
  2520. /* Just recreate the zip with the internal iterator tuple */
  2521. if (lz->strict) {
  2522. return PyTuple_Pack(3, Py_TYPE(lz), lz->ittuple, Py_True);
  2523. }
  2524. return PyTuple_Pack(2, Py_TYPE(lz), lz->ittuple);
  2525. }
  2526. PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
  2527. static PyObject *
  2528. zip_setstate(zipobject *lz, PyObject *state)
  2529. {
  2530. int strict = PyObject_IsTrue(state);
  2531. if (strict < 0) {
  2532. return NULL;
  2533. }
  2534. lz->strict = strict;
  2535. Py_RETURN_NONE;
  2536. }
  2537. static PyMethodDef zip_methods[] = {
  2538. {"__reduce__", _PyCFunction_CAST(zip_reduce), METH_NOARGS, reduce_doc},
  2539. {"__setstate__", _PyCFunction_CAST(zip_setstate), METH_O, setstate_doc},
  2540. {NULL} /* sentinel */
  2541. };
  2542. PyDoc_STRVAR(zip_doc,
  2543. "zip(*iterables, strict=False) --> Yield tuples until an input is exhausted.\n\
  2544. \n\
  2545. >>> list(zip('abcdefg', range(3), range(4)))\n\
  2546. [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]\n\
  2547. \n\
  2548. The zip object yields n-length tuples, where n is the number of iterables\n\
  2549. passed as positional arguments to zip(). The i-th element in every tuple\n\
  2550. comes from the i-th iterable argument to zip(). This continues until the\n\
  2551. shortest argument is exhausted.\n\
  2552. \n\
  2553. If strict is true and one of the arguments is exhausted before the others,\n\
  2554. raise a ValueError.");
  2555. PyTypeObject PyZip_Type = {
  2556. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  2557. "zip", /* tp_name */
  2558. sizeof(zipobject), /* tp_basicsize */
  2559. 0, /* tp_itemsize */
  2560. /* methods */
  2561. (destructor)zip_dealloc, /* tp_dealloc */
  2562. 0, /* tp_vectorcall_offset */
  2563. 0, /* tp_getattr */
  2564. 0, /* tp_setattr */
  2565. 0, /* tp_as_async */
  2566. 0, /* tp_repr */
  2567. 0, /* tp_as_number */
  2568. 0, /* tp_as_sequence */
  2569. 0, /* tp_as_mapping */
  2570. 0, /* tp_hash */
  2571. 0, /* tp_call */
  2572. 0, /* tp_str */
  2573. PyObject_GenericGetAttr, /* tp_getattro */
  2574. 0, /* tp_setattro */
  2575. 0, /* tp_as_buffer */
  2576. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  2577. Py_TPFLAGS_BASETYPE, /* tp_flags */
  2578. zip_doc, /* tp_doc */
  2579. (traverseproc)zip_traverse, /* tp_traverse */
  2580. 0, /* tp_clear */
  2581. 0, /* tp_richcompare */
  2582. 0, /* tp_weaklistoffset */
  2583. PyObject_SelfIter, /* tp_iter */
  2584. (iternextfunc)zip_next, /* tp_iternext */
  2585. zip_methods, /* tp_methods */
  2586. 0, /* tp_members */
  2587. 0, /* tp_getset */
  2588. 0, /* tp_base */
  2589. 0, /* tp_dict */
  2590. 0, /* tp_descr_get */
  2591. 0, /* tp_descr_set */
  2592. 0, /* tp_dictoffset */
  2593. 0, /* tp_init */
  2594. PyType_GenericAlloc, /* tp_alloc */
  2595. zip_new, /* tp_new */
  2596. PyObject_GC_Del, /* tp_free */
  2597. };
  2598. static PyMethodDef builtin_methods[] = {
  2599. {"__build_class__", _PyCFunction_CAST(builtin___build_class__),
  2600. METH_FASTCALL | METH_KEYWORDS, build_class_doc},
  2601. BUILTIN___IMPORT___METHODDEF
  2602. BUILTIN_ABS_METHODDEF
  2603. BUILTIN_ALL_METHODDEF
  2604. BUILTIN_ANY_METHODDEF
  2605. BUILTIN_ASCII_METHODDEF
  2606. BUILTIN_BIN_METHODDEF
  2607. {"breakpoint", _PyCFunction_CAST(builtin_breakpoint), METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
  2608. BUILTIN_CALLABLE_METHODDEF
  2609. BUILTIN_CHR_METHODDEF
  2610. BUILTIN_COMPILE_METHODDEF
  2611. BUILTIN_DELATTR_METHODDEF
  2612. BUILTIN_DIR_METHODDEF
  2613. BUILTIN_DIVMOD_METHODDEF
  2614. BUILTIN_EVAL_METHODDEF
  2615. BUILTIN_EXEC_METHODDEF
  2616. BUILTIN_FORMAT_METHODDEF
  2617. BUILTIN_GETATTR_METHODDEF
  2618. BUILTIN_GLOBALS_METHODDEF
  2619. BUILTIN_HASATTR_METHODDEF
  2620. BUILTIN_HASH_METHODDEF
  2621. BUILTIN_HEX_METHODDEF
  2622. BUILTIN_ID_METHODDEF
  2623. BUILTIN_INPUT_METHODDEF
  2624. BUILTIN_ISINSTANCE_METHODDEF
  2625. BUILTIN_ISSUBCLASS_METHODDEF
  2626. BUILTIN_ITER_METHODDEF
  2627. BUILTIN_AITER_METHODDEF
  2628. BUILTIN_LEN_METHODDEF
  2629. BUILTIN_LOCALS_METHODDEF
  2630. {"max", _PyCFunction_CAST(builtin_max), METH_VARARGS | METH_KEYWORDS, max_doc},
  2631. {"min", _PyCFunction_CAST(builtin_min), METH_VARARGS | METH_KEYWORDS, min_doc},
  2632. BUILTIN_NEXT_METHODDEF
  2633. BUILTIN_ANEXT_METHODDEF
  2634. BUILTIN_OCT_METHODDEF
  2635. BUILTIN_ORD_METHODDEF
  2636. BUILTIN_POW_METHODDEF
  2637. BUILTIN_PRINT_METHODDEF
  2638. BUILTIN_REPR_METHODDEF
  2639. BUILTIN_ROUND_METHODDEF
  2640. BUILTIN_SETATTR_METHODDEF
  2641. BUILTIN_SORTED_METHODDEF
  2642. BUILTIN_SUM_METHODDEF
  2643. BUILTIN_VARS_METHODDEF
  2644. {NULL, NULL},
  2645. };
  2646. PyDoc_STRVAR(builtin_doc,
  2647. "Built-in functions, types, exceptions, and other objects.\n\
  2648. \n\
  2649. This module provides direct access to all 'built-in'\n\
  2650. identifiers of Python; for example, builtins.len is\n\
  2651. the full name for the built-in function len().\n\
  2652. \n\
  2653. This module is not normally accessed explicitly by most\n\
  2654. applications, but can be useful in modules that provide\n\
  2655. objects with the same name as a built-in value, but in\n\
  2656. which the built-in of that name is also needed.");
  2657. static struct PyModuleDef builtinsmodule = {
  2658. PyModuleDef_HEAD_INIT,
  2659. "builtins",
  2660. builtin_doc,
  2661. -1, /* multiple "initialization" just copies the module dict. */
  2662. builtin_methods,
  2663. NULL,
  2664. NULL,
  2665. NULL,
  2666. NULL
  2667. };
  2668. PyObject *
  2669. _PyBuiltin_Init(PyInterpreterState *interp)
  2670. {
  2671. PyObject *mod, *dict, *debug;
  2672. const PyConfig *config = _PyInterpreterState_GetConfig(interp);
  2673. mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
  2674. if (mod == NULL)
  2675. return NULL;
  2676. dict = PyModule_GetDict(mod);
  2677. #ifdef Py_TRACE_REFS
  2678. /* "builtins" exposes a number of statically allocated objects
  2679. * that, before this code was added in 2.3, never showed up in
  2680. * the list of "all objects" maintained by Py_TRACE_REFS. As a
  2681. * result, programs leaking references to None and False (etc)
  2682. * couldn't be diagnosed by examining sys.getobjects(0).
  2683. */
  2684. #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
  2685. #else
  2686. #define ADD_TO_ALL(OBJECT) (void)0
  2687. #endif
  2688. #define SETBUILTIN(NAME, OBJECT) \
  2689. if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
  2690. return NULL; \
  2691. ADD_TO_ALL(OBJECT)
  2692. SETBUILTIN("None", Py_None);
  2693. SETBUILTIN("Ellipsis", Py_Ellipsis);
  2694. SETBUILTIN("NotImplemented", Py_NotImplemented);
  2695. SETBUILTIN("False", Py_False);
  2696. SETBUILTIN("True", Py_True);
  2697. SETBUILTIN("bool", &PyBool_Type);
  2698. SETBUILTIN("memoryview", &PyMemoryView_Type);
  2699. SETBUILTIN("bytearray", &PyByteArray_Type);
  2700. SETBUILTIN("bytes", &PyBytes_Type);
  2701. SETBUILTIN("classmethod", &PyClassMethod_Type);
  2702. SETBUILTIN("complex", &PyComplex_Type);
  2703. SETBUILTIN("dict", &PyDict_Type);
  2704. SETBUILTIN("enumerate", &PyEnum_Type);
  2705. SETBUILTIN("filter", &PyFilter_Type);
  2706. SETBUILTIN("float", &PyFloat_Type);
  2707. SETBUILTIN("frozenset", &PyFrozenSet_Type);
  2708. SETBUILTIN("property", &PyProperty_Type);
  2709. SETBUILTIN("int", &PyLong_Type);
  2710. SETBUILTIN("list", &PyList_Type);
  2711. SETBUILTIN("map", &PyMap_Type);
  2712. SETBUILTIN("object", &PyBaseObject_Type);
  2713. SETBUILTIN("range", &PyRange_Type);
  2714. SETBUILTIN("reversed", &PyReversed_Type);
  2715. SETBUILTIN("set", &PySet_Type);
  2716. SETBUILTIN("slice", &PySlice_Type);
  2717. SETBUILTIN("staticmethod", &PyStaticMethod_Type);
  2718. SETBUILTIN("str", &PyUnicode_Type);
  2719. SETBUILTIN("super", &PySuper_Type);
  2720. SETBUILTIN("tuple", &PyTuple_Type);
  2721. SETBUILTIN("type", &PyType_Type);
  2722. SETBUILTIN("zip", &PyZip_Type);
  2723. debug = PyBool_FromLong(config->optimization_level == 0);
  2724. if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
  2725. Py_DECREF(debug);
  2726. return NULL;
  2727. }
  2728. Py_DECREF(debug);
  2729. return mod;
  2730. #undef ADD_TO_ALL
  2731. #undef SETBUILTIN
  2732. }