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