LCOV - code coverage report
Current view: top level - Python - bltinmodule.c (source / functions) Hit Total Coverage
Test: CPython lcov report Lines: 327 1400 23.4 %
Date: 2017-04-19 Functions: 27 61 44.3 %

          Line data    Source code
       1             : /* Built-in functions */
       2             : 
       3             : #include "Python.h"
       4             : #include "Python-ast.h"
       5             : 
       6             : #include "node.h"
       7             : #include "code.h"
       8             : #include "eval.h"
       9             : 
      10             : #include <ctype.h>
      11             : #include <float.h> /* for DBL_MANT_DIG and friends */
      12             : 
      13             : #ifdef RISCOS
      14             : #include "unixstuff.h"
      15             : #endif
      16             : 
      17             : /* The default encoding used by the platform file system APIs
      18             :    Can remain NULL for all platforms that don't have such a concept
      19             : */
      20             : #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
      21             : const char *Py_FileSystemDefaultEncoding = "mbcs";
      22             : #elif defined(__APPLE__)
      23             : const char *Py_FileSystemDefaultEncoding = "utf-8";
      24             : #else
      25             : const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
      26             : #endif
      27             : 
      28             : /* Forward */
      29             : static PyObject *filterstring(PyObject *, PyObject *);
      30             : #ifdef Py_USING_UNICODE
      31             : static PyObject *filterunicode(PyObject *, PyObject *);
      32             : #endif
      33             : static PyObject *filtertuple (PyObject *, PyObject *);
      34             : 
      35             : static PyObject *
      36        1164 : builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
      37             : {
      38             :     static char *kwlist[] = {"name", "globals", "locals", "fromlist",
      39             :                              "level", 0};
      40             :     char *name;
      41        1164 :     PyObject *globals = NULL;
      42        1164 :     PyObject *locals = NULL;
      43        1164 :     PyObject *fromlist = NULL;
      44        1164 :     int level = -1;
      45             : 
      46        1164 :     if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
      47             :                     kwlist, &name, &globals, &locals, &fromlist, &level))
      48           0 :         return NULL;
      49        1164 :     return PyImport_ImportModuleLevel(name, globals, locals,
      50             :                                       fromlist, level);
      51             : }
      52             : 
      53             : PyDoc_STRVAR(import_doc,
      54             : "__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
      55             : \n\
      56             : Import a module. Because this function is meant for use by the Python\n\
      57             : interpreter and not for general use it is better to use\n\
      58             : importlib.import_module() to programmatically import a module.\n\
      59             : \n\
      60             : The globals argument is only used to determine the context;\n\
      61             : they are not modified.  The locals argument is unused.  The fromlist\n\
      62             : should be a list of names to emulate ``from name import ...'', or an\n\
      63             : empty list to emulate ``import name''.\n\
      64             : When importing a module from a package, note that __import__('A.B', ...)\n\
      65             : returns package A when fromlist is empty, but its submodule B when\n\
      66             : fromlist is not empty.  Level is used to determine whether to perform \n\
      67             : absolute or relative imports.  -1 is the original strategy of attempting\n\
      68             : both absolute and relative imports, 0 is absolute, a positive number\n\
      69             : is the number of parent directories to search relative to the current module.");
      70             : 
      71             : 
      72             : static PyObject *
      73           0 : builtin_abs(PyObject *self, PyObject *v)
      74             : {
      75           0 :     return PyNumber_Absolute(v);
      76             : }
      77             : 
      78             : PyDoc_STRVAR(abs_doc,
      79             : "abs(number) -> number\n\
      80             : \n\
      81             : Return the absolute value of the argument.");
      82             : 
      83             : static PyObject *
      84         141 : builtin_all(PyObject *self, PyObject *v)
      85             : {
      86             :     PyObject *it, *item;
      87             :     PyObject *(*iternext)(PyObject *);
      88             :     int cmp;
      89             : 
      90         141 :     it = PyObject_GetIter(v);
      91         141 :     if (it == NULL)
      92           0 :         return NULL;
      93         141 :     iternext = *Py_TYPE(it)->tp_iternext;
      94             : 
      95             :     for (;;) {
      96        1101 :         item = iternext(it);
      97        1101 :         if (item == NULL)
      98         141 :             break;
      99         960 :         cmp = PyObject_IsTrue(item);
     100         960 :         Py_DECREF(item);
     101         960 :         if (cmp < 0) {
     102           0 :             Py_DECREF(it);
     103           0 :             return NULL;
     104             :         }
     105         960 :         if (cmp == 0) {
     106           0 :             Py_DECREF(it);
     107           0 :             Py_RETURN_FALSE;
     108             :         }
     109         960 :     }
     110         141 :     Py_DECREF(it);
     111         141 :     if (PyErr_Occurred()) {
     112           0 :         if (PyErr_ExceptionMatches(PyExc_StopIteration))
     113           0 :             PyErr_Clear();
     114             :         else
     115           0 :             return NULL;
     116             :     }
     117         141 :     Py_RETURN_TRUE;
     118             : }
     119             : 
     120             : PyDoc_STRVAR(all_doc,
     121             : "all(iterable) -> bool\n\
     122             : \n\
     123             : Return True if bool(x) is True for all values x in the iterable.\n\
     124             : If the iterable is empty, return True.");
     125             : 
     126             : static PyObject *
     127           3 : builtin_any(PyObject *self, PyObject *v)
     128             : {
     129             :     PyObject *it, *item;
     130             :     PyObject *(*iternext)(PyObject *);
     131             :     int cmp;
     132             : 
     133           3 :     it = PyObject_GetIter(v);
     134           3 :     if (it == NULL)
     135           0 :         return NULL;
     136           3 :     iternext = *Py_TYPE(it)->tp_iternext;
     137             : 
     138             :     for (;;) {
     139          12 :         item = iternext(it);
     140          12 :         if (item == NULL)
     141           3 :             break;
     142           9 :         cmp = PyObject_IsTrue(item);
     143           9 :         Py_DECREF(item);
     144           9 :         if (cmp < 0) {
     145           0 :             Py_DECREF(it);
     146           0 :             return NULL;
     147             :         }
     148           9 :         if (cmp == 1) {
     149           0 :             Py_DECREF(it);
     150           0 :             Py_RETURN_TRUE;
     151             :         }
     152           9 :     }
     153           3 :     Py_DECREF(it);
     154           3 :     if (PyErr_Occurred()) {
     155           0 :         if (PyErr_ExceptionMatches(PyExc_StopIteration))
     156           0 :             PyErr_Clear();
     157             :         else
     158           0 :             return NULL;
     159             :     }
     160           3 :     Py_RETURN_FALSE;
     161             : }
     162             : 
     163             : PyDoc_STRVAR(any_doc,
     164             : "any(iterable) -> bool\n\
     165             : \n\
     166             : Return True if bool(x) is True for any x in the iterable.\n\
     167             : If the iterable is empty, return False.");
     168             : 
     169             : static PyObject *
     170           0 : builtin_apply(PyObject *self, PyObject *args)
     171             : {
     172           0 :     PyObject *func, *alist = NULL, *kwdict = NULL;
     173           0 :     PyObject *t = NULL, *retval = NULL;
     174             : 
     175           0 :     if (PyErr_WarnPy3k("apply() not supported in 3.x; "
     176           0 :                        "use func(*args, **kwargs)", 1) < 0)
     177           0 :         return NULL;
     178             : 
     179           0 :     if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict))
     180           0 :         return NULL;
     181           0 :     if (alist != NULL) {
     182           0 :         if (!PyTuple_Check(alist)) {
     183           0 :             if (!PySequence_Check(alist)) {
     184           0 :                 PyErr_Format(PyExc_TypeError,
     185             :                      "apply() arg 2 expected sequence, found %s",
     186           0 :                          alist->ob_type->tp_name);
     187           0 :                 return NULL;
     188             :             }
     189           0 :             t = PySequence_Tuple(alist);
     190           0 :             if (t == NULL)
     191           0 :                 return NULL;
     192           0 :             alist = t;
     193             :         }
     194             :     }
     195           0 :     if (kwdict != NULL && !PyDict_Check(kwdict)) {
     196           0 :         PyErr_Format(PyExc_TypeError,
     197             :                      "apply() arg 3 expected dictionary, found %s",
     198           0 :                      kwdict->ob_type->tp_name);
     199           0 :         goto finally;
     200             :     }
     201           0 :     retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
     202             :   finally:
     203           0 :     Py_XDECREF(t);
     204           0 :     return retval;
     205             : }
     206             : 
     207             : PyDoc_STRVAR(apply_doc,
     208             : "apply(object[, args[, kwargs]]) -> value\n\
     209             : \n\
     210             : Call a callable object with positional arguments taken from the tuple args,\n\
     211             : and keyword arguments taken from the optional dictionary kwargs.\n\
     212             : Note that classes are callable, as are instances with a __call__() method.\n\
     213             : \n\
     214             : Deprecated since release 2.3. Instead, use the extended call syntax:\n\
     215             :     function(*args, **keywords).");
     216             : 
     217             : 
     218             : static PyObject *
     219           0 : builtin_bin(PyObject *self, PyObject *v)
     220             : {
     221           0 :     return PyNumber_ToBase(v, 2);
     222             : }
     223             : 
     224             : PyDoc_STRVAR(bin_doc,
     225             : "bin(number) -> string\n\
     226             : \n\
     227             : Return the binary representation of an integer or long integer.");
     228             : 
     229             : 
     230             : static PyObject *
     231           0 : builtin_callable(PyObject *self, PyObject *v)
     232             : {
     233           0 :     return PyBool_FromLong((long)PyCallable_Check(v));
     234             : }
     235             : 
     236             : PyDoc_STRVAR(callable_doc,
     237             : "callable(object) -> bool\n\
     238             : \n\
     239             : Return whether the object is callable (i.e., some kind of function).\n\
     240             : Note that classes are callable, as are instances with a __call__() method.");
     241             : 
     242             : 
     243             : static PyObject *
     244          33 : builtin_filter(PyObject *self, PyObject *args)
     245             : {
     246             :     PyObject *func, *seq, *result, *it, *arg;
     247             :     Py_ssize_t len;   /* guess for result list size */
     248             :     register Py_ssize_t j;
     249             : 
     250          33 :     if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
     251           0 :         return NULL;
     252             : 
     253             :     /* Strings and tuples return a result of the same type. */
     254          33 :     if (PyString_Check(seq))
     255           0 :         return filterstring(func, seq);
     256             : #ifdef Py_USING_UNICODE
     257          33 :     if (PyUnicode_Check(seq))
     258           0 :         return filterunicode(func, seq);
     259             : #endif
     260          33 :     if (PyTuple_Check(seq))
     261          33 :         return filtertuple(func, seq);
     262             : 
     263             :     /* Pre-allocate argument list tuple. */
     264           0 :     arg = PyTuple_New(1);
     265           0 :     if (arg == NULL)
     266           0 :         return NULL;
     267             : 
     268             :     /* Get iterator. */
     269           0 :     it = PyObject_GetIter(seq);
     270           0 :     if (it == NULL)
     271           0 :         goto Fail_arg;
     272             : 
     273             :     /* Guess a result list size. */
     274           0 :     len = _PyObject_LengthHint(seq, 8);
     275           0 :     if (len == -1)
     276           0 :         goto Fail_it;
     277             : 
     278             :     /* Get a result list. */
     279           0 :     if (PyList_Check(seq) && seq->ob_refcnt == 1) {
     280             :         /* Eww - can modify the list in-place. */
     281           0 :         Py_INCREF(seq);
     282           0 :         result = seq;
     283             :     }
     284             :     else {
     285           0 :         result = PyList_New(len);
     286           0 :         if (result == NULL)
     287           0 :             goto Fail_it;
     288             :     }
     289             : 
     290             :     /* Build the result list. */
     291           0 :     j = 0;
     292             :     for (;;) {
     293             :         PyObject *item;
     294             :         int ok;
     295             : 
     296           0 :         item = PyIter_Next(it);
     297           0 :         if (item == NULL) {
     298           0 :             if (PyErr_Occurred())
     299           0 :                 goto Fail_result_it;
     300           0 :             break;
     301             :         }
     302             : 
     303           0 :         if (func == (PyObject *)&PyBool_Type || func == Py_None) {
     304           0 :             ok = PyObject_IsTrue(item);
     305             :         }
     306             :         else {
     307             :             PyObject *good;
     308           0 :             PyTuple_SET_ITEM(arg, 0, item);
     309           0 :             good = PyObject_Call(func, arg, NULL);
     310           0 :             PyTuple_SET_ITEM(arg, 0, NULL);
     311           0 :             if (good == NULL) {
     312           0 :                 Py_DECREF(item);
     313           0 :                 goto Fail_result_it;
     314             :             }
     315           0 :             ok = PyObject_IsTrue(good);
     316           0 :             Py_DECREF(good);
     317             :         }
     318           0 :         if (ok > 0) {
     319           0 :             if (j < len)
     320           0 :                 PyList_SET_ITEM(result, j, item);
     321             :             else {
     322           0 :                 int status = PyList_Append(result, item);
     323           0 :                 Py_DECREF(item);
     324           0 :                 if (status < 0)
     325           0 :                     goto Fail_result_it;
     326             :             }
     327           0 :             ++j;
     328             :         }
     329             :         else {
     330           0 :             Py_DECREF(item);
     331           0 :             if (ok < 0)
     332           0 :                 goto Fail_result_it;
     333             :         }
     334           0 :     }
     335             : 
     336             : 
     337             :     /* Cut back result list if len is too big. */
     338           0 :     if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
     339           0 :         goto Fail_result_it;
     340             : 
     341           0 :     Py_DECREF(it);
     342           0 :     Py_DECREF(arg);
     343           0 :     return result;
     344             : 
     345             : Fail_result_it:
     346           0 :     Py_DECREF(result);
     347             : Fail_it:
     348           0 :     Py_DECREF(it);
     349             : Fail_arg:
     350           0 :     Py_DECREF(arg);
     351           0 :     return NULL;
     352             : }
     353             : 
     354             : PyDoc_STRVAR(filter_doc,
     355             : "filter(function or None, sequence) -> list, tuple, or string\n"
     356             : "\n"
     357             : "Return those items of sequence for which function(item) is true.  If\n"
     358             : "function is None, return the items that are true.  If sequence is a tuple\n"
     359             : "or string, return the same type, else return a list.");
     360             : 
     361             : static PyObject *
     362           0 : builtin_format(PyObject *self, PyObject *args)
     363             : {
     364             :     PyObject *value;
     365           0 :     PyObject *format_spec = NULL;
     366             : 
     367           0 :     if (!PyArg_ParseTuple(args, "O|O:format", &value, &format_spec))
     368           0 :         return NULL;
     369             : 
     370           0 :     return PyObject_Format(value, format_spec);
     371             : }
     372             : 
     373             : PyDoc_STRVAR(format_doc,
     374             : "format(value[, format_spec]) -> string\n\
     375             : \n\
     376             : Returns value.__format__(format_spec)\n\
     377             : format_spec defaults to \"\"");
     378             : 
     379             : static PyObject *
     380        3084 : builtin_chr(PyObject *self, PyObject *args)
     381             : {
     382             :     long x;
     383             :     char s[1];
     384             : 
     385        3084 :     if (!PyArg_ParseTuple(args, "l:chr", &x))
     386           0 :         return NULL;
     387        3084 :     if (x < 0 || x >= 256) {
     388           0 :         PyErr_SetString(PyExc_ValueError,
     389             :                         "chr() arg not in range(256)");
     390           0 :         return NULL;
     391             :     }
     392        3084 :     s[0] = (char)x;
     393        3084 :     return PyString_FromStringAndSize(s, 1);
     394             : }
     395             : 
     396             : PyDoc_STRVAR(chr_doc,
     397             : "chr(i) -> character\n\
     398             : \n\
     399             : Return a string of one character with ordinal i; 0 <= i < 256.");
     400             : 
     401             : 
     402             : #ifdef Py_USING_UNICODE
     403             : static PyObject *
     404           0 : builtin_unichr(PyObject *self, PyObject *args)
     405             : {
     406             :     int x;
     407             : 
     408           0 :     if (!PyArg_ParseTuple(args, "i:unichr", &x))
     409           0 :         return NULL;
     410             : 
     411           0 :     return PyUnicode_FromOrdinal(x);
     412             : }
     413             : 
     414             : PyDoc_STRVAR(unichr_doc,
     415             : "unichr(i) -> Unicode character\n\
     416             : \n\
     417             : Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
     418             : #endif
     419             : 
     420             : 
     421             : static PyObject *
     422           0 : builtin_cmp(PyObject *self, PyObject *args)
     423             : {
     424             :     PyObject *a, *b;
     425             :     int c;
     426             : 
     427           0 :     if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
     428           0 :         return NULL;
     429           0 :     if (PyObject_Cmp(a, b, &c) < 0)
     430           0 :         return NULL;
     431           0 :     return PyInt_FromLong((long)c);
     432             : }
     433             : 
     434             : PyDoc_STRVAR(cmp_doc,
     435             : "cmp(x, y) -> integer\n\
     436             : \n\
     437             : Return negative if x<y, zero if x==y, positive if x>y.");
     438             : 
     439             : 
     440             : static PyObject *
     441           0 : builtin_coerce(PyObject *self, PyObject *args)
     442             : {
     443             :     PyObject *v, *w;
     444             :     PyObject *res;
     445             : 
     446           0 :     if (PyErr_WarnPy3k("coerce() not supported in 3.x", 1) < 0)
     447           0 :         return NULL;
     448             : 
     449           0 :     if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))
     450           0 :         return NULL;
     451           0 :     if (PyNumber_Coerce(&v, &w) < 0)
     452           0 :         return NULL;
     453           0 :     res = PyTuple_Pack(2, v, w);
     454           0 :     Py_DECREF(v);
     455           0 :     Py_DECREF(w);
     456           0 :     return res;
     457             : }
     458             : 
     459             : PyDoc_STRVAR(coerce_doc,
     460             : "coerce(x, y) -> (x1, y1)\n\
     461             : \n\
     462             : Return a tuple consisting of the two numeric arguments converted to\n\
     463             : a common type, using the same rules as used by arithmetic operations.\n\
     464             : If coercion is not possible, raise TypeError.");
     465             : 
     466             : static PyObject *
     467           0 : builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
     468             : {
     469             :     char *str;
     470             :     char *filename;
     471             :     char *startstr;
     472           0 :     int mode = -1;
     473           0 :     int dont_inherit = 0;
     474           0 :     int supplied_flags = 0;
     475             :     int is_ast;
     476             :     PyCompilerFlags cf;
     477           0 :     PyObject *result = NULL, *cmd, *tmp = NULL;
     478             :     Py_ssize_t length;
     479             :     static char *kwlist[] = {"source", "filename", "mode", "flags",
     480             :                              "dont_inherit", NULL};
     481           0 :     int start[] = {Py_file_input, Py_eval_input, Py_single_input};
     482             : 
     483           0 :     if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
     484             :                                      kwlist, &cmd, &filename, &startstr,
     485             :                                      &supplied_flags, &dont_inherit))
     486           0 :         return NULL;
     487             : 
     488           0 :     cf.cf_flags = supplied_flags;
     489             : 
     490           0 :     if (supplied_flags &
     491             :         ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
     492             :     {
     493           0 :         PyErr_SetString(PyExc_ValueError,
     494             :                         "compile(): unrecognised flags");
     495           0 :         return NULL;
     496             :     }
     497             :     /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
     498             : 
     499           0 :     if (!dont_inherit) {
     500           0 :         PyEval_MergeCompilerFlags(&cf);
     501             :     }
     502             : 
     503           0 :     if (strcmp(startstr, "exec") == 0)
     504           0 :         mode = 0;
     505           0 :     else if (strcmp(startstr, "eval") == 0)
     506           0 :         mode = 1;
     507           0 :     else if (strcmp(startstr, "single") == 0)
     508           0 :         mode = 2;
     509             :     else {
     510           0 :         PyErr_SetString(PyExc_ValueError,
     511             :                         "compile() arg 3 must be 'exec', 'eval' or 'single'");
     512           0 :         return NULL;
     513             :     }
     514             : 
     515           0 :     is_ast = PyAST_Check(cmd);
     516           0 :     if (is_ast == -1)
     517           0 :         return NULL;
     518           0 :     if (is_ast) {
     519           0 :         if (supplied_flags & PyCF_ONLY_AST) {
     520           0 :             Py_INCREF(cmd);
     521           0 :             result = cmd;
     522             :         }
     523             :         else {
     524             :             PyArena *arena;
     525             :             mod_ty mod;
     526             : 
     527           0 :             arena = PyArena_New();
     528           0 :             if (arena == NULL)
     529           0 :                 return NULL;
     530           0 :             mod = PyAST_obj2mod(cmd, arena, mode);
     531           0 :             if (mod == NULL) {
     532           0 :                 PyArena_Free(arena);
     533           0 :                 return NULL;
     534             :             }
     535           0 :             result = (PyObject*)PyAST_Compile(mod, filename,
     536             :                                               &cf, arena);
     537           0 :             PyArena_Free(arena);
     538             :         }
     539           0 :         return result;
     540             :     }
     541           0 :     if (PyString_Check(cmd)) {
     542           0 :         str = PyString_AS_STRING(cmd);
     543           0 :         length = PyString_GET_SIZE(cmd);
     544             :     }
     545             : #ifdef Py_USING_UNICODE
     546           0 :     else if (PyUnicode_Check(cmd)) {
     547           0 :         tmp = PyUnicode_AsUTF8String(cmd);
     548           0 :         if (tmp == NULL)
     549           0 :             return NULL;
     550           0 :         cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
     551           0 :         str = PyString_AS_STRING(tmp);
     552           0 :         length = PyString_GET_SIZE(tmp);
     553             :     }
     554             : #endif
     555           0 :     else if (!PyObject_AsReadBuffer(cmd, (const void **)&str, &length)) {
     556             :         /* Copy to NUL-terminated buffer. */
     557           0 :         tmp = PyString_FromStringAndSize(str, length);
     558           0 :         if (tmp == NULL)
     559           0 :             return NULL;
     560           0 :         str = PyString_AS_STRING(tmp);
     561           0 :         length = PyString_GET_SIZE(tmp);
     562             :     }
     563             :     else
     564           0 :         goto cleanup;
     565           0 :     if ((size_t)length != strlen(str)) {
     566           0 :         PyErr_SetString(PyExc_TypeError,
     567             :                         "compile() expected string without null bytes");
     568           0 :         goto cleanup;
     569             :     }
     570           0 :     result = Py_CompileStringFlags(str, filename, start[mode], &cf);
     571             : cleanup:
     572           0 :     Py_XDECREF(tmp);
     573           0 :     return result;
     574             : }
     575             : 
     576             : PyDoc_STRVAR(compile_doc,
     577             : "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
     578             : \n\
     579             : Compile the source string (a Python module, statement or expression)\n\
     580             : into a code object that can be executed by the exec statement or eval().\n\
     581             : The filename will be used for run-time error messages.\n\
     582             : The mode must be 'exec' to compile a module, 'single' to compile a\n\
     583             : single (interactive) statement, or 'eval' to compile an expression.\n\
     584             : The flags argument, if present, controls which future statements influence\n\
     585             : the compilation of the code.\n\
     586             : The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
     587             : the effects of any future statements in effect in the code calling\n\
     588             : compile; if absent or zero these statements do influence the compilation,\n\
     589             : in addition to any features explicitly specified.");
     590             : 
     591             : static PyObject *
     592           6 : builtin_dir(PyObject *self, PyObject *args)
     593             : {
     594           6 :     PyObject *arg = NULL;
     595             : 
     596           6 :     if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
     597           0 :         return NULL;
     598           6 :     return PyObject_Dir(arg);
     599             : }
     600             : 
     601             : PyDoc_STRVAR(dir_doc,
     602             : "dir([object]) -> list of strings\n"
     603             : "\n"
     604             : "If called without an argument, return the names in the current scope.\n"
     605             : "Else, return an alphabetized list of names comprising (some of) the attributes\n"
     606             : "of the given object, and of attributes reachable from it.\n"
     607             : "If the object supplies a method named __dir__, it will be used; otherwise\n"
     608             : "the default dir() logic is used and returns:\n"
     609             : "  for a module object: the module's attributes.\n"
     610             : "  for a class object:  its attributes, and recursively the attributes\n"
     611             : "    of its bases.\n"
     612             : "  for any other object: its attributes, its class's attributes, and\n"
     613             : "    recursively the attributes of its class's base classes.");
     614             : 
     615             : static PyObject *
     616           0 : builtin_divmod(PyObject *self, PyObject *args)
     617             : {
     618             :     PyObject *v, *w;
     619             : 
     620           0 :     if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
     621           0 :         return NULL;
     622           0 :     return PyNumber_Divmod(v, w);
     623             : }
     624             : 
     625             : PyDoc_STRVAR(divmod_doc,
     626             : "divmod(x, y) -> (quotient, remainder)\n\
     627             : \n\
     628             : Return the tuple (x//y, x%y).  Invariant: div*y + mod == x.");
     629             : 
     630             : 
     631             : static PyObject *
     632           0 : builtin_eval(PyObject *self, PyObject *args)
     633             : {
     634           0 :     PyObject *cmd, *result, *tmp = NULL;
     635           0 :     PyObject *globals = Py_None, *locals = Py_None;
     636             :     char *str;
     637             :     PyCompilerFlags cf;
     638             : 
     639           0 :     if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
     640           0 :         return NULL;
     641           0 :     if (locals != Py_None && !PyMapping_Check(locals)) {
     642           0 :         PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
     643           0 :         return NULL;
     644             :     }
     645           0 :     if (globals != Py_None && !PyDict_Check(globals)) {
     646           0 :         PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
     647             :             "globals must be a real dict; try eval(expr, {}, mapping)"
     648             :             : "globals must be a dict");
     649           0 :         return NULL;
     650             :     }
     651           0 :     if (globals == Py_None) {
     652           0 :         globals = PyEval_GetGlobals();
     653           0 :         if (locals == Py_None)
     654           0 :             locals = PyEval_GetLocals();
     655             :     }
     656           0 :     else if (locals == Py_None)
     657           0 :         locals = globals;
     658             : 
     659           0 :     if (globals == NULL || locals == NULL) {
     660           0 :         PyErr_SetString(PyExc_TypeError,
     661             :             "eval must be given globals and locals "
     662             :             "when called without a frame");
     663           0 :         return NULL;
     664             :     }
     665             : 
     666           0 :     if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
     667           0 :         if (PyDict_SetItemString(globals, "__builtins__",
     668             :                                  PyEval_GetBuiltins()) != 0)
     669           0 :             return NULL;
     670             :     }
     671             : 
     672           0 :     if (PyCode_Check(cmd)) {
     673           0 :         if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
     674           0 :             PyErr_SetString(PyExc_TypeError,
     675             :         "code object passed to eval() may not contain free variables");
     676           0 :             return NULL;
     677             :         }
     678           0 :         return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
     679             :     }
     680             : 
     681           0 :     if (!PyString_Check(cmd) &&
     682           0 :         !PyUnicode_Check(cmd)) {
     683           0 :         PyErr_SetString(PyExc_TypeError,
     684             :                    "eval() arg 1 must be a string or code object");
     685           0 :         return NULL;
     686             :     }
     687           0 :     cf.cf_flags = 0;
     688             : 
     689             : #ifdef Py_USING_UNICODE
     690           0 :     if (PyUnicode_Check(cmd)) {
     691           0 :         tmp = PyUnicode_AsUTF8String(cmd);
     692           0 :         if (tmp == NULL)
     693           0 :             return NULL;
     694           0 :         cmd = tmp;
     695           0 :         cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
     696             :     }
     697             : #endif
     698           0 :     if (PyString_AsStringAndSize(cmd, &str, NULL)) {
     699           0 :         Py_XDECREF(tmp);
     700           0 :         return NULL;
     701             :     }
     702           0 :     while (*str == ' ' || *str == '\t')
     703           0 :         str++;
     704             : 
     705           0 :     (void)PyEval_MergeCompilerFlags(&cf);
     706           0 :     result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
     707           0 :     Py_XDECREF(tmp);
     708           0 :     return result;
     709             : }
     710             : 
     711             : PyDoc_STRVAR(eval_doc,
     712             : "eval(source[, globals[, locals]]) -> value\n\
     713             : \n\
     714             : Evaluate the source in the context of globals and locals.\n\
     715             : The source may be a string representing a Python expression\n\
     716             : or a code object as returned by compile().\n\
     717             : The globals must be a dictionary and locals can be any mapping,\n\
     718             : defaulting to the current globals and locals.\n\
     719             : If only globals is given, locals defaults to it.\n");
     720             : 
     721             : 
     722             : static PyObject *
     723           0 : builtin_execfile(PyObject *self, PyObject *args)
     724             : {
     725             :     char *filename;
     726           0 :     PyObject *globals = Py_None, *locals = Py_None;
     727             :     PyObject *res;
     728           0 :     FILE* fp = NULL;
     729             :     PyCompilerFlags cf;
     730             :     int exists;
     731             : 
     732           0 :     if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",
     733           0 :                        1) < 0)
     734           0 :         return NULL;
     735             : 
     736           0 :     if (!PyArg_ParseTuple(args, "s|O!O:execfile",
     737             :                     &filename,
     738             :                     &PyDict_Type, &globals,
     739             :                     &locals))
     740           0 :         return NULL;
     741           0 :     if (locals != Py_None && !PyMapping_Check(locals)) {
     742           0 :         PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
     743           0 :         return NULL;
     744             :     }
     745           0 :     if (globals == Py_None) {
     746           0 :         globals = PyEval_GetGlobals();
     747           0 :         if (locals == Py_None)
     748           0 :             locals = PyEval_GetLocals();
     749             :     }
     750           0 :     else if (locals == Py_None)
     751           0 :         locals = globals;
     752           0 :     if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
     753           0 :         if (PyDict_SetItemString(globals, "__builtins__",
     754             :                                  PyEval_GetBuiltins()) != 0)
     755           0 :             return NULL;
     756             :     }
     757             : 
     758           0 :     exists = 0;
     759             :     /* Test for existence or directory. */
     760             : #if defined(PLAN9)
     761             :     {
     762             :         Dir *d;
     763             : 
     764             :         if ((d = dirstat(filename))!=nil) {
     765             :             if(d->mode & DMDIR)
     766             :                 werrstr("is a directory");
     767             :             else
     768             :                 exists = 1;
     769             :             free(d);
     770             :         }
     771             :     }
     772             : #elif defined(RISCOS)
     773             :     if (object_exists(filename)) {
     774             :         if (isdir(filename))
     775             :             errno = EISDIR;
     776             :         else
     777             :             exists = 1;
     778             :     }
     779             : #else   /* standard Posix */
     780             :     {
     781             :         struct stat s;
     782           0 :         if (stat(filename, &s) == 0) {
     783           0 :             if (S_ISDIR(s.st_mode))
     784             : #                               if defined(PYOS_OS2) && defined(PYCC_VACPP)
     785             :                             errno = EOS2ERR;
     786             : #                               else
     787           0 :                             errno = EISDIR;
     788             : #                               endif
     789             :             else
     790           0 :                 exists = 1;
     791             :         }
     792             :     }
     793             : #endif
     794             : 
     795           0 :     if (exists) {
     796             :         Py_BEGIN_ALLOW_THREADS
     797           0 :         fp = fopen(filename, "r" PY_STDIOTEXTMODE);
     798             :         Py_END_ALLOW_THREADS
     799             : 
     800           0 :         if (fp == NULL) {
     801           0 :             exists = 0;
     802             :         }
     803             :     }
     804             : 
     805           0 :     if (!exists) {
     806           0 :         PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
     807           0 :         return NULL;
     808             :     }
     809           0 :     cf.cf_flags = 0;
     810           0 :     if (PyEval_MergeCompilerFlags(&cf))
     811           0 :         res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
     812             :                            locals, 1, &cf);
     813             :     else
     814           0 :         res = PyRun_FileEx(fp, filename, Py_file_input, globals,
     815             :                            locals, 1);
     816           0 :     return res;
     817             : }
     818             : 
     819             : PyDoc_STRVAR(execfile_doc,
     820             : "execfile(filename[, globals[, locals]])\n\
     821             : \n\
     822             : Read and execute a Python script from a file.\n\
     823             : The globals and locals are dictionaries, defaulting to the current\n\
     824             : globals and locals.  If only globals is given, locals defaults to it.");
     825             : 
     826             : 
     827             : static PyObject *
     828         735 : builtin_getattr(PyObject *self, PyObject *args)
     829             : {
     830         735 :     PyObject *v, *result, *dflt = NULL;
     831             :     PyObject *name;
     832             : 
     833         735 :     if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
     834           0 :         return NULL;
     835             : #ifdef Py_USING_UNICODE
     836         735 :     if (PyUnicode_Check(name)) {
     837           0 :         name = _PyUnicode_AsDefaultEncodedString(name, NULL);
     838           0 :         if (name == NULL)
     839           0 :             return NULL;
     840             :     }
     841             : #endif
     842             : 
     843         735 :     if (!PyString_Check(name)) {
     844           0 :         PyErr_SetString(PyExc_TypeError,
     845             :                         "getattr(): attribute name must be string");
     846           0 :         return NULL;
     847             :     }
     848         735 :     result = PyObject_GetAttr(v, name);
     849        1107 :     if (result == NULL && dflt != NULL &&
     850         372 :         PyErr_ExceptionMatches(PyExc_AttributeError))
     851             :     {
     852         372 :         PyErr_Clear();
     853         372 :         Py_INCREF(dflt);
     854         372 :         result = dflt;
     855             :     }
     856         735 :     return result;
     857             : }
     858             : 
     859             : PyDoc_STRVAR(getattr_doc,
     860             : "getattr(object, name[, default]) -> value\n\
     861             : \n\
     862             : Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
     863             : When a default argument is given, it is returned when the attribute doesn't\n\
     864             : exist; without it, an exception is raised in that case.");
     865             : 
     866             : 
     867             : static PyObject *
     868          51 : builtin_globals(PyObject *self)
     869             : {
     870             :     PyObject *d;
     871             : 
     872          51 :     d = PyEval_GetGlobals();
     873          51 :     Py_XINCREF(d);
     874          51 :     return d;
     875             : }
     876             : 
     877             : PyDoc_STRVAR(globals_doc,
     878             : "globals() -> dictionary\n\
     879             : \n\
     880             : Return the dictionary containing the current scope's global variables.");
     881             : 
     882             : 
     883             : static PyObject *
     884          57 : builtin_hasattr(PyObject *self, PyObject *args)
     885             : {
     886             :     PyObject *v;
     887             :     PyObject *name;
     888             : 
     889          57 :     if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
     890           0 :         return NULL;
     891             : #ifdef Py_USING_UNICODE
     892          57 :     if (PyUnicode_Check(name)) {
     893           0 :         name = _PyUnicode_AsDefaultEncodedString(name, NULL);
     894           0 :         if (name == NULL)
     895           0 :             return NULL;
     896             :     }
     897             : #endif
     898             : 
     899          57 :     if (!PyString_Check(name)) {
     900           0 :         PyErr_SetString(PyExc_TypeError,
     901             :                         "hasattr(): attribute name must be string");
     902           0 :         return NULL;
     903             :     }
     904          57 :     v = PyObject_GetAttr(v, name);
     905          57 :     if (v == NULL) {
     906          12 :         if (!PyErr_ExceptionMatches(PyExc_Exception))
     907           0 :             return NULL;
     908             :         else {
     909          12 :             PyErr_Clear();
     910          12 :             Py_INCREF(Py_False);
     911          12 :             return Py_False;
     912             :         }
     913             :     }
     914          45 :     Py_DECREF(v);
     915          45 :     Py_INCREF(Py_True);
     916          45 :     return Py_True;
     917             : }
     918             : 
     919             : PyDoc_STRVAR(hasattr_doc,
     920             : "hasattr(object, name) -> bool\n\
     921             : \n\
     922             : Return whether the object has an attribute with the given name.\n\
     923             : (This is done by calling getattr(object, name) and catching exceptions.)");
     924             : 
     925             : 
     926             : static PyObject *
     927           0 : builtin_id(PyObject *self, PyObject *v)
     928             : {
     929           0 :     return PyLong_FromVoidPtr(v);
     930             : }
     931             : 
     932             : PyDoc_STRVAR(id_doc,
     933             : "id(object) -> integer\n\
     934             : \n\
     935             : Return the identity of an object.  This is guaranteed to be unique among\n\
     936             : simultaneously existing objects.  (Hint: it's the object's memory address.)");
     937             : 
     938             : 
     939             : static PyObject *
     940          54 : builtin_map(PyObject *self, PyObject *args)
     941             : {
     942             :     typedef struct {
     943             :         PyObject *it;           /* the iterator object */
     944             :         int saw_StopIteration;  /* bool:  did the iterator end? */
     945             :     } sequence;
     946             : 
     947             :     PyObject *func, *result;
     948          54 :     sequence *seqs = NULL, *sqp;
     949             :     Py_ssize_t n, len;
     950             :     register int i, j;
     951             : 
     952          54 :     n = PyTuple_Size(args);
     953          54 :     if (n < 2) {
     954           0 :         PyErr_SetString(PyExc_TypeError,
     955             :                         "map() requires at least two args");
     956           0 :         return NULL;
     957             :     }
     958             : 
     959          54 :     func = PyTuple_GetItem(args, 0);
     960          54 :     n--;
     961             : 
     962          54 :     if (func == Py_None) {
     963           0 :         if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "
     964           0 :                            "use list(...)", 1) < 0)
     965           0 :             return NULL;
     966           0 :         if (n == 1) {
     967             :             /* map(None, S) is the same as list(S). */
     968           0 :             return PySequence_List(PyTuple_GetItem(args, 1));
     969             :         }
     970             :     }
     971             : 
     972             :     /* Get space for sequence descriptors.  Must NULL out the iterator
     973             :      * pointers so that jumping to Fail_2 later doesn't see trash.
     974             :      */
     975          54 :     if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
     976           0 :         PyErr_NoMemory();
     977           0 :         return NULL;
     978             :     }
     979         108 :     for (i = 0; i < n; ++i) {
     980          54 :         seqs[i].it = (PyObject*)NULL;
     981          54 :         seqs[i].saw_StopIteration = 0;
     982             :     }
     983             : 
     984             :     /* Do a first pass to obtain iterators for the arguments, and set len
     985             :      * to the largest of their lengths.
     986             :      */
     987          54 :     len = 0;
     988         108 :     for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
     989             :         PyObject *curseq;
     990             :         Py_ssize_t curlen;
     991             : 
     992             :         /* Get iterator. */
     993          54 :         curseq = PyTuple_GetItem(args, i+1);
     994          54 :         sqp->it = PyObject_GetIter(curseq);
     995          54 :         if (sqp->it == NULL) {
     996             :             static char errmsg[] =
     997             :                 "argument %d to map() must support iteration";
     998             :             char errbuf[sizeof(errmsg) + 25];
     999           0 :             PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
    1000           0 :             PyErr_SetString(PyExc_TypeError, errbuf);
    1001           0 :             goto Fail_2;
    1002             :         }
    1003             : 
    1004             :         /* Update len. */
    1005          54 :         curlen = _PyObject_LengthHint(curseq, 8);
    1006          54 :         if (curlen > len)
    1007          54 :             len = curlen;
    1008             :     }
    1009             : 
    1010             :     /* Get space for the result list. */
    1011          54 :     if ((result = (PyObject *) PyList_New(len)) == NULL)
    1012           0 :         goto Fail_2;
    1013             : 
    1014             :     /* Iterate over the sequences until all have stopped. */
    1015        1338 :     for (i = 0; ; ++i) {
    1016        1338 :         PyObject *alist, *item=NULL, *value;
    1017        1338 :         int numactive = 0;
    1018             : 
    1019        1338 :         if (func == Py_None && n == 1)
    1020           0 :             alist = NULL;
    1021        1338 :         else if ((alist = PyTuple_New(n)) == NULL)
    1022           0 :             goto Fail_1;
    1023             : 
    1024        2676 :         for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
    1025        1338 :             if (sqp->saw_StopIteration) {
    1026           0 :                 Py_INCREF(Py_None);
    1027           0 :                 item = Py_None;
    1028             :             }
    1029             :             else {
    1030        1338 :                 item = PyIter_Next(sqp->it);
    1031        1338 :                 if (item)
    1032        1284 :                     ++numactive;
    1033             :                 else {
    1034          54 :                     if (PyErr_Occurred()) {
    1035           0 :                         Py_XDECREF(alist);
    1036           0 :                         goto Fail_1;
    1037             :                     }
    1038          54 :                     Py_INCREF(Py_None);
    1039          54 :                     item = Py_None;
    1040          54 :                     sqp->saw_StopIteration = 1;
    1041             :                 }
    1042             :             }
    1043        1338 :             if (alist)
    1044        1338 :                 PyTuple_SET_ITEM(alist, j, item);
    1045             :             else
    1046           0 :                 break;
    1047             :         }
    1048             : 
    1049        1338 :         if (!alist)
    1050           0 :             alist = item;
    1051             : 
    1052        1338 :         if (numactive == 0) {
    1053          54 :             Py_DECREF(alist);
    1054          54 :             break;
    1055             :         }
    1056             : 
    1057        1284 :         if (func == Py_None)
    1058           0 :             value = alist;
    1059             :         else {
    1060        1284 :             value = PyEval_CallObject(func, alist);
    1061        1284 :             Py_DECREF(alist);
    1062        1284 :             if (value == NULL)
    1063           0 :                 goto Fail_1;
    1064             :         }
    1065        1284 :         if (i >= len) {
    1066           0 :             int status = PyList_Append(result, value);
    1067           0 :             Py_DECREF(value);
    1068           0 :             if (status < 0)
    1069           0 :                 goto Fail_1;
    1070             :         }
    1071        1284 :         else if (PyList_SetItem(result, i, value) < 0)
    1072           0 :             goto Fail_1;
    1073        1284 :     }
    1074             : 
    1075          54 :     if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
    1076           0 :         goto Fail_1;
    1077             : 
    1078          54 :     goto Succeed;
    1079             : 
    1080             : Fail_1:
    1081           0 :     Py_DECREF(result);
    1082             : Fail_2:
    1083           0 :     result = NULL;
    1084             : Succeed:
    1085             :     assert(seqs);
    1086         108 :     for (i = 0; i < n; ++i)
    1087          54 :         Py_XDECREF(seqs[i].it);
    1088          54 :     PyMem_DEL(seqs);
    1089          54 :     return result;
    1090             : }
    1091             : 
    1092             : PyDoc_STRVAR(map_doc,
    1093             : "map(function, sequence[, sequence, ...]) -> list\n\
    1094             : \n\
    1095             : Return a list of the results of applying the function to the items of\n\
    1096             : the argument sequence(s).  If more than one sequence is given, the\n\
    1097             : function is called with an argument list consisting of the corresponding\n\
    1098             : item of each sequence, substituting None for missing values when not all\n\
    1099             : sequences have the same length.  If the function is None, return a list of\n\
    1100             : the items of the sequence (or a list of tuples if more than one sequence).");
    1101             : 
    1102             : 
    1103             : static PyObject *
    1104        2418 : builtin_next(PyObject *self, PyObject *args)
    1105             : {
    1106             :     PyObject *it, *res;
    1107        2418 :     PyObject *def = NULL;
    1108             : 
    1109        2418 :     if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
    1110           0 :         return NULL;
    1111        2418 :     if (!PyIter_Check(it)) {
    1112           0 :         PyErr_Format(PyExc_TypeError,
    1113             :             "%.200s object is not an iterator",
    1114           0 :             it->ob_type->tp_name);
    1115           0 :         return NULL;
    1116             :     }
    1117             : 
    1118        2418 :     res = (*it->ob_type->tp_iternext)(it);
    1119        2418 :     if (res != NULL) {
    1120        2412 :         return res;
    1121           6 :     } else if (def != NULL) {
    1122           0 :         if (PyErr_Occurred()) {
    1123           0 :             if (!PyErr_ExceptionMatches(PyExc_StopIteration))
    1124           0 :                 return NULL;
    1125           0 :             PyErr_Clear();
    1126             :         }
    1127           0 :         Py_INCREF(def);
    1128           0 :         return def;
    1129           6 :     } else if (PyErr_Occurred()) {
    1130           0 :         return NULL;
    1131             :     } else {
    1132           6 :         PyErr_SetNone(PyExc_StopIteration);
    1133           6 :         return NULL;
    1134             :     }
    1135             : }
    1136             : 
    1137             : PyDoc_STRVAR(next_doc,
    1138             : "next(iterator[, default])\n\
    1139             : \n\
    1140             : Return the next item from the iterator. If default is given and the iterator\n\
    1141             : is exhausted, it is returned instead of raising StopIteration.");
    1142             : 
    1143             : 
    1144             : static PyObject *
    1145        1509 : builtin_setattr(PyObject *self, PyObject *args)
    1146             : {
    1147             :     PyObject *v;
    1148             :     PyObject *name;
    1149             :     PyObject *value;
    1150             : 
    1151        1509 :     if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
    1152           0 :         return NULL;
    1153        1509 :     if (PyObject_SetAttr(v, name, value) != 0)
    1154           0 :         return NULL;
    1155        1509 :     Py_INCREF(Py_None);
    1156        1509 :     return Py_None;
    1157             : }
    1158             : 
    1159             : PyDoc_STRVAR(setattr_doc,
    1160             : "setattr(object, name, value)\n\
    1161             : \n\
    1162             : Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
    1163             : ``x.y = v''.");
    1164             : 
    1165             : 
    1166             : static PyObject *
    1167           0 : builtin_delattr(PyObject *self, PyObject *args)
    1168             : {
    1169             :     PyObject *v;
    1170             :     PyObject *name;
    1171             : 
    1172           0 :     if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
    1173           0 :         return NULL;
    1174           0 :     if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
    1175           0 :         return NULL;
    1176           0 :     Py_INCREF(Py_None);
    1177           0 :     return Py_None;
    1178             : }
    1179             : 
    1180             : PyDoc_STRVAR(delattr_doc,
    1181             : "delattr(object, name)\n\
    1182             : \n\
    1183             : Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
    1184             : ``del x.y''.");
    1185             : 
    1186             : 
    1187             : static PyObject *
    1188         823 : builtin_hash(PyObject *self, PyObject *v)
    1189             : {
    1190             :     long x;
    1191             : 
    1192         823 :     x = PyObject_Hash(v);
    1193         823 :     if (x == -1)
    1194           0 :         return NULL;
    1195         823 :     return PyInt_FromLong(x);
    1196             : }
    1197             : 
    1198             : PyDoc_STRVAR(hash_doc,
    1199             : "hash(object) -> integer\n\
    1200             : \n\
    1201             : Return a hash value for the object.  Two objects with the same value have\n\
    1202             : the same hash value.  The reverse is not necessarily true, but likely.");
    1203             : 
    1204             : 
    1205             : static PyObject *
    1206           0 : builtin_hex(PyObject *self, PyObject *v)
    1207             : {
    1208             :     PyNumberMethods *nb;
    1209             :     PyObject *res;
    1210             : 
    1211           0 :     if ((nb = v->ob_type->tp_as_number) == NULL ||
    1212           0 :         nb->nb_hex == NULL) {
    1213           0 :         PyErr_SetString(PyExc_TypeError,
    1214             :                    "hex() argument can't be converted to hex");
    1215           0 :         return NULL;
    1216             :     }
    1217           0 :     res = (*nb->nb_hex)(v);
    1218           0 :     if (res && !PyString_Check(res)) {
    1219           0 :         PyErr_Format(PyExc_TypeError,
    1220             :                      "__hex__ returned non-string (type %.200s)",
    1221           0 :                      res->ob_type->tp_name);
    1222           0 :         Py_DECREF(res);
    1223           0 :         return NULL;
    1224             :     }
    1225           0 :     return res;
    1226             : }
    1227             : 
    1228             : PyDoc_STRVAR(hex_doc,
    1229             : "hex(number) -> string\n\
    1230             : \n\
    1231             : Return the hexadecimal representation of an integer or long integer.");
    1232             : 
    1233             : 
    1234             : static PyObject *builtin_raw_input(PyObject *, PyObject *);
    1235             : 
    1236             : static PyObject *
    1237           0 : builtin_input(PyObject *self, PyObject *args)
    1238             : {
    1239             :     PyObject *line;
    1240             :     char *str;
    1241             :     PyObject *res;
    1242             :     PyObject *globals, *locals;
    1243             :     PyCompilerFlags cf;
    1244             : 
    1245           0 :     line = builtin_raw_input(self, args);
    1246           0 :     if (line == NULL)
    1247           0 :         return line;
    1248           0 :     if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
    1249           0 :         return NULL;
    1250           0 :     while (*str == ' ' || *str == '\t')
    1251           0 :                     str++;
    1252           0 :     globals = PyEval_GetGlobals();
    1253           0 :     locals = PyEval_GetLocals();
    1254           0 :     if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
    1255           0 :         if (PyDict_SetItemString(globals, "__builtins__",
    1256             :                                  PyEval_GetBuiltins()) != 0)
    1257           0 :             return NULL;
    1258             :     }
    1259           0 :     cf.cf_flags = 0;
    1260           0 :     PyEval_MergeCompilerFlags(&cf);
    1261           0 :     res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
    1262           0 :     Py_DECREF(line);
    1263           0 :     return res;
    1264             : }
    1265             : 
    1266             : PyDoc_STRVAR(input_doc,
    1267             : "input([prompt]) -> value\n\
    1268             : \n\
    1269             : Equivalent to eval(raw_input(prompt)).");
    1270             : 
    1271             : 
    1272             : static PyObject *
    1273           0 : builtin_intern(PyObject *self, PyObject *args)
    1274             : {
    1275             :     PyObject *s;
    1276           0 :     if (!PyArg_ParseTuple(args, "S:intern", &s))
    1277           0 :         return NULL;
    1278           0 :     if (!PyString_CheckExact(s)) {
    1279           0 :         PyErr_SetString(PyExc_TypeError,
    1280             :                         "can't intern subclass of string");
    1281           0 :         return NULL;
    1282             :     }
    1283           0 :     Py_INCREF(s);
    1284           0 :     PyString_InternInPlace(&s);
    1285           0 :     return s;
    1286             : }
    1287             : 
    1288             : PyDoc_STRVAR(intern_doc,
    1289             : "intern(string) -> string\n\
    1290             : \n\
    1291             : ``Intern'' the given string.  This enters the string in the (global)\n\
    1292             : table of interned strings whose purpose is to speed up dictionary lookups.\n\
    1293             : Return the string itself or the previously interned string object with the\n\
    1294             : same value.");
    1295             : 
    1296             : 
    1297             : static PyObject *
    1298           0 : builtin_iter(PyObject *self, PyObject *args)
    1299             : {
    1300           0 :     PyObject *v, *w = NULL;
    1301             : 
    1302           0 :     if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
    1303           0 :         return NULL;
    1304           0 :     if (w == NULL)
    1305           0 :         return PyObject_GetIter(v);
    1306           0 :     if (!PyCallable_Check(v)) {
    1307           0 :         PyErr_SetString(PyExc_TypeError,
    1308             :                         "iter(v, w): v must be callable");
    1309           0 :         return NULL;
    1310             :     }
    1311           0 :     return PyCallIter_New(v, w);
    1312             : }
    1313             : 
    1314             : PyDoc_STRVAR(iter_doc,
    1315             : "iter(collection) -> iterator\n\
    1316             : iter(callable, sentinel) -> iterator\n\
    1317             : \n\
    1318             : Get an iterator from an object.  In the first form, the argument must\n\
    1319             : supply its own iterator, or be a sequence.\n\
    1320             : In the second form, the callable is called until it returns the sentinel.");
    1321             : 
    1322             : 
    1323             : static PyObject *
    1324       41617 : builtin_len(PyObject *self, PyObject *v)
    1325             : {
    1326             :     Py_ssize_t res;
    1327             : 
    1328       41617 :     res = PyObject_Size(v);
    1329       41617 :     if (res < 0 && PyErr_Occurred())
    1330           0 :         return NULL;
    1331       41617 :     return PyInt_FromSsize_t(res);
    1332             : }
    1333             : 
    1334             : PyDoc_STRVAR(len_doc,
    1335             : "len(object) -> integer\n\
    1336             : \n\
    1337             : Return the number of items of a sequence or collection.");
    1338             : 
    1339             : 
    1340             : static PyObject *
    1341           0 : builtin_locals(PyObject *self)
    1342             : {
    1343             :     PyObject *d;
    1344             : 
    1345           0 :     d = PyEval_GetLocals();
    1346           0 :     Py_XINCREF(d);
    1347           0 :     return d;
    1348             : }
    1349             : 
    1350             : PyDoc_STRVAR(locals_doc,
    1351             : "locals() -> dictionary\n\
    1352             : \n\
    1353             : Update and return a dictionary containing the current scope's local variables.");
    1354             : 
    1355             : 
    1356             : static PyObject *
    1357        4725 : min_max(PyObject *args, PyObject *kwds, int op)
    1358             : {
    1359        4725 :     PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
    1360        4725 :     const char *name = op == Py_LT ? "min" : "max";
    1361             : 
    1362        4725 :     if (PyTuple_Size(args) > 1)
    1363        4692 :         v = args;
    1364          33 :     else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
    1365           0 :         return NULL;
    1366             : 
    1367        4725 :     if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
    1368          33 :         keyfunc = PyDict_GetItemString(kwds, "key");
    1369          33 :         if (PyDict_Size(kwds)!=1  ||  keyfunc == NULL) {
    1370           0 :             PyErr_Format(PyExc_TypeError,
    1371             :                 "%s() got an unexpected keyword argument", name);
    1372           0 :             return NULL;
    1373             :         }
    1374          33 :         Py_INCREF(keyfunc);
    1375             :     }
    1376             : 
    1377        4725 :     it = PyObject_GetIter(v);
    1378        4725 :     if (it == NULL) {
    1379           0 :         Py_XDECREF(keyfunc);
    1380           0 :         return NULL;
    1381             :     }
    1382             : 
    1383        4725 :     maxitem = NULL; /* the result */
    1384        4725 :     maxval = NULL;  /* the value associated with the result */
    1385       18897 :     while (( item = PyIter_Next(it) )) {
    1386             :         /* get the value from the key function */
    1387        9447 :         if (keyfunc != NULL) {
    1388          63 :             val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
    1389          63 :             if (val == NULL)
    1390           0 :                 goto Fail_it_item;
    1391             :         }
    1392             :         /* no key function; the value is the item */
    1393             :         else {
    1394        9384 :             val = item;
    1395        9384 :             Py_INCREF(val);
    1396             :         }
    1397             : 
    1398             :         /* maximum value and item are unset; set them */
    1399        9447 :         if (maxval == NULL) {
    1400        4725 :             maxitem = item;
    1401        4725 :             maxval = val;
    1402             :         }
    1403             :         /* maximum value and item are set; update them as necessary */
    1404             :         else {
    1405        4722 :             int cmp = PyObject_RichCompareBool(val, maxval, op);
    1406        4722 :             if (cmp < 0)
    1407           0 :                 goto Fail_it_item_and_val;
    1408        4722 :             else if (cmp > 0) {
    1409         582 :                 Py_DECREF(maxval);
    1410         582 :                 Py_DECREF(maxitem);
    1411         582 :                 maxval = val;
    1412         582 :                 maxitem = item;
    1413             :             }
    1414             :             else {
    1415        4140 :                 Py_DECREF(item);
    1416        4140 :                 Py_DECREF(val);
    1417             :             }
    1418             :         }
    1419             :     }
    1420        4725 :     if (PyErr_Occurred())
    1421           0 :         goto Fail_it;
    1422        4725 :     if (maxval == NULL) {
    1423           0 :         PyErr_Format(PyExc_ValueError,
    1424             :                      "%s() arg is an empty sequence", name);
    1425             :         assert(maxitem == NULL);
    1426             :     }
    1427             :     else
    1428        4725 :         Py_DECREF(maxval);
    1429        4725 :     Py_DECREF(it);
    1430        4725 :     Py_XDECREF(keyfunc);
    1431        4725 :     return maxitem;
    1432             : 
    1433             : Fail_it_item_and_val:
    1434           0 :     Py_DECREF(val);
    1435             : Fail_it_item:
    1436           0 :     Py_DECREF(item);
    1437             : Fail_it:
    1438           0 :     Py_XDECREF(maxval);
    1439           0 :     Py_XDECREF(maxitem);
    1440           0 :     Py_DECREF(it);
    1441           0 :     Py_XDECREF(keyfunc);
    1442           0 :     return NULL;
    1443             : }
    1444             : 
    1445             : static PyObject *
    1446        4341 : builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
    1447             : {
    1448        4341 :     return min_max(args, kwds, Py_LT);
    1449             : }
    1450             : 
    1451             : PyDoc_STRVAR(min_doc,
    1452             : "min(iterable[, key=func]) -> value\n\
    1453             : min(a, b, c, ...[, key=func]) -> value\n\
    1454             : \n\
    1455             : With a single iterable argument, return its smallest item.\n\
    1456             : With two or more arguments, return the smallest argument.");
    1457             : 
    1458             : 
    1459             : static PyObject *
    1460         384 : builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
    1461             : {
    1462         384 :     return min_max(args, kwds, Py_GT);
    1463             : }
    1464             : 
    1465             : PyDoc_STRVAR(max_doc,
    1466             : "max(iterable[, key=func]) -> value\n\
    1467             : max(a, b, c, ...[, key=func]) -> value\n\
    1468             : \n\
    1469             : With a single iterable argument, return its largest item.\n\
    1470             : With two or more arguments, return the largest argument.");
    1471             : 
    1472             : 
    1473             : static PyObject *
    1474           0 : builtin_oct(PyObject *self, PyObject *v)
    1475             : {
    1476             :     PyNumberMethods *nb;
    1477             :     PyObject *res;
    1478             : 
    1479           0 :     if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
    1480           0 :         nb->nb_oct == NULL) {
    1481           0 :         PyErr_SetString(PyExc_TypeError,
    1482             :                    "oct() argument can't be converted to oct");
    1483           0 :         return NULL;
    1484             :     }
    1485           0 :     res = (*nb->nb_oct)(v);
    1486           0 :     if (res && !PyString_Check(res)) {
    1487           0 :         PyErr_Format(PyExc_TypeError,
    1488             :                      "__oct__ returned non-string (type %.200s)",
    1489           0 :                      res->ob_type->tp_name);
    1490           0 :         Py_DECREF(res);
    1491           0 :         return NULL;
    1492             :     }
    1493           0 :     return res;
    1494             : }
    1495             : 
    1496             : PyDoc_STRVAR(oct_doc,
    1497             : "oct(number) -> string\n\
    1498             : \n\
    1499             : Return the octal representation of an integer or long integer.");
    1500             : 
    1501             : 
    1502             : static PyObject *
    1503           9 : builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
    1504             : {
    1505           9 :     return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
    1506             : }
    1507             : 
    1508             : PyDoc_STRVAR(open_doc,
    1509             : "open(name[, mode[, buffering]]) -> file object\n\
    1510             : \n\
    1511             : Open a file using the file() type, returns a file object.  This is the\n\
    1512             : preferred way to open a file.  See file.__doc__ for further information.");
    1513             : 
    1514             : 
    1515             : static PyObject *
    1516        4632 : builtin_ord(PyObject *self, PyObject* obj)
    1517             : {
    1518             :     long ord;
    1519             :     Py_ssize_t size;
    1520             : 
    1521        4632 :     if (PyString_Check(obj)) {
    1522        4629 :         size = PyString_GET_SIZE(obj);
    1523        4629 :         if (size == 1) {
    1524        4629 :             ord = (long)((unsigned char)*PyString_AS_STRING(obj));
    1525        4629 :             return PyInt_FromLong(ord);
    1526             :         }
    1527           3 :     } else if (PyByteArray_Check(obj)) {
    1528           0 :         size = PyByteArray_GET_SIZE(obj);
    1529           0 :         if (size == 1) {
    1530           0 :             ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
    1531           0 :             return PyInt_FromLong(ord);
    1532             :         }
    1533             : 
    1534             : #ifdef Py_USING_UNICODE
    1535           3 :     } else if (PyUnicode_Check(obj)) {
    1536           3 :         size = PyUnicode_GET_SIZE(obj);
    1537           3 :         if (size == 1) {
    1538           3 :             ord = (long)*PyUnicode_AS_UNICODE(obj);
    1539           3 :             return PyInt_FromLong(ord);
    1540             :         }
    1541             : #endif
    1542             :     } else {
    1543           0 :         PyErr_Format(PyExc_TypeError,
    1544             :                      "ord() expected string of length 1, but " \
    1545           0 :                      "%.200s found", obj->ob_type->tp_name);
    1546           0 :         return NULL;
    1547             :     }
    1548             : 
    1549           0 :     PyErr_Format(PyExc_TypeError,
    1550             :                  "ord() expected a character, "
    1551             :                  "but string of length %zd found",
    1552             :                  size);
    1553           0 :     return NULL;
    1554             : }
    1555             : 
    1556             : PyDoc_STRVAR(ord_doc,
    1557             : "ord(c) -> integer\n\
    1558             : \n\
    1559             : Return the integer ordinal of a one-character string.");
    1560             : 
    1561             : 
    1562             : static PyObject *
    1563           0 : builtin_pow(PyObject *self, PyObject *args)
    1564             : {
    1565           0 :     PyObject *v, *w, *z = Py_None;
    1566             : 
    1567           0 :     if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
    1568           0 :         return NULL;
    1569           0 :     return PyNumber_Power(v, w, z);
    1570             : }
    1571             : 
    1572             : PyDoc_STRVAR(pow_doc,
    1573             : "pow(x, y[, z]) -> number\n\
    1574             : \n\
    1575             : With two arguments, equivalent to x**y.  With three arguments,\n\
    1576             : equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
    1577             : 
    1578             : 
    1579             : static PyObject *
    1580           0 : builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
    1581             : {
    1582             :     static char *kwlist[] = {"sep", "end", "file", 0};
    1583             :     static PyObject *dummy_args = NULL;
    1584             :     static PyObject *unicode_newline = NULL, *unicode_space = NULL;
    1585             :     static PyObject *str_newline = NULL, *str_space = NULL;
    1586             :     PyObject *newline, *space;
    1587           0 :     PyObject *sep = NULL, *end = NULL, *file = NULL;
    1588           0 :     int i, err, use_unicode = 0;
    1589             : 
    1590           0 :     if (dummy_args == NULL) {
    1591           0 :         if (!(dummy_args = PyTuple_New(0)))
    1592           0 :             return NULL;
    1593             :     }
    1594           0 :     if (str_newline == NULL) {
    1595           0 :         str_newline = PyString_FromString("\n");
    1596           0 :         if (str_newline == NULL)
    1597           0 :             return NULL;
    1598           0 :         str_space = PyString_FromString(" ");
    1599           0 :         if (str_space == NULL) {
    1600           0 :             Py_CLEAR(str_newline);
    1601           0 :             return NULL;
    1602             :         }
    1603             : #ifdef Py_USING_UNICODE
    1604           0 :         unicode_newline = PyUnicode_FromString("\n");
    1605           0 :         if (unicode_newline == NULL) {
    1606           0 :             Py_CLEAR(str_newline);
    1607           0 :             Py_CLEAR(str_space);
    1608           0 :             return NULL;
    1609             :         }
    1610           0 :         unicode_space = PyUnicode_FromString(" ");
    1611           0 :         if (unicode_space == NULL) {
    1612           0 :             Py_CLEAR(str_newline);
    1613           0 :             Py_CLEAR(str_space);
    1614           0 :             Py_CLEAR(unicode_space);
    1615           0 :             return NULL;
    1616             :         }
    1617             : #endif
    1618             :     }
    1619           0 :     if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
    1620             :                                      kwlist, &sep, &end, &file))
    1621           0 :         return NULL;
    1622           0 :     if (file == NULL || file == Py_None) {
    1623           0 :         file = PySys_GetObject("stdout");
    1624             :         /* sys.stdout may be None when FILE* stdout isn't connected */
    1625           0 :         if (file == Py_None)
    1626           0 :             Py_RETURN_NONE;
    1627             :     }
    1628           0 :     if (sep == Py_None) {
    1629           0 :         sep = NULL;
    1630             :     }
    1631           0 :     else if (sep) {
    1632           0 :         if (PyUnicode_Check(sep)) {
    1633           0 :             use_unicode = 1;
    1634             :         }
    1635           0 :         else if (!PyString_Check(sep)) {
    1636           0 :             PyErr_Format(PyExc_TypeError,
    1637             :                          "sep must be None, str or unicode, not %.200s",
    1638           0 :                          sep->ob_type->tp_name);
    1639           0 :             return NULL;
    1640             :         }
    1641             :     }
    1642           0 :     if (end == Py_None)
    1643           0 :         end = NULL;
    1644           0 :     else if (end) {
    1645           0 :         if (PyUnicode_Check(end)) {
    1646           0 :             use_unicode = 1;
    1647             :         }
    1648           0 :         else if (!PyString_Check(end)) {
    1649           0 :             PyErr_Format(PyExc_TypeError,
    1650             :                          "end must be None, str or unicode, not %.200s",
    1651           0 :                          end->ob_type->tp_name);
    1652           0 :             return NULL;
    1653             :         }
    1654             :     }
    1655             : 
    1656           0 :     if (!use_unicode) {
    1657           0 :         for (i = 0; i < PyTuple_Size(args); i++) {
    1658           0 :             if (PyUnicode_Check(PyTuple_GET_ITEM(args, i))) {
    1659           0 :                 use_unicode = 1;
    1660           0 :                 break;
    1661             :             }
    1662             :         }
    1663             :     }
    1664           0 :     if (use_unicode) {
    1665           0 :         newline = unicode_newline;
    1666           0 :         space = unicode_space;
    1667             :     }
    1668             :     else {
    1669           0 :         newline = str_newline;
    1670           0 :         space = str_space;
    1671             :     }
    1672             : 
    1673           0 :     for (i = 0; i < PyTuple_Size(args); i++) {
    1674           0 :         if (i > 0) {
    1675           0 :             if (sep == NULL)
    1676           0 :                 err = PyFile_WriteObject(space, file,
    1677             :                                          Py_PRINT_RAW);
    1678             :             else
    1679           0 :                 err = PyFile_WriteObject(sep, file,
    1680             :                                          Py_PRINT_RAW);
    1681           0 :             if (err)
    1682           0 :                 return NULL;
    1683             :         }
    1684           0 :         err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
    1685             :                                  Py_PRINT_RAW);
    1686           0 :         if (err)
    1687           0 :             return NULL;
    1688             :     }
    1689             : 
    1690           0 :     if (end == NULL)
    1691           0 :         err = PyFile_WriteObject(newline, file, Py_PRINT_RAW);
    1692             :     else
    1693           0 :         err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
    1694           0 :     if (err)
    1695           0 :         return NULL;
    1696             : 
    1697           0 :     Py_RETURN_NONE;
    1698             : }
    1699             : 
    1700             : PyDoc_STRVAR(print_doc,
    1701             : "print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
    1702             : \n\
    1703             : Prints the values to a stream, or to sys.stdout by default.\n\
    1704             : Optional keyword arguments:\n\
    1705             : file: a file-like object (stream); defaults to the current sys.stdout.\n\
    1706             : sep:  string inserted between values, default a space.\n\
    1707             : end:  string appended after the last value, default a newline.");
    1708             : 
    1709             : 
    1710             : /* Return number of items in range (lo, hi, step), when arguments are
    1711             :  * PyInt or PyLong objects.  step > 0 required.  Return a value < 0 if
    1712             :  * & only if the true value is too large to fit in a signed long.
    1713             :  * Arguments MUST return 1 with either PyInt_Check() or
    1714             :  * PyLong_Check().  Return -1 when there is an error.
    1715             :  */
    1716             : static long
    1717           0 : get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
    1718             : {
    1719             :     /* -------------------------------------------------------------
    1720             :     Algorithm is equal to that of get_len_of_range(), but it operates
    1721             :     on PyObjects (which are assumed to be PyLong or PyInt objects).
    1722             :     ---------------------------------------------------------------*/
    1723             :     long n;
    1724           0 :     PyObject *diff = NULL;
    1725           0 :     PyObject *one = NULL;
    1726           0 :     PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
    1727             :         /* holds sub-expression evaluations */
    1728             : 
    1729             :     /* if (lo >= hi), return length of 0. */
    1730           0 :     if (PyObject_Compare(lo, hi) >= 0)
    1731           0 :         return 0;
    1732             : 
    1733           0 :     if ((one = PyLong_FromLong(1L)) == NULL)
    1734           0 :         goto Fail;
    1735             : 
    1736           0 :     if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
    1737           0 :         goto Fail;
    1738             : 
    1739           0 :     if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
    1740           0 :         goto Fail;
    1741             : 
    1742           0 :     if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
    1743           0 :         goto Fail;
    1744             : 
    1745           0 :     if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
    1746           0 :         goto Fail;
    1747             : 
    1748           0 :     n = PyLong_AsLong(tmp3);
    1749           0 :     if (PyErr_Occurred()) {  /* Check for Overflow */
    1750           0 :         PyErr_Clear();
    1751           0 :         goto Fail;
    1752             :     }
    1753             : 
    1754           0 :     Py_DECREF(tmp3);
    1755           0 :     Py_DECREF(tmp2);
    1756           0 :     Py_DECREF(diff);
    1757           0 :     Py_DECREF(tmp1);
    1758           0 :     Py_DECREF(one);
    1759           0 :     return n;
    1760             : 
    1761             :   Fail:
    1762           0 :     Py_XDECREF(tmp3);
    1763           0 :     Py_XDECREF(tmp2);
    1764           0 :     Py_XDECREF(diff);
    1765           0 :     Py_XDECREF(tmp1);
    1766           0 :     Py_XDECREF(one);
    1767           0 :     return -1;
    1768             : }
    1769             : 
    1770             : /* Helper function for handle_range_longs.  If arg is int or long
    1771             :    object, returns it with incremented reference count.  If arg is
    1772             :    float, raises type error. As a last resort, creates a new int by
    1773             :    calling arg type's nb_int method if it is defined.  Returns NULL
    1774             :    and sets exception on error.
    1775             : 
    1776             :    Returns a new reference to an int object. */
    1777             : static PyObject *
    1778           0 : get_range_long_argument(PyObject *arg, const char *name)
    1779             : {
    1780             :     PyObject *v;
    1781             :     PyNumberMethods *nb;
    1782           0 :     if (PyInt_Check(arg) || PyLong_Check(arg)) {
    1783           0 :         Py_INCREF(arg);
    1784           0 :         return arg;
    1785             :     }
    1786           0 :     if (PyFloat_Check(arg) ||
    1787           0 :         (nb = Py_TYPE(arg)->tp_as_number) == NULL ||
    1788           0 :         nb->nb_int == NULL) {
    1789           0 :         PyErr_Format(PyExc_TypeError,
    1790             :                      "range() integer %s argument expected, got %s.",
    1791           0 :                      name, arg->ob_type->tp_name);
    1792           0 :         return NULL;
    1793             :     }
    1794           0 :     v = nb->nb_int(arg);
    1795           0 :     if (v == NULL)
    1796           0 :         return NULL;
    1797           0 :     if (PyInt_Check(v) || PyLong_Check(v))
    1798           0 :         return v;
    1799           0 :     Py_DECREF(v);
    1800           0 :     PyErr_SetString(PyExc_TypeError,
    1801             :                     "__int__ should return int object");
    1802           0 :     return NULL;
    1803             : }
    1804             : 
    1805             : /* An extension of builtin_range() that handles the case when PyLong
    1806             :  * arguments are given. */
    1807             : static PyObject *
    1808           0 : handle_range_longs(PyObject *self, PyObject *args)
    1809             : {
    1810           0 :     PyObject *ilow = NULL;
    1811           0 :     PyObject *ihigh = NULL;
    1812           0 :     PyObject *istep = NULL;
    1813             : 
    1814           0 :     PyObject *low = NULL;
    1815           0 :     PyObject *high = NULL;
    1816           0 :     PyObject *step = NULL;
    1817             : 
    1818           0 :     PyObject *curnum = NULL;
    1819           0 :     PyObject *v = NULL;
    1820             :     long bign;
    1821             :     Py_ssize_t i, n;
    1822             :     int cmp_result;
    1823             : 
    1824           0 :     PyObject *zero = PyLong_FromLong(0);
    1825             : 
    1826           0 :     if (zero == NULL)
    1827           0 :         return NULL;
    1828             : 
    1829           0 :     if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
    1830           0 :         Py_DECREF(zero);
    1831           0 :         return NULL;
    1832             :     }
    1833             : 
    1834             :     /* Figure out which way we were called, supply defaults, and be
    1835             :      * sure to incref everything so that the decrefs at the end
    1836             :      * are correct. NB: ilow, ihigh and istep are borrowed references.
    1837             :      */
    1838             :     assert(ilow != NULL);
    1839           0 :     if (ihigh == NULL) {
    1840             :         /* only 1 arg -- it's the upper limit */
    1841           0 :         ihigh = ilow;
    1842           0 :         ilow = NULL;
    1843             :     }
    1844             : 
    1845             :     /* convert ihigh if necessary */
    1846             :     assert(ihigh != NULL);
    1847           0 :     high = get_range_long_argument(ihigh, "end");
    1848           0 :     if (high == NULL)
    1849           0 :         goto Fail;
    1850             : 
    1851             :     /* ihigh correct now; do ilow */
    1852           0 :     if (ilow == NULL) {
    1853           0 :         Py_INCREF(zero);
    1854           0 :         low = zero;
    1855             :     }
    1856             :     else {
    1857           0 :         low = get_range_long_argument(ilow, "start");
    1858           0 :         if (low == NULL)
    1859           0 :             goto Fail;
    1860             :     }
    1861             : 
    1862             :     /* ilow and ihigh correct now; do istep */
    1863           0 :     if (istep == NULL)
    1864           0 :         step = PyLong_FromLong(1);
    1865             :     else
    1866           0 :         step = get_range_long_argument(istep, "step");
    1867           0 :     if (step == NULL)
    1868           0 :         goto Fail;
    1869             : 
    1870           0 :     if (PyObject_Cmp(step, zero, &cmp_result) == -1)
    1871           0 :         goto Fail;
    1872             : 
    1873           0 :     if (cmp_result == 0) {
    1874           0 :         PyErr_SetString(PyExc_ValueError,
    1875             :                         "range() step argument must not be zero");
    1876           0 :         goto Fail;
    1877             :     }
    1878             : 
    1879           0 :     if (cmp_result > 0)
    1880           0 :         bign = get_len_of_range_longs(low, high, step);
    1881             :     else {
    1882           0 :         PyObject *neg_step = PyNumber_Negative(step);
    1883           0 :         if (neg_step == NULL)
    1884           0 :             goto Fail;
    1885           0 :         bign = get_len_of_range_longs(high, low, neg_step);
    1886           0 :         Py_DECREF(neg_step);
    1887             :     }
    1888             : 
    1889           0 :     n = (Py_ssize_t)bign;
    1890           0 :     if (bign < 0 || (long)n != bign) {
    1891           0 :         PyErr_SetString(PyExc_OverflowError,
    1892             :                         "range() result has too many items");
    1893           0 :         goto Fail;
    1894             :     }
    1895             : 
    1896           0 :     v = PyList_New(n);
    1897           0 :     if (v == NULL)
    1898           0 :         goto Fail;
    1899             : 
    1900           0 :     curnum = low;
    1901           0 :     Py_INCREF(curnum);
    1902             : 
    1903           0 :     for (i = 0; i < n; i++) {
    1904           0 :         PyObject *w = PyNumber_Long(curnum);
    1905             :         PyObject *tmp_num;
    1906           0 :         if (w == NULL)
    1907           0 :             goto Fail;
    1908             : 
    1909           0 :         PyList_SET_ITEM(v, i, w);
    1910             : 
    1911           0 :         tmp_num = PyNumber_Add(curnum, step);
    1912           0 :         if (tmp_num == NULL)
    1913           0 :             goto Fail;
    1914             : 
    1915           0 :         Py_DECREF(curnum);
    1916           0 :         curnum = tmp_num;
    1917             :     }
    1918           0 :     Py_DECREF(low);
    1919           0 :     Py_DECREF(high);
    1920           0 :     Py_DECREF(step);
    1921           0 :     Py_DECREF(zero);
    1922           0 :     Py_DECREF(curnum);
    1923           0 :     return v;
    1924             : 
    1925             :   Fail:
    1926           0 :     Py_XDECREF(low);
    1927           0 :     Py_XDECREF(high);
    1928           0 :     Py_XDECREF(step);
    1929           0 :     Py_DECREF(zero);
    1930           0 :     Py_XDECREF(curnum);
    1931           0 :     Py_XDECREF(v);
    1932           0 :     return NULL;
    1933             : }
    1934             : 
    1935             : /* Return number of items in range/xrange (lo, hi, step).  step > 0
    1936             :  * required.  Return a value < 0 if & only if the true value is too
    1937             :  * large to fit in a signed long.
    1938             :  */
    1939             : static long
    1940         586 : get_len_of_range(long lo, long hi, long step)
    1941             : {
    1942             :     /* -------------------------------------------------------------
    1943             :     If lo >= hi, the range is empty.
    1944             :     Else if n values are in the range, the last one is
    1945             :     lo + (n-1)*step, which must be <= hi-1.  Rearranging,
    1946             :     n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
    1947             :     the proper value.  Since lo < hi in this case, hi-lo-1 >= 0, so
    1948             :     the RHS is non-negative and so truncation is the same as the
    1949             :     floor.  Letting M be the largest positive long, the worst case
    1950             :     for the RHS numerator is hi=M, lo=-M-1, and then
    1951             :     hi-lo-1 = M-(-M-1)-1 = 2*M.  Therefore unsigned long has enough
    1952             :     precision to compute the RHS exactly.
    1953             :     ---------------------------------------------------------------*/
    1954         586 :     long n = 0;
    1955         586 :     if (lo < hi) {
    1956         586 :         unsigned long uhi = (unsigned long)hi;
    1957         586 :         unsigned long ulo = (unsigned long)lo;
    1958         586 :         unsigned long diff = uhi - ulo - 1;
    1959         586 :         n = (long)(diff / (unsigned long)step + 1);
    1960             :     }
    1961         586 :     return n;
    1962             : }
    1963             : 
    1964             : static PyObject *
    1965         586 : builtin_range(PyObject *self, PyObject *args)
    1966             : {
    1967         586 :     long ilow = 0, ihigh = 0, istep = 1;
    1968             :     long bign;
    1969             :     Py_ssize_t i, n;
    1970             : 
    1971             :     PyObject *v;
    1972             : 
    1973         586 :     if (PyTuple_Size(args) <= 1) {
    1974          51 :         if (!PyArg_ParseTuple(args,
    1975             :                         "l;range() requires 1-3 int arguments",
    1976             :                         &ihigh)) {
    1977           0 :             PyErr_Clear();
    1978           0 :             return handle_range_longs(self, args);
    1979             :         }
    1980             :     }
    1981             :     else {
    1982         535 :         if (!PyArg_ParseTuple(args,
    1983             :                         "ll|l;range() requires 1-3 int arguments",
    1984             :                         &ilow, &ihigh, &istep)) {
    1985           0 :             PyErr_Clear();
    1986           0 :             return handle_range_longs(self, args);
    1987             :         }
    1988             :     }
    1989         586 :     if (istep == 0) {
    1990           0 :         PyErr_SetString(PyExc_ValueError,
    1991             :                         "range() step argument must not be zero");
    1992           0 :         return NULL;
    1993             :     }
    1994         586 :     if (istep > 0)
    1995         378 :         bign = get_len_of_range(ilow, ihigh, istep);
    1996             :     else
    1997         208 :         bign = get_len_of_range(ihigh, ilow, -istep);
    1998         586 :     n = (Py_ssize_t)bign;
    1999         586 :     if (bign < 0 || (long)n != bign) {
    2000           0 :         PyErr_SetString(PyExc_OverflowError,
    2001             :                         "range() result has too many items");
    2002           0 :         return NULL;
    2003             :     }
    2004         586 :     v = PyList_New(n);
    2005         586 :     if (v == NULL)
    2006           0 :         return NULL;
    2007       11045 :     for (i = 0; i < n; i++) {
    2008       10459 :         PyObject *w = PyInt_FromLong(ilow);
    2009       10459 :         if (w == NULL) {
    2010           0 :             Py_DECREF(v);
    2011           0 :             return NULL;
    2012             :         }
    2013       10459 :         PyList_SET_ITEM(v, i, w);
    2014       10459 :         ilow += istep;
    2015             :     }
    2016         586 :     return v;
    2017             : }
    2018             : 
    2019             : PyDoc_STRVAR(range_doc,
    2020             : "range(stop) -> list of integers\n\
    2021             : range(start, stop[, step]) -> list of integers\n\
    2022             : \n\
    2023             : Return a list containing an arithmetic progression of integers.\n\
    2024             : range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
    2025             : When step is given, it specifies the increment (or decrement).\n\
    2026             : For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!\n\
    2027             : These are exactly the valid indices for a list of 4 elements.");
    2028             : 
    2029             : 
    2030             : static PyObject *
    2031           0 : builtin_raw_input(PyObject *self, PyObject *args)
    2032             : {
    2033           0 :     PyObject *v = NULL;
    2034           0 :     PyObject *fin = PySys_GetObject("stdin");
    2035           0 :     PyObject *fout = PySys_GetObject("stdout");
    2036             : 
    2037           0 :     if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))
    2038           0 :         return NULL;
    2039             : 
    2040           0 :     if (fin == NULL) {
    2041           0 :         PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
    2042           0 :         return NULL;
    2043             :     }
    2044           0 :     if (fout == NULL) {
    2045           0 :         PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
    2046           0 :         return NULL;
    2047             :     }
    2048           0 :     if (PyFile_SoftSpace(fout, 0)) {
    2049           0 :         if (PyFile_WriteString(" ", fout) != 0)
    2050           0 :             return NULL;
    2051             :     }
    2052           0 :     if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
    2053           0 :         && isatty(fileno(PyFile_AsFile(fin)))
    2054           0 :         && isatty(fileno(PyFile_AsFile(fout)))) {
    2055             :         PyObject *po;
    2056             :         char *prompt;
    2057             :         char *s;
    2058             :         PyObject *result;
    2059           0 :         if (v != NULL) {
    2060           0 :             po = PyObject_Str(v);
    2061           0 :             if (po == NULL)
    2062           0 :                 return NULL;
    2063           0 :             prompt = PyString_AsString(po);
    2064           0 :             if (prompt == NULL)
    2065           0 :                 return NULL;
    2066             :         }
    2067             :         else {
    2068           0 :             po = NULL;
    2069           0 :             prompt = "";
    2070             :         }
    2071           0 :         s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
    2072             :                           prompt);
    2073           0 :         Py_XDECREF(po);
    2074           0 :         if (s == NULL) {
    2075           0 :             if (!PyErr_Occurred())
    2076           0 :                 PyErr_SetNone(PyExc_KeyboardInterrupt);
    2077           0 :             return NULL;
    2078             :         }
    2079           0 :         if (*s == '\0') {
    2080           0 :             PyErr_SetNone(PyExc_EOFError);
    2081           0 :             result = NULL;
    2082             :         }
    2083             :         else { /* strip trailing '\n' */
    2084           0 :             size_t len = strlen(s);
    2085           0 :             if (len > PY_SSIZE_T_MAX) {
    2086           0 :                 PyErr_SetString(PyExc_OverflowError,
    2087             :                                 "[raw_]input: input too long");
    2088           0 :                 result = NULL;
    2089             :             }
    2090             :             else {
    2091           0 :                 result = PyString_FromStringAndSize(s, len-1);
    2092             :             }
    2093             :         }
    2094           0 :         PyMem_FREE(s);
    2095           0 :         return result;
    2096             :     }
    2097           0 :     if (v != NULL) {
    2098           0 :         if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
    2099           0 :             return NULL;
    2100             :     }
    2101           0 :     return PyFile_GetLine(fin, -1);
    2102             : }
    2103             : 
    2104             : PyDoc_STRVAR(raw_input_doc,
    2105             : "raw_input([prompt]) -> string\n\
    2106             : \n\
    2107             : Read a string from standard input.  The trailing newline is stripped.\n\
    2108             : If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
    2109             : On Unix, GNU readline is used if enabled.  The prompt string, if given,\n\
    2110             : is printed without a trailing newline before reading.");
    2111             : 
    2112             : 
    2113             : static PyObject *
    2114           0 : builtin_reduce(PyObject *self, PyObject *args)
    2115             : {
    2116             :     static PyObject *functools_reduce = NULL;
    2117             : 
    2118           0 :     if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
    2119           0 :                        "use functools.reduce()", 1) < 0)
    2120           0 :         return NULL;
    2121             : 
    2122           0 :     if (functools_reduce == NULL) {
    2123           0 :         PyObject *functools = PyImport_ImportModule("functools");
    2124           0 :         if (functools == NULL)
    2125           0 :             return NULL;
    2126           0 :         functools_reduce = PyObject_GetAttrString(functools, "reduce");
    2127           0 :         Py_DECREF(functools);
    2128           0 :         if (functools_reduce == NULL)
    2129           0 :             return NULL;
    2130             :     }
    2131           0 :     return PyObject_Call(functools_reduce, args, NULL);
    2132             : }
    2133             : 
    2134             : PyDoc_STRVAR(reduce_doc,
    2135             : "reduce(function, sequence[, initial]) -> value\n\
    2136             : \n\
    2137             : Apply a function of two arguments cumulatively to the items of a sequence,\n\
    2138             : from left to right, so as to reduce the sequence to a single value.\n\
    2139             : For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
    2140             : ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items\n\
    2141             : of the sequence in the calculation, and serves as a default when the\n\
    2142             : sequence is empty.");
    2143             : 
    2144             : 
    2145             : static PyObject *
    2146           0 : builtin_reload(PyObject *self, PyObject *v)
    2147             : {
    2148           0 :     if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",
    2149           0 :                        1) < 0)
    2150           0 :         return NULL;
    2151             : 
    2152           0 :     return PyImport_ReloadModule(v);
    2153             : }
    2154             : 
    2155             : PyDoc_STRVAR(reload_doc,
    2156             : "reload(module) -> module\n\
    2157             : \n\
    2158             : Reload the module.  The module must have been successfully imported before.");
    2159             : 
    2160             : 
    2161             : static PyObject *
    2162          27 : builtin_repr(PyObject *self, PyObject *v)
    2163             : {
    2164          27 :     return PyObject_Repr(v);
    2165             : }
    2166             : 
    2167             : PyDoc_STRVAR(repr_doc,
    2168             : "repr(object) -> string\n\
    2169             : \n\
    2170             : Return the canonical string representation of the object.\n\
    2171             : For most object types, eval(repr(object)) == object.");
    2172             : 
    2173             : 
    2174             : static PyObject *
    2175           0 : builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
    2176             : {
    2177             :     double x;
    2178           0 :     PyObject *o_ndigits = NULL;
    2179             :     Py_ssize_t ndigits;
    2180             :     static char *kwlist[] = {"number", "ndigits", 0};
    2181             : 
    2182           0 :     if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|O:round",
    2183             :         kwlist, &x, &o_ndigits))
    2184           0 :         return NULL;
    2185             : 
    2186           0 :     if (o_ndigits == NULL) {
    2187             :         /* second argument defaults to 0 */
    2188           0 :         ndigits = 0;
    2189             :     }
    2190             :     else {
    2191             :         /* interpret 2nd argument as a Py_ssize_t; clip on overflow */
    2192           0 :         ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
    2193           0 :         if (ndigits == -1 && PyErr_Occurred())
    2194           0 :             return NULL;
    2195             :     }
    2196             : 
    2197             :     /* nans, infinities and zeros round to themselves */
    2198           0 :     if (!Py_IS_FINITE(x) || x == 0.0)
    2199           0 :         return PyFloat_FromDouble(x);
    2200             : 
    2201             :     /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
    2202             :        always rounds to itself.  For ndigits < NDIGITS_MIN, x always
    2203             :        rounds to +-0.0.  Here 0.30103 is an upper bound for log10(2). */
    2204             : #define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
    2205             : #define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
    2206           0 :     if (ndigits > NDIGITS_MAX)
    2207             :         /* return x */
    2208           0 :         return PyFloat_FromDouble(x);
    2209           0 :     else if (ndigits < NDIGITS_MIN)
    2210             :         /* return 0.0, but with sign of x */
    2211           0 :         return PyFloat_FromDouble(0.0*x);
    2212             :     else
    2213             :         /* finite x, and ndigits is not unreasonably large */
    2214             :         /* _Py_double_round is defined in floatobject.c */
    2215           0 :         return _Py_double_round(x, (int)ndigits);
    2216             : #undef NDIGITS_MAX
    2217             : #undef NDIGITS_MIN
    2218             : }
    2219             : 
    2220             : PyDoc_STRVAR(round_doc,
    2221             : "round(number[, ndigits]) -> floating point number\n\
    2222             : \n\
    2223             : Round a number to a given precision in decimal digits (default 0 digits).\n\
    2224             : This always returns a floating point number.  Precision may be negative.");
    2225             : 
    2226             : static PyObject *
    2227           3 : builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
    2228             : {
    2229           3 :     PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
    2230             :     PyObject *callable;
    2231             :     static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
    2232             :     int reverse;
    2233             : 
    2234             :     /* args 1-4 should match listsort in Objects/listobject.c */
    2235           3 :     if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
    2236             :         kwlist, &seq, &compare, &keyfunc, &reverse))
    2237           0 :         return NULL;
    2238             : 
    2239           3 :     newlist = PySequence_List(seq);
    2240           3 :     if (newlist == NULL)
    2241           0 :         return NULL;
    2242             : 
    2243           3 :     callable = PyObject_GetAttrString(newlist, "sort");
    2244           3 :     if (callable == NULL) {
    2245           0 :         Py_DECREF(newlist);
    2246           0 :         return NULL;
    2247             :     }
    2248             : 
    2249           3 :     newargs = PyTuple_GetSlice(args, 1, 4);
    2250           3 :     if (newargs == NULL) {
    2251           0 :         Py_DECREF(newlist);
    2252           0 :         Py_DECREF(callable);
    2253           0 :         return NULL;
    2254             :     }
    2255             : 
    2256           3 :     v = PyObject_Call(callable, newargs, kwds);
    2257           3 :     Py_DECREF(newargs);
    2258           3 :     Py_DECREF(callable);
    2259           3 :     if (v == NULL) {
    2260           0 :         Py_DECREF(newlist);
    2261           0 :         return NULL;
    2262             :     }
    2263           3 :     Py_DECREF(v);
    2264           3 :     return newlist;
    2265             : }
    2266             : 
    2267             : PyDoc_STRVAR(sorted_doc,
    2268             : "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
    2269             : 
    2270             : static PyObject *
    2271           0 : builtin_vars(PyObject *self, PyObject *args)
    2272             : {
    2273           0 :     PyObject *v = NULL;
    2274             :     PyObject *d;
    2275             : 
    2276           0 :     if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
    2277           0 :         return NULL;
    2278           0 :     if (v == NULL) {
    2279           0 :         d = PyEval_GetLocals();
    2280           0 :         if (d == NULL) {
    2281           0 :             if (!PyErr_Occurred())
    2282           0 :                 PyErr_SetString(PyExc_SystemError,
    2283             :                                 "vars(): no locals!?");
    2284             :         }
    2285             :         else
    2286           0 :             Py_INCREF(d);
    2287             :     }
    2288             :     else {
    2289           0 :         d = PyObject_GetAttrString(v, "__dict__");
    2290           0 :         if (d == NULL) {
    2291           0 :             PyErr_SetString(PyExc_TypeError,
    2292             :                 "vars() argument must have __dict__ attribute");
    2293           0 :             return NULL;
    2294             :         }
    2295             :     }
    2296           0 :     return d;
    2297             : }
    2298             : 
    2299             : PyDoc_STRVAR(vars_doc,
    2300             : "vars([object]) -> dictionary\n\
    2301             : \n\
    2302             : Without arguments, equivalent to locals().\n\
    2303             : With an argument, equivalent to object.__dict__.");
    2304             : 
    2305             : 
    2306             : static PyObject*
    2307           0 : builtin_sum(PyObject *self, PyObject *args)
    2308             : {
    2309             :     PyObject *seq;
    2310           0 :     PyObject *result = NULL;
    2311             :     PyObject *temp, *item, *iter;
    2312             : 
    2313           0 :     if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
    2314           0 :         return NULL;
    2315             : 
    2316           0 :     iter = PyObject_GetIter(seq);
    2317           0 :     if (iter == NULL)
    2318           0 :         return NULL;
    2319             : 
    2320           0 :     if (result == NULL) {
    2321           0 :         result = PyInt_FromLong(0);
    2322           0 :         if (result == NULL) {
    2323           0 :             Py_DECREF(iter);
    2324           0 :             return NULL;
    2325             :         }
    2326             :     } else {
    2327             :         /* reject string values for 'start' parameter */
    2328           0 :         if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
    2329           0 :             PyErr_SetString(PyExc_TypeError,
    2330             :                 "sum() can't sum strings [use ''.join(seq) instead]");
    2331           0 :             Py_DECREF(iter);
    2332           0 :             return NULL;
    2333             :         }
    2334           0 :         Py_INCREF(result);
    2335             :     }
    2336             : 
    2337             : #ifndef SLOW_SUM
    2338             :     /* Fast addition by keeping temporary sums in C instead of new Python objects.
    2339             :        Assumes all inputs are the same type.  If the assumption fails, default
    2340             :        to the more general routine.
    2341             :     */
    2342           0 :     if (PyInt_CheckExact(result)) {
    2343           0 :         long i_result = PyInt_AS_LONG(result);
    2344           0 :         Py_DECREF(result);
    2345           0 :         result = NULL;
    2346           0 :         while(result == NULL) {
    2347           0 :             item = PyIter_Next(iter);
    2348           0 :             if (item == NULL) {
    2349           0 :                 Py_DECREF(iter);
    2350           0 :                 if (PyErr_Occurred())
    2351           0 :                     return NULL;
    2352           0 :                 return PyInt_FromLong(i_result);
    2353             :             }
    2354           0 :             if (PyInt_CheckExact(item)) {
    2355           0 :                 long b = PyInt_AS_LONG(item);
    2356           0 :                 long x = i_result + b;
    2357           0 :                 if ((x^i_result) >= 0 || (x^b) >= 0) {
    2358           0 :                     i_result = x;
    2359           0 :                     Py_DECREF(item);
    2360           0 :                     continue;
    2361             :                 }
    2362             :             }
    2363             :             /* Either overflowed or is not an int. Restore real objects and process normally */
    2364           0 :             result = PyInt_FromLong(i_result);
    2365           0 :             temp = PyNumber_Add(result, item);
    2366           0 :             Py_DECREF(result);
    2367           0 :             Py_DECREF(item);
    2368           0 :             result = temp;
    2369           0 :             if (result == NULL) {
    2370           0 :                 Py_DECREF(iter);
    2371           0 :                 return NULL;
    2372             :             }
    2373             :         }
    2374             :     }
    2375             : 
    2376           0 :     if (PyFloat_CheckExact(result)) {
    2377           0 :         double f_result = PyFloat_AS_DOUBLE(result);
    2378           0 :         Py_DECREF(result);
    2379           0 :         result = NULL;
    2380           0 :         while(result == NULL) {
    2381           0 :             item = PyIter_Next(iter);
    2382           0 :             if (item == NULL) {
    2383           0 :                 Py_DECREF(iter);
    2384           0 :                 if (PyErr_Occurred())
    2385           0 :                     return NULL;
    2386           0 :                 return PyFloat_FromDouble(f_result);
    2387             :             }
    2388           0 :             if (PyFloat_CheckExact(item)) {
    2389             :                 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
    2390           0 :                 f_result += PyFloat_AS_DOUBLE(item);
    2391             :                 PyFPE_END_PROTECT(f_result)
    2392           0 :                 Py_DECREF(item);
    2393           0 :                 continue;
    2394             :             }
    2395           0 :             if (PyInt_CheckExact(item)) {
    2396             :                 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
    2397           0 :                 f_result += (double)PyInt_AS_LONG(item);
    2398             :                 PyFPE_END_PROTECT(f_result)
    2399           0 :                 Py_DECREF(item);
    2400           0 :                 continue;
    2401             :             }
    2402           0 :             result = PyFloat_FromDouble(f_result);
    2403           0 :             temp = PyNumber_Add(result, item);
    2404           0 :             Py_DECREF(result);
    2405           0 :             Py_DECREF(item);
    2406           0 :             result = temp;
    2407           0 :             if (result == NULL) {
    2408           0 :                 Py_DECREF(iter);
    2409           0 :                 return NULL;
    2410             :             }
    2411             :         }
    2412             :     }
    2413             : #endif
    2414             : 
    2415             :     for(;;) {
    2416           0 :         item = PyIter_Next(iter);
    2417           0 :         if (item == NULL) {
    2418             :             /* error, or end-of-sequence */
    2419           0 :             if (PyErr_Occurred()) {
    2420           0 :                 Py_DECREF(result);
    2421           0 :                 result = NULL;
    2422             :             }
    2423           0 :             break;
    2424             :         }
    2425             :         /* It's tempting to use PyNumber_InPlaceAdd instead of
    2426             :            PyNumber_Add here, to avoid quadratic running time
    2427             :            when doing 'sum(list_of_lists, [])'.  However, this
    2428             :            would produce a change in behaviour: a snippet like
    2429             : 
    2430             :              empty = []
    2431             :              sum([[x] for x in range(10)], empty)
    2432             : 
    2433             :            would change the value of empty. */
    2434           0 :         temp = PyNumber_Add(result, item);
    2435           0 :         Py_DECREF(result);
    2436           0 :         Py_DECREF(item);
    2437           0 :         result = temp;
    2438           0 :         if (result == NULL)
    2439           0 :             break;
    2440           0 :     }
    2441           0 :     Py_DECREF(iter);
    2442           0 :     return result;
    2443             : }
    2444             : 
    2445             : PyDoc_STRVAR(sum_doc,
    2446             : "sum(sequence[, start]) -> value\n\
    2447             : \n\
    2448             : Return the sum of a sequence of numbers (NOT strings) plus the value\n\
    2449             : of parameter 'start' (which defaults to 0).  When the sequence is\n\
    2450             : empty, return start.");
    2451             : 
    2452             : 
    2453             : static PyObject *
    2454       14128 : builtin_isinstance(PyObject *self, PyObject *args)
    2455             : {
    2456             :     PyObject *inst;
    2457             :     PyObject *cls;
    2458             :     int retval;
    2459             : 
    2460       14128 :     if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
    2461           0 :         return NULL;
    2462             : 
    2463       14128 :     retval = PyObject_IsInstance(inst, cls);
    2464       14128 :     if (retval < 0)
    2465           0 :         return NULL;
    2466       14128 :     return PyBool_FromLong(retval);
    2467             : }
    2468             : 
    2469             : PyDoc_STRVAR(isinstance_doc,
    2470             : "isinstance(object, class-or-type-or-tuple) -> bool\n\
    2471             : \n\
    2472             : Return whether an object is an instance of a class or of a subclass thereof.\n\
    2473             : With a type as second argument, return whether that is the object's type.\n\
    2474             : The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
    2475             : isinstance(x, A) or isinstance(x, B) or ... (etc.).");
    2476             : 
    2477             : 
    2478             : static PyObject *
    2479         180 : builtin_issubclass(PyObject *self, PyObject *args)
    2480             : {
    2481             :     PyObject *derived;
    2482             :     PyObject *cls;
    2483             :     int retval;
    2484             : 
    2485         180 :     if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
    2486           0 :         return NULL;
    2487             : 
    2488         180 :     retval = PyObject_IsSubclass(derived, cls);
    2489         180 :     if (retval < 0)
    2490           0 :         return NULL;
    2491         180 :     return PyBool_FromLong(retval);
    2492             : }
    2493             : 
    2494             : PyDoc_STRVAR(issubclass_doc,
    2495             : "issubclass(C, B) -> bool\n\
    2496             : \n\
    2497             : Return whether class C is a subclass (i.e., a derived class) of class B.\n\
    2498             : When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
    2499             : is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
    2500             : 
    2501             : 
    2502             : static PyObject*
    2503           0 : builtin_zip(PyObject *self, PyObject *args)
    2504             : {
    2505             :     PyObject *ret;
    2506           0 :     const Py_ssize_t itemsize = PySequence_Length(args);
    2507             :     Py_ssize_t i;
    2508             :     PyObject *itlist;  /* tuple of iterators */
    2509             :     Py_ssize_t len;        /* guess at result length */
    2510             : 
    2511           0 :     if (itemsize == 0)
    2512           0 :         return PyList_New(0);
    2513             : 
    2514             :     /* args must be a tuple */
    2515             :     assert(PyTuple_Check(args));
    2516             : 
    2517             :     /* Guess at result length:  the shortest of the input lengths.
    2518             :        If some argument refuses to say, we refuse to guess too, lest
    2519             :        an argument like xrange(sys.maxint) lead us astray.*/
    2520           0 :     len = -1;           /* unknown */
    2521           0 :     for (i = 0; i < itemsize; ++i) {
    2522           0 :         PyObject *item = PyTuple_GET_ITEM(args, i);
    2523           0 :         Py_ssize_t thislen = _PyObject_LengthHint(item, -2);
    2524           0 :         if (thislen < 0) {
    2525           0 :             if (thislen == -1)
    2526           0 :                 return NULL;
    2527           0 :             len = -1;
    2528           0 :             break;
    2529             :         }
    2530           0 :         else if (len < 0 || thislen < len)
    2531           0 :             len = thislen;
    2532             :     }
    2533             : 
    2534             :     /* allocate result list */
    2535           0 :     if (len < 0)
    2536           0 :         len = 10;               /* arbitrary */
    2537           0 :     if ((ret = PyList_New(len)) == NULL)
    2538           0 :         return NULL;
    2539             : 
    2540             :     /* obtain iterators */
    2541           0 :     itlist = PyTuple_New(itemsize);
    2542           0 :     if (itlist == NULL)
    2543           0 :         goto Fail_ret;
    2544           0 :     for (i = 0; i < itemsize; ++i) {
    2545           0 :         PyObject *item = PyTuple_GET_ITEM(args, i);
    2546           0 :         PyObject *it = PyObject_GetIter(item);
    2547           0 :         if (it == NULL) {
    2548           0 :             if (PyErr_ExceptionMatches(PyExc_TypeError))
    2549           0 :                 PyErr_Format(PyExc_TypeError,
    2550             :                     "zip argument #%zd must support iteration",
    2551             :                     i+1);
    2552           0 :             goto Fail_ret_itlist;
    2553             :         }
    2554           0 :         PyTuple_SET_ITEM(itlist, i, it);
    2555             :     }
    2556             : 
    2557             :     /* build result into ret list */
    2558           0 :     for (i = 0; ; ++i) {
    2559             :         int j;
    2560           0 :         PyObject *next = PyTuple_New(itemsize);
    2561           0 :         if (!next)
    2562           0 :             goto Fail_ret_itlist;
    2563             : 
    2564           0 :         for (j = 0; j < itemsize; j++) {
    2565           0 :             PyObject *it = PyTuple_GET_ITEM(itlist, j);
    2566           0 :             PyObject *item = PyIter_Next(it);
    2567           0 :             if (!item) {
    2568           0 :                 if (PyErr_Occurred()) {
    2569           0 :                     Py_DECREF(ret);
    2570           0 :                     ret = NULL;
    2571             :                 }
    2572           0 :                 Py_DECREF(next);
    2573           0 :                 Py_DECREF(itlist);
    2574           0 :                 goto Done;
    2575             :             }
    2576           0 :             PyTuple_SET_ITEM(next, j, item);
    2577             :         }
    2578             : 
    2579           0 :         if (i < len)
    2580           0 :             PyList_SET_ITEM(ret, i, next);
    2581             :         else {
    2582           0 :             int status = PyList_Append(ret, next);
    2583           0 :             Py_DECREF(next);
    2584           0 :             ++len;
    2585           0 :             if (status < 0)
    2586           0 :                 goto Fail_ret_itlist;
    2587             :         }
    2588           0 :     }
    2589             : 
    2590             : Done:
    2591           0 :     if (ret != NULL && i < len) {
    2592             :         /* The list is too big. */
    2593           0 :         if (PyList_SetSlice(ret, i, len, NULL) < 0)
    2594           0 :             return NULL;
    2595             :     }
    2596           0 :     return ret;
    2597             : 
    2598             : Fail_ret_itlist:
    2599           0 :     Py_DECREF(itlist);
    2600             : Fail_ret:
    2601           0 :     Py_DECREF(ret);
    2602           0 :     return NULL;
    2603             : }
    2604             : 
    2605             : 
    2606             : PyDoc_STRVAR(zip_doc,
    2607             : "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
    2608             : \n\
    2609             : Return a list of tuples, where each tuple contains the i-th element\n\
    2610             : from each of the argument sequences.  The returned list is truncated\n\
    2611             : in length to the length of the shortest argument sequence.");
    2612             : 
    2613             : 
    2614             : static PyMethodDef builtin_methods[] = {
    2615             :     {"__import__",      (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
    2616             :     {"abs",             builtin_abs,        METH_O, abs_doc},
    2617             :     {"all",             builtin_all,        METH_O, all_doc},
    2618             :     {"any",             builtin_any,        METH_O, any_doc},
    2619             :     {"apply",           builtin_apply,      METH_VARARGS, apply_doc},
    2620             :     {"bin",             builtin_bin,        METH_O, bin_doc},
    2621             :     {"callable",        builtin_callable,   METH_O, callable_doc},
    2622             :     {"chr",             builtin_chr,        METH_VARARGS, chr_doc},
    2623             :     {"cmp",             builtin_cmp,        METH_VARARGS, cmp_doc},
    2624             :     {"coerce",          builtin_coerce,     METH_VARARGS, coerce_doc},
    2625             :     {"compile",         (PyCFunction)builtin_compile,    METH_VARARGS | METH_KEYWORDS, compile_doc},
    2626             :     {"delattr",         builtin_delattr,    METH_VARARGS, delattr_doc},
    2627             :     {"dir",             builtin_dir,        METH_VARARGS, dir_doc},
    2628             :     {"divmod",          builtin_divmod,     METH_VARARGS, divmod_doc},
    2629             :     {"eval",            builtin_eval,       METH_VARARGS, eval_doc},
    2630             :     {"execfile",        builtin_execfile,   METH_VARARGS, execfile_doc},
    2631             :     {"filter",          builtin_filter,     METH_VARARGS, filter_doc},
    2632             :     {"format",          builtin_format,     METH_VARARGS, format_doc},
    2633             :     {"getattr",         builtin_getattr,    METH_VARARGS, getattr_doc},
    2634             :     {"globals",         (PyCFunction)builtin_globals,    METH_NOARGS, globals_doc},
    2635             :     {"hasattr",         builtin_hasattr,    METH_VARARGS, hasattr_doc},
    2636             :     {"hash",            builtin_hash,       METH_O, hash_doc},
    2637             :     {"hex",             builtin_hex,        METH_O, hex_doc},
    2638             :     {"id",              builtin_id,         METH_O, id_doc},
    2639             :     {"input",           builtin_input,      METH_VARARGS, input_doc},
    2640             :     {"intern",          builtin_intern,     METH_VARARGS, intern_doc},
    2641             :     {"isinstance",  builtin_isinstance, METH_VARARGS, isinstance_doc},
    2642             :     {"issubclass",  builtin_issubclass, METH_VARARGS, issubclass_doc},
    2643             :     {"iter",            builtin_iter,       METH_VARARGS, iter_doc},
    2644             :     {"len",             builtin_len,        METH_O, len_doc},
    2645             :     {"locals",          (PyCFunction)builtin_locals,     METH_NOARGS, locals_doc},
    2646             :     {"map",             builtin_map,        METH_VARARGS, map_doc},
    2647             :     {"max",             (PyCFunction)builtin_max,        METH_VARARGS | METH_KEYWORDS, max_doc},
    2648             :     {"min",             (PyCFunction)builtin_min,        METH_VARARGS | METH_KEYWORDS, min_doc},
    2649             :     {"next",            builtin_next,       METH_VARARGS, next_doc},
    2650             :     {"oct",             builtin_oct,        METH_O, oct_doc},
    2651             :     {"open",            (PyCFunction)builtin_open,       METH_VARARGS | METH_KEYWORDS, open_doc},
    2652             :     {"ord",             builtin_ord,        METH_O, ord_doc},
    2653             :     {"pow",             builtin_pow,        METH_VARARGS, pow_doc},
    2654             :     {"print",           (PyCFunction)builtin_print,      METH_VARARGS | METH_KEYWORDS, print_doc},
    2655             :     {"range",           builtin_range,      METH_VARARGS, range_doc},
    2656             :     {"raw_input",       builtin_raw_input,  METH_VARARGS, raw_input_doc},
    2657             :     {"reduce",          builtin_reduce,     METH_VARARGS, reduce_doc},
    2658             :     {"reload",          builtin_reload,     METH_O, reload_doc},
    2659             :     {"repr",            builtin_repr,       METH_O, repr_doc},
    2660             :     {"round",           (PyCFunction)builtin_round,      METH_VARARGS | METH_KEYWORDS, round_doc},
    2661             :     {"setattr",         builtin_setattr,    METH_VARARGS, setattr_doc},
    2662             :     {"sorted",          (PyCFunction)builtin_sorted,     METH_VARARGS | METH_KEYWORDS, sorted_doc},
    2663             :     {"sum",             builtin_sum,        METH_VARARGS, sum_doc},
    2664             : #ifdef Py_USING_UNICODE
    2665             :     {"unichr",          builtin_unichr,     METH_VARARGS, unichr_doc},
    2666             : #endif
    2667             :     {"vars",            builtin_vars,       METH_VARARGS, vars_doc},
    2668             :     {"zip",         builtin_zip,        METH_VARARGS, zip_doc},
    2669             :     {NULL,              NULL},
    2670             : };
    2671             : 
    2672             : PyDoc_STRVAR(builtin_doc,
    2673             : "Built-in functions, exceptions, and other objects.\n\
    2674             : \n\
    2675             : Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
    2676             : 
    2677             : PyObject *
    2678           3 : _PyBuiltin_Init(void)
    2679             : {
    2680             :     PyObject *mod, *dict, *debug;
    2681           3 :     mod = Py_InitModule4("__builtin__", builtin_methods,
    2682             :                          builtin_doc, (PyObject *)NULL,
    2683             :                          PYTHON_API_VERSION);
    2684           3 :     if (mod == NULL)
    2685           0 :         return NULL;
    2686           3 :     dict = PyModule_GetDict(mod);
    2687             : 
    2688             : #ifdef Py_TRACE_REFS
    2689             :     /* __builtin__ exposes a number of statically allocated objects
    2690             :      * that, before this code was added in 2.3, never showed up in
    2691             :      * the list of "all objects" maintained by Py_TRACE_REFS.  As a
    2692             :      * result, programs leaking references to None and False (etc)
    2693             :      * couldn't be diagnosed by examining sys.getobjects(0).
    2694             :      */
    2695             : #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
    2696             : #else
    2697             : #define ADD_TO_ALL(OBJECT) (void)0
    2698             : #endif
    2699             : 
    2700             : #define SETBUILTIN(NAME, OBJECT) \
    2701             :     if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0)       \
    2702             :         return NULL;                                                    \
    2703             :     ADD_TO_ALL(OBJECT)
    2704             : 
    2705           3 :     SETBUILTIN("None",                  Py_None);
    2706           3 :     SETBUILTIN("Ellipsis",              Py_Ellipsis);
    2707           3 :     SETBUILTIN("NotImplemented",        Py_NotImplemented);
    2708           3 :     SETBUILTIN("False",                 Py_False);
    2709           3 :     SETBUILTIN("True",                  Py_True);
    2710           3 :     SETBUILTIN("basestring",            &PyBaseString_Type);
    2711           3 :     SETBUILTIN("bool",                  &PyBool_Type);
    2712           3 :     SETBUILTIN("memoryview",        &PyMemoryView_Type);
    2713           3 :     SETBUILTIN("bytearray",             &PyByteArray_Type);
    2714           3 :     SETBUILTIN("bytes",                 &PyString_Type);
    2715           3 :     SETBUILTIN("buffer",                &PyBuffer_Type);
    2716           3 :     SETBUILTIN("classmethod",           &PyClassMethod_Type);
    2717             : #ifndef WITHOUT_COMPLEX
    2718           3 :     SETBUILTIN("complex",               &PyComplex_Type);
    2719             : #endif
    2720           3 :     SETBUILTIN("dict",                  &PyDict_Type);
    2721           3 :     SETBUILTIN("enumerate",             &PyEnum_Type);
    2722           3 :     SETBUILTIN("file",                  &PyFile_Type);
    2723           3 :     SETBUILTIN("float",                 &PyFloat_Type);
    2724           3 :     SETBUILTIN("frozenset",             &PyFrozenSet_Type);
    2725           3 :     SETBUILTIN("property",              &PyProperty_Type);
    2726           3 :     SETBUILTIN("int",                   &PyInt_Type);
    2727           3 :     SETBUILTIN("list",                  &PyList_Type);
    2728           3 :     SETBUILTIN("long",                  &PyLong_Type);
    2729           3 :     SETBUILTIN("object",                &PyBaseObject_Type);
    2730           3 :     SETBUILTIN("reversed",              &PyReversed_Type);
    2731           3 :     SETBUILTIN("set",                   &PySet_Type);
    2732           3 :     SETBUILTIN("slice",                 &PySlice_Type);
    2733           3 :     SETBUILTIN("staticmethod",          &PyStaticMethod_Type);
    2734           3 :     SETBUILTIN("str",                   &PyString_Type);
    2735           3 :     SETBUILTIN("super",                 &PySuper_Type);
    2736           3 :     SETBUILTIN("tuple",                 &PyTuple_Type);
    2737           3 :     SETBUILTIN("type",                  &PyType_Type);
    2738           3 :     SETBUILTIN("xrange",                &PyRange_Type);
    2739             : #ifdef Py_USING_UNICODE
    2740           3 :     SETBUILTIN("unicode",               &PyUnicode_Type);
    2741             : #endif
    2742           3 :     debug = PyBool_FromLong(Py_OptimizeFlag == 0);
    2743           3 :     if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
    2744           0 :         Py_XDECREF(debug);
    2745           0 :         return NULL;
    2746             :     }
    2747           3 :     Py_XDECREF(debug);
    2748             : 
    2749           3 :     return mod;
    2750             : #undef ADD_TO_ALL
    2751             : #undef SETBUILTIN
    2752             : }
    2753             : 
    2754             : /* Helper for filter(): filter a tuple through a function */
    2755             : 
    2756             : static PyObject *
    2757          33 : filtertuple(PyObject *func, PyObject *tuple)
    2758             : {
    2759             :     PyObject *result;
    2760             :     Py_ssize_t i, j;
    2761          33 :     Py_ssize_t len = PyTuple_Size(tuple);
    2762             : 
    2763          33 :     if (len == 0) {
    2764           0 :         if (PyTuple_CheckExact(tuple))
    2765           0 :             Py_INCREF(tuple);
    2766             :         else
    2767           0 :             tuple = PyTuple_New(0);
    2768           0 :         return tuple;
    2769             :     }
    2770             : 
    2771          33 :     if ((result = PyTuple_New(len)) == NULL)
    2772           0 :         return NULL;
    2773             : 
    2774          69 :     for (i = j = 0; i < len; ++i) {
    2775             :         PyObject *item, *good;
    2776             :         int ok;
    2777             : 
    2778          72 :         if (tuple->ob_type->tp_as_sequence &&
    2779          36 :             tuple->ob_type->tp_as_sequence->sq_item) {
    2780          36 :             item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
    2781          72 :             if (item == NULL)
    2782           0 :                 goto Fail_1;
    2783             :         } else {
    2784           0 :             PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
    2785           0 :             goto Fail_1;
    2786             :         }
    2787          36 :         if (func == Py_None) {
    2788          36 :             Py_INCREF(item);
    2789          36 :             good = item;
    2790             :         }
    2791             :         else {
    2792           0 :             PyObject *arg = PyTuple_Pack(1, item);
    2793           0 :             if (arg == NULL) {
    2794           0 :                 Py_DECREF(item);
    2795           0 :                 goto Fail_1;
    2796             :             }
    2797           0 :             good = PyEval_CallObject(func, arg);
    2798           0 :             Py_DECREF(arg);
    2799           0 :             if (good == NULL) {
    2800           0 :                 Py_DECREF(item);
    2801           0 :                 goto Fail_1;
    2802             :             }
    2803             :         }
    2804          36 :         ok = PyObject_IsTrue(good);
    2805          36 :         Py_DECREF(good);
    2806          36 :         if (ok > 0) {
    2807          36 :             if (PyTuple_SetItem(result, j++, item) < 0)
    2808           0 :                 goto Fail_1;
    2809             :         }
    2810             :         else {
    2811           0 :             Py_DECREF(item);
    2812           0 :             if (ok < 0)
    2813           0 :                 goto Fail_1;
    2814             :         }
    2815             :     }
    2816             : 
    2817          33 :     if (_PyTuple_Resize(&result, j) < 0)
    2818           0 :         return NULL;
    2819             : 
    2820          33 :     return result;
    2821             : 
    2822             : Fail_1:
    2823           0 :     Py_DECREF(result);
    2824           0 :     return NULL;
    2825             : }
    2826             : 
    2827             : 
    2828             : /* Helper for filter(): filter a string through a function */
    2829             : 
    2830             : static PyObject *
    2831           0 : filterstring(PyObject *func, PyObject *strobj)
    2832             : {
    2833             :     PyObject *result;
    2834             :     Py_ssize_t i, j;
    2835           0 :     Py_ssize_t len = PyString_Size(strobj);
    2836           0 :     Py_ssize_t outlen = len;
    2837             : 
    2838           0 :     if (func == Py_None) {
    2839             :         /* If it's a real string we can return the original,
    2840             :          * as no character is ever false and __getitem__
    2841             :          * does return this character. If it's a subclass
    2842             :          * we must go through the __getitem__ loop */
    2843           0 :         if (PyString_CheckExact(strobj)) {
    2844           0 :             Py_INCREF(strobj);
    2845           0 :             return strobj;
    2846             :         }
    2847             :     }
    2848           0 :     if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
    2849           0 :         return NULL;
    2850             : 
    2851           0 :     for (i = j = 0; i < len; ++i) {
    2852             :         PyObject *item;
    2853             :         int ok;
    2854             : 
    2855           0 :         item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
    2856           0 :         if (item == NULL)
    2857           0 :             goto Fail_1;
    2858           0 :         if (func==Py_None) {
    2859           0 :             ok = 1;
    2860             :         } else {
    2861             :             PyObject *arg, *good;
    2862           0 :             arg = PyTuple_Pack(1, item);
    2863           0 :             if (arg == NULL) {
    2864           0 :                 Py_DECREF(item);
    2865           0 :                 goto Fail_1;
    2866             :             }
    2867           0 :             good = PyEval_CallObject(func, arg);
    2868           0 :             Py_DECREF(arg);
    2869           0 :             if (good == NULL) {
    2870           0 :                 Py_DECREF(item);
    2871           0 :                 goto Fail_1;
    2872             :             }
    2873           0 :             ok = PyObject_IsTrue(good);
    2874           0 :             Py_DECREF(good);
    2875             :         }
    2876           0 :         if (ok > 0) {
    2877             :             Py_ssize_t reslen;
    2878           0 :             if (!PyString_Check(item)) {
    2879           0 :                 PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
    2880             :                     " __getitem__ returned different type");
    2881           0 :                 Py_DECREF(item);
    2882           0 :                 goto Fail_1;
    2883             :             }
    2884           0 :             reslen = PyString_GET_SIZE(item);
    2885           0 :             if (reslen == 1) {
    2886           0 :                 PyString_AS_STRING(result)[j++] =
    2887           0 :                     PyString_AS_STRING(item)[0];
    2888             :             } else {
    2889             :                 /* do we need more space? */
    2890           0 :                 Py_ssize_t need = j;
    2891             : 
    2892             :                 /* calculate space requirements while checking for overflow */
    2893           0 :                 if (need > PY_SSIZE_T_MAX - reslen) {
    2894           0 :                     Py_DECREF(item);
    2895           0 :                     goto Fail_1;
    2896             :                 }
    2897             : 
    2898           0 :                 need += reslen;
    2899             : 
    2900           0 :                 if (need > PY_SSIZE_T_MAX - len) {
    2901           0 :                     Py_DECREF(item);
    2902           0 :                     goto Fail_1;
    2903             :                 }
    2904             : 
    2905           0 :                 need += len;
    2906             : 
    2907           0 :                 if (need <= i) {
    2908           0 :                     Py_DECREF(item);
    2909           0 :                     goto Fail_1;
    2910             :                 }
    2911             : 
    2912           0 :                 need = need - i - 1;
    2913             : 
    2914             :                 assert(need >= 0);
    2915             :                 assert(outlen >= 0);
    2916             : 
    2917           0 :                 if (need > outlen) {
    2918             :                     /* overallocate, to avoid reallocations */
    2919           0 :                     if (outlen > PY_SSIZE_T_MAX / 2) {
    2920           0 :                         Py_DECREF(item);
    2921           0 :                         return NULL;
    2922             :                     }
    2923             : 
    2924           0 :                     if (need<2*outlen) {
    2925           0 :                         need = 2*outlen;
    2926             :                     }
    2927           0 :                     if (_PyString_Resize(&result, need)) {
    2928           0 :                         Py_DECREF(item);
    2929           0 :                         return NULL;
    2930             :                     }
    2931           0 :                     outlen = need;
    2932             :                 }
    2933           0 :                 memcpy(
    2934           0 :                     PyString_AS_STRING(result) + j,
    2935           0 :                     PyString_AS_STRING(item),
    2936             :                     reslen
    2937             :                 );
    2938           0 :                 j += reslen;
    2939             :             }
    2940             :         }
    2941           0 :         Py_DECREF(item);
    2942           0 :         if (ok < 0)
    2943           0 :             goto Fail_1;
    2944             :     }
    2945             : 
    2946           0 :     if (j < outlen)
    2947           0 :         _PyString_Resize(&result, j);
    2948             : 
    2949           0 :     return result;
    2950             : 
    2951             : Fail_1:
    2952           0 :     Py_DECREF(result);
    2953           0 :     return NULL;
    2954             : }
    2955             : 
    2956             : #ifdef Py_USING_UNICODE
    2957             : /* Helper for filter(): filter a Unicode object through a function */
    2958             : 
    2959             : static PyObject *
    2960           0 : filterunicode(PyObject *func, PyObject *strobj)
    2961             : {
    2962             :     PyObject *result;
    2963             :     register Py_ssize_t i, j;
    2964           0 :     Py_ssize_t len = PyUnicode_GetSize(strobj);
    2965           0 :     Py_ssize_t outlen = len;
    2966             : 
    2967           0 :     if (func == Py_None) {
    2968             :         /* If it's a real string we can return the original,
    2969             :          * as no character is ever false and __getitem__
    2970             :          * does return this character. If it's a subclass
    2971             :          * we must go through the __getitem__ loop */
    2972           0 :         if (PyUnicode_CheckExact(strobj)) {
    2973           0 :             Py_INCREF(strobj);
    2974           0 :             return strobj;
    2975             :         }
    2976             :     }
    2977           0 :     if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
    2978           0 :         return NULL;
    2979             : 
    2980           0 :     for (i = j = 0; i < len; ++i) {
    2981             :         PyObject *item, *arg, *good;
    2982             :         int ok;
    2983             : 
    2984           0 :         item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
    2985           0 :         if (item == NULL)
    2986           0 :             goto Fail_1;
    2987           0 :         if (func == Py_None) {
    2988           0 :             ok = 1;
    2989             :         } else {
    2990           0 :             arg = PyTuple_Pack(1, item);
    2991           0 :             if (arg == NULL) {
    2992           0 :                 Py_DECREF(item);
    2993           0 :                 goto Fail_1;
    2994             :             }
    2995           0 :             good = PyEval_CallObject(func, arg);
    2996           0 :             Py_DECREF(arg);
    2997           0 :             if (good == NULL) {
    2998           0 :                 Py_DECREF(item);
    2999           0 :                 goto Fail_1;
    3000             :             }
    3001           0 :             ok = PyObject_IsTrue(good);
    3002           0 :             Py_DECREF(good);
    3003             :         }
    3004           0 :         if (ok > 0) {
    3005             :             Py_ssize_t reslen;
    3006           0 :             if (!PyUnicode_Check(item)) {
    3007           0 :                 PyErr_SetString(PyExc_TypeError,
    3008             :                 "can't filter unicode to unicode:"
    3009             :                 " __getitem__ returned different type");
    3010           0 :                 Py_DECREF(item);
    3011           0 :                 goto Fail_1;
    3012             :             }
    3013           0 :             reslen = PyUnicode_GET_SIZE(item);
    3014           0 :             if (reslen == 1)
    3015           0 :                 PyUnicode_AS_UNICODE(result)[j++] =
    3016           0 :                     PyUnicode_AS_UNICODE(item)[0];
    3017             :             else {
    3018             :                 /* do we need more space? */
    3019           0 :                 Py_ssize_t need = j + reslen + len - i - 1;
    3020             : 
    3021             :                 /* check that didnt overflow */
    3022           0 :                 if ((j > PY_SSIZE_T_MAX - reslen) ||
    3023           0 :                     ((j + reslen) > PY_SSIZE_T_MAX - len) ||
    3024           0 :                         ((j + reslen + len) < i) ||
    3025           0 :                             ((j + reslen + len - i) <= 0)) {
    3026           0 :                     Py_DECREF(item);
    3027           0 :                     return NULL;
    3028             :                 }
    3029             : 
    3030             :                 assert(need >= 0);
    3031             :                 assert(outlen >= 0);
    3032             : 
    3033           0 :                 if (need > outlen) {
    3034             :                     /* overallocate, to avoid reallocations */
    3035           0 :                     if (need < 2 * outlen) {
    3036           0 :                         if (outlen > PY_SSIZE_T_MAX / 2) {
    3037           0 :                             Py_DECREF(item);
    3038           0 :                             return NULL;
    3039             :                         } else {
    3040           0 :                             need = 2 * outlen;
    3041             :                         }
    3042             :                     }
    3043             : 
    3044           0 :                     if (PyUnicode_Resize(&result, need) < 0) {
    3045           0 :                         Py_DECREF(item);
    3046           0 :                         goto Fail_1;
    3047             :                     }
    3048           0 :                     outlen = need;
    3049             :                 }
    3050           0 :                 memcpy(PyUnicode_AS_UNICODE(result) + j,
    3051           0 :                    PyUnicode_AS_UNICODE(item),
    3052             :                    reslen*sizeof(Py_UNICODE));
    3053           0 :                 j += reslen;
    3054             :             }
    3055             :         }
    3056           0 :         Py_DECREF(item);
    3057           0 :         if (ok < 0)
    3058           0 :             goto Fail_1;
    3059             :     }
    3060             : 
    3061           0 :     if (j < outlen)
    3062           0 :         PyUnicode_Resize(&result, j);
    3063             : 
    3064           0 :     return result;
    3065             : 
    3066             : Fail_1:
    3067           0 :     Py_DECREF(result);
    3068           0 :     return NULL;
    3069             : }
    3070             : #endif

Generated by: LCOV version 1.10