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