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