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