blob: 9f83c036d0929e69123ddad421025279525b9d20 [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Built-in functions */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Guido van Rossum6bf62da1997-04-11 20:37:35 +00004#include <ctype.h>
Victor Stinner5f2df882018-11-12 00:56:19 +01005#include "ast.h"
Victor Stinner3bb183d2018-11-22 18:38:38 +01006#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinnereec8e612021-03-18 14:57:49 +01007#include "pycore_ast.h" // _PyAST_Validate()
Victor Stinnerc96d00e2020-06-22 18:02:49 +02008#include "pycore_object.h" // _Py_AddToAllObjects()
Victor Stinner384621c2020-06-22 17:27:35 +02009#include "pycore_pyerrors.h" // _PyErr_NoMemory()
10#include "pycore_pystate.h" // _PyThreadState_GET()
11#include "pycore_tuple.h" // _PyTuple_FromArray()
Mark Shannon0332e562021-02-01 10:42:03 +000012#include "pycore_ceval.h" // _PyEval_Vector()
Guido van Rossum6bf62da1997-04-11 20:37:35 +000013
Victor Stinnerbd303c12013-11-07 23:07:29 +010014_Py_IDENTIFIER(__builtins__);
15_Py_IDENTIFIER(__dict__);
16_Py_IDENTIFIER(__prepare__);
17_Py_IDENTIFIER(__round__);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010018_Py_IDENTIFIER(__mro_entries__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010019_Py_IDENTIFIER(encoding);
20_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020021_Py_IDENTIFIER(fileno);
22_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010023_Py_IDENTIFIER(metaclass);
24_Py_IDENTIFIER(sort);
25_Py_IDENTIFIER(stdin);
26_Py_IDENTIFIER(stdout);
27_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020028
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030029#include "clinic/bltinmodule.c.h"
30
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010031static PyObject*
Victor Stinner05d68a82018-01-18 11:15:25 +010032update_bases(PyObject *bases, PyObject *const *args, Py_ssize_t nargs)
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010033{
Victor Stinner05d68a82018-01-18 11:15:25 +010034 Py_ssize_t i, j;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010035 PyObject *base, *meth, *new_base, *result, *new_bases = NULL;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010036 assert(PyTuple_Check(bases));
37
38 for (i = 0; i < nargs; i++) {
39 base = args[i];
40 if (PyType_Check(base)) {
41 if (new_bases) {
42 /* If we already have made a replacement, then we append every normal base,
43 otherwise just skip it. */
44 if (PyList_Append(new_bases, base) < 0) {
45 goto error;
46 }
47 }
48 continue;
49 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +020050 if (_PyObject_LookupAttrId(base, &PyId___mro_entries__, &meth) < 0) {
51 goto error;
52 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010053 if (!meth) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010054 if (new_bases) {
55 if (PyList_Append(new_bases, base) < 0) {
56 goto error;
57 }
58 }
59 continue;
60 }
Petr Viktorinffd97532020-02-11 17:46:57 +010061 new_base = PyObject_CallOneArg(meth, bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010062 Py_DECREF(meth);
63 if (!new_base) {
64 goto error;
65 }
66 if (!PyTuple_Check(new_base)) {
67 PyErr_SetString(PyExc_TypeError,
68 "__mro_entries__ must return a tuple");
69 Py_DECREF(new_base);
70 goto error;
71 }
72 if (!new_bases) {
73 /* If this is a first successful replacement, create new_bases list and
74 copy previously encountered bases. */
75 if (!(new_bases = PyList_New(i))) {
76 goto error;
77 }
78 for (j = 0; j < i; j++) {
79 base = args[j];
80 PyList_SET_ITEM(new_bases, j, base);
81 Py_INCREF(base);
82 }
83 }
84 j = PyList_GET_SIZE(new_bases);
85 if (PyList_SetSlice(new_bases, j, j, new_base) < 0) {
86 goto error;
87 }
88 Py_DECREF(new_base);
89 }
90 if (!new_bases) {
91 return bases;
92 }
93 result = PyList_AsTuple(new_bases);
94 Py_DECREF(new_bases);
95 return result;
96
97error:
98 Py_XDECREF(new_bases);
99 return NULL;
100}
101
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000102/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000103static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200104builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
Victor Stinner773dc6d2017-01-16 23:46:26 +0100105 PyObject *kwnames)
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000106{
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100107 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *orig_bases;
Nick Coghlan19d24672016-12-05 16:47:55 +1000108 PyObject *cls = NULL, *cell = NULL;
Victor Stinner0c39b1b2015-03-18 15:02:06 +0100109 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 if (nargs < 2) {
112 PyErr_SetString(PyExc_TypeError,
113 "__build_class__: not enough arguments");
114 return NULL;
115 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100116 func = args[0]; /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -0500117 if (!PyFunction_Check(func)) {
118 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -0500119 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -0500120 return NULL;
121 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100122 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 if (!PyUnicode_Check(name)) {
124 PyErr_SetString(PyExc_TypeError,
125 "__build_class__: name is not a string");
126 return NULL;
127 }
Sergey Fedoseevf1b9abe2019-02-26 02:37:26 +0500128 orig_bases = _PyTuple_FromArray(args + 2, nargs - 2);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100129 if (orig_bases == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000131
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100132 bases = update_bases(orig_bases, args + 2, nargs - 2);
133 if (bases == NULL) {
134 Py_DECREF(orig_bases);
135 return NULL;
136 }
137
Victor Stinner773dc6d2017-01-16 23:46:26 +0100138 if (kwnames == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 meta = NULL;
140 mkw = NULL;
141 }
142 else {
Victor Stinner773dc6d2017-01-16 23:46:26 +0100143 mkw = _PyStack_AsDict(args + nargs, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 if (mkw == NULL) {
145 Py_DECREF(bases);
146 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000147 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100148
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200149 meta = _PyDict_GetItemIdWithError(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 if (meta != NULL) {
151 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +0100152 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 Py_DECREF(meta);
154 Py_DECREF(mkw);
155 Py_DECREF(bases);
156 return NULL;
157 }
Nick Coghlande31b192011-10-23 22:04:16 +1000158 /* metaclass is explicitly given, check if it's indeed a class */
159 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200161 else if (PyErr_Occurred()) {
162 Py_DECREF(mkw);
163 Py_DECREF(bases);
164 return NULL;
165 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 }
167 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000168 /* if there are no bases, use type: */
169 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000171 }
172 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 else {
174 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
Victor Stinnera102ed72020-02-07 02:24:48 +0100175 meta = (PyObject *)Py_TYPE(base0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 }
177 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000178 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000180
Nick Coghlande31b192011-10-23 22:04:16 +1000181 if (isclass) {
182 /* meta is really a class, so check for a more derived
183 metaclass, or possible metaclass conflicts: */
184 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
185 bases);
186 if (winner == NULL) {
187 Py_DECREF(meta);
188 Py_XDECREF(mkw);
189 Py_DECREF(bases);
190 return NULL;
191 }
192 if (winner != meta) {
193 Py_DECREF(meta);
194 meta = winner;
195 Py_INCREF(meta);
196 }
197 }
198 /* else: meta is not a class, so we cannot do the metaclass
199 calculation, so we will use the explicitly given object as it is */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200200 if (_PyObject_LookupAttrId(meta, &PyId___prepare__, &prep) < 0) {
201 ns = NULL;
202 }
203 else if (prep == NULL) {
204 ns = PyDict_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 }
206 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200207 PyObject *pargs[2] = {name, bases};
Petr Viktorinffd97532020-02-11 17:46:57 +0100208 ns = PyObject_VectorcallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 Py_DECREF(prep);
210 }
211 if (ns == NULL) {
212 Py_DECREF(meta);
213 Py_XDECREF(mkw);
214 Py_DECREF(bases);
215 return NULL;
216 }
Oren Milman5837d042017-09-27 17:04:37 +0300217 if (!PyMapping_Check(ns)) {
218 PyErr_Format(PyExc_TypeError,
219 "%.200s.__prepare__() must return a mapping, not %.200s",
220 isclass ? ((PyTypeObject *)meta)->tp_name : "<metaclass>",
221 Py_TYPE(ns)->tp_name);
222 goto error;
223 }
Mark Shannon0332e562021-02-01 10:42:03 +0000224 PyFrameConstructor *f = PyFunction_AS_FRAME_CONSTRUCTOR(func);
225 PyThreadState *tstate = PyThreadState_GET();
226 cell = _PyEval_Vector(tstate, f, ns, NULL, 0, NULL);
Nick Coghlan19d24672016-12-05 16:47:55 +1000227 if (cell != NULL) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100228 if (bases != orig_bases) {
229 if (PyMapping_SetItemString(ns, "__orig_bases__", orig_bases) < 0) {
230 goto error;
231 }
232 }
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200233 PyObject *margs[3] = {name, bases, ns};
Petr Viktorinffd97532020-02-11 17:46:57 +0100234 cls = PyObject_VectorcallDict(meta, margs, 3, mkw);
Nick Coghlan19d24672016-12-05 16:47:55 +1000235 if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
236 PyObject *cell_cls = PyCell_GET(cell);
237 if (cell_cls != cls) {
Nick Coghlan19d24672016-12-05 16:47:55 +1000238 if (cell_cls == NULL) {
239 const char *msg =
240 "__class__ not set defining %.200R as %.200R. "
241 "Was __classcell__ propagated to type.__new__?";
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300242 PyErr_Format(PyExc_RuntimeError, msg, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000243 } else {
244 const char *msg =
245 "__class__ set to %.200R defining %.200R as %.200R";
246 PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000247 }
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300248 Py_DECREF(cls);
249 cls = NULL;
250 goto error;
Nick Coghlan19d24672016-12-05 16:47:55 +1000251 }
252 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000254error:
255 Py_XDECREF(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 Py_DECREF(ns);
257 Py_DECREF(meta);
258 Py_XDECREF(mkw);
259 Py_DECREF(bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100260 if (bases != orig_bases) {
261 Py_DECREF(orig_bases);
262 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000264}
265
266PyDoc_STRVAR(build_class_doc,
Pablo Galindoe3babbd2019-10-13 16:35:41 +0100267"__build_class__(func, name, /, *bases, [metaclass], **kwds) -> class\n\
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000268\n\
269Internal helper function used by the class statement.");
270
271static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000272builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
275 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400276 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400277 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000278
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400279 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 kwlist, &name, &globals, &locals, &fromlist, &level))
281 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400282 return PyImport_ImportModuleLevelObject(name, globals, locals,
283 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000284}
285
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000286PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400287"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000288\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000289Import a module. Because this function is meant for use by the Python\n\
oldk461d2252018-02-02 12:20:00 +0800290interpreter and not for general use, it is better to use\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000291importlib.import_module() to programmatically import a module.\n\
292\n\
293The globals argument is only used to determine the context;\n\
294they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000295should be a list of names to emulate ``from name import ...'', or an\n\
296empty list to emulate ``import name''.\n\
297When importing a module from a package, note that __import__('A.B', ...)\n\
298returns package A when fromlist is empty, but its submodule B when\n\
oldk461d2252018-02-02 12:20:00 +0800299fromlist is not empty. The level argument is used to determine whether to\n\
300perform absolute or relative imports: 0 is absolute, while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000301is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000302
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000303
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000304/*[clinic input]
305abs as builtin_abs
306
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300307 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000308 /
309
310Return the absolute value of the argument.
311[clinic start generated code]*/
312
Guido van Rossum79f25d91997-04-29 20:08:16 +0000313static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300314builtin_abs(PyObject *module, PyObject *x)
315/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000316{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000317 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000318}
319
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000320/*[clinic input]
321all as builtin_all
322
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300323 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000324 /
325
326Return True if bool(x) is True for all values x in the iterable.
327
328If the iterable is empty, return True.
329[clinic start generated code]*/
330
Raymond Hettinger96229b12005-03-11 06:49:40 +0000331static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300332builtin_all(PyObject *module, PyObject *iterable)
333/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 PyObject *it, *item;
336 PyObject *(*iternext)(PyObject *);
337 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000338
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000339 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 if (it == NULL)
341 return NULL;
342 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 for (;;) {
345 item = iternext(it);
346 if (item == NULL)
347 break;
348 cmp = PyObject_IsTrue(item);
349 Py_DECREF(item);
350 if (cmp < 0) {
351 Py_DECREF(it);
352 return NULL;
353 }
354 if (cmp == 0) {
355 Py_DECREF(it);
356 Py_RETURN_FALSE;
357 }
358 }
359 Py_DECREF(it);
360 if (PyErr_Occurred()) {
361 if (PyErr_ExceptionMatches(PyExc_StopIteration))
362 PyErr_Clear();
363 else
364 return NULL;
365 }
366 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000367}
368
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000369/*[clinic input]
370any as builtin_any
371
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300372 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000373 /
374
375Return True if bool(x) is True for any x in the iterable.
376
377If the iterable is empty, return False.
378[clinic start generated code]*/
379
Raymond Hettinger96229b12005-03-11 06:49:40 +0000380static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300381builtin_any(PyObject *module, PyObject *iterable)
382/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 PyObject *it, *item;
385 PyObject *(*iternext)(PyObject *);
386 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000387
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000388 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 if (it == NULL)
390 return NULL;
391 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 for (;;) {
394 item = iternext(it);
395 if (item == NULL)
396 break;
397 cmp = PyObject_IsTrue(item);
398 Py_DECREF(item);
399 if (cmp < 0) {
400 Py_DECREF(it);
401 return NULL;
402 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400403 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 Py_DECREF(it);
405 Py_RETURN_TRUE;
406 }
407 }
408 Py_DECREF(it);
409 if (PyErr_Occurred()) {
410 if (PyErr_ExceptionMatches(PyExc_StopIteration))
411 PyErr_Clear();
412 else
413 return NULL;
414 }
415 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000416}
417
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000418/*[clinic input]
419ascii as builtin_ascii
420
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300421 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000422 /
423
424Return an ASCII-only representation of an object.
425
426As repr(), return a string containing a printable representation of an
427object, but escape the non-ASCII characters in the string returned by
428repr() using \\x, \\u or \\U escapes. This generates a string similar
429to that returned by repr() in Python 2.
430[clinic start generated code]*/
431
Georg Brandl559e5d72008-06-11 18:37:52 +0000432static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300433builtin_ascii(PyObject *module, PyObject *obj)
434/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000435{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000436 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000437}
438
Georg Brandl559e5d72008-06-11 18:37:52 +0000439
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000440/*[clinic input]
441bin as builtin_bin
442
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300443 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000444 /
445
446Return the binary representation of an integer.
447
448 >>> bin(2796202)
449 '0b1010101010101010101010'
450[clinic start generated code]*/
451
Guido van Rossum79f25d91997-04-29 20:08:16 +0000452static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300453builtin_bin(PyObject *module, PyObject *number)
454/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000455{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000456 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000457}
458
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000459
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000460/*[clinic input]
461callable as builtin_callable
462
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300463 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000464 /
465
466Return whether the object is callable (i.e., some kind of function).
467
468Note that classes are callable, as are instances of classes with a
469__call__() method.
470[clinic start generated code]*/
471
Antoine Pitroue71362d2010-11-27 22:00:11 +0000472static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300473builtin_callable(PyObject *module, PyObject *obj)
474/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000475{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000476 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000477}
478
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400479static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200480builtin_breakpoint(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400481{
482 PyObject *hook = PySys_GetObject("breakpointhook");
483
484 if (hook == NULL) {
485 PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook");
486 return NULL;
487 }
Steve Dower60419a72019-06-24 08:42:54 -0700488
489 if (PySys_Audit("builtins.breakpoint", "O", hook) < 0) {
490 return NULL;
491 }
492
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400493 Py_INCREF(hook);
Petr Viktorinffd97532020-02-11 17:46:57 +0100494 PyObject *retval = PyObject_Vectorcall(hook, args, nargs, keywords);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400495 Py_DECREF(hook);
496 return retval;
497}
498
499PyDoc_STRVAR(breakpoint_doc,
500"breakpoint(*args, **kws)\n\
501\n\
502Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept\n\
503whatever arguments are passed.\n\
504\n\
505By default, this drops you into the pdb debugger.");
Antoine Pitroue71362d2010-11-27 22:00:11 +0000506
Raymond Hettinger17301e92008-03-13 00:19:26 +0000507typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 PyObject_HEAD
509 PyObject *func;
510 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000511} filterobject;
512
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000513static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000514filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 PyObject *func, *seq;
517 PyObject *it;
518 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000519
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +0300520 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
524 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 /* Get iterator. */
527 it = PyObject_GetIter(seq);
528 if (it == NULL)
529 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 /* create filterobject structure */
532 lz = (filterobject *)type->tp_alloc(type, 0);
533 if (lz == NULL) {
534 Py_DECREF(it);
535 return NULL;
536 }
Dong-hee Na9a9c11a2021-03-11 01:39:52 +0900537
538 lz->func = Py_NewRef(func);
539 lz->it = it;
540
541 return (PyObject *)lz;
542}
543
544static PyObject *
545filter_vectorcall(PyObject *type, PyObject * const*args,
546 size_t nargsf, PyObject *kwnames)
547{
548 PyTypeObject *tp = (PyTypeObject *)type;
549 if (tp == &PyFilter_Type && !_PyArg_NoKwnames("filter", kwnames)) {
550 return NULL;
551 }
552
553 Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
554 if (!_PyArg_CheckPositional("filter", nargs, 2, 2)) {
555 return NULL;
556 }
557
558 PyObject *it = PyObject_GetIter(args[1]);
559 if (it == NULL) {
560 return NULL;
561 }
562
563 filterobject *lz = (filterobject *)tp->tp_alloc(tp, 0);
564
565 if (lz == NULL) {
566 Py_DECREF(it);
567 return NULL;
568 }
569
570 lz->func = Py_NewRef(args[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000574}
575
576static void
577filter_dealloc(filterobject *lz)
578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 PyObject_GC_UnTrack(lz);
580 Py_XDECREF(lz->func);
581 Py_XDECREF(lz->it);
582 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000583}
584
585static int
586filter_traverse(filterobject *lz, visitproc visit, void *arg)
587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 Py_VISIT(lz->it);
589 Py_VISIT(lz->func);
590 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000591}
592
593static PyObject *
594filter_next(filterobject *lz)
595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 PyObject *item;
597 PyObject *it = lz->it;
598 long ok;
599 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400600 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 iternext = *Py_TYPE(it)->tp_iternext;
603 for (;;) {
604 item = iternext(it);
605 if (item == NULL)
606 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000607
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400608 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 ok = PyObject_IsTrue(item);
610 } else {
611 PyObject *good;
Petr Viktorinffd97532020-02-11 17:46:57 +0100612 good = PyObject_CallOneArg(lz->func, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 if (good == NULL) {
614 Py_DECREF(item);
615 return NULL;
616 }
617 ok = PyObject_IsTrue(good);
618 Py_DECREF(good);
619 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200620 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 return item;
622 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200623 if (ok < 0)
624 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000626}
627
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000628static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530629filter_reduce(filterobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000630{
631 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
632}
633
634PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
635
636static PyMethodDef filter_methods[] = {
637 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
638 {NULL, NULL} /* sentinel */
639};
640
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000641PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000642"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000643\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000644Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000645is true. If function is None, return the items that are true.");
646
647PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 PyVarObject_HEAD_INIT(&PyType_Type, 0)
649 "filter", /* tp_name */
650 sizeof(filterobject), /* tp_basicsize */
651 0, /* tp_itemsize */
652 /* methods */
653 (destructor)filter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200654 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 0, /* tp_getattr */
656 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200657 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 0, /* tp_repr */
659 0, /* tp_as_number */
660 0, /* tp_as_sequence */
661 0, /* tp_as_mapping */
662 0, /* tp_hash */
663 0, /* tp_call */
664 0, /* tp_str */
665 PyObject_GenericGetAttr, /* tp_getattro */
666 0, /* tp_setattro */
667 0, /* tp_as_buffer */
668 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
669 Py_TPFLAGS_BASETYPE, /* tp_flags */
670 filter_doc, /* tp_doc */
671 (traverseproc)filter_traverse, /* tp_traverse */
672 0, /* tp_clear */
673 0, /* tp_richcompare */
674 0, /* tp_weaklistoffset */
675 PyObject_SelfIter, /* tp_iter */
676 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000677 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 0, /* tp_members */
679 0, /* tp_getset */
680 0, /* tp_base */
681 0, /* tp_dict */
682 0, /* tp_descr_get */
683 0, /* tp_descr_set */
684 0, /* tp_dictoffset */
685 0, /* tp_init */
686 PyType_GenericAlloc, /* tp_alloc */
687 filter_new, /* tp_new */
688 PyObject_GC_Del, /* tp_free */
Dong-hee Na9a9c11a2021-03-11 01:39:52 +0900689 .tp_vectorcall = (vectorcallfunc)filter_vectorcall
Raymond Hettinger17301e92008-03-13 00:19:26 +0000690};
691
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000692
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000693/*[clinic input]
694format as builtin_format
695
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300696 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000697 format_spec: unicode(c_default="NULL") = ''
698 /
699
700Return value.__format__(format_spec)
701
Amit Kumar2e6bb442017-05-29 06:32:26 +0530702format_spec defaults to the empty string.
703See the Format Specification Mini-Language section of help('FORMATTING') for
704details.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000705[clinic start generated code]*/
706
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000707static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300708builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
Amit Kumar2e6bb442017-05-29 06:32:26 +0530709/*[clinic end generated code: output=2f40bdfa4954b077 input=88339c93ea522b33]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000710{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000711 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000712}
713
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000714/*[clinic input]
715chr as builtin_chr
716
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300717 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000718 /
719
720Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
721[clinic start generated code]*/
722
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000723static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300724builtin_chr_impl(PyObject *module, int i)
725/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000726{
727 return PyUnicode_FromOrdinal(i);
728}
Guido van Rossum09095f32000-03-10 23:00:52 +0000729
730
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000731/*[clinic input]
732compile as builtin_compile
733
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300734 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000735 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300736 mode: str
737 flags: int = 0
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200738 dont_inherit: bool(accept={int}) = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300739 optimize: int = -1
Victor Stinnerefdf6ca2019-06-12 02:52:16 +0200740 *
741 _feature_version as feature_version: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000742
743Compile source into a code object that can be executed by exec() or eval().
744
745The source code may represent a Python module, statement or expression.
746The filename will be used for run-time error messages.
747The mode must be 'exec' to compile a module, 'single' to compile a
748single (interactive) statement, or 'eval' to compile an expression.
749The flags argument, if present, controls which future statements influence
750the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300751The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000752the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300753compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000754in addition to any features explicitly specified.
755[clinic start generated code]*/
756
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000757static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300758builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
759 const char *mode, int flags, int dont_inherit,
Guido van Rossum495da292019-03-07 12:38:08 -0800760 int optimize, int feature_version)
Victor Stinnerefdf6ca2019-06-12 02:52:16 +0200761/*[clinic end generated code: output=b0c09c84f116d3d7 input=40171fb92c1d580d]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000762{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000763 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200764 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000765 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 int is_ast;
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800767 int start[] = {Py_file_input, Py_eval_input, Py_single_input, Py_func_type_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000768 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000769
Victor Stinner37d66d72019-06-13 02:16:41 +0200770 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000771 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Guido van Rossum495da292019-03-07 12:38:08 -0800772 if (feature_version >= 0 && (flags & PyCF_ONLY_AST)) {
773 cf.cf_feature_version = feature_version;
774 }
Tim Peters6cd6a822001-08-17 22:11:27 +0000775
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000776 if (flags &
Batuhan Taşkaya44540572020-04-22 19:09:03 +0300777 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_COMPILE_MASK))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 {
779 PyErr_SetString(PyExc_ValueError,
780 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000781 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 }
783 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000784
Georg Brandl8334fd92010-12-04 10:26:46 +0000785 if (optimize < -1 || optimize > 2) {
786 PyErr_SetString(PyExc_ValueError,
787 "compile(): invalid optimize value");
788 goto error;
789 }
790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 if (!dont_inherit) {
792 PyEval_MergeCompilerFlags(&cf);
793 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000794
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000795 if (strcmp(mode, "exec") == 0)
796 compile_mode = 0;
797 else if (strcmp(mode, "eval") == 0)
798 compile_mode = 1;
799 else if (strcmp(mode, "single") == 0)
800 compile_mode = 2;
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800801 else if (strcmp(mode, "func_type") == 0) {
802 if (!(flags & PyCF_ONLY_AST)) {
803 PyErr_SetString(PyExc_ValueError,
804 "compile() mode 'func_type' requires flag PyCF_ONLY_AST");
805 goto error;
806 }
807 compile_mode = 3;
808 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 else {
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800810 const char *msg;
811 if (flags & PyCF_ONLY_AST)
812 msg = "compile() mode must be 'exec', 'eval', 'single' or 'func_type'";
813 else
814 msg = "compile() mode must be 'exec', 'eval' or 'single'";
815 PyErr_SetString(PyExc_ValueError, msg);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000816 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000818
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000819 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000821 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000823 if (flags & PyCF_ONLY_AST) {
824 Py_INCREF(source);
825 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 }
827 else {
828 PyArena *arena;
829 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200832 if (arena == NULL)
833 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000834 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 if (mod == NULL) {
836 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000837 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 }
Victor Stinnereec8e612021-03-18 14:57:49 +0100839 if (!_PyAST_Validate(mod)) {
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500840 PyArena_Free(arena);
841 goto error;
842 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200843 result = (PyObject*)PyAST_CompileObject(mod, filename,
844 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 PyArena_Free(arena);
846 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000847 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000849
Dino Viehland41540692019-05-28 16:21:17 -0700850 str = _Py_SourceAsString(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000852 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000853
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000854 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Guido van Rossumc001c092020-04-30 12:12:19 -0700855
Martin Panter61d6e4a2015-11-07 02:56:11 +0000856 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000857 goto finally;
858
859error:
860 result = NULL;
861finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200862 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000863 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000864}
865
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000866/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000867static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000868builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
873 return NULL;
874 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000875}
876
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000877PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000878"dir([object]) -> list of strings\n"
879"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000880"If called without an argument, return the names in the current scope.\n"
881"Else, return an alphabetized list of names comprising (some of) the attributes\n"
882"of the given object, and of attributes reachable from it.\n"
883"If the object supplies a method named __dir__, it will be used; otherwise\n"
884"the default dir() logic is used and returns:\n"
885" for a module object: the module's attributes.\n"
886" for a class object: its attributes, and recursively the attributes\n"
887" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000888" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000889" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000890
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000891/*[clinic input]
892divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000893
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300894 x: object
895 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000896 /
897
Zachary Ware7f227d92016-04-28 14:39:50 -0500898Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000899[clinic start generated code]*/
900
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000901static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300902builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
903/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000904{
905 return PyNumber_Divmod(x, y);
906}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000907
908
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000909/*[clinic input]
910eval as builtin_eval
911
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300912 source: object
913 globals: object = None
914 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000915 /
916
917Evaluate the given source in the context of globals and locals.
918
919The source may be a string representing a Python expression
920or a code object as returned by compile().
921The globals must be a dictionary and locals can be any mapping,
922defaulting to the current globals and locals.
923If only globals is given, locals defaults to it.
924[clinic start generated code]*/
925
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000926static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300927builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400928 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300929/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000930{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000931 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200932 const char *str;
Guido van Rossum590baa41993-11-30 13:40:46 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 if (locals != Py_None && !PyMapping_Check(locals)) {
935 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
936 return NULL;
937 }
938 if (globals != Py_None && !PyDict_Check(globals)) {
939 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
940 "globals must be a real dict; try eval(expr, {}, mapping)"
941 : "globals must be a dict");
942 return NULL;
943 }
944 if (globals == Py_None) {
945 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100946 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100948 if (locals == NULL)
949 return NULL;
950 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 }
952 else if (locals == Py_None)
953 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 if (globals == NULL || locals == NULL) {
956 PyErr_SetString(PyExc_TypeError,
957 "eval must be given globals and locals "
958 "when called without a frame");
959 return NULL;
960 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000961
Serhiy Storchakab510e102020-10-26 12:47:57 +0200962 int r = _PyDict_ContainsId(globals, &PyId___builtins__);
963 if (r == 0) {
964 r = _PyDict_SetItemId(globals, &PyId___builtins__,
965 PyEval_GetBuiltins());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 }
Serhiy Storchakab510e102020-10-26 12:47:57 +0200967 if (r < 0) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200968 return NULL;
969 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000970
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000971 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700972 if (PySys_Audit("exec", "O", source) < 0) {
973 return NULL;
974 }
975
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000976 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 PyErr_SetString(PyExc_TypeError,
Steve Dowerb82e17e2019-05-23 08:45:22 -0700978 "code object passed to eval() may not contain free variables");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 return NULL;
980 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000981 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000983
Victor Stinner37d66d72019-06-13 02:16:41 +0200984 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -0700986 str = _Py_SourceAsString(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 if (str == NULL)
988 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 while (*str == ' ' || *str == '\t')
991 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 (void)PyEval_MergeCompilerFlags(&cf);
994 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000995 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000997}
998
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000999/*[clinic input]
1000exec as builtin_exec
1001
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001002 source: object
1003 globals: object = None
1004 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001005 /
1006
1007Execute the given source in the context of globals and locals.
1008
1009The source may be a string representing one or more Python statements
1010or a code object as returned by compile().
1011The globals must be a dictionary and locals can be any mapping,
1012defaulting to the current globals and locals.
1013If only globals is given, locals defaults to it.
1014[clinic start generated code]*/
1015
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001016static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001017builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -04001018 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001019/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +00001020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 if (globals == Py_None) {
1024 globals = PyEval_GetGlobals();
1025 if (locals == Py_None) {
1026 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001027 if (locals == NULL)
1028 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 }
1030 if (!globals || !locals) {
1031 PyErr_SetString(PyExc_SystemError,
1032 "globals and locals cannot be NULL");
1033 return NULL;
1034 }
1035 }
1036 else if (locals == Py_None)
1037 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001040 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001041 Py_TYPE(globals)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 return NULL;
1043 }
1044 if (!PyMapping_Check(locals)) {
1045 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001046 "locals must be a mapping or None, not %.100s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001047 Py_TYPE(locals)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 return NULL;
1049 }
Serhiy Storchakab510e102020-10-26 12:47:57 +02001050 int r = _PyDict_ContainsId(globals, &PyId___builtins__);
1051 if (r == 0) {
1052 r = _PyDict_SetItemId(globals, &PyId___builtins__,
1053 PyEval_GetBuiltins());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 }
Serhiy Storchakab510e102020-10-26 12:47:57 +02001055 if (r < 0) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001056 return NULL;
1057 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001059 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001060 if (PySys_Audit("exec", "O", source) < 0) {
1061 return NULL;
1062 }
1063
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001064 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 PyErr_SetString(PyExc_TypeError,
1066 "code object passed to exec() may not "
1067 "contain free variables");
1068 return NULL;
1069 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001070 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 }
1072 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +00001073 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001074 const char *str;
Victor Stinner37d66d72019-06-13 02:16:41 +02001075 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -07001077 str = _Py_SourceAsString(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +00001078 "string, bytes or code", &cf,
1079 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 if (str == NULL)
1081 return NULL;
1082 if (PyEval_MergeCompilerFlags(&cf))
1083 v = PyRun_StringFlags(str, Py_file_input, globals,
1084 locals, &cf);
1085 else
1086 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +00001087 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 }
1089 if (v == NULL)
1090 return NULL;
1091 Py_DECREF(v);
1092 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001093}
1094
Georg Brandl7cae87c2006-09-06 06:51:57 +00001095
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001096/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001097static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001098builtin_getattr(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum33894be1992-01-27 16:53:09 +00001099{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001100 PyObject *v, *name, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001101
Serhiy Storchaka79342662019-01-12 08:25:41 +02001102 if (!_PyArg_CheckPositional("getattr", nargs, 2, 3))
Sylvain96c7c062017-06-15 17:05:23 +02001103 return NULL;
1104
Serhiy Storchaka79342662019-01-12 08:25:41 +02001105 v = args[0];
1106 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 if (!PyUnicode_Check(name)) {
1108 PyErr_SetString(PyExc_TypeError,
1109 "getattr(): attribute name must be string");
1110 return NULL;
1111 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001112 if (nargs > 2) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001113 if (_PyObject_LookupAttr(v, name, &result) == 0) {
Serhiy Storchaka79342662019-01-12 08:25:41 +02001114 PyObject *dflt = args[2];
INADA Naoki378edee2018-01-16 20:52:41 +09001115 Py_INCREF(dflt);
1116 return dflt;
1117 }
1118 }
1119 else {
1120 result = PyObject_GetAttr(v, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 }
1122 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001123}
1124
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001125PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001126"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001127\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001128Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1129When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001130exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001131
1132
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001133/*[clinic input]
1134globals as builtin_globals
1135
1136Return the dictionary containing the current scope's global variables.
1137
1138NOTE: Updates to this dictionary *will* affect name lookups in the current
1139global scope and vice-versa.
1140[clinic start generated code]*/
1141
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001142static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001143builtin_globals_impl(PyObject *module)
1144/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 d = PyEval_GetGlobals();
1149 Py_XINCREF(d);
1150 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001151}
1152
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001153
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001154/*[clinic input]
1155hasattr as builtin_hasattr
1156
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001157 obj: object
1158 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001159 /
1160
1161Return whether the object has an attribute with the given name.
1162
1163This is done by calling getattr(obj, name) and catching AttributeError.
1164[clinic start generated code]*/
1165
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001166static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001167builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1168/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001169{
1170 PyObject *v;
1171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 if (!PyUnicode_Check(name)) {
1173 PyErr_SetString(PyExc_TypeError,
1174 "hasattr(): attribute name must be string");
1175 return NULL;
1176 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001177 if (_PyObject_LookupAttr(obj, name, &v) < 0) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001178 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001180 if (v == NULL) {
1181 Py_RETURN_FALSE;
1182 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001184 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001185}
1186
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001187
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001188/* AC: gdb's integration with CPython relies on builtin_id having
1189 * the *exact* parameter names of "self" and "v", so we ensure we
1190 * preserve those name rather than using the AC defaults.
1191 */
1192/*[clinic input]
1193id as builtin_id
1194
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001195 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001196 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001197 /
1198
1199Return the identity of an object.
1200
1201This is guaranteed to be unique among simultaneously existing objects.
1202(CPython uses the object's memory address.)
1203[clinic start generated code]*/
1204
Guido van Rossum79f25d91997-04-29 20:08:16 +00001205static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001206builtin_id(PyModuleDef *self, PyObject *v)
1207/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001208{
Steve Dowerb82e17e2019-05-23 08:45:22 -07001209 PyObject *id = PyLong_FromVoidPtr(v);
1210
1211 if (id && PySys_Audit("builtins.id", "O", id) < 0) {
1212 Py_DECREF(id);
1213 return NULL;
1214 }
1215
1216 return id;
Guido van Rossum5b722181993-03-30 17:46:03 +00001217}
1218
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001219
Raymond Hettingera6c60372008-03-13 01:26:19 +00001220/* map object ************************************************************/
1221
1222typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 PyObject_HEAD
1224 PyObject *iters;
1225 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001226} mapobject;
1227
Guido van Rossum79f25d91997-04-29 20:08:16 +00001228static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001229map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 PyObject *it, *iters, *func;
1232 mapobject *lz;
1233 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001234
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001235 if (type == &PyMap_Type && !_PyArg_NoKeywords("map", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 numargs = PyTuple_Size(args);
1239 if (numargs < 2) {
1240 PyErr_SetString(PyExc_TypeError,
1241 "map() must have at least two arguments.");
1242 return NULL;
1243 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 iters = PyTuple_New(numargs-1);
1246 if (iters == NULL)
1247 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 for (i=1 ; i<numargs ; i++) {
1250 /* Get iterator. */
1251 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1252 if (it == NULL) {
1253 Py_DECREF(iters);
1254 return NULL;
1255 }
1256 PyTuple_SET_ITEM(iters, i-1, it);
1257 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 /* create mapobject structure */
1260 lz = (mapobject *)type->tp_alloc(type, 0);
1261 if (lz == NULL) {
1262 Py_DECREF(iters);
1263 return NULL;
1264 }
1265 lz->iters = iters;
1266 func = PyTuple_GET_ITEM(args, 0);
Dong-hee Na86883d42021-03-22 19:01:14 +09001267 lz->func = Py_NewRef(func);
1268
1269 return (PyObject *)lz;
1270}
1271
1272static PyObject *
1273map_vectorcall(PyObject *type, PyObject * const*args,
1274 size_t nargsf, PyObject *kwnames)
1275{
1276 PyTypeObject *tp = (PyTypeObject *)type;
1277 if (tp == &PyMap_Type && !_PyArg_NoKwnames("map", kwnames)) {
1278 return NULL;
1279 }
1280
1281 Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
1282 if (nargs < 2) {
1283 PyErr_SetString(PyExc_TypeError,
1284 "map() must have at least two arguments.");
1285 return NULL;
1286 }
1287
1288 PyObject *iters = PyTuple_New(nargs-1);
1289 if (iters == NULL) {
1290 return NULL;
1291 }
1292
1293 for (int i=1; i<nargs; i++) {
1294 PyObject *it = PyObject_GetIter(args[i]);
1295 if (it == NULL) {
1296 Py_DECREF(iters);
1297 return NULL;
1298 }
1299 PyTuple_SET_ITEM(iters, i-1, it);
1300 }
1301
1302 mapobject *lz = (mapobject *)tp->tp_alloc(tp, 0);
1303 if (lz == NULL) {
1304 Py_DECREF(iters);
1305 return NULL;
1306 }
1307 lz->iters = iters;
1308 lz->func = Py_NewRef(args[0]);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001311}
1312
1313static void
1314map_dealloc(mapobject *lz)
1315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 PyObject_GC_UnTrack(lz);
1317 Py_XDECREF(lz->iters);
1318 Py_XDECREF(lz->func);
1319 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001320}
1321
1322static int
1323map_traverse(mapobject *lz, visitproc visit, void *arg)
1324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 Py_VISIT(lz->iters);
1326 Py_VISIT(lz->func);
1327 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001328}
1329
1330static PyObject *
1331map_next(mapobject *lz)
1332{
Victor Stinnerbc08ab42016-12-15 12:40:53 +01001333 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001334 PyObject **stack;
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001335 PyObject *result = NULL;
Victor Stinner4d231bc2019-11-14 13:36:21 +01001336 PyThreadState *tstate = _PyThreadState_GET();
Raymond Hettingera6c60372008-03-13 01:26:19 +00001337
Victor Stinner4d231bc2019-11-14 13:36:21 +01001338 const Py_ssize_t niters = PyTuple_GET_SIZE(lz->iters);
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001339 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1340 stack = small_stack;
1341 }
1342 else {
1343 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1344 if (stack == NULL) {
Victor Stinner4d231bc2019-11-14 13:36:21 +01001345 _PyErr_NoMemory(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 return NULL;
1347 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001349
Victor Stinner4d231bc2019-11-14 13:36:21 +01001350 Py_ssize_t nargs = 0;
1351 for (Py_ssize_t i=0; i < niters; i++) {
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001352 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1353 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1354 if (val == NULL) {
1355 goto exit;
1356 }
1357 stack[i] = val;
1358 nargs++;
1359 }
1360
Victor Stinner4d231bc2019-11-14 13:36:21 +01001361 result = _PyObject_VectorcallTstate(tstate, lz->func, stack, nargs, NULL);
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001362
1363exit:
Victor Stinner4d231bc2019-11-14 13:36:21 +01001364 for (Py_ssize_t i=0; i < nargs; i++) {
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001365 Py_DECREF(stack[i]);
1366 }
1367 if (stack != small_stack) {
1368 PyMem_Free(stack);
1369 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001371}
1372
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001373static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301374map_reduce(mapobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001375{
1376 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1377 PyObject *args = PyTuple_New(numargs+1);
1378 Py_ssize_t i;
1379 if (args == NULL)
1380 return NULL;
1381 Py_INCREF(lz->func);
1382 PyTuple_SET_ITEM(args, 0, lz->func);
1383 for (i = 0; i<numargs; i++){
1384 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1385 Py_INCREF(it);
1386 PyTuple_SET_ITEM(args, i+1, it);
1387 }
1388
1389 return Py_BuildValue("ON", Py_TYPE(lz), args);
1390}
1391
1392static PyMethodDef map_methods[] = {
1393 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1394 {NULL, NULL} /* sentinel */
1395};
1396
1397
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001398PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001399"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001400\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001401Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001403
Raymond Hettingera6c60372008-03-13 01:26:19 +00001404PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1406 "map", /* tp_name */
1407 sizeof(mapobject), /* tp_basicsize */
1408 0, /* tp_itemsize */
1409 /* methods */
1410 (destructor)map_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001411 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 0, /* tp_getattr */
1413 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001414 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 0, /* tp_repr */
1416 0, /* tp_as_number */
1417 0, /* tp_as_sequence */
1418 0, /* tp_as_mapping */
1419 0, /* tp_hash */
1420 0, /* tp_call */
1421 0, /* tp_str */
1422 PyObject_GenericGetAttr, /* tp_getattro */
1423 0, /* tp_setattro */
1424 0, /* tp_as_buffer */
1425 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1426 Py_TPFLAGS_BASETYPE, /* tp_flags */
1427 map_doc, /* tp_doc */
1428 (traverseproc)map_traverse, /* tp_traverse */
1429 0, /* tp_clear */
1430 0, /* tp_richcompare */
1431 0, /* tp_weaklistoffset */
1432 PyObject_SelfIter, /* tp_iter */
1433 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001434 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 0, /* tp_members */
1436 0, /* tp_getset */
1437 0, /* tp_base */
1438 0, /* tp_dict */
1439 0, /* tp_descr_get */
1440 0, /* tp_descr_set */
1441 0, /* tp_dictoffset */
1442 0, /* tp_init */
1443 PyType_GenericAlloc, /* tp_alloc */
1444 map_new, /* tp_new */
1445 PyObject_GC_Del, /* tp_free */
Dong-hee Na86883d42021-03-22 19:01:14 +09001446 .tp_vectorcall = (vectorcallfunc)map_vectorcall
Raymond Hettingera6c60372008-03-13 01:26:19 +00001447};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001448
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001449
1450/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001451static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001452builtin_next(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Georg Brandla18af4e2007-04-21 15:47:16 +00001453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 PyObject *it, *res;
Georg Brandla18af4e2007-04-21 15:47:16 +00001455
Serhiy Storchaka79342662019-01-12 08:25:41 +02001456 if (!_PyArg_CheckPositional("next", nargs, 1, 2))
Sylvain96c7c062017-06-15 17:05:23 +02001457 return NULL;
1458
Serhiy Storchaka79342662019-01-12 08:25:41 +02001459 it = args[0];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 if (!PyIter_Check(it)) {
1461 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001462 "'%.200s' object is not an iterator",
Victor Stinnera102ed72020-02-07 02:24:48 +01001463 Py_TYPE(it)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 return NULL;
1465 }
1466
Victor Stinnera102ed72020-02-07 02:24:48 +01001467 res = (*Py_TYPE(it)->tp_iternext)(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 if (res != NULL) {
1469 return res;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001470 } else if (nargs > 1) {
1471 PyObject *def = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 if (PyErr_Occurred()) {
1473 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1474 return NULL;
1475 PyErr_Clear();
1476 }
1477 Py_INCREF(def);
1478 return def;
1479 } else if (PyErr_Occurred()) {
1480 return NULL;
1481 } else {
1482 PyErr_SetNone(PyExc_StopIteration);
1483 return NULL;
1484 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001485}
1486
1487PyDoc_STRVAR(next_doc,
1488"next(iterator[, default])\n\
1489\n\
1490Return the next item from the iterator. If default is given and the iterator\n\
1491is exhausted, it is returned instead of raising StopIteration.");
1492
1493
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001494/*[clinic input]
1495setattr as builtin_setattr
1496
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001497 obj: object
1498 name: object
1499 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001500 /
1501
1502Sets the named attribute on the given object to the specified value.
1503
1504setattr(x, 'y', v) is equivalent to ``x.y = v''
1505[clinic start generated code]*/
1506
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001507static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001508builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001509 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001510/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001511{
1512 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001514 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001515}
1516
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001517
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001518/*[clinic input]
1519delattr as builtin_delattr
1520
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001521 obj: object
1522 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001523 /
1524
1525Deletes the named attribute from the given object.
1526
1527delattr(x, 'y') is equivalent to ``del x.y''
1528[clinic start generated code]*/
1529
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001530static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001531builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1532/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001533{
1534 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001536 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001537}
1538
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001539
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001540/*[clinic input]
1541hash as builtin_hash
1542
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001543 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001544 /
1545
1546Return the hash value for the given object.
1547
1548Two objects that compare equal must also have the same hash value, but the
1549reverse is not necessarily true.
1550[clinic start generated code]*/
1551
Guido van Rossum79f25d91997-04-29 20:08:16 +00001552static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001553builtin_hash(PyObject *module, PyObject *obj)
1554/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001555{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001556 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001557
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001558 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 if (x == -1)
1560 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001561 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001562}
1563
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001564
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001565/*[clinic input]
1566hex as builtin_hex
1567
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001568 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001569 /
1570
1571Return the hexadecimal representation of an integer.
1572
1573 >>> hex(12648430)
1574 '0xc0ffee'
1575[clinic start generated code]*/
1576
Guido van Rossum79f25d91997-04-29 20:08:16 +00001577static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001578builtin_hex(PyObject *module, PyObject *number)
1579/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001580{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001581 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001582}
1583
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001584
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001585/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001586static PyObject *
Serhiy Storchaka79342662019-01-12 08:25:41 +02001587builtin_iter(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001588{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001589 PyObject *v;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001590
Serhiy Storchaka79342662019-01-12 08:25:41 +02001591 if (!_PyArg_CheckPositional("iter", nargs, 1, 2))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 return NULL;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001593 v = args[0];
1594 if (nargs == 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 return PyObject_GetIter(v);
1596 if (!PyCallable_Check(v)) {
1597 PyErr_SetString(PyExc_TypeError,
1598 "iter(v, w): v must be callable");
1599 return NULL;
1600 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001601 PyObject *sentinel = args[1];
1602 return PyCallIter_New(v, sentinel);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001603}
1604
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001605PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001606"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001607iter(callable, sentinel) -> iterator\n\
1608\n\
1609Get an iterator from an object. In the first form, the argument must\n\
1610supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001611In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001612
1613
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001614/*[clinic input]
1615len as builtin_len
1616
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001617 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001618 /
1619
1620Return the number of items in a container.
1621[clinic start generated code]*/
1622
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001623static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001624builtin_len(PyObject *module, PyObject *obj)
1625/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001628
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001629 res = PyObject_Size(obj);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001630 if (res < 0) {
1631 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 return NULL;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001633 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001635}
1636
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001637
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001638/*[clinic input]
1639locals as builtin_locals
1640
1641Return a dictionary containing the current scope's local variables.
1642
1643NOTE: Whether or not updates to this dictionary will affect name lookups in
1644the local scope and vice-versa is *implementation dependent* and not
1645covered by any backwards compatibility guarantees.
1646[clinic start generated code]*/
1647
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001648static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001649builtin_locals_impl(PyObject *module)
1650/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 d = PyEval_GetLocals();
1655 Py_XINCREF(d);
1656 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001657}
1658
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001659
Guido van Rossum79f25d91997-04-29 20:08:16 +00001660static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001661min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001664 PyObject *emptytuple, *defaultval = NULL;
1665 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001667 const int positional = PyTuple_Size(args) > 1;
1668 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001669
Dong-hee Naabdc6342020-01-11 01:31:43 +09001670 if (positional) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 v = args;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001672 }
1673 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v)) {
1674 if (PyExceptionClass_Check(PyExc_TypeError)) {
1675 PyErr_Format(PyExc_TypeError, "%s expected at least 1 argument, got 0", name);
1676 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 return NULL;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001678 }
Tim Peters67d687a2002-04-29 21:27:32 +00001679
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001680 emptytuple = PyTuple_New(0);
1681 if (emptytuple == NULL)
1682 return NULL;
Oren Milman58cf7482017-08-21 20:19:07 +03001683 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1684 (op == Py_LT) ? "|$OO:min" : "|$OO:max",
1685 kwlist, &keyfunc, &defaultval);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001686 Py_DECREF(emptytuple);
1687 if (!ret)
1688 return NULL;
1689
1690 if (positional && defaultval != NULL) {
1691 PyErr_Format(PyExc_TypeError,
1692 "Cannot specify a default for %s() with multiple "
1693 "positional arguments", name);
1694 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 it = PyObject_GetIter(v);
1698 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 return NULL;
1700 }
Tim Petersc3074532001-05-03 07:00:32 +00001701
Alexander Marshalove22072f2018-07-24 10:58:21 +07001702 if (keyfunc == Py_None) {
1703 keyfunc = NULL;
1704 }
1705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 maxitem = NULL; /* the result */
1707 maxval = NULL; /* the value associated with the result */
1708 while (( item = PyIter_Next(it) )) {
1709 /* get the value from the key function */
1710 if (keyfunc != NULL) {
Petr Viktorinffd97532020-02-11 17:46:57 +01001711 val = PyObject_CallOneArg(keyfunc, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 if (val == NULL)
1713 goto Fail_it_item;
1714 }
1715 /* no key function; the value is the item */
1716 else {
1717 val = item;
1718 Py_INCREF(val);
1719 }
Tim Petersc3074532001-05-03 07:00:32 +00001720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 /* maximum value and item are unset; set them */
1722 if (maxval == NULL) {
1723 maxitem = item;
1724 maxval = val;
1725 }
1726 /* maximum value and item are set; update them as necessary */
1727 else {
1728 int cmp = PyObject_RichCompareBool(val, maxval, op);
1729 if (cmp < 0)
1730 goto Fail_it_item_and_val;
1731 else if (cmp > 0) {
1732 Py_DECREF(maxval);
1733 Py_DECREF(maxitem);
1734 maxval = val;
1735 maxitem = item;
1736 }
1737 else {
1738 Py_DECREF(item);
1739 Py_DECREF(val);
1740 }
1741 }
1742 }
1743 if (PyErr_Occurred())
1744 goto Fail_it;
1745 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001747 if (defaultval != NULL) {
1748 Py_INCREF(defaultval);
1749 maxitem = defaultval;
1750 } else {
1751 PyErr_Format(PyExc_ValueError,
1752 "%s() arg is an empty sequence", name);
1753 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 }
1755 else
1756 Py_DECREF(maxval);
1757 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001759
1760Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001762Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001764Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 Py_XDECREF(maxval);
1766 Py_XDECREF(maxitem);
1767 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001769}
1770
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001771/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001772static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001773builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001776}
1777
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001778PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001779"min(iterable, *[, default=obj, key=func]) -> value\n\
1780min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001781\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001782With a single iterable argument, return its smallest item. The\n\
1783default keyword-only argument specifies an object to return if\n\
1784the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001785With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001786
1787
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001788/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001789static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001790builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001793}
1794
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001795PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001796"max(iterable, *[, default=obj, key=func]) -> value\n\
1797max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001798\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001799With a single iterable argument, return its biggest item. The\n\
1800default keyword-only argument specifies an object to return if\n\
1801the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001802With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001803
1804
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001805/*[clinic input]
1806oct as builtin_oct
1807
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001808 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001809 /
1810
1811Return the octal representation of an integer.
1812
1813 >>> oct(342391)
1814 '0o1234567'
1815[clinic start generated code]*/
1816
Guido van Rossum79f25d91997-04-29 20:08:16 +00001817static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001818builtin_oct(PyObject *module, PyObject *number)
1819/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001820{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001821 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001822}
1823
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001824
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001825/*[clinic input]
1826ord as builtin_ord
1827
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001828 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001829 /
1830
1831Return the Unicode code point for a one-character string.
1832[clinic start generated code]*/
1833
Guido van Rossum79f25d91997-04-29 20:08:16 +00001834static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001835builtin_ord(PyObject *module, PyObject *c)
1836/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 long ord;
1839 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001840
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001841 if (PyBytes_Check(c)) {
1842 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001844 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 return PyLong_FromLong(ord);
1846 }
1847 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001848 else if (PyUnicode_Check(c)) {
1849 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001850 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001851 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001853 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 return PyLong_FromLong(ord);
1855 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001857 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001859 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001861 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 return PyLong_FromLong(ord);
1863 }
1864 }
1865 else {
1866 PyErr_Format(PyExc_TypeError,
1867 "ord() expected string of length 1, but " \
Victor Stinnera102ed72020-02-07 02:24:48 +01001868 "%.200s found", Py_TYPE(c)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 return NULL;
1870 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 PyErr_Format(PyExc_TypeError,
1873 "ord() expected a character, "
1874 "but string of length %zd found",
1875 size);
1876 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001877}
1878
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001879
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001880/*[clinic input]
1881pow as builtin_pow
1882
Ammar Askar87d6cd32019-09-21 00:28:49 -04001883 base: object
1884 exp: object
1885 mod: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001886
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001887Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001888
1889Some types, such as ints, are able to use a more efficient algorithm when
1890invoked using the three argument form.
1891[clinic start generated code]*/
1892
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001893static PyObject *
Ammar Askar87d6cd32019-09-21 00:28:49 -04001894builtin_pow_impl(PyObject *module, PyObject *base, PyObject *exp,
1895 PyObject *mod)
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001896/*[clinic end generated code: output=3ca1538221bbf15f input=435dbd48a12efb23]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001897{
Ammar Askar87d6cd32019-09-21 00:28:49 -04001898 return PyNumber_Power(base, exp, mod);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001899}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001900
1901
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001902/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001903static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001904builtin_print(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001905{
INADA Naokibd584f12017-01-19 12:50:34 +01001906 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001907 static struct _PyArg_Parser _parser = {"|OOOp:print", _keywords, 0};
1908 PyObject *sep = NULL, *end = NULL, *file = NULL;
1909 int flush = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001911
INADA Naokibd584f12017-01-19 12:50:34 +01001912 if (kwnames != NULL &&
1913 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1914 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001915 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001916 }
1917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001919 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001920 if (file == NULL) {
1921 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1922 return NULL;
1923 }
1924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 /* sys.stdout may be None when FILE* stdout isn't connected */
1926 if (file == Py_None)
1927 Py_RETURN_NONE;
1928 }
Guido van Rossum34343512006-11-30 22:13:52 +00001929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 if (sep == Py_None) {
1931 sep = NULL;
1932 }
1933 else if (sep && !PyUnicode_Check(sep)) {
1934 PyErr_Format(PyExc_TypeError,
1935 "sep must be None or a string, not %.200s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001936 Py_TYPE(sep)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 return NULL;
1938 }
1939 if (end == Py_None) {
1940 end = NULL;
1941 }
1942 else if (end && !PyUnicode_Check(end)) {
1943 PyErr_Format(PyExc_TypeError,
1944 "end must be None or a string, not %.200s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001945 Py_TYPE(end)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 return NULL;
1947 }
Guido van Rossum34343512006-11-30 22:13:52 +00001948
INADA Naokibd584f12017-01-19 12:50:34 +01001949 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 if (i > 0) {
1951 if (sep == NULL)
1952 err = PyFile_WriteString(" ", file);
1953 else
1954 err = PyFile_WriteObject(sep, file,
1955 Py_PRINT_RAW);
1956 if (err)
1957 return NULL;
1958 }
INADA Naokibd584f12017-01-19 12:50:34 +01001959 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 if (err)
1961 return NULL;
1962 }
Guido van Rossum34343512006-11-30 22:13:52 +00001963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 if (end == NULL)
1965 err = PyFile_WriteString("\n", file);
1966 else
1967 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1968 if (err)
1969 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001970
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001971 if (flush) {
1972 PyObject *tmp = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
1973 if (tmp == NULL)
Georg Brandlbc3b6822012-01-13 19:41:25 +01001974 return NULL;
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001975 Py_DECREF(tmp);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001976 }
1977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001979}
1980
1981PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001982"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001983\n\
1984Prints the values to a stream, or to sys.stdout by default.\n\
1985Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001986file: a file-like object (stream); defaults to the current sys.stdout.\n\
1987sep: string inserted between values, default a space.\n\
1988end: string appended after the last value, default a newline.\n\
1989flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001990
1991
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001992/*[clinic input]
1993input as builtin_input
1994
1995 prompt: object(c_default="NULL") = None
1996 /
1997
1998Read a string from standard input. The trailing newline is stripped.
1999
2000The prompt string, if given, is printed to standard output without a
2001trailing newline before reading input.
2002
2003If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
2004On *nix systems, readline is used if available.
2005[clinic start generated code]*/
2006
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002007static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002008builtin_input_impl(PyObject *module, PyObject *prompt)
2009/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002010{
Victor Stinnerbd303c12013-11-07 23:07:29 +01002011 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
2012 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
2013 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 PyObject *tmp;
2015 long fd;
2016 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00002017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 /* Check that stdin/out/err are intact */
2019 if (fin == NULL || fin == Py_None) {
2020 PyErr_SetString(PyExc_RuntimeError,
2021 "input(): lost sys.stdin");
2022 return NULL;
2023 }
2024 if (fout == NULL || fout == Py_None) {
2025 PyErr_SetString(PyExc_RuntimeError,
2026 "input(): lost sys.stdout");
2027 return NULL;
2028 }
2029 if (ferr == NULL || ferr == Py_None) {
2030 PyErr_SetString(PyExc_RuntimeError,
2031 "input(): lost sys.stderr");
2032 return NULL;
2033 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002034
Steve Dowerb82e17e2019-05-23 08:45:22 -07002035 if (PySys_Audit("builtins.input", "O", prompt ? prompt : Py_None) < 0) {
2036 return NULL;
2037 }
2038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 /* First of all, flush stderr */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002040 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 if (tmp == NULL)
2042 PyErr_Clear();
2043 else
2044 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00002045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 /* We should only use (GNU) readline if Python's sys.stdin and
2047 sys.stdout are the same as C's stdin and stdout, because we
2048 need to pass it those. */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002049 tmp = _PyObject_CallMethodIdNoArgs(fin, &PyId_fileno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 if (tmp == NULL) {
2051 PyErr_Clear();
2052 tty = 0;
2053 }
2054 else {
2055 fd = PyLong_AsLong(tmp);
2056 Py_DECREF(tmp);
2057 if (fd < 0 && PyErr_Occurred())
2058 return NULL;
2059 tty = fd == fileno(stdin) && isatty(fd);
2060 }
2061 if (tty) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002062 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_fileno);
Martin Panterc9a6ab52015-10-10 01:25:38 +00002063 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00002065 tty = 0;
2066 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 else {
2068 fd = PyLong_AsLong(tmp);
2069 Py_DECREF(tmp);
2070 if (fd < 0 && PyErr_Occurred())
2071 return NULL;
2072 tty = fd == fileno(stdout) && isatty(fd);
2073 }
2074 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 /* If we're interactive, use (GNU) readline */
2077 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002078 PyObject *po = NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002079 const char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002080 char *s = NULL;
2081 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
2082 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002083 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002085 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00002086
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002087 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002088 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002089 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002090 if (!stdin_encoding || !stdin_errors ||
2091 !PyUnicode_Check(stdin_encoding) ||
2092 !PyUnicode_Check(stdin_errors)) {
2093 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002094 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002095 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002096 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
2097 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002098 if (!stdin_encoding_str || !stdin_errors_str)
2099 goto _readline_errors;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002100 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 if (tmp == NULL)
2102 PyErr_Clear();
2103 else
2104 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002105 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002106 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002107 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002109 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002110 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002111 if (!stdout_encoding || !stdout_errors ||
2112 !PyUnicode_Check(stdout_encoding) ||
2113 !PyUnicode_Check(stdout_errors)) {
2114 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002115 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002116 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002117 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
2118 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002119 if (!stdout_encoding_str || !stdout_errors_str)
2120 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002121 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002122 if (stringpo == NULL)
2123 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002125 stdout_encoding_str, stdout_errors_str);
2126 Py_CLEAR(stdout_encoding);
2127 Py_CLEAR(stdout_errors);
2128 Py_CLEAR(stringpo);
2129 if (po == NULL)
2130 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03002131 assert(PyBytes_Check(po));
2132 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 }
2134 else {
2135 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002136 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002138 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002140 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 if (!PyErr_Occurred())
2142 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002143 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002145
2146 len = strlen(s);
2147 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 PyErr_SetNone(PyExc_EOFError);
2149 result = NULL;
2150 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002151 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 if (len > PY_SSIZE_T_MAX) {
2153 PyErr_SetString(PyExc_OverflowError,
2154 "input: input too long");
2155 result = NULL;
2156 }
2157 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002158 len--; /* strip trailing '\n' */
2159 if (len != 0 && s[len-1] == '\r')
2160 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002161 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2162 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 }
2164 }
2165 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002166 Py_DECREF(stdin_errors);
2167 Py_XDECREF(po);
Victor Stinner00d7abd2020-12-01 09:56:42 +01002168 PyMem_Free(s);
Steve Dowerb82e17e2019-05-23 08:45:22 -07002169
2170 if (result != NULL) {
2171 if (PySys_Audit("builtins.input/result", "O", result) < 0) {
2172 return NULL;
2173 }
2174 }
2175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002177
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002178 _readline_errors:
2179 Py_XDECREF(stdin_encoding);
2180 Py_XDECREF(stdout_encoding);
2181 Py_XDECREF(stdin_errors);
2182 Py_XDECREF(stdout_errors);
2183 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002184 if (tty)
2185 return NULL;
2186
2187 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002191 if (prompt != NULL) {
2192 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 return NULL;
2194 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002195 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 if (tmp == NULL)
2197 PyErr_Clear();
2198 else
2199 Py_DECREF(tmp);
2200 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002201}
2202
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002203
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002204/*[clinic input]
2205repr as builtin_repr
2206
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002207 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002208 /
2209
2210Return the canonical string representation of the object.
2211
2212For many object types, including most builtins, eval(repr(obj)) == obj.
2213[clinic start generated code]*/
2214
Guido van Rossum79f25d91997-04-29 20:08:16 +00002215static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002216builtin_repr(PyObject *module, PyObject *obj)
2217/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002218{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002219 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002220}
2221
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002222
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002223/*[clinic input]
2224round as builtin_round
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002225
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002226 number: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002227 ndigits: object = None
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002228
2229Round a number to a given precision in decimal digits.
2230
2231The return value is an integer if ndigits is omitted or None. Otherwise
2232the return value has the same type as the number. ndigits may be negative.
2233[clinic start generated code]*/
2234
2235static PyObject *
2236builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002237/*[clinic end generated code: output=ff0d9dd176c02ede input=275678471d7aca15]*/
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002238{
2239 PyObject *round, *result;
Alex Martelliae211f92007-08-22 23:21:33 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 if (Py_TYPE(number)->tp_dict == NULL) {
2242 if (PyType_Ready(Py_TYPE(number)) < 0)
2243 return NULL;
2244 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002245
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002246 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002248 if (!PyErr_Occurred())
2249 PyErr_Format(PyExc_TypeError,
2250 "type %.100s doesn't define __round__ method",
2251 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 return NULL;
2253 }
Alex Martelliae211f92007-08-22 23:21:33 +00002254
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002255 if (ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002256 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 else
Petr Viktorinffd97532020-02-11 17:46:57 +01002258 result = PyObject_CallOneArg(round, ndigits);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002259 Py_DECREF(round);
2260 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002261}
2262
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002263
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002264/*AC: we need to keep the kwds dict intact to easily call into the
2265 * list.sort method, which isn't currently supported in AC. So we just use
2266 * the initially generated signature with a custom implementation.
2267 */
2268/* [disabled clinic input]
2269sorted as builtin_sorted
2270
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002271 iterable as seq: object
2272 key as keyfunc: object = None
2273 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002274
2275Return a new list containing all items from the iterable in ascending order.
2276
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002277A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002278reverse flag can be set to request the result in descending order.
2279[end disabled clinic input]*/
2280
2281PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002282"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002283"--\n"
2284"\n"
2285"Return a new list containing all items from the iterable in ascending order.\n"
2286"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002287"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002288"reverse flag can be set to request the result in descending order.");
2289
2290#define BUILTIN_SORTED_METHODDEF \
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002291 {"sorted", (PyCFunction)(void(*)(void))builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002292
Raymond Hettinger64958a12003-12-17 20:43:33 +00002293static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02002294builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002295{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002296 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002297
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002298 /* Keyword arguments are passed through list.sort() which will check
2299 them. */
2300 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 newlist = PySequence_List(seq);
2304 if (newlist == NULL)
2305 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002306
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002307 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 if (callable == NULL) {
2309 Py_DECREF(newlist);
2310 return NULL;
2311 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002312
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002313 assert(nargs >= 1);
Petr Viktorinffd97532020-02-11 17:46:57 +01002314 v = PyObject_Vectorcall(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 Py_DECREF(callable);
2316 if (v == NULL) {
2317 Py_DECREF(newlist);
2318 return NULL;
2319 }
2320 Py_DECREF(v);
2321 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002322}
2323
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002324
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002325/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002326static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002327builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 PyObject *v = NULL;
2330 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2333 return NULL;
2334 if (v == NULL) {
2335 d = PyEval_GetLocals();
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002336 Py_XINCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 }
2338 else {
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002339 if (_PyObject_LookupAttrId(v, &PyId___dict__, &d) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 PyErr_SetString(PyExc_TypeError,
2341 "vars() argument must have __dict__ attribute");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 }
2343 }
2344 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002345}
2346
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002347PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002348"vars([object]) -> dictionary\n\
2349\n\
2350Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002351With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002352
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002353
2354/*[clinic input]
2355sum as builtin_sum
2356
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002357 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002358 /
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002359 start: object(c_default="NULL") = 0
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002360
2361Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2362
2363When the iterable is empty, return the start value.
2364This function is intended specifically for use with numeric values and may
2365reject non-numeric types.
2366[clinic start generated code]*/
2367
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002368static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002369builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002370/*[clinic end generated code: output=df758cec7d1d302f input=162b50765250d222]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002371{
2372 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002374
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002375 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 if (iter == NULL)
2377 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 if (result == NULL) {
2380 result = PyLong_FromLong(0);
2381 if (result == NULL) {
2382 Py_DECREF(iter);
2383 return NULL;
2384 }
2385 } else {
2386 /* reject string values for 'start' parameter */
2387 if (PyUnicode_Check(result)) {
2388 PyErr_SetString(PyExc_TypeError,
2389 "sum() can't sum strings [use ''.join(seq) instead]");
2390 Py_DECREF(iter);
2391 return NULL;
2392 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002393 if (PyBytes_Check(result)) {
2394 PyErr_SetString(PyExc_TypeError,
2395 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002396 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002397 return NULL;
2398 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 if (PyByteArray_Check(result)) {
2400 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002401 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 Py_DECREF(iter);
2403 return NULL;
2404 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 Py_INCREF(result);
2406 }
Alex Martellia70b1912003-04-22 08:12:33 +00002407
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002408#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2410 Assumes all inputs are the same type. If the assumption fails, default
2411 to the more general routine.
2412 */
2413 if (PyLong_CheckExact(result)) {
2414 int overflow;
2415 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2416 /* If this already overflowed, don't even enter the loop. */
2417 if (overflow == 0) {
2418 Py_DECREF(result);
2419 result = NULL;
2420 }
2421 while(result == NULL) {
2422 item = PyIter_Next(iter);
2423 if (item == NULL) {
2424 Py_DECREF(iter);
2425 if (PyErr_Occurred())
2426 return NULL;
2427 return PyLong_FromLong(i_result);
2428 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002429 if (PyLong_CheckExact(item) || PyBool_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 long b = PyLong_AsLongAndOverflow(item, &overflow);
Serhiy Storchaka29500732019-05-05 14:26:23 +03002431 if (overflow == 0 &&
2432 (i_result >= 0 ? (b <= LONG_MAX - i_result)
2433 : (b >= LONG_MIN - i_result)))
2434 {
2435 i_result += b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 Py_DECREF(item);
2437 continue;
2438 }
2439 }
2440 /* Either overflowed or is not an int. Restore real objects and process normally */
2441 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002442 if (result == NULL) {
2443 Py_DECREF(item);
2444 Py_DECREF(iter);
2445 return NULL;
2446 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 temp = PyNumber_Add(result, item);
2448 Py_DECREF(result);
2449 Py_DECREF(item);
2450 result = temp;
2451 if (result == NULL) {
2452 Py_DECREF(iter);
2453 return NULL;
2454 }
2455 }
2456 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 if (PyFloat_CheckExact(result)) {
2459 double f_result = PyFloat_AS_DOUBLE(result);
2460 Py_DECREF(result);
2461 result = NULL;
2462 while(result == NULL) {
2463 item = PyIter_Next(iter);
2464 if (item == NULL) {
2465 Py_DECREF(iter);
2466 if (PyErr_Occurred())
2467 return NULL;
2468 return PyFloat_FromDouble(f_result);
2469 }
2470 if (PyFloat_CheckExact(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 f_result += PyFloat_AS_DOUBLE(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 Py_DECREF(item);
2473 continue;
2474 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002475 if (PyLong_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 long value;
2477 int overflow;
2478 value = PyLong_AsLongAndOverflow(item, &overflow);
2479 if (!overflow) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 f_result += (double)value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 Py_DECREF(item);
2482 continue;
2483 }
2484 }
2485 result = PyFloat_FromDouble(f_result);
Alexey Izbyshev2b824b22018-08-24 07:27:52 +03002486 if (result == NULL) {
2487 Py_DECREF(item);
2488 Py_DECREF(iter);
2489 return NULL;
2490 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 temp = PyNumber_Add(result, item);
2492 Py_DECREF(result);
2493 Py_DECREF(item);
2494 result = temp;
2495 if (result == NULL) {
2496 Py_DECREF(iter);
2497 return NULL;
2498 }
2499 }
2500 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002501#endif
2502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 for(;;) {
2504 item = PyIter_Next(iter);
2505 if (item == NULL) {
2506 /* error, or end-of-sequence */
2507 if (PyErr_Occurred()) {
2508 Py_DECREF(result);
2509 result = NULL;
2510 }
2511 break;
2512 }
2513 /* It's tempting to use PyNumber_InPlaceAdd instead of
2514 PyNumber_Add here, to avoid quadratic running time
2515 when doing 'sum(list_of_lists, [])'. However, this
2516 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 empty = []
2519 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002520
Brandt Bucherabb9a442020-02-01 03:08:34 -08002521 would change the value of empty. In fact, using
2522 in-place addition rather that binary addition for
2523 any of the steps introduces subtle behavior changes:
Victor Stinner58f4e1a2020-02-05 18:24:33 +01002524
Brandt Bucherabb9a442020-02-01 03:08:34 -08002525 https://bugs.python.org/issue18305 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 temp = PyNumber_Add(result, item);
2527 Py_DECREF(result);
2528 Py_DECREF(item);
2529 result = temp;
2530 if (result == NULL)
2531 break;
2532 }
2533 Py_DECREF(iter);
2534 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002535}
2536
Alex Martellia70b1912003-04-22 08:12:33 +00002537
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002538/*[clinic input]
2539isinstance as builtin_isinstance
2540
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002541 obj: object
2542 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002543 /
2544
2545Return whether an object is an instance of a class or of a subclass thereof.
2546
2547A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2548check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2549or ...`` etc.
2550[clinic start generated code]*/
2551
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002552static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002553builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002554 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002555/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002558
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002559 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 if (retval < 0)
2561 return NULL;
2562 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002563}
2564
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002565
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002566/*[clinic input]
2567issubclass as builtin_issubclass
2568
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002569 cls: object
2570 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002571 /
2572
Alex Poveldf773f82020-06-03 15:19:45 +02002573Return whether 'cls' is derived from another class or is the same class.
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002574
2575A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2576check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
Alex Poveldf773f82020-06-03 15:19:45 +02002577or ...``.
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002578[clinic start generated code]*/
2579
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002580static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002581builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002582 PyObject *class_or_tuple)
Alex Poveldf773f82020-06-03 15:19:45 +02002583/*[clinic end generated code: output=358412410cd7a250 input=a24b9f3d58c370d6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002586
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002587 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 if (retval < 0)
2589 return NULL;
2590 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002591}
2592
2593
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002594typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 PyObject_HEAD
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002596 Py_ssize_t tuplesize;
2597 PyObject *ittuple; /* tuple of iterators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 PyObject *result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002599 int strict;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002600} zipobject;
2601
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002602static PyObject *
2603zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 zipobject *lz;
2606 Py_ssize_t i;
2607 PyObject *ittuple; /* tuple of iterators */
2608 PyObject *result;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002609 Py_ssize_t tuplesize;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002610 int strict = 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002611
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002612 if (kwds) {
2613 PyObject *empty = PyTuple_New(0);
2614 if (empty == NULL) {
2615 return NULL;
2616 }
2617 static char *kwlist[] = {"strict", NULL};
2618 int parsed = PyArg_ParseTupleAndKeywords(
2619 empty, kwds, "|$p:zip", kwlist, &strict);
2620 Py_DECREF(empty);
2621 if (!parsed) {
2622 return NULL;
2623 }
2624 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 /* args must be a tuple */
2627 assert(PyTuple_Check(args));
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002628 tuplesize = PyTuple_GET_SIZE(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00002629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 /* obtain iterators */
2631 ittuple = PyTuple_New(tuplesize);
2632 if (ittuple == NULL)
2633 return NULL;
2634 for (i=0; i < tuplesize; ++i) {
2635 PyObject *item = PyTuple_GET_ITEM(args, i);
2636 PyObject *it = PyObject_GetIter(item);
2637 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 Py_DECREF(ittuple);
2639 return NULL;
2640 }
2641 PyTuple_SET_ITEM(ittuple, i, it);
2642 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 /* create a result holder */
2645 result = PyTuple_New(tuplesize);
2646 if (result == NULL) {
2647 Py_DECREF(ittuple);
2648 return NULL;
2649 }
2650 for (i=0 ; i < tuplesize ; i++) {
2651 Py_INCREF(Py_None);
2652 PyTuple_SET_ITEM(result, i, Py_None);
2653 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 /* create zipobject structure */
2656 lz = (zipobject *)type->tp_alloc(type, 0);
2657 if (lz == NULL) {
2658 Py_DECREF(ittuple);
2659 Py_DECREF(result);
2660 return NULL;
2661 }
2662 lz->ittuple = ittuple;
2663 lz->tuplesize = tuplesize;
2664 lz->result = result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002665 lz->strict = strict;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002668}
2669
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002670static void
2671zip_dealloc(zipobject *lz)
2672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 PyObject_GC_UnTrack(lz);
2674 Py_XDECREF(lz->ittuple);
2675 Py_XDECREF(lz->result);
2676 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002677}
2678
2679static int
2680zip_traverse(zipobject *lz, visitproc visit, void *arg)
2681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 Py_VISIT(lz->ittuple);
2683 Py_VISIT(lz->result);
2684 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002685}
2686
2687static PyObject *
2688zip_next(zipobject *lz)
2689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 Py_ssize_t i;
2691 Py_ssize_t tuplesize = lz->tuplesize;
2692 PyObject *result = lz->result;
2693 PyObject *it;
2694 PyObject *item;
2695 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 if (tuplesize == 0)
2698 return NULL;
2699 if (Py_REFCNT(result) == 1) {
2700 Py_INCREF(result);
2701 for (i=0 ; i < tuplesize ; i++) {
2702 it = PyTuple_GET_ITEM(lz->ittuple, i);
2703 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002704 if (item == NULL) {
2705 Py_DECREF(result);
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002706 if (lz->strict) {
2707 goto check;
2708 }
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002709 return NULL;
2710 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 olditem = PyTuple_GET_ITEM(result, i);
2712 PyTuple_SET_ITEM(result, i, item);
2713 Py_DECREF(olditem);
2714 }
Brandt Bucher226a0122020-12-04 19:45:57 -08002715 // bpo-42536: The GC may have untracked this result tuple. Since we're
2716 // recycling it, make sure it's tracked again:
2717 if (!_PyObject_GC_IS_TRACKED(result)) {
2718 _PyObject_GC_TRACK(result);
2719 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 } else {
2721 result = PyTuple_New(tuplesize);
2722 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002723 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 for (i=0 ; i < tuplesize ; i++) {
2725 it = PyTuple_GET_ITEM(lz->ittuple, i);
2726 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002727 if (item == NULL) {
2728 Py_DECREF(result);
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002729 if (lz->strict) {
2730 goto check;
2731 }
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002732 return NULL;
2733 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 PyTuple_SET_ITEM(result, i, item);
2735 }
2736 }
2737 return result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002738check:
2739 if (PyErr_Occurred()) {
2740 if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
2741 // next() on argument i raised an exception (not StopIteration)
2742 return NULL;
2743 }
2744 PyErr_Clear();
2745 }
2746 if (i) {
2747 // ValueError: zip() argument 2 is shorter than argument 1
2748 // ValueError: zip() argument 3 is shorter than arguments 1-2
2749 const char* plural = i == 1 ? " " : "s 1-";
2750 return PyErr_Format(PyExc_ValueError,
2751 "zip() argument %d is shorter than argument%s%d",
2752 i + 1, plural, i);
2753 }
2754 for (i = 1; i < tuplesize; i++) {
2755 it = PyTuple_GET_ITEM(lz->ittuple, i);
2756 item = (*Py_TYPE(it)->tp_iternext)(it);
2757 if (item) {
2758 Py_DECREF(item);
2759 const char* plural = i == 1 ? " " : "s 1-";
2760 return PyErr_Format(PyExc_ValueError,
2761 "zip() argument %d is longer than argument%s%d",
2762 i + 1, plural, i);
2763 }
2764 if (PyErr_Occurred()) {
2765 if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
2766 // next() on argument i raised an exception (not StopIteration)
2767 return NULL;
2768 }
2769 PyErr_Clear();
2770 }
2771 // Argument i is exhausted. So far so good...
2772 }
2773 // All arguments are exhausted. Success!
2774 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002775}
Barry Warsawbd599b52000-08-03 15:45:29 +00002776
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002777static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302778zip_reduce(zipobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002779{
2780 /* Just recreate the zip with the internal iterator tuple */
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002781 if (lz->strict) {
2782 return PyTuple_Pack(3, Py_TYPE(lz), lz->ittuple, Py_True);
2783 }
2784 return PyTuple_Pack(2, Py_TYPE(lz), lz->ittuple);
2785}
2786
2787PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
2788
2789static PyObject *
2790zip_setstate(zipobject *lz, PyObject *state)
2791{
2792 int strict = PyObject_IsTrue(state);
2793 if (strict < 0) {
2794 return NULL;
2795 }
2796 lz->strict = strict;
2797 Py_RETURN_NONE;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002798}
2799
2800static PyMethodDef zip_methods[] = {
2801 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002802 {"__setstate__", (PyCFunction)zip_setstate, METH_O, setstate_doc},
2803 {NULL} /* sentinel */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002804};
2805
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002806PyDoc_STRVAR(zip_doc,
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002807"zip(*iterables, strict=False) --> Yield tuples until an input is exhausted.\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002808\n\
Gregory P. Smith6a5d3ff2020-05-15 14:26:00 -07002809 >>> list(zip('abcdefg', range(3), range(4)))\n\
2810 [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]\n\
2811\n\
2812The zip object yields n-length tuples, where n is the number of iterables\n\
2813passed as positional arguments to zip(). The i-th element in every tuple\n\
2814comes from the i-th iterable argument to zip(). This continues until the\n\
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002815shortest argument is exhausted.\n\
2816\n\
2817If strict is true and one of the arguments is exhausted before the others,\n\
2818raise a ValueError.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002819
2820PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2822 "zip", /* tp_name */
2823 sizeof(zipobject), /* tp_basicsize */
2824 0, /* tp_itemsize */
2825 /* methods */
2826 (destructor)zip_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002827 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 0, /* tp_getattr */
2829 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002830 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 0, /* tp_repr */
2832 0, /* tp_as_number */
2833 0, /* tp_as_sequence */
2834 0, /* tp_as_mapping */
2835 0, /* tp_hash */
2836 0, /* tp_call */
2837 0, /* tp_str */
2838 PyObject_GenericGetAttr, /* tp_getattro */
2839 0, /* tp_setattro */
2840 0, /* tp_as_buffer */
2841 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2842 Py_TPFLAGS_BASETYPE, /* tp_flags */
2843 zip_doc, /* tp_doc */
2844 (traverseproc)zip_traverse, /* tp_traverse */
2845 0, /* tp_clear */
2846 0, /* tp_richcompare */
2847 0, /* tp_weaklistoffset */
2848 PyObject_SelfIter, /* tp_iter */
2849 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002850 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 0, /* tp_members */
2852 0, /* tp_getset */
2853 0, /* tp_base */
2854 0, /* tp_dict */
2855 0, /* tp_descr_get */
2856 0, /* tp_descr_set */
2857 0, /* tp_dictoffset */
2858 0, /* tp_init */
2859 PyType_GenericAlloc, /* tp_alloc */
2860 zip_new, /* tp_new */
2861 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002862};
Barry Warsawbd599b52000-08-03 15:45:29 +00002863
2864
Guido van Rossum79f25d91997-04-29 20:08:16 +00002865static PyMethodDef builtin_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002866 {"__build_class__", (PyCFunction)(void(*)(void))builtin___build_class__,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002867 METH_FASTCALL | METH_KEYWORDS, build_class_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002868 {"__import__", (PyCFunction)(void(*)(void))builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002869 BUILTIN_ABS_METHODDEF
2870 BUILTIN_ALL_METHODDEF
2871 BUILTIN_ANY_METHODDEF
2872 BUILTIN_ASCII_METHODDEF
2873 BUILTIN_BIN_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002874 {"breakpoint", (PyCFunction)(void(*)(void))builtin_breakpoint, METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002875 BUILTIN_CALLABLE_METHODDEF
2876 BUILTIN_CHR_METHODDEF
2877 BUILTIN_COMPILE_METHODDEF
2878 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002880 BUILTIN_DIVMOD_METHODDEF
2881 BUILTIN_EVAL_METHODDEF
2882 BUILTIN_EXEC_METHODDEF
2883 BUILTIN_FORMAT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002884 {"getattr", (PyCFunction)(void(*)(void))builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002885 BUILTIN_GLOBALS_METHODDEF
2886 BUILTIN_HASATTR_METHODDEF
2887 BUILTIN_HASH_METHODDEF
2888 BUILTIN_HEX_METHODDEF
2889 BUILTIN_ID_METHODDEF
2890 BUILTIN_INPUT_METHODDEF
2891 BUILTIN_ISINSTANCE_METHODDEF
2892 BUILTIN_ISSUBCLASS_METHODDEF
Serhiy Storchaka79342662019-01-12 08:25:41 +02002893 {"iter", (PyCFunction)(void(*)(void))builtin_iter, METH_FASTCALL, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002894 BUILTIN_LEN_METHODDEF
2895 BUILTIN_LOCALS_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002896 {"max", (PyCFunction)(void(*)(void))builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2897 {"min", (PyCFunction)(void(*)(void))builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2898 {"next", (PyCFunction)(void(*)(void))builtin_next, METH_FASTCALL, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002899 BUILTIN_OCT_METHODDEF
2900 BUILTIN_ORD_METHODDEF
2901 BUILTIN_POW_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002902 {"print", (PyCFunction)(void(*)(void))builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002903 BUILTIN_REPR_METHODDEF
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002904 BUILTIN_ROUND_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002905 BUILTIN_SETATTR_METHODDEF
2906 BUILTIN_SORTED_METHODDEF
2907 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2909 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002910};
2911
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002912PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002913"Built-in functions, exceptions, and other objects.\n\
2914\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002915Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002916
Martin v. Löwis1a214512008-06-11 05:26:20 +00002917static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 PyModuleDef_HEAD_INIT,
2919 "builtins",
2920 builtin_doc,
2921 -1, /* multiple "initialization" just copies the module dict. */
2922 builtin_methods,
2923 NULL,
2924 NULL,
2925 NULL,
2926 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002927};
2928
2929
Guido van Rossum25ce5661997-08-02 03:10:38 +00002930PyObject *
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002931_PyBuiltin_Init(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002932{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002934
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002935 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002936
Benjamin Peterson42124a72012-10-30 23:41:54 -04002937 if (PyType_Ready(&PyFilter_Type) < 0 ||
2938 PyType_Ready(&PyMap_Type) < 0 ||
2939 PyType_Ready(&PyZip_Type) < 0)
2940 return NULL;
2941
Eric Snowd393c1b2017-09-14 12:18:12 -06002942 mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 if (mod == NULL)
2944 return NULL;
2945 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002946
Tim Peters7571a0f2003-03-23 17:52:28 +00002947#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948 /* "builtins" exposes a number of statically allocated objects
2949 * that, before this code was added in 2.3, never showed up in
2950 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2951 * result, programs leaking references to None and False (etc)
2952 * couldn't be diagnosed by examining sys.getobjects(0).
2953 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002954#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2955#else
2956#define ADD_TO_ALL(OBJECT) (void)0
2957#endif
2958
Tim Peters4b7625e2001-09-13 21:37:17 +00002959#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2961 return NULL; \
2962 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 SETBUILTIN("None", Py_None);
2965 SETBUILTIN("Ellipsis", Py_Ellipsis);
2966 SETBUILTIN("NotImplemented", Py_NotImplemented);
2967 SETBUILTIN("False", Py_False);
2968 SETBUILTIN("True", Py_True);
2969 SETBUILTIN("bool", &PyBool_Type);
2970 SETBUILTIN("memoryview", &PyMemoryView_Type);
2971 SETBUILTIN("bytearray", &PyByteArray_Type);
2972 SETBUILTIN("bytes", &PyBytes_Type);
2973 SETBUILTIN("classmethod", &PyClassMethod_Type);
2974 SETBUILTIN("complex", &PyComplex_Type);
2975 SETBUILTIN("dict", &PyDict_Type);
2976 SETBUILTIN("enumerate", &PyEnum_Type);
2977 SETBUILTIN("filter", &PyFilter_Type);
2978 SETBUILTIN("float", &PyFloat_Type);
2979 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2980 SETBUILTIN("property", &PyProperty_Type);
2981 SETBUILTIN("int", &PyLong_Type);
2982 SETBUILTIN("list", &PyList_Type);
2983 SETBUILTIN("map", &PyMap_Type);
2984 SETBUILTIN("object", &PyBaseObject_Type);
2985 SETBUILTIN("range", &PyRange_Type);
2986 SETBUILTIN("reversed", &PyReversed_Type);
2987 SETBUILTIN("set", &PySet_Type);
2988 SETBUILTIN("slice", &PySlice_Type);
2989 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2990 SETBUILTIN("str", &PyUnicode_Type);
2991 SETBUILTIN("super", &PySuper_Type);
2992 SETBUILTIN("tuple", &PyTuple_Type);
2993 SETBUILTIN("type", &PyType_Type);
2994 SETBUILTIN("zip", &PyZip_Type);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002995 debug = PyBool_FromLong(config->optimization_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002997 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 return NULL;
2999 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03003000 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00003001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00003003#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00003004#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00003005}