blob: 8aa1ba01d659c8add1a210619384995dd3325fc3 [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"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00004#include "Python-ast.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
6#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008
Benjamin Petersonea281a52011-08-12 23:10:50 -05009#include "asdl.h"
10#include "ast.h"
11
Guido van Rossum6bf62da1997-04-11 20:37:35 +000012#include <ctype.h>
13
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;
36 PyObject *stack[1] = {bases};
37 assert(PyTuple_Check(bases));
38
39 for (i = 0; i < nargs; i++) {
40 base = args[i];
41 if (PyType_Check(base)) {
42 if (new_bases) {
43 /* If we already have made a replacement, then we append every normal base,
44 otherwise just skip it. */
45 if (PyList_Append(new_bases, base) < 0) {
46 goto error;
47 }
48 }
49 continue;
50 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +020051 if (_PyObject_LookupAttrId(base, &PyId___mro_entries__, &meth) < 0) {
52 goto error;
53 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010054 if (!meth) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010055 if (new_bases) {
56 if (PyList_Append(new_bases, base) < 0) {
57 goto error;
58 }
59 }
60 continue;
61 }
62 new_base = _PyObject_FastCall(meth, stack, 1);
63 Py_DECREF(meth);
64 if (!new_base) {
65 goto error;
66 }
67 if (!PyTuple_Check(new_base)) {
68 PyErr_SetString(PyExc_TypeError,
69 "__mro_entries__ must return a tuple");
70 Py_DECREF(new_base);
71 goto error;
72 }
73 if (!new_bases) {
74 /* If this is a first successful replacement, create new_bases list and
75 copy previously encountered bases. */
76 if (!(new_bases = PyList_New(i))) {
77 goto error;
78 }
79 for (j = 0; j < i; j++) {
80 base = args[j];
81 PyList_SET_ITEM(new_bases, j, base);
82 Py_INCREF(base);
83 }
84 }
85 j = PyList_GET_SIZE(new_bases);
86 if (PyList_SetSlice(new_bases, j, j, new_base) < 0) {
87 goto error;
88 }
89 Py_DECREF(new_base);
90 }
91 if (!new_bases) {
92 return bases;
93 }
94 result = PyList_AsTuple(new_bases);
95 Py_DECREF(new_bases);
96 return result;
97
98error:
99 Py_XDECREF(new_bases);
100 return NULL;
101}
102
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000103/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000104static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200105builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
Victor Stinner773dc6d2017-01-16 23:46:26 +0100106 PyObject *kwnames)
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000107{
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100108 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *orig_bases;
Nick Coghlan19d24672016-12-05 16:47:55 +1000109 PyObject *cls = NULL, *cell = NULL;
Victor Stinner0c39b1b2015-03-18 15:02:06 +0100110 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 if (nargs < 2) {
113 PyErr_SetString(PyExc_TypeError,
114 "__build_class__: not enough arguments");
115 return NULL;
116 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100117 func = args[0]; /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -0500118 if (!PyFunction_Check(func)) {
119 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -0500120 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -0500121 return NULL;
122 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100123 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 if (!PyUnicode_Check(name)) {
125 PyErr_SetString(PyExc_TypeError,
126 "__build_class__: name is not a string");
127 return NULL;
128 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100129 orig_bases = _PyStack_AsTupleSlice(args, nargs, 2, nargs);
130 if (orig_bases == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000132
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100133 bases = update_bases(orig_bases, args + 2, nargs - 2);
134 if (bases == NULL) {
135 Py_DECREF(orig_bases);
136 return NULL;
137 }
138
Victor Stinner773dc6d2017-01-16 23:46:26 +0100139 if (kwnames == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 meta = NULL;
141 mkw = NULL;
142 }
143 else {
Victor Stinner773dc6d2017-01-16 23:46:26 +0100144 mkw = _PyStack_AsDict(args + nargs, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 if (mkw == NULL) {
146 Py_DECREF(bases);
147 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000148 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100149
Victor Stinnerae9f1612013-11-06 22:46:51 +0100150 meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 if (meta != NULL) {
152 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +0100153 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 Py_DECREF(meta);
155 Py_DECREF(mkw);
156 Py_DECREF(bases);
157 return NULL;
158 }
Nick Coghlande31b192011-10-23 22:04:16 +1000159 /* metaclass is explicitly given, check if it's indeed a class */
160 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 }
162 }
163 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000164 /* if there are no bases, use type: */
165 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000167 }
168 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 else {
170 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
171 meta = (PyObject *) (base0->ob_type);
172 }
173 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000174 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000176
Nick Coghlande31b192011-10-23 22:04:16 +1000177 if (isclass) {
178 /* meta is really a class, so check for a more derived
179 metaclass, or possible metaclass conflicts: */
180 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
181 bases);
182 if (winner == NULL) {
183 Py_DECREF(meta);
184 Py_XDECREF(mkw);
185 Py_DECREF(bases);
186 return NULL;
187 }
188 if (winner != meta) {
189 Py_DECREF(meta);
190 meta = winner;
191 Py_INCREF(meta);
192 }
193 }
194 /* else: meta is not a class, so we cannot do the metaclass
195 calculation, so we will use the explicitly given object as it is */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200196 if (_PyObject_LookupAttrId(meta, &PyId___prepare__, &prep) < 0) {
197 ns = NULL;
198 }
199 else if (prep == NULL) {
200 ns = PyDict_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 }
202 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200203 PyObject *pargs[2] = {name, bases};
204 ns = _PyObject_FastCallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 Py_DECREF(prep);
206 }
207 if (ns == NULL) {
208 Py_DECREF(meta);
209 Py_XDECREF(mkw);
210 Py_DECREF(bases);
211 return NULL;
212 }
Oren Milman5837d042017-09-27 17:04:37 +0300213 if (!PyMapping_Check(ns)) {
214 PyErr_Format(PyExc_TypeError,
215 "%.200s.__prepare__() must return a mapping, not %.200s",
216 isclass ? ((PyTypeObject *)meta)->tp_name : "<metaclass>",
217 Py_TYPE(ns)->tp_name);
218 goto error;
219 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000220 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
Benjamin Petersone8e14592013-05-16 14:37:25 -0500221 NULL, 0, NULL, 0, NULL, 0, NULL,
222 PyFunction_GET_CLOSURE(func));
Nick Coghlan19d24672016-12-05 16:47:55 +1000223 if (cell != NULL) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100224 if (bases != orig_bases) {
225 if (PyMapping_SetItemString(ns, "__orig_bases__", orig_bases) < 0) {
226 goto error;
227 }
228 }
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200229 PyObject *margs[3] = {name, bases, ns};
230 cls = _PyObject_FastCallDict(meta, margs, 3, mkw);
Nick Coghlan19d24672016-12-05 16:47:55 +1000231 if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
232 PyObject *cell_cls = PyCell_GET(cell);
233 if (cell_cls != cls) {
Nick Coghlan19d24672016-12-05 16:47:55 +1000234 if (cell_cls == NULL) {
235 const char *msg =
236 "__class__ not set defining %.200R as %.200R. "
237 "Was __classcell__ propagated to type.__new__?";
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300238 PyErr_Format(PyExc_RuntimeError, msg, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000239 } else {
240 const char *msg =
241 "__class__ set to %.200R defining %.200R as %.200R";
242 PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000243 }
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300244 Py_DECREF(cls);
245 cls = NULL;
246 goto error;
Nick Coghlan19d24672016-12-05 16:47:55 +1000247 }
248 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000250error:
251 Py_XDECREF(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 Py_DECREF(ns);
253 Py_DECREF(meta);
254 Py_XDECREF(mkw);
255 Py_DECREF(bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100256 if (bases != orig_bases) {
257 Py_DECREF(orig_bases);
258 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000260}
261
262PyDoc_STRVAR(build_class_doc,
263"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
264\n\
265Internal helper function used by the class statement.");
266
267static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000268builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
271 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400272 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400273 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000274
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400275 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 kwlist, &name, &globals, &locals, &fromlist, &level))
277 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400278 return PyImport_ImportModuleLevelObject(name, globals, locals,
279 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000280}
281
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000282PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400283"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000284\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000285Import a module. Because this function is meant for use by the Python\n\
oldk461d2252018-02-02 12:20:00 +0800286interpreter and not for general use, it is better to use\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000287importlib.import_module() to programmatically import a module.\n\
288\n\
289The globals argument is only used to determine the context;\n\
290they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000291should be a list of names to emulate ``from name import ...'', or an\n\
292empty list to emulate ``import name''.\n\
293When importing a module from a package, note that __import__('A.B', ...)\n\
294returns package A when fromlist is empty, but its submodule B when\n\
oldk461d2252018-02-02 12:20:00 +0800295fromlist is not empty. The level argument is used to determine whether to\n\
296perform absolute or relative imports: 0 is absolute, while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000297is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000298
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000299
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000300/*[clinic input]
301abs as builtin_abs
302
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300303 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000304 /
305
306Return the absolute value of the argument.
307[clinic start generated code]*/
308
Guido van Rossum79f25d91997-04-29 20:08:16 +0000309static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300310builtin_abs(PyObject *module, PyObject *x)
311/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000312{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000313 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000314}
315
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000316/*[clinic input]
317all as builtin_all
318
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300319 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000320 /
321
322Return True if bool(x) is True for all values x in the iterable.
323
324If the iterable is empty, return True.
325[clinic start generated code]*/
326
Raymond Hettinger96229b12005-03-11 06:49:40 +0000327static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300328builtin_all(PyObject *module, PyObject *iterable)
329/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 PyObject *it, *item;
332 PyObject *(*iternext)(PyObject *);
333 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000334
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000335 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 if (it == NULL)
337 return NULL;
338 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 for (;;) {
341 item = iternext(it);
342 if (item == NULL)
343 break;
344 cmp = PyObject_IsTrue(item);
345 Py_DECREF(item);
346 if (cmp < 0) {
347 Py_DECREF(it);
348 return NULL;
349 }
350 if (cmp == 0) {
351 Py_DECREF(it);
352 Py_RETURN_FALSE;
353 }
354 }
355 Py_DECREF(it);
356 if (PyErr_Occurred()) {
357 if (PyErr_ExceptionMatches(PyExc_StopIteration))
358 PyErr_Clear();
359 else
360 return NULL;
361 }
362 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000363}
364
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000365/*[clinic input]
366any as builtin_any
367
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300368 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000369 /
370
371Return True if bool(x) is True for any x in the iterable.
372
373If the iterable is empty, return False.
374[clinic start generated code]*/
375
Raymond Hettinger96229b12005-03-11 06:49:40 +0000376static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300377builtin_any(PyObject *module, PyObject *iterable)
378/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 PyObject *it, *item;
381 PyObject *(*iternext)(PyObject *);
382 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000383
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000384 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 if (it == NULL)
386 return NULL;
387 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 for (;;) {
390 item = iternext(it);
391 if (item == NULL)
392 break;
393 cmp = PyObject_IsTrue(item);
394 Py_DECREF(item);
395 if (cmp < 0) {
396 Py_DECREF(it);
397 return NULL;
398 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400399 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 Py_DECREF(it);
401 Py_RETURN_TRUE;
402 }
403 }
404 Py_DECREF(it);
405 if (PyErr_Occurred()) {
406 if (PyErr_ExceptionMatches(PyExc_StopIteration))
407 PyErr_Clear();
408 else
409 return NULL;
410 }
411 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000412}
413
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000414/*[clinic input]
415ascii as builtin_ascii
416
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300417 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000418 /
419
420Return an ASCII-only representation of an object.
421
422As repr(), return a string containing a printable representation of an
423object, but escape the non-ASCII characters in the string returned by
424repr() using \\x, \\u or \\U escapes. This generates a string similar
425to that returned by repr() in Python 2.
426[clinic start generated code]*/
427
Georg Brandl559e5d72008-06-11 18:37:52 +0000428static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300429builtin_ascii(PyObject *module, PyObject *obj)
430/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000431{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000432 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000433}
434
Georg Brandl559e5d72008-06-11 18:37:52 +0000435
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000436/*[clinic input]
437bin as builtin_bin
438
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300439 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000440 /
441
442Return the binary representation of an integer.
443
444 >>> bin(2796202)
445 '0b1010101010101010101010'
446[clinic start generated code]*/
447
Guido van Rossum79f25d91997-04-29 20:08:16 +0000448static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300449builtin_bin(PyObject *module, PyObject *number)
450/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000451{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000452 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000453}
454
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000455
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000456/*[clinic input]
457callable as builtin_callable
458
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300459 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000460 /
461
462Return whether the object is callable (i.e., some kind of function).
463
464Note that classes are callable, as are instances of classes with a
465__call__() method.
466[clinic start generated code]*/
467
Antoine Pitroue71362d2010-11-27 22:00:11 +0000468static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300469builtin_callable(PyObject *module, PyObject *obj)
470/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000471{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000472 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000473}
474
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400475static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200476builtin_breakpoint(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400477{
478 PyObject *hook = PySys_GetObject("breakpointhook");
479
480 if (hook == NULL) {
481 PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook");
482 return NULL;
483 }
484 Py_INCREF(hook);
485 PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords);
486 Py_DECREF(hook);
487 return retval;
488}
489
490PyDoc_STRVAR(breakpoint_doc,
491"breakpoint(*args, **kws)\n\
492\n\
493Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept\n\
494whatever arguments are passed.\n\
495\n\
496By default, this drops you into the pdb debugger.");
Antoine Pitroue71362d2010-11-27 22:00:11 +0000497
Raymond Hettinger17301e92008-03-13 00:19:26 +0000498typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 PyObject_HEAD
500 PyObject *func;
501 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000502} filterobject;
503
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000504static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000505filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 PyObject *func, *seq;
508 PyObject *it;
509 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000510
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +0300511 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
515 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 /* Get iterator. */
518 it = PyObject_GetIter(seq);
519 if (it == NULL)
520 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 /* create filterobject structure */
523 lz = (filterobject *)type->tp_alloc(type, 0);
524 if (lz == NULL) {
525 Py_DECREF(it);
526 return NULL;
527 }
528 Py_INCREF(func);
529 lz->func = func;
530 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000533}
534
535static void
536filter_dealloc(filterobject *lz)
537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 PyObject_GC_UnTrack(lz);
539 Py_XDECREF(lz->func);
540 Py_XDECREF(lz->it);
541 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000542}
543
544static int
545filter_traverse(filterobject *lz, visitproc visit, void *arg)
546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 Py_VISIT(lz->it);
548 Py_VISIT(lz->func);
549 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000550}
551
552static PyObject *
553filter_next(filterobject *lz)
554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 PyObject *item;
556 PyObject *it = lz->it;
557 long ok;
558 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400559 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 iternext = *Py_TYPE(it)->tp_iternext;
562 for (;;) {
563 item = iternext(it);
564 if (item == NULL)
565 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000566
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400567 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 ok = PyObject_IsTrue(item);
569 } else {
570 PyObject *good;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100571 good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 if (good == NULL) {
573 Py_DECREF(item);
574 return NULL;
575 }
576 ok = PyObject_IsTrue(good);
577 Py_DECREF(good);
578 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200579 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 return item;
581 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200582 if (ok < 0)
583 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000585}
586
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000587static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530588filter_reduce(filterobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000589{
590 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
591}
592
593PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
594
595static PyMethodDef filter_methods[] = {
596 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
597 {NULL, NULL} /* sentinel */
598};
599
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000600PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000601"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000602\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000603Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000604is true. If function is None, return the items that are true.");
605
606PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 PyVarObject_HEAD_INIT(&PyType_Type, 0)
608 "filter", /* tp_name */
609 sizeof(filterobject), /* tp_basicsize */
610 0, /* tp_itemsize */
611 /* methods */
612 (destructor)filter_dealloc, /* tp_dealloc */
613 0, /* tp_print */
614 0, /* tp_getattr */
615 0, /* tp_setattr */
616 0, /* tp_reserved */
617 0, /* tp_repr */
618 0, /* tp_as_number */
619 0, /* tp_as_sequence */
620 0, /* tp_as_mapping */
621 0, /* tp_hash */
622 0, /* tp_call */
623 0, /* tp_str */
624 PyObject_GenericGetAttr, /* tp_getattro */
625 0, /* tp_setattro */
626 0, /* tp_as_buffer */
627 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
628 Py_TPFLAGS_BASETYPE, /* tp_flags */
629 filter_doc, /* tp_doc */
630 (traverseproc)filter_traverse, /* tp_traverse */
631 0, /* tp_clear */
632 0, /* tp_richcompare */
633 0, /* tp_weaklistoffset */
634 PyObject_SelfIter, /* tp_iter */
635 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000636 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 0, /* tp_members */
638 0, /* tp_getset */
639 0, /* tp_base */
640 0, /* tp_dict */
641 0, /* tp_descr_get */
642 0, /* tp_descr_set */
643 0, /* tp_dictoffset */
644 0, /* tp_init */
645 PyType_GenericAlloc, /* tp_alloc */
646 filter_new, /* tp_new */
647 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000648};
649
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000650
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000651/*[clinic input]
652format as builtin_format
653
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300654 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000655 format_spec: unicode(c_default="NULL") = ''
656 /
657
658Return value.__format__(format_spec)
659
Amit Kumar2e6bb442017-05-29 06:32:26 +0530660format_spec defaults to the empty string.
661See the Format Specification Mini-Language section of help('FORMATTING') for
662details.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000663[clinic start generated code]*/
664
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000665static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300666builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
Amit Kumar2e6bb442017-05-29 06:32:26 +0530667/*[clinic end generated code: output=2f40bdfa4954b077 input=88339c93ea522b33]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000668{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000669 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000670}
671
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000672/*[clinic input]
673chr as builtin_chr
674
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300675 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000676 /
677
678Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
679[clinic start generated code]*/
680
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000681static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300682builtin_chr_impl(PyObject *module, int i)
683/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000684{
685 return PyUnicode_FromOrdinal(i);
686}
Guido van Rossum09095f32000-03-10 23:00:52 +0000687
688
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200689static const char *
Martin Pantereeb896c2015-11-07 02:32:21 +0000690source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000691{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200692 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 Py_ssize_t size;
Martin Pantereeb896c2015-11-07 02:32:21 +0000694 Py_buffer view;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000695
Martin Pantereeb896c2015-11-07 02:32:21 +0000696 *cmd_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 if (PyUnicode_Check(cmd)) {
698 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200699 str = PyUnicode_AsUTF8AndSize(cmd, &size);
700 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 return NULL;
702 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000703 else if (PyBytes_Check(cmd)) {
704 str = PyBytes_AS_STRING(cmd);
705 size = PyBytes_GET_SIZE(cmd);
706 }
707 else if (PyByteArray_Check(cmd)) {
708 str = PyByteArray_AS_STRING(cmd);
709 size = PyByteArray_GET_SIZE(cmd);
710 }
711 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
712 /* Copy to NUL-terminated buffer. */
713 *cmd_copy = PyBytes_FromStringAndSize(
714 (const char *)view.buf, view.len);
715 PyBuffer_Release(&view);
716 if (*cmd_copy == NULL) {
717 return NULL;
718 }
719 str = PyBytes_AS_STRING(*cmd_copy);
720 size = PyBytes_GET_SIZE(*cmd_copy);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200721 }
722 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 PyErr_Format(PyExc_TypeError,
724 "%s() arg 1 must be a %s object",
725 funcname, what);
726 return NULL;
727 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200728
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200729 if (strlen(str) != (size_t)size) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300730 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 "source code string cannot contain null bytes");
Martin Pantereeb896c2015-11-07 02:32:21 +0000732 Py_CLEAR(*cmd_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 return NULL;
734 }
735 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000736}
737
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000738/*[clinic input]
739compile as builtin_compile
740
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300741 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000742 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300743 mode: str
744 flags: int = 0
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200745 dont_inherit: bool(accept={int}) = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300746 optimize: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000747
748Compile source into a code object that can be executed by exec() or eval().
749
750The source code may represent a Python module, statement or expression.
751The filename will be used for run-time error messages.
752The mode must be 'exec' to compile a module, 'single' to compile a
753single (interactive) statement, or 'eval' to compile an expression.
754The flags argument, if present, controls which future statements influence
755the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300756The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000757the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300758compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000759in addition to any features explicitly specified.
760[clinic start generated code]*/
761
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000762static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300763builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
764 const char *mode, int flags, int dont_inherit,
765 int optimize)
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200766/*[clinic end generated code: output=1fa176e33452bb63 input=0ff726f595eb9fcd]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000767{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000768 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200769 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000770 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 int is_ast;
772 PyCompilerFlags cf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000774 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000775
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000776 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Tim Peters6cd6a822001-08-17 22:11:27 +0000777
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000778 if (flags &
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
780 {
781 PyErr_SetString(PyExc_ValueError,
782 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000783 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 }
785 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000786
Georg Brandl8334fd92010-12-04 10:26:46 +0000787 if (optimize < -1 || optimize > 2) {
788 PyErr_SetString(PyExc_ValueError,
789 "compile(): invalid optimize value");
790 goto error;
791 }
792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 if (!dont_inherit) {
794 PyEval_MergeCompilerFlags(&cf);
795 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000796
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000797 if (strcmp(mode, "exec") == 0)
798 compile_mode = 0;
799 else if (strcmp(mode, "eval") == 0)
800 compile_mode = 1;
801 else if (strcmp(mode, "single") == 0)
802 compile_mode = 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 else {
804 PyErr_SetString(PyExc_ValueError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000805 "compile() mode must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000806 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000808
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000809 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000811 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000813 if (flags & PyCF_ONLY_AST) {
814 Py_INCREF(source);
815 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 }
817 else {
818 PyArena *arena;
819 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200822 if (arena == NULL)
823 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000824 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 if (mod == NULL) {
826 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000827 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500829 if (!PyAST_Validate(mod)) {
830 PyArena_Free(arena);
831 goto error;
832 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200833 result = (PyObject*)PyAST_CompileObject(mod, filename,
834 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 PyArena_Free(arena);
836 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000837 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000839
Martin Panter61d6e4a2015-11-07 02:56:11 +0000840 str = source_as_string(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000842 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000843
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000844 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000845 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000846 goto finally;
847
848error:
849 result = NULL;
850finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200851 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000852 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000853}
854
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000855/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000856static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000857builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
862 return NULL;
863 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000864}
865
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000866PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000867"dir([object]) -> list of strings\n"
868"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000869"If called without an argument, return the names in the current scope.\n"
870"Else, return an alphabetized list of names comprising (some of) the attributes\n"
871"of the given object, and of attributes reachable from it.\n"
872"If the object supplies a method named __dir__, it will be used; otherwise\n"
873"the default dir() logic is used and returns:\n"
874" for a module object: the module's attributes.\n"
875" for a class object: its attributes, and recursively the attributes\n"
876" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000877" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000878" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000879
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000880/*[clinic input]
881divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000882
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300883 x: object
884 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000885 /
886
Zachary Ware7f227d92016-04-28 14:39:50 -0500887Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000888[clinic start generated code]*/
889
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000890static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300891builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
892/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000893{
894 return PyNumber_Divmod(x, y);
895}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000896
897
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000898/*[clinic input]
899eval as builtin_eval
900
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300901 source: object
902 globals: object = None
903 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000904 /
905
906Evaluate the given source in the context of globals and locals.
907
908The source may be a string representing a Python expression
909or a code object as returned by compile().
910The globals must be a dictionary and locals can be any mapping,
911defaulting to the current globals and locals.
912If only globals is given, locals defaults to it.
913[clinic start generated code]*/
914
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000915static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300916builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400917 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300918/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000919{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000920 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200921 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 if (locals != Py_None && !PyMapping_Check(locals)) {
925 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
926 return NULL;
927 }
928 if (globals != Py_None && !PyDict_Check(globals)) {
929 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
930 "globals must be a real dict; try eval(expr, {}, mapping)"
931 : "globals must be a dict");
932 return NULL;
933 }
934 if (globals == Py_None) {
935 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100936 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100938 if (locals == NULL)
939 return NULL;
940 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 }
942 else if (locals == Py_None)
943 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 if (globals == NULL || locals == NULL) {
946 PyErr_SetString(PyExc_TypeError,
947 "eval must be given globals and locals "
948 "when called without a frame");
949 return NULL;
950 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000951
Victor Stinnerb44562b2013-11-06 19:03:11 +0100952 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
953 if (_PyDict_SetItemId(globals, &PyId___builtins__,
954 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 return NULL;
956 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000957
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000958 if (PyCode_Check(source)) {
959 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 PyErr_SetString(PyExc_TypeError,
961 "code object passed to eval() may not contain free variables");
962 return NULL;
963 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000964 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Martin Panter61d6e4a2015-11-07 02:56:11 +0000968 str = source_as_string(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 if (str == NULL)
970 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 while (*str == ' ' || *str == '\t')
973 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 (void)PyEval_MergeCompilerFlags(&cf);
976 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000977 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000979}
980
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000981/*[clinic input]
982exec as builtin_exec
983
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300984 source: object
985 globals: object = None
986 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000987 /
988
989Execute the given source in the context of globals and locals.
990
991The source may be a string representing one or more Python statements
992or a code object as returned by compile().
993The globals must be a dictionary and locals can be any mapping,
994defaulting to the current globals and locals.
995If only globals is given, locals defaults to it.
996[clinic start generated code]*/
997
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000998static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300999builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -04001000 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001001/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +00001002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 if (globals == Py_None) {
1006 globals = PyEval_GetGlobals();
1007 if (locals == Py_None) {
1008 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001009 if (locals == NULL)
1010 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 }
1012 if (!globals || !locals) {
1013 PyErr_SetString(PyExc_SystemError,
1014 "globals and locals cannot be NULL");
1015 return NULL;
1016 }
1017 }
1018 else if (locals == Py_None)
1019 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001022 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 globals->ob_type->tp_name);
1024 return NULL;
1025 }
1026 if (!PyMapping_Check(locals)) {
1027 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001028 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 locals->ob_type->tp_name);
1030 return NULL;
1031 }
Victor Stinnerb44562b2013-11-06 19:03:11 +01001032 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
1033 if (_PyDict_SetItemId(globals, &PyId___builtins__,
1034 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 return NULL;
1036 }
1037
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001038 if (PyCode_Check(source)) {
1039 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 PyErr_SetString(PyExc_TypeError,
1041 "code object passed to exec() may not "
1042 "contain free variables");
1043 return NULL;
1044 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001045 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 }
1047 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +00001048 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001049 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 PyCompilerFlags cf;
1051 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001052 str = source_as_string(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +00001053 "string, bytes or code", &cf,
1054 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 if (str == NULL)
1056 return NULL;
1057 if (PyEval_MergeCompilerFlags(&cf))
1058 v = PyRun_StringFlags(str, Py_file_input, globals,
1059 locals, &cf);
1060 else
1061 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +00001062 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 }
1064 if (v == NULL)
1065 return NULL;
1066 Py_DECREF(v);
1067 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001068}
1069
Georg Brandl7cae87c2006-09-06 06:51:57 +00001070
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001071/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001072static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001073builtin_getattr(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum33894be1992-01-27 16:53:09 +00001074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 PyObject *v, *result, *dflt = NULL;
1076 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001077
Sylvain96c7c062017-06-15 17:05:23 +02001078 if (!_PyArg_UnpackStack(args, nargs, "getattr", 2, 3, &v, &name, &dflt))
1079 return NULL;
1080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 if (!PyUnicode_Check(name)) {
1082 PyErr_SetString(PyExc_TypeError,
1083 "getattr(): attribute name must be string");
1084 return NULL;
1085 }
INADA Naoki378edee2018-01-16 20:52:41 +09001086 if (dflt != NULL) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001087 if (_PyObject_LookupAttr(v, name, &result) == 0) {
INADA Naoki378edee2018-01-16 20:52:41 +09001088 Py_INCREF(dflt);
1089 return dflt;
1090 }
1091 }
1092 else {
1093 result = PyObject_GetAttr(v, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 }
1095 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001096}
1097
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001098PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001099"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001100\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001101Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1102When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001103exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001104
1105
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001106/*[clinic input]
1107globals as builtin_globals
1108
1109Return the dictionary containing the current scope's global variables.
1110
1111NOTE: Updates to this dictionary *will* affect name lookups in the current
1112global scope and vice-versa.
1113[clinic start generated code]*/
1114
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001115static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001116builtin_globals_impl(PyObject *module)
1117/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 d = PyEval_GetGlobals();
1122 Py_XINCREF(d);
1123 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001124}
1125
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001126
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001127/*[clinic input]
1128hasattr as builtin_hasattr
1129
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001130 obj: object
1131 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001132 /
1133
1134Return whether the object has an attribute with the given name.
1135
1136This is done by calling getattr(obj, name) and catching AttributeError.
1137[clinic start generated code]*/
1138
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001139static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001140builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1141/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001142{
1143 PyObject *v;
1144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 if (!PyUnicode_Check(name)) {
1146 PyErr_SetString(PyExc_TypeError,
1147 "hasattr(): attribute name must be string");
1148 return NULL;
1149 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001150 if (_PyObject_LookupAttr(obj, name, &v) < 0) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001151 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001153 if (v == NULL) {
1154 Py_RETURN_FALSE;
1155 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001157 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001158}
1159
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001160
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001161/* AC: gdb's integration with CPython relies on builtin_id having
1162 * the *exact* parameter names of "self" and "v", so we ensure we
1163 * preserve those name rather than using the AC defaults.
1164 */
1165/*[clinic input]
1166id as builtin_id
1167
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001168 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001169 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001170 /
1171
1172Return the identity of an object.
1173
1174This is guaranteed to be unique among simultaneously existing objects.
1175(CPython uses the object's memory address.)
1176[clinic start generated code]*/
1177
Guido van Rossum79f25d91997-04-29 20:08:16 +00001178static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001179builtin_id(PyModuleDef *self, PyObject *v)
1180/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +00001183}
1184
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001185
Raymond Hettingera6c60372008-03-13 01:26:19 +00001186/* map object ************************************************************/
1187
1188typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 PyObject_HEAD
1190 PyObject *iters;
1191 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001192} mapobject;
1193
Guido van Rossum79f25d91997-04-29 20:08:16 +00001194static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001195map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 PyObject *it, *iters, *func;
1198 mapobject *lz;
1199 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001200
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001201 if (type == &PyMap_Type && !_PyArg_NoKeywords("map", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 numargs = PyTuple_Size(args);
1205 if (numargs < 2) {
1206 PyErr_SetString(PyExc_TypeError,
1207 "map() must have at least two arguments.");
1208 return NULL;
1209 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 iters = PyTuple_New(numargs-1);
1212 if (iters == NULL)
1213 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 for (i=1 ; i<numargs ; i++) {
1216 /* Get iterator. */
1217 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1218 if (it == NULL) {
1219 Py_DECREF(iters);
1220 return NULL;
1221 }
1222 PyTuple_SET_ITEM(iters, i-1, it);
1223 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 /* create mapobject structure */
1226 lz = (mapobject *)type->tp_alloc(type, 0);
1227 if (lz == NULL) {
1228 Py_DECREF(iters);
1229 return NULL;
1230 }
1231 lz->iters = iters;
1232 func = PyTuple_GET_ITEM(args, 0);
1233 Py_INCREF(func);
1234 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001237}
1238
1239static void
1240map_dealloc(mapobject *lz)
1241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 PyObject_GC_UnTrack(lz);
1243 Py_XDECREF(lz->iters);
1244 Py_XDECREF(lz->func);
1245 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001246}
1247
1248static int
1249map_traverse(mapobject *lz, visitproc visit, void *arg)
1250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 Py_VISIT(lz->iters);
1252 Py_VISIT(lz->func);
1253 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001254}
1255
1256static PyObject *
1257map_next(mapobject *lz)
1258{
Victor Stinnerbc08ab42016-12-15 12:40:53 +01001259 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001260 PyObject **stack;
1261 Py_ssize_t niters, nargs, i;
1262 PyObject *result = NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001263
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001264 niters = PyTuple_GET_SIZE(lz->iters);
1265 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1266 stack = small_stack;
1267 }
1268 else {
1269 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1270 if (stack == NULL) {
1271 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 return NULL;
1273 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001275
1276 nargs = 0;
1277 for (i=0; i < niters; i++) {
1278 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1279 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1280 if (val == NULL) {
1281 goto exit;
1282 }
1283 stack[i] = val;
1284 nargs++;
1285 }
1286
1287 result = _PyObject_FastCall(lz->func, stack, nargs);
1288
1289exit:
1290 for (i=0; i < nargs; i++) {
1291 Py_DECREF(stack[i]);
1292 }
1293 if (stack != small_stack) {
1294 PyMem_Free(stack);
1295 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001297}
1298
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001299static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301300map_reduce(mapobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001301{
1302 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1303 PyObject *args = PyTuple_New(numargs+1);
1304 Py_ssize_t i;
1305 if (args == NULL)
1306 return NULL;
1307 Py_INCREF(lz->func);
1308 PyTuple_SET_ITEM(args, 0, lz->func);
1309 for (i = 0; i<numargs; i++){
1310 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1311 Py_INCREF(it);
1312 PyTuple_SET_ITEM(args, i+1, it);
1313 }
1314
1315 return Py_BuildValue("ON", Py_TYPE(lz), args);
1316}
1317
1318static PyMethodDef map_methods[] = {
1319 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1320 {NULL, NULL} /* sentinel */
1321};
1322
1323
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001324PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001325"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001326\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001327Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001329
Raymond Hettingera6c60372008-03-13 01:26:19 +00001330PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1332 "map", /* tp_name */
1333 sizeof(mapobject), /* tp_basicsize */
1334 0, /* tp_itemsize */
1335 /* methods */
1336 (destructor)map_dealloc, /* tp_dealloc */
1337 0, /* tp_print */
1338 0, /* tp_getattr */
1339 0, /* tp_setattr */
1340 0, /* tp_reserved */
1341 0, /* tp_repr */
1342 0, /* tp_as_number */
1343 0, /* tp_as_sequence */
1344 0, /* tp_as_mapping */
1345 0, /* tp_hash */
1346 0, /* tp_call */
1347 0, /* tp_str */
1348 PyObject_GenericGetAttr, /* tp_getattro */
1349 0, /* tp_setattro */
1350 0, /* tp_as_buffer */
1351 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1352 Py_TPFLAGS_BASETYPE, /* tp_flags */
1353 map_doc, /* tp_doc */
1354 (traverseproc)map_traverse, /* tp_traverse */
1355 0, /* tp_clear */
1356 0, /* tp_richcompare */
1357 0, /* tp_weaklistoffset */
1358 PyObject_SelfIter, /* tp_iter */
1359 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001360 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 0, /* tp_members */
1362 0, /* tp_getset */
1363 0, /* tp_base */
1364 0, /* tp_dict */
1365 0, /* tp_descr_get */
1366 0, /* tp_descr_set */
1367 0, /* tp_dictoffset */
1368 0, /* tp_init */
1369 PyType_GenericAlloc, /* tp_alloc */
1370 map_new, /* tp_new */
1371 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001372};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001373
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001374
1375/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001376static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001377builtin_next(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Georg Brandla18af4e2007-04-21 15:47:16 +00001378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 PyObject *it, *res;
1380 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001381
Sylvain96c7c062017-06-15 17:05:23 +02001382 if (!_PyArg_UnpackStack(args, nargs, "next", 1, 2, &it, &def))
1383 return NULL;
1384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 if (!PyIter_Check(it)) {
1386 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001387 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 it->ob_type->tp_name);
1389 return NULL;
1390 }
1391
1392 res = (*it->ob_type->tp_iternext)(it);
1393 if (res != NULL) {
1394 return res;
1395 } else if (def != NULL) {
1396 if (PyErr_Occurred()) {
1397 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1398 return NULL;
1399 PyErr_Clear();
1400 }
1401 Py_INCREF(def);
1402 return def;
1403 } else if (PyErr_Occurred()) {
1404 return NULL;
1405 } else {
1406 PyErr_SetNone(PyExc_StopIteration);
1407 return NULL;
1408 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001409}
1410
1411PyDoc_STRVAR(next_doc,
1412"next(iterator[, default])\n\
1413\n\
1414Return the next item from the iterator. If default is given and the iterator\n\
1415is exhausted, it is returned instead of raising StopIteration.");
1416
1417
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001418/*[clinic input]
1419setattr as builtin_setattr
1420
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001421 obj: object
1422 name: object
1423 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001424 /
1425
1426Sets the named attribute on the given object to the specified value.
1427
1428setattr(x, 'y', v) is equivalent to ``x.y = v''
1429[clinic start generated code]*/
1430
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001431static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001432builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001433 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001434/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001435{
1436 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001438 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001439}
1440
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001441
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001442/*[clinic input]
1443delattr as builtin_delattr
1444
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001445 obj: object
1446 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001447 /
1448
1449Deletes the named attribute from the given object.
1450
1451delattr(x, 'y') is equivalent to ``del x.y''
1452[clinic start generated code]*/
1453
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001454static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001455builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1456/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001457{
1458 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001460 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001461}
1462
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001463
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001464/*[clinic input]
1465hash as builtin_hash
1466
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001467 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001468 /
1469
1470Return the hash value for the given object.
1471
1472Two objects that compare equal must also have the same hash value, but the
1473reverse is not necessarily true.
1474[clinic start generated code]*/
1475
Guido van Rossum79f25d91997-04-29 20:08:16 +00001476static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001477builtin_hash(PyObject *module, PyObject *obj)
1478/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001479{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001480 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001481
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001482 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 if (x == -1)
1484 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001485 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001486}
1487
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001488
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001489/*[clinic input]
1490hex as builtin_hex
1491
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001492 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001493 /
1494
1495Return the hexadecimal representation of an integer.
1496
1497 >>> hex(12648430)
1498 '0xc0ffee'
1499[clinic start generated code]*/
1500
Guido van Rossum79f25d91997-04-29 20:08:16 +00001501static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001502builtin_hex(PyObject *module, PyObject *number)
1503/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001504{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001505 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001506}
1507
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001508
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001509/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001510static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001511builtin_iter(PyObject *self, PyObject *args)
1512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1516 return NULL;
1517 if (w == NULL)
1518 return PyObject_GetIter(v);
1519 if (!PyCallable_Check(v)) {
1520 PyErr_SetString(PyExc_TypeError,
1521 "iter(v, w): v must be callable");
1522 return NULL;
1523 }
1524 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001525}
1526
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001527PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001528"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001529iter(callable, sentinel) -> iterator\n\
1530\n\
1531Get an iterator from an object. In the first form, the argument must\n\
1532supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001533In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001534
1535
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001536/*[clinic input]
1537len as builtin_len
1538
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001539 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001540 /
1541
1542Return the number of items in a container.
1543[clinic start generated code]*/
1544
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001545static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001546builtin_len(PyObject *module, PyObject *obj)
1547/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001550
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001551 res = PyObject_Size(obj);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001552 if (res < 0) {
1553 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 return NULL;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001555 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001557}
1558
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001559
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001560/*[clinic input]
1561locals as builtin_locals
1562
1563Return a dictionary containing the current scope's local variables.
1564
1565NOTE: Whether or not updates to this dictionary will affect name lookups in
1566the local scope and vice-versa is *implementation dependent* and not
1567covered by any backwards compatibility guarantees.
1568[clinic start generated code]*/
1569
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001570static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001571builtin_locals_impl(PyObject *module)
1572/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 d = PyEval_GetLocals();
1577 Py_XINCREF(d);
1578 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001579}
1580
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001581
Guido van Rossum79f25d91997-04-29 20:08:16 +00001582static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001583min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001586 PyObject *emptytuple, *defaultval = NULL;
1587 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001589 const int positional = PyTuple_Size(args) > 1;
1590 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001591
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001592 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001594 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001596
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001597 emptytuple = PyTuple_New(0);
1598 if (emptytuple == NULL)
1599 return NULL;
Oren Milman58cf7482017-08-21 20:19:07 +03001600 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1601 (op == Py_LT) ? "|$OO:min" : "|$OO:max",
1602 kwlist, &keyfunc, &defaultval);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001603 Py_DECREF(emptytuple);
1604 if (!ret)
1605 return NULL;
1606
1607 if (positional && defaultval != NULL) {
1608 PyErr_Format(PyExc_TypeError,
1609 "Cannot specify a default for %s() with multiple "
1610 "positional arguments", name);
1611 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 it = PyObject_GetIter(v);
1615 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 return NULL;
1617 }
Tim Petersc3074532001-05-03 07:00:32 +00001618
Alexander Marshalove22072f2018-07-24 10:58:21 +07001619 if (keyfunc == Py_None) {
1620 keyfunc = NULL;
1621 }
1622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 maxitem = NULL; /* the result */
1624 maxval = NULL; /* the value associated with the result */
1625 while (( item = PyIter_Next(it) )) {
1626 /* get the value from the key function */
1627 if (keyfunc != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001628 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 if (val == NULL)
1630 goto Fail_it_item;
1631 }
1632 /* no key function; the value is the item */
1633 else {
1634 val = item;
1635 Py_INCREF(val);
1636 }
Tim Petersc3074532001-05-03 07:00:32 +00001637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 /* maximum value and item are unset; set them */
1639 if (maxval == NULL) {
1640 maxitem = item;
1641 maxval = val;
1642 }
1643 /* maximum value and item are set; update them as necessary */
1644 else {
1645 int cmp = PyObject_RichCompareBool(val, maxval, op);
1646 if (cmp < 0)
1647 goto Fail_it_item_and_val;
1648 else if (cmp > 0) {
1649 Py_DECREF(maxval);
1650 Py_DECREF(maxitem);
1651 maxval = val;
1652 maxitem = item;
1653 }
1654 else {
1655 Py_DECREF(item);
1656 Py_DECREF(val);
1657 }
1658 }
1659 }
1660 if (PyErr_Occurred())
1661 goto Fail_it;
1662 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001664 if (defaultval != NULL) {
1665 Py_INCREF(defaultval);
1666 maxitem = defaultval;
1667 } else {
1668 PyErr_Format(PyExc_ValueError,
1669 "%s() arg is an empty sequence", name);
1670 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 }
1672 else
1673 Py_DECREF(maxval);
1674 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001676
1677Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001679Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001681Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 Py_XDECREF(maxval);
1683 Py_XDECREF(maxitem);
1684 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001686}
1687
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001688/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001689static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001690builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001693}
1694
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001695PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001696"min(iterable, *[, default=obj, key=func]) -> value\n\
1697min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001698\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001699With a single iterable argument, return its smallest item. The\n\
1700default keyword-only argument specifies an object to return if\n\
1701the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001702With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001703
1704
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001705/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001706static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001707builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001710}
1711
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001712PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001713"max(iterable, *[, default=obj, key=func]) -> value\n\
1714max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001715\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001716With a single iterable argument, return its biggest item. The\n\
1717default keyword-only argument specifies an object to return if\n\
1718the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001719With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001720
1721
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001722/*[clinic input]
1723oct as builtin_oct
1724
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001725 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001726 /
1727
1728Return the octal representation of an integer.
1729
1730 >>> oct(342391)
1731 '0o1234567'
1732[clinic start generated code]*/
1733
Guido van Rossum79f25d91997-04-29 20:08:16 +00001734static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001735builtin_oct(PyObject *module, PyObject *number)
1736/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001737{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001738 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001739}
1740
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001741
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001742/*[clinic input]
1743ord as builtin_ord
1744
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001745 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001746 /
1747
1748Return the Unicode code point for a one-character string.
1749[clinic start generated code]*/
1750
Guido van Rossum79f25d91997-04-29 20:08:16 +00001751static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001752builtin_ord(PyObject *module, PyObject *c)
1753/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 long ord;
1756 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001757
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001758 if (PyBytes_Check(c)) {
1759 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001761 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 return PyLong_FromLong(ord);
1763 }
1764 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001765 else if (PyUnicode_Check(c)) {
1766 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001767 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001768 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001770 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 return PyLong_FromLong(ord);
1772 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001774 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001776 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001778 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 return PyLong_FromLong(ord);
1780 }
1781 }
1782 else {
1783 PyErr_Format(PyExc_TypeError,
1784 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001785 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 return NULL;
1787 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 PyErr_Format(PyExc_TypeError,
1790 "ord() expected a character, "
1791 "but string of length %zd found",
1792 size);
1793 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001794}
1795
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001796
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001797/*[clinic input]
1798pow as builtin_pow
1799
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001800 x: object
1801 y: object
1802 z: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001803 /
1804
1805Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
1806
1807Some types, such as ints, are able to use a more efficient algorithm when
1808invoked using the three argument form.
1809[clinic start generated code]*/
1810
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001811static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001812builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z)
1813/*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001814{
1815 return PyNumber_Power(x, y, z);
1816}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001817
1818
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001819/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001820static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001821builtin_print(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001822{
INADA Naokibd584f12017-01-19 12:50:34 +01001823 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
1824 static struct _PyArg_Parser _parser = {"|OOOO:print", _keywords, 0};
Georg Brandlbc3b6822012-01-13 19:41:25 +01001825 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001827
INADA Naokibd584f12017-01-19 12:50:34 +01001828 if (kwnames != NULL &&
1829 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1830 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001831 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001832 }
1833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001835 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001836 if (file == NULL) {
1837 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1838 return NULL;
1839 }
1840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 /* sys.stdout may be None when FILE* stdout isn't connected */
1842 if (file == Py_None)
1843 Py_RETURN_NONE;
1844 }
Guido van Rossum34343512006-11-30 22:13:52 +00001845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 if (sep == Py_None) {
1847 sep = NULL;
1848 }
1849 else if (sep && !PyUnicode_Check(sep)) {
1850 PyErr_Format(PyExc_TypeError,
1851 "sep must be None or a string, not %.200s",
1852 sep->ob_type->tp_name);
1853 return NULL;
1854 }
1855 if (end == Py_None) {
1856 end = NULL;
1857 }
1858 else if (end && !PyUnicode_Check(end)) {
1859 PyErr_Format(PyExc_TypeError,
1860 "end must be None or a string, not %.200s",
1861 end->ob_type->tp_name);
1862 return NULL;
1863 }
Guido van Rossum34343512006-11-30 22:13:52 +00001864
INADA Naokibd584f12017-01-19 12:50:34 +01001865 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 if (i > 0) {
1867 if (sep == NULL)
1868 err = PyFile_WriteString(" ", file);
1869 else
1870 err = PyFile_WriteObject(sep, file,
1871 Py_PRINT_RAW);
1872 if (err)
1873 return NULL;
1874 }
INADA Naokibd584f12017-01-19 12:50:34 +01001875 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 if (err)
1877 return NULL;
1878 }
Guido van Rossum34343512006-11-30 22:13:52 +00001879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 if (end == NULL)
1881 err = PyFile_WriteString("\n", file);
1882 else
1883 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1884 if (err)
1885 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001886
Georg Brandlbc3b6822012-01-13 19:41:25 +01001887 if (flush != NULL) {
1888 PyObject *tmp;
1889 int do_flush = PyObject_IsTrue(flush);
1890 if (do_flush == -1)
1891 return NULL;
1892 else if (do_flush) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001893 tmp = _PyObject_CallMethodId(file, &PyId_flush, NULL);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001894 if (tmp == NULL)
1895 return NULL;
1896 else
1897 Py_DECREF(tmp);
1898 }
1899 }
1900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001902}
1903
1904PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001905"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001906\n\
1907Prints the values to a stream, or to sys.stdout by default.\n\
1908Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001909file: a file-like object (stream); defaults to the current sys.stdout.\n\
1910sep: string inserted between values, default a space.\n\
1911end: string appended after the last value, default a newline.\n\
1912flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001913
1914
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001915/*[clinic input]
1916input as builtin_input
1917
1918 prompt: object(c_default="NULL") = None
1919 /
1920
1921Read a string from standard input. The trailing newline is stripped.
1922
1923The prompt string, if given, is printed to standard output without a
1924trailing newline before reading input.
1925
1926If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1927On *nix systems, readline is used if available.
1928[clinic start generated code]*/
1929
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001930static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001931builtin_input_impl(PyObject *module, PyObject *prompt)
1932/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001933{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001934 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1935 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1936 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 PyObject *tmp;
1938 long fd;
1939 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 /* Check that stdin/out/err are intact */
1942 if (fin == NULL || fin == Py_None) {
1943 PyErr_SetString(PyExc_RuntimeError,
1944 "input(): lost sys.stdin");
1945 return NULL;
1946 }
1947 if (fout == NULL || fout == Py_None) {
1948 PyErr_SetString(PyExc_RuntimeError,
1949 "input(): lost sys.stdout");
1950 return NULL;
1951 }
1952 if (ferr == NULL || ferr == Py_None) {
1953 PyErr_SetString(PyExc_RuntimeError,
1954 "input(): lost sys.stderr");
1955 return NULL;
1956 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 /* First of all, flush stderr */
Victor Stinner3466bde2016-09-05 18:16:01 -07001959 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 if (tmp == NULL)
1961 PyErr_Clear();
1962 else
1963 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 /* We should only use (GNU) readline if Python's sys.stdin and
1966 sys.stdout are the same as C's stdin and stdout, because we
1967 need to pass it those. */
Victor Stinner3466bde2016-09-05 18:16:01 -07001968 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 if (tmp == NULL) {
1970 PyErr_Clear();
1971 tty = 0;
1972 }
1973 else {
1974 fd = PyLong_AsLong(tmp);
1975 Py_DECREF(tmp);
1976 if (fd < 0 && PyErr_Occurred())
1977 return NULL;
1978 tty = fd == fileno(stdin) && isatty(fd);
1979 }
1980 if (tty) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001981 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, NULL);
Martin Panterc9a6ab52015-10-10 01:25:38 +00001982 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00001984 tty = 0;
1985 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 else {
1987 fd = PyLong_AsLong(tmp);
1988 Py_DECREF(tmp);
1989 if (fd < 0 && PyErr_Occurred())
1990 return NULL;
1991 tty = fd == fileno(stdout) && isatty(fd);
1992 }
1993 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 /* If we're interactive, use (GNU) readline */
1996 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001997 PyObject *po = NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001998 const char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001999 char *s = NULL;
2000 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
2001 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002002 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002004 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00002005
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002006 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002007 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002008 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002009 if (!stdin_encoding || !stdin_errors ||
2010 !PyUnicode_Check(stdin_encoding) ||
2011 !PyUnicode_Check(stdin_errors)) {
2012 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002013 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002014 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002015 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
2016 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002017 if (!stdin_encoding_str || !stdin_errors_str)
2018 goto _readline_errors;
Victor Stinner3466bde2016-09-05 18:16:01 -07002019 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 if (tmp == NULL)
2021 PyErr_Clear();
2022 else
2023 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002024 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002025 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002026 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002028 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002029 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002030 if (!stdout_encoding || !stdout_errors ||
2031 !PyUnicode_Check(stdout_encoding) ||
2032 !PyUnicode_Check(stdout_errors)) {
2033 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002034 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002035 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002036 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
2037 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002038 if (!stdout_encoding_str || !stdout_errors_str)
2039 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002040 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002041 if (stringpo == NULL)
2042 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002044 stdout_encoding_str, stdout_errors_str);
2045 Py_CLEAR(stdout_encoding);
2046 Py_CLEAR(stdout_errors);
2047 Py_CLEAR(stringpo);
2048 if (po == NULL)
2049 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03002050 assert(PyBytes_Check(po));
2051 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 }
2053 else {
2054 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002055 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002057 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002059 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 if (!PyErr_Occurred())
2061 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002062 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002064
2065 len = strlen(s);
2066 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 PyErr_SetNone(PyExc_EOFError);
2068 result = NULL;
2069 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002070 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 if (len > PY_SSIZE_T_MAX) {
2072 PyErr_SetString(PyExc_OverflowError,
2073 "input: input too long");
2074 result = NULL;
2075 }
2076 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002077 len--; /* strip trailing '\n' */
2078 if (len != 0 && s[len-1] == '\r')
2079 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002080 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2081 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 }
2083 }
2084 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002085 Py_DECREF(stdin_errors);
2086 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 PyMem_FREE(s);
2088 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002089
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002090 _readline_errors:
2091 Py_XDECREF(stdin_encoding);
2092 Py_XDECREF(stdout_encoding);
2093 Py_XDECREF(stdin_errors);
2094 Py_XDECREF(stdout_errors);
2095 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002096 if (tty)
2097 return NULL;
2098
2099 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002103 if (prompt != NULL) {
2104 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 return NULL;
2106 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002107 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 if (tmp == NULL)
2109 PyErr_Clear();
2110 else
2111 Py_DECREF(tmp);
2112 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002113}
2114
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002115
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002116/*[clinic input]
2117repr as builtin_repr
2118
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002119 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002120 /
2121
2122Return the canonical string representation of the object.
2123
2124For many object types, including most builtins, eval(repr(obj)) == obj.
2125[clinic start generated code]*/
2126
Guido van Rossum79f25d91997-04-29 20:08:16 +00002127static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002128builtin_repr(PyObject *module, PyObject *obj)
2129/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002130{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002131 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002132}
2133
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002134
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002135/*[clinic input]
2136round as builtin_round
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002137
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002138 number: object
2139 ndigits: object = NULL
2140
2141Round a number to a given precision in decimal digits.
2142
2143The return value is an integer if ndigits is omitted or None. Otherwise
2144the return value has the same type as the number. ndigits may be negative.
2145[clinic start generated code]*/
2146
2147static PyObject *
2148builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
2149/*[clinic end generated code: output=ff0d9dd176c02ede input=854bc3a217530c3d]*/
2150{
2151 PyObject *round, *result;
Alex Martelliae211f92007-08-22 23:21:33 +00002152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 if (Py_TYPE(number)->tp_dict == NULL) {
2154 if (PyType_Ready(Py_TYPE(number)) < 0)
2155 return NULL;
2156 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002157
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002158 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002160 if (!PyErr_Occurred())
2161 PyErr_Format(PyExc_TypeError,
2162 "type %.100s doesn't define __round__ method",
2163 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 return NULL;
2165 }
Alex Martelliae211f92007-08-22 23:21:33 +00002166
Raymond Hettingerf0f1c232016-09-03 01:55:11 -07002167 if (ndigits == NULL || ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002168 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 else
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002170 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002171 Py_DECREF(round);
2172 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002173}
2174
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002175
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002176/*AC: we need to keep the kwds dict intact to easily call into the
2177 * list.sort method, which isn't currently supported in AC. So we just use
2178 * the initially generated signature with a custom implementation.
2179 */
2180/* [disabled clinic input]
2181sorted as builtin_sorted
2182
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002183 iterable as seq: object
2184 key as keyfunc: object = None
2185 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002186
2187Return a new list containing all items from the iterable in ascending order.
2188
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002189A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002190reverse flag can be set to request the result in descending order.
2191[end disabled clinic input]*/
2192
2193PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002194"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002195"--\n"
2196"\n"
2197"Return a new list containing all items from the iterable in ascending order.\n"
2198"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002199"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002200"reverse flag can be set to request the result in descending order.");
2201
2202#define BUILTIN_SORTED_METHODDEF \
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002203 {"sorted", (PyCFunction)builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002204
Raymond Hettinger64958a12003-12-17 20:43:33 +00002205static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02002206builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002207{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002208 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002209
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002210 /* Keyword arguments are passed through list.sort() which will check
2211 them. */
2212 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 newlist = PySequence_List(seq);
2216 if (newlist == NULL)
2217 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002218
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002219 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 if (callable == NULL) {
2221 Py_DECREF(newlist);
2222 return NULL;
2223 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002224
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002225 assert(nargs >= 1);
Victor Stinner5a60eca2017-01-17 15:17:49 +01002226 v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 Py_DECREF(callable);
2228 if (v == NULL) {
2229 Py_DECREF(newlist);
2230 return NULL;
2231 }
2232 Py_DECREF(v);
2233 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002234}
2235
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002236
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002237/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002238static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002239builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 PyObject *v = NULL;
2242 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2245 return NULL;
2246 if (v == NULL) {
2247 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01002248 if (d == NULL)
2249 return NULL;
2250 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 }
2252 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002253 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 if (d == NULL) {
2255 PyErr_SetString(PyExc_TypeError,
2256 "vars() argument must have __dict__ attribute");
2257 return NULL;
2258 }
2259 }
2260 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002261}
2262
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002263PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002264"vars([object]) -> dictionary\n\
2265\n\
2266Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002267With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002268
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002269
2270/*[clinic input]
2271sum as builtin_sum
2272
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002273 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002274 start: object(c_default="NULL") = 0
2275 /
2276
2277Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2278
2279When the iterable is empty, return the start value.
2280This function is intended specifically for use with numeric values and may
2281reject non-numeric types.
2282[clinic start generated code]*/
2283
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002284static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002285builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
2286/*[clinic end generated code: output=df758cec7d1d302f input=3b5b7a9d7611c73a]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002287{
2288 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002290
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002291 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 if (iter == NULL)
2293 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 if (result == NULL) {
2296 result = PyLong_FromLong(0);
2297 if (result == NULL) {
2298 Py_DECREF(iter);
2299 return NULL;
2300 }
2301 } else {
2302 /* reject string values for 'start' parameter */
2303 if (PyUnicode_Check(result)) {
2304 PyErr_SetString(PyExc_TypeError,
2305 "sum() can't sum strings [use ''.join(seq) instead]");
2306 Py_DECREF(iter);
2307 return NULL;
2308 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002309 if (PyBytes_Check(result)) {
2310 PyErr_SetString(PyExc_TypeError,
2311 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002312 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002313 return NULL;
2314 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 if (PyByteArray_Check(result)) {
2316 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002317 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 Py_DECREF(iter);
2319 return NULL;
2320 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 Py_INCREF(result);
2322 }
Alex Martellia70b1912003-04-22 08:12:33 +00002323
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002324#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2326 Assumes all inputs are the same type. If the assumption fails, default
2327 to the more general routine.
2328 */
2329 if (PyLong_CheckExact(result)) {
2330 int overflow;
2331 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2332 /* If this already overflowed, don't even enter the loop. */
2333 if (overflow == 0) {
2334 Py_DECREF(result);
2335 result = NULL;
2336 }
2337 while(result == NULL) {
2338 item = PyIter_Next(iter);
2339 if (item == NULL) {
2340 Py_DECREF(iter);
2341 if (PyErr_Occurred())
2342 return NULL;
2343 return PyLong_FromLong(i_result);
2344 }
2345 if (PyLong_CheckExact(item)) {
2346 long b = PyLong_AsLongAndOverflow(item, &overflow);
2347 long x = i_result + b;
2348 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2349 i_result = x;
2350 Py_DECREF(item);
2351 continue;
2352 }
2353 }
2354 /* Either overflowed or is not an int. Restore real objects and process normally */
2355 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002356 if (result == NULL) {
2357 Py_DECREF(item);
2358 Py_DECREF(iter);
2359 return NULL;
2360 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 temp = PyNumber_Add(result, item);
2362 Py_DECREF(result);
2363 Py_DECREF(item);
2364 result = temp;
2365 if (result == NULL) {
2366 Py_DECREF(iter);
2367 return NULL;
2368 }
2369 }
2370 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 if (PyFloat_CheckExact(result)) {
2373 double f_result = PyFloat_AS_DOUBLE(result);
2374 Py_DECREF(result);
2375 result = NULL;
2376 while(result == NULL) {
2377 item = PyIter_Next(iter);
2378 if (item == NULL) {
2379 Py_DECREF(iter);
2380 if (PyErr_Occurred())
2381 return NULL;
2382 return PyFloat_FromDouble(f_result);
2383 }
2384 if (PyFloat_CheckExact(item)) {
2385 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2386 f_result += PyFloat_AS_DOUBLE(item);
2387 PyFPE_END_PROTECT(f_result)
2388 Py_DECREF(item);
2389 continue;
2390 }
2391 if (PyLong_CheckExact(item)) {
2392 long value;
2393 int overflow;
2394 value = PyLong_AsLongAndOverflow(item, &overflow);
2395 if (!overflow) {
2396 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2397 f_result += (double)value;
2398 PyFPE_END_PROTECT(f_result)
2399 Py_DECREF(item);
2400 continue;
2401 }
2402 }
2403 result = PyFloat_FromDouble(f_result);
Alexey Izbyshev2b824b22018-08-24 07:27:52 +03002404 if (result == NULL) {
2405 Py_DECREF(item);
2406 Py_DECREF(iter);
2407 return NULL;
2408 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 temp = PyNumber_Add(result, item);
2410 Py_DECREF(result);
2411 Py_DECREF(item);
2412 result = temp;
2413 if (result == NULL) {
2414 Py_DECREF(iter);
2415 return NULL;
2416 }
2417 }
2418 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002419#endif
2420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 for(;;) {
2422 item = PyIter_Next(iter);
2423 if (item == NULL) {
2424 /* error, or end-of-sequence */
2425 if (PyErr_Occurred()) {
2426 Py_DECREF(result);
2427 result = NULL;
2428 }
2429 break;
2430 }
2431 /* It's tempting to use PyNumber_InPlaceAdd instead of
2432 PyNumber_Add here, to avoid quadratic running time
2433 when doing 'sum(list_of_lists, [])'. However, this
2434 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 empty = []
2437 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 would change the value of empty. */
2440 temp = PyNumber_Add(result, item);
2441 Py_DECREF(result);
2442 Py_DECREF(item);
2443 result = temp;
2444 if (result == NULL)
2445 break;
2446 }
2447 Py_DECREF(iter);
2448 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002449}
2450
Alex Martellia70b1912003-04-22 08:12:33 +00002451
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002452/*[clinic input]
2453isinstance as builtin_isinstance
2454
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002455 obj: object
2456 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002457 /
2458
2459Return whether an object is an instance of a class or of a subclass thereof.
2460
2461A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2462check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2463or ...`` etc.
2464[clinic start generated code]*/
2465
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002466static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002467builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002468 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002469/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002472
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002473 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 if (retval < 0)
2475 return NULL;
2476 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002477}
2478
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002479
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002480/*[clinic input]
2481issubclass as builtin_issubclass
2482
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002483 cls: object
2484 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002485 /
2486
2487Return whether 'cls' is a derived from another class or is the same class.
2488
2489A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2490check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2491or ...`` etc.
2492[clinic start generated code]*/
2493
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002494static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002495builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002496 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002497/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002500
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002501 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 if (retval < 0)
2503 return NULL;
2504 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002505}
2506
2507
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002508typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 PyObject_HEAD
2510 Py_ssize_t tuplesize;
2511 PyObject *ittuple; /* tuple of iterators */
2512 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002513} zipobject;
2514
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002515static PyObject *
2516zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 zipobject *lz;
2519 Py_ssize_t i;
2520 PyObject *ittuple; /* tuple of iterators */
2521 PyObject *result;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002522 Py_ssize_t tuplesize;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002523
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03002524 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 /* args must be a tuple */
2528 assert(PyTuple_Check(args));
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002529 tuplesize = PyTuple_GET_SIZE(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00002530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 /* obtain iterators */
2532 ittuple = PyTuple_New(tuplesize);
2533 if (ittuple == NULL)
2534 return NULL;
2535 for (i=0; i < tuplesize; ++i) {
2536 PyObject *item = PyTuple_GET_ITEM(args, i);
2537 PyObject *it = PyObject_GetIter(item);
2538 if (it == NULL) {
2539 if (PyErr_ExceptionMatches(PyExc_TypeError))
2540 PyErr_Format(PyExc_TypeError,
2541 "zip argument #%zd must support iteration",
2542 i+1);
2543 Py_DECREF(ittuple);
2544 return NULL;
2545 }
2546 PyTuple_SET_ITEM(ittuple, i, it);
2547 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 /* create a result holder */
2550 result = PyTuple_New(tuplesize);
2551 if (result == NULL) {
2552 Py_DECREF(ittuple);
2553 return NULL;
2554 }
2555 for (i=0 ; i < tuplesize ; i++) {
2556 Py_INCREF(Py_None);
2557 PyTuple_SET_ITEM(result, i, Py_None);
2558 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 /* create zipobject structure */
2561 lz = (zipobject *)type->tp_alloc(type, 0);
2562 if (lz == NULL) {
2563 Py_DECREF(ittuple);
2564 Py_DECREF(result);
2565 return NULL;
2566 }
2567 lz->ittuple = ittuple;
2568 lz->tuplesize = tuplesize;
2569 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002572}
2573
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002574static void
2575zip_dealloc(zipobject *lz)
2576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 PyObject_GC_UnTrack(lz);
2578 Py_XDECREF(lz->ittuple);
2579 Py_XDECREF(lz->result);
2580 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002581}
2582
2583static int
2584zip_traverse(zipobject *lz, visitproc visit, void *arg)
2585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 Py_VISIT(lz->ittuple);
2587 Py_VISIT(lz->result);
2588 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002589}
2590
2591static PyObject *
2592zip_next(zipobject *lz)
2593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 Py_ssize_t i;
2595 Py_ssize_t tuplesize = lz->tuplesize;
2596 PyObject *result = lz->result;
2597 PyObject *it;
2598 PyObject *item;
2599 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 if (tuplesize == 0)
2602 return NULL;
2603 if (Py_REFCNT(result) == 1) {
2604 Py_INCREF(result);
2605 for (i=0 ; i < tuplesize ; i++) {
2606 it = PyTuple_GET_ITEM(lz->ittuple, i);
2607 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002608 if (item == NULL) {
2609 Py_DECREF(result);
2610 return NULL;
2611 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 olditem = PyTuple_GET_ITEM(result, i);
2613 PyTuple_SET_ITEM(result, i, item);
2614 Py_DECREF(olditem);
2615 }
2616 } else {
2617 result = PyTuple_New(tuplesize);
2618 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002619 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 for (i=0 ; i < tuplesize ; i++) {
2621 it = PyTuple_GET_ITEM(lz->ittuple, i);
2622 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002623 if (item == NULL) {
2624 Py_DECREF(result);
2625 return NULL;
2626 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 PyTuple_SET_ITEM(result, i, item);
2628 }
2629 }
2630 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002631}
Barry Warsawbd599b52000-08-03 15:45:29 +00002632
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002633static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302634zip_reduce(zipobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002635{
2636 /* Just recreate the zip with the internal iterator tuple */
2637 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2638}
2639
2640static PyMethodDef zip_methods[] = {
2641 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2642 {NULL, NULL} /* sentinel */
2643};
2644
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002645PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002646"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002647\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002648Return a zip object whose .__next__() method returns a tuple where\n\
2649the i-th element comes from the i-th iterable argument. The .__next__()\n\
2650method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002651is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002652
2653PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2655 "zip", /* tp_name */
2656 sizeof(zipobject), /* tp_basicsize */
2657 0, /* tp_itemsize */
2658 /* methods */
2659 (destructor)zip_dealloc, /* tp_dealloc */
2660 0, /* tp_print */
2661 0, /* tp_getattr */
2662 0, /* tp_setattr */
2663 0, /* tp_reserved */
2664 0, /* tp_repr */
2665 0, /* tp_as_number */
2666 0, /* tp_as_sequence */
2667 0, /* tp_as_mapping */
2668 0, /* tp_hash */
2669 0, /* tp_call */
2670 0, /* tp_str */
2671 PyObject_GenericGetAttr, /* tp_getattro */
2672 0, /* tp_setattro */
2673 0, /* tp_as_buffer */
2674 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2675 Py_TPFLAGS_BASETYPE, /* tp_flags */
2676 zip_doc, /* tp_doc */
2677 (traverseproc)zip_traverse, /* tp_traverse */
2678 0, /* tp_clear */
2679 0, /* tp_richcompare */
2680 0, /* tp_weaklistoffset */
2681 PyObject_SelfIter, /* tp_iter */
2682 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002683 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 0, /* tp_members */
2685 0, /* tp_getset */
2686 0, /* tp_base */
2687 0, /* tp_dict */
2688 0, /* tp_descr_get */
2689 0, /* tp_descr_set */
2690 0, /* tp_dictoffset */
2691 0, /* tp_init */
2692 PyType_GenericAlloc, /* tp_alloc */
2693 zip_new, /* tp_new */
2694 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002695};
Barry Warsawbd599b52000-08-03 15:45:29 +00002696
2697
Guido van Rossum79f25d91997-04-29 20:08:16 +00002698static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 {"__build_class__", (PyCFunction)builtin___build_class__,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002700 METH_FASTCALL | METH_KEYWORDS, build_class_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002702 BUILTIN_ABS_METHODDEF
2703 BUILTIN_ALL_METHODDEF
2704 BUILTIN_ANY_METHODDEF
2705 BUILTIN_ASCII_METHODDEF
2706 BUILTIN_BIN_METHODDEF
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002707 {"breakpoint", (PyCFunction)builtin_breakpoint, METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002708 BUILTIN_CALLABLE_METHODDEF
2709 BUILTIN_CHR_METHODDEF
2710 BUILTIN_COMPILE_METHODDEF
2711 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002713 BUILTIN_DIVMOD_METHODDEF
2714 BUILTIN_EVAL_METHODDEF
2715 BUILTIN_EXEC_METHODDEF
2716 BUILTIN_FORMAT_METHODDEF
Victor Stinner84b388b2017-01-17 03:52:27 +01002717 {"getattr", (PyCFunction)builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002718 BUILTIN_GLOBALS_METHODDEF
2719 BUILTIN_HASATTR_METHODDEF
2720 BUILTIN_HASH_METHODDEF
2721 BUILTIN_HEX_METHODDEF
2722 BUILTIN_ID_METHODDEF
2723 BUILTIN_INPUT_METHODDEF
2724 BUILTIN_ISINSTANCE_METHODDEF
2725 BUILTIN_ISSUBCLASS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 {"iter", builtin_iter, METH_VARARGS, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002727 BUILTIN_LEN_METHODDEF
2728 BUILTIN_LOCALS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2730 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
Victor Stinnerfda6d0a2017-01-17 04:09:14 +01002731 {"next", (PyCFunction)builtin_next, METH_FASTCALL, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002732 BUILTIN_OCT_METHODDEF
2733 BUILTIN_ORD_METHODDEF
2734 BUILTIN_POW_METHODDEF
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002735 {"print", (PyCFunction)builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002736 BUILTIN_REPR_METHODDEF
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002737 BUILTIN_ROUND_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002738 BUILTIN_SETATTR_METHODDEF
2739 BUILTIN_SORTED_METHODDEF
2740 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2742 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002743};
2744
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002745PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002746"Built-in functions, exceptions, and other objects.\n\
2747\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002748Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002749
Martin v. Löwis1a214512008-06-11 05:26:20 +00002750static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 PyModuleDef_HEAD_INIT,
2752 "builtins",
2753 builtin_doc,
2754 -1, /* multiple "initialization" just copies the module dict. */
2755 builtin_methods,
2756 NULL,
2757 NULL,
2758 NULL,
2759 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002760};
2761
2762
Guido van Rossum25ce5661997-08-02 03:10:38 +00002763PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002764_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002767
2768 if (PyType_Ready(&PyFilter_Type) < 0 ||
2769 PyType_Ready(&PyMap_Type) < 0 ||
2770 PyType_Ready(&PyZip_Type) < 0)
2771 return NULL;
2772
Eric Snowd393c1b2017-09-14 12:18:12 -06002773 mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 if (mod == NULL)
2775 return NULL;
2776 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002777
Tim Peters7571a0f2003-03-23 17:52:28 +00002778#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 /* "builtins" exposes a number of statically allocated objects
2780 * that, before this code was added in 2.3, never showed up in
2781 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2782 * result, programs leaking references to None and False (etc)
2783 * couldn't be diagnosed by examining sys.getobjects(0).
2784 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002785#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2786#else
2787#define ADD_TO_ALL(OBJECT) (void)0
2788#endif
2789
Tim Peters4b7625e2001-09-13 21:37:17 +00002790#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2792 return NULL; \
2793 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 SETBUILTIN("None", Py_None);
2796 SETBUILTIN("Ellipsis", Py_Ellipsis);
2797 SETBUILTIN("NotImplemented", Py_NotImplemented);
2798 SETBUILTIN("False", Py_False);
2799 SETBUILTIN("True", Py_True);
2800 SETBUILTIN("bool", &PyBool_Type);
2801 SETBUILTIN("memoryview", &PyMemoryView_Type);
2802 SETBUILTIN("bytearray", &PyByteArray_Type);
2803 SETBUILTIN("bytes", &PyBytes_Type);
2804 SETBUILTIN("classmethod", &PyClassMethod_Type);
2805 SETBUILTIN("complex", &PyComplex_Type);
2806 SETBUILTIN("dict", &PyDict_Type);
2807 SETBUILTIN("enumerate", &PyEnum_Type);
2808 SETBUILTIN("filter", &PyFilter_Type);
2809 SETBUILTIN("float", &PyFloat_Type);
2810 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2811 SETBUILTIN("property", &PyProperty_Type);
2812 SETBUILTIN("int", &PyLong_Type);
2813 SETBUILTIN("list", &PyList_Type);
2814 SETBUILTIN("map", &PyMap_Type);
2815 SETBUILTIN("object", &PyBaseObject_Type);
2816 SETBUILTIN("range", &PyRange_Type);
2817 SETBUILTIN("reversed", &PyReversed_Type);
2818 SETBUILTIN("set", &PySet_Type);
2819 SETBUILTIN("slice", &PySlice_Type);
2820 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2821 SETBUILTIN("str", &PyUnicode_Type);
2822 SETBUILTIN("super", &PySuper_Type);
2823 SETBUILTIN("tuple", &PyTuple_Type);
2824 SETBUILTIN("type", &PyType_Type);
2825 SETBUILTIN("zip", &PyZip_Type);
2826 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2827 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002828 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 return NULL;
2830 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002831 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002834#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002835#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002836}