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