+++ /dev/null
-/* Built-in functions */\r
-\r
-#include "Python.h"\r
-#include "Python-ast.h"\r
-\r
-#include "node.h"\r
-#include "code.h"\r
-#include "eval.h"\r
-\r
-#include <ctype.h>\r
-#include <float.h> /* for DBL_MANT_DIG and friends */\r
-\r
-#ifdef RISCOS\r
-#include "unixstuff.h"\r
-#endif\r
-\r
-/* The default encoding used by the platform file system APIs\r
- Can remain NULL for all platforms that don't have such a concept\r
-*/\r
-#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)\r
-const char *Py_FileSystemDefaultEncoding = "mbcs";\r
-#elif defined(__APPLE__)\r
-const char *Py_FileSystemDefaultEncoding = "utf-8";\r
-#else\r
-const char *Py_FileSystemDefaultEncoding = NULL; /* use default */\r
-#endif\r
-\r
-/* Forward */\r
-static PyObject *filterstring(PyObject *, PyObject *);\r
-#ifdef Py_USING_UNICODE\r
-static PyObject *filterunicode(PyObject *, PyObject *);\r
-#endif\r
-static PyObject *filtertuple (PyObject *, PyObject *);\r
-\r
-static PyObject *\r
-builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)\r
-{\r
- static char *kwlist[] = {"name", "globals", "locals", "fromlist",\r
- "level", 0};\r
- char *name;\r
- PyObject *globals = NULL;\r
- PyObject *locals = NULL;\r
- PyObject *fromlist = NULL;\r
- int level = -1;\r
-\r
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",\r
- kwlist, &name, &globals, &locals, &fromlist, &level))\r
- return NULL;\r
- return PyImport_ImportModuleLevel(name, globals, locals,\r
- fromlist, level);\r
-}\r
-\r
-PyDoc_STRVAR(import_doc,\r
-"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\\r
-\n\\r
-Import a module. Because this function is meant for use by the Python\n\\r
-interpreter and not for general use it is better to use\n\\r
-importlib.import_module() to programmatically import a module.\n\\r
-\n\\r
-The globals argument is only used to determine the context;\n\\r
-they are not modified. The locals argument is unused. The fromlist\n\\r
-should be a list of names to emulate ``from name import ...'', or an\n\\r
-empty list to emulate ``import name''.\n\\r
-When importing a module from a package, note that __import__('A.B', ...)\n\\r
-returns package A when fromlist is empty, but its submodule B when\n\\r
-fromlist is not empty. Level is used to determine whether to perform \n\\r
-absolute or relative imports. -1 is the original strategy of attempting\n\\r
-both absolute and relative imports, 0 is absolute, a positive number\n\\r
-is the number of parent directories to search relative to the current module.");\r
-\r
-\r
-static PyObject *\r
-builtin_abs(PyObject *self, PyObject *v)\r
-{\r
- return PyNumber_Absolute(v);\r
-}\r
-\r
-PyDoc_STRVAR(abs_doc,\r
-"abs(number) -> number\n\\r
-\n\\r
-Return the absolute value of the argument.");\r
-\r
-static PyObject *\r
-builtin_all(PyObject *self, PyObject *v)\r
-{\r
- PyObject *it, *item;\r
- PyObject *(*iternext)(PyObject *);\r
- int cmp;\r
-\r
- it = PyObject_GetIter(v);\r
- if (it == NULL)\r
- return NULL;\r
- iternext = *Py_TYPE(it)->tp_iternext;\r
-\r
- for (;;) {\r
- item = iternext(it);\r
- if (item == NULL)\r
- break;\r
- cmp = PyObject_IsTrue(item);\r
- Py_DECREF(item);\r
- if (cmp < 0) {\r
- Py_DECREF(it);\r
- return NULL;\r
- }\r
- if (cmp == 0) {\r
- Py_DECREF(it);\r
- Py_RETURN_FALSE;\r
- }\r
- }\r
- Py_DECREF(it);\r
- if (PyErr_Occurred()) {\r
- if (PyErr_ExceptionMatches(PyExc_StopIteration))\r
- PyErr_Clear();\r
- else\r
- return NULL;\r
- }\r
- Py_RETURN_TRUE;\r
-}\r
-\r
-PyDoc_STRVAR(all_doc,\r
-"all(iterable) -> bool\n\\r
-\n\\r
-Return True if bool(x) is True for all values x in the iterable.\n\\r
-If the iterable is empty, return True.");\r
-\r
-static PyObject *\r
-builtin_any(PyObject *self, PyObject *v)\r
-{\r
- PyObject *it, *item;\r
- PyObject *(*iternext)(PyObject *);\r
- int cmp;\r
-\r
- it = PyObject_GetIter(v);\r
- if (it == NULL)\r
- return NULL;\r
- iternext = *Py_TYPE(it)->tp_iternext;\r
-\r
- for (;;) {\r
- item = iternext(it);\r
- if (item == NULL)\r
- break;\r
- cmp = PyObject_IsTrue(item);\r
- Py_DECREF(item);\r
- if (cmp < 0) {\r
- Py_DECREF(it);\r
- return NULL;\r
- }\r
- if (cmp == 1) {\r
- Py_DECREF(it);\r
- Py_RETURN_TRUE;\r
- }\r
- }\r
- Py_DECREF(it);\r
- if (PyErr_Occurred()) {\r
- if (PyErr_ExceptionMatches(PyExc_StopIteration))\r
- PyErr_Clear();\r
- else\r
- return NULL;\r
- }\r
- Py_RETURN_FALSE;\r
-}\r
-\r
-PyDoc_STRVAR(any_doc,\r
-"any(iterable) -> bool\n\\r
-\n\\r
-Return True if bool(x) is True for any x in the iterable.\n\\r
-If the iterable is empty, return False.");\r
-\r
-static PyObject *\r
-builtin_apply(PyObject *self, PyObject *args)\r
-{\r
- PyObject *func, *alist = NULL, *kwdict = NULL;\r
- PyObject *t = NULL, *retval = NULL;\r
-\r
- if (PyErr_WarnPy3k("apply() not supported in 3.x; "\r
- "use func(*args, **kwargs)", 1) < 0)\r
- return NULL;\r
-\r
- if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict))\r
- return NULL;\r
- if (alist != NULL) {\r
- if (!PyTuple_Check(alist)) {\r
- if (!PySequence_Check(alist)) {\r
- PyErr_Format(PyExc_TypeError,\r
- "apply() arg 2 expected sequence, found %s",\r
- alist->ob_type->tp_name);\r
- return NULL;\r
- }\r
- t = PySequence_Tuple(alist);\r
- if (t == NULL)\r
- return NULL;\r
- alist = t;\r
- }\r
- }\r
- if (kwdict != NULL && !PyDict_Check(kwdict)) {\r
- PyErr_Format(PyExc_TypeError,\r
- "apply() arg 3 expected dictionary, found %s",\r
- kwdict->ob_type->tp_name);\r
- goto finally;\r
- }\r
- retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);\r
- finally:\r
- Py_XDECREF(t);\r
- return retval;\r
-}\r
-\r
-PyDoc_STRVAR(apply_doc,\r
-"apply(object[, args[, kwargs]]) -> value\n\\r
-\n\\r
-Call a callable object with positional arguments taken from the tuple args,\n\\r
-and keyword arguments taken from the optional dictionary kwargs.\n\\r
-Note that classes are callable, as are instances with a __call__() method.\n\\r
-\n\\r
-Deprecated since release 2.3. Instead, use the extended call syntax:\n\\r
- function(*args, **keywords).");\r
-\r
-\r
-static PyObject *\r
-builtin_bin(PyObject *self, PyObject *v)\r
-{\r
- return PyNumber_ToBase(v, 2);\r
-}\r
-\r
-PyDoc_STRVAR(bin_doc,\r
-"bin(number) -> string\n\\r
-\n\\r
-Return the binary representation of an integer or long integer.");\r
-\r
-\r
-static PyObject *\r
-builtin_callable(PyObject *self, PyObject *v)\r
-{\r
- return PyBool_FromLong((long)PyCallable_Check(v));\r
-}\r
-\r
-PyDoc_STRVAR(callable_doc,\r
-"callable(object) -> bool\n\\r
-\n\\r
-Return whether the object is callable (i.e., some kind of function).\n\\r
-Note that classes are callable, as are instances with a __call__() method.");\r
-\r
-\r
-static PyObject *\r
-builtin_filter(PyObject *self, PyObject *args)\r
-{\r
- PyObject *func, *seq, *result, *it, *arg;\r
- Py_ssize_t len; /* guess for result list size */\r
- register Py_ssize_t j;\r
-\r
- if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))\r
- return NULL;\r
-\r
- /* Strings and tuples return a result of the same type. */\r
- if (PyString_Check(seq))\r
- return filterstring(func, seq);\r
-#ifdef Py_USING_UNICODE\r
- if (PyUnicode_Check(seq))\r
- return filterunicode(func, seq);\r
-#endif\r
- if (PyTuple_Check(seq))\r
- return filtertuple(func, seq);\r
-\r
- /* Pre-allocate argument list tuple. */\r
- arg = PyTuple_New(1);\r
- if (arg == NULL)\r
- return NULL;\r
-\r
- /* Get iterator. */\r
- it = PyObject_GetIter(seq);\r
- if (it == NULL)\r
- goto Fail_arg;\r
-\r
- /* Guess a result list size. */\r
- len = _PyObject_LengthHint(seq, 8);\r
- if (len == -1)\r
- goto Fail_it;\r
-\r
- /* Get a result list. */\r
- if (PyList_Check(seq) && seq->ob_refcnt == 1) {\r
- /* Eww - can modify the list in-place. */\r
- Py_INCREF(seq);\r
- result = seq;\r
- }\r
- else {\r
- result = PyList_New(len);\r
- if (result == NULL)\r
- goto Fail_it;\r
- }\r
-\r
- /* Build the result list. */\r
- j = 0;\r
- for (;;) {\r
- PyObject *item;\r
- int ok;\r
-\r
- item = PyIter_Next(it);\r
- if (item == NULL) {\r
- if (PyErr_Occurred())\r
- goto Fail_result_it;\r
- break;\r
- }\r
-\r
- if (func == (PyObject *)&PyBool_Type || func == Py_None) {\r
- ok = PyObject_IsTrue(item);\r
- }\r
- else {\r
- PyObject *good;\r
- PyTuple_SET_ITEM(arg, 0, item);\r
- good = PyObject_Call(func, arg, NULL);\r
- PyTuple_SET_ITEM(arg, 0, NULL);\r
- if (good == NULL) {\r
- Py_DECREF(item);\r
- goto Fail_result_it;\r
- }\r
- ok = PyObject_IsTrue(good);\r
- Py_DECREF(good);\r
- }\r
- if (ok > 0) {\r
- if (j < len)\r
- PyList_SET_ITEM(result, j, item);\r
- else {\r
- int status = PyList_Append(result, item);\r
- Py_DECREF(item);\r
- if (status < 0)\r
- goto Fail_result_it;\r
- }\r
- ++j;\r
- }\r
- else {\r
- Py_DECREF(item);\r
- if (ok < 0)\r
- goto Fail_result_it;\r
- }\r
- }\r
-\r
-\r
- /* Cut back result list if len is too big. */\r
- if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)\r
- goto Fail_result_it;\r
-\r
- Py_DECREF(it);\r
- Py_DECREF(arg);\r
- return result;\r
-\r
-Fail_result_it:\r
- Py_DECREF(result);\r
-Fail_it:\r
- Py_DECREF(it);\r
-Fail_arg:\r
- Py_DECREF(arg);\r
- return NULL;\r
-}\r
-\r
-PyDoc_STRVAR(filter_doc,\r
-"filter(function or None, sequence) -> list, tuple, or string\n"\r
-"\n"\r
-"Return those items of sequence for which function(item) is true. If\n"\r
-"function is None, return the items that are true. If sequence is a tuple\n"\r
-"or string, return the same type, else return a list.");\r
-\r
-static PyObject *\r
-builtin_format(PyObject *self, PyObject *args)\r
-{\r
- PyObject *value;\r
- PyObject *format_spec = NULL;\r
-\r
- if (!PyArg_ParseTuple(args, "O|O:format", &value, &format_spec))\r
- return NULL;\r
-\r
- return PyObject_Format(value, format_spec);\r
-}\r
-\r
-PyDoc_STRVAR(format_doc,\r
-"format(value[, format_spec]) -> string\n\\r
-\n\\r
-Returns value.__format__(format_spec)\n\\r
-format_spec defaults to \"\"");\r
-\r
-static PyObject *\r
-builtin_chr(PyObject *self, PyObject *args)\r
-{\r
- long x;\r
- char s[1];\r
-\r
- if (!PyArg_ParseTuple(args, "l:chr", &x))\r
- return NULL;\r
- if (x < 0 || x >= 256) {\r
- PyErr_SetString(PyExc_ValueError,\r
- "chr() arg not in range(256)");\r
- return NULL;\r
- }\r
- s[0] = (char)x;\r
- return PyString_FromStringAndSize(s, 1);\r
-}\r
-\r
-PyDoc_STRVAR(chr_doc,\r
-"chr(i) -> character\n\\r
-\n\\r
-Return a string of one character with ordinal i; 0 <= i < 256.");\r
-\r
-\r
-#ifdef Py_USING_UNICODE\r
-static PyObject *\r
-builtin_unichr(PyObject *self, PyObject *args)\r
-{\r
- int x;\r
-\r
- if (!PyArg_ParseTuple(args, "i:unichr", &x))\r
- return NULL;\r
-\r
- return PyUnicode_FromOrdinal(x);\r
-}\r
-\r
-PyDoc_STRVAR(unichr_doc,\r
-"unichr(i) -> Unicode character\n\\r
-\n\\r
-Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");\r
-#endif\r
-\r
-\r
-static PyObject *\r
-builtin_cmp(PyObject *self, PyObject *args)\r
-{\r
- PyObject *a, *b;\r
- int c;\r
-\r
- if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))\r
- return NULL;\r
- if (PyObject_Cmp(a, b, &c) < 0)\r
- return NULL;\r
- return PyInt_FromLong((long)c);\r
-}\r
-\r
-PyDoc_STRVAR(cmp_doc,\r
-"cmp(x, y) -> integer\n\\r
-\n\\r
-Return negative if x<y, zero if x==y, positive if x>y.");\r
-\r
-\r
-static PyObject *\r
-builtin_coerce(PyObject *self, PyObject *args)\r
-{\r
- PyObject *v, *w;\r
- PyObject *res;\r
-\r
- if (PyErr_WarnPy3k("coerce() not supported in 3.x", 1) < 0)\r
- return NULL;\r
-\r
- if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))\r
- return NULL;\r
- if (PyNumber_Coerce(&v, &w) < 0)\r
- return NULL;\r
- res = PyTuple_Pack(2, v, w);\r
- Py_DECREF(v);\r
- Py_DECREF(w);\r
- return res;\r
-}\r
-\r
-PyDoc_STRVAR(coerce_doc,\r
-"coerce(x, y) -> (x1, y1)\n\\r
-\n\\r
-Return a tuple consisting of the two numeric arguments converted to\n\\r
-a common type, using the same rules as used by arithmetic operations.\n\\r
-If coercion is not possible, raise TypeError.");\r
-\r
-static PyObject *\r
-builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)\r
-{\r
- char *str;\r
- char *filename;\r
- char *startstr;\r
- int mode = -1;\r
- int dont_inherit = 0;\r
- int supplied_flags = 0;\r
- int is_ast;\r
- PyCompilerFlags cf;\r
- PyObject *result = NULL, *cmd, *tmp = NULL;\r
- Py_ssize_t length;\r
- static char *kwlist[] = {"source", "filename", "mode", "flags",\r
- "dont_inherit", NULL};\r
- int start[] = {Py_file_input, Py_eval_input, Py_single_input};\r
-\r
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",\r
- kwlist, &cmd, &filename, &startstr,\r
- &supplied_flags, &dont_inherit))\r
- return NULL;\r
-\r
- cf.cf_flags = supplied_flags;\r
-\r
- if (supplied_flags &\r
- ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))\r
- {\r
- PyErr_SetString(PyExc_ValueError,\r
- "compile(): unrecognised flags");\r
- return NULL;\r
- }\r
- /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */\r
-\r
- if (!dont_inherit) {\r
- PyEval_MergeCompilerFlags(&cf);\r
- }\r
-\r
- if (strcmp(startstr, "exec") == 0)\r
- mode = 0;\r
- else if (strcmp(startstr, "eval") == 0)\r
- mode = 1;\r
- else if (strcmp(startstr, "single") == 0)\r
- mode = 2;\r
- else {\r
- PyErr_SetString(PyExc_ValueError,\r
- "compile() arg 3 must be 'exec', 'eval' or 'single'");\r
- return NULL;\r
- }\r
-\r
- is_ast = PyAST_Check(cmd);\r
- if (is_ast == -1)\r
- return NULL;\r
- if (is_ast) {\r
- if (supplied_flags & PyCF_ONLY_AST) {\r
- Py_INCREF(cmd);\r
- result = cmd;\r
- }\r
- else {\r
- PyArena *arena;\r
- mod_ty mod;\r
-\r
- arena = PyArena_New();\r
- if (arena == NULL)\r
- return NULL;\r
- mod = PyAST_obj2mod(cmd, arena, mode);\r
- if (mod == NULL) {\r
- PyArena_Free(arena);\r
- return NULL;\r
- }\r
- result = (PyObject*)PyAST_Compile(mod, filename,\r
- &cf, arena);\r
- PyArena_Free(arena);\r
- }\r
- return result;\r
- }\r
-\r
-#ifdef Py_USING_UNICODE\r
- if (PyUnicode_Check(cmd)) {\r
- tmp = PyUnicode_AsUTF8String(cmd);\r
- if (tmp == NULL)\r
- return NULL;\r
- cmd = tmp;\r
- cf.cf_flags |= PyCF_SOURCE_IS_UTF8;\r
- }\r
-#endif\r
-\r
- if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length))\r
- goto cleanup;\r
- if ((size_t)length != strlen(str)) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "compile() expected string without null bytes");\r
- goto cleanup;\r
- }\r
- result = Py_CompileStringFlags(str, filename, start[mode], &cf);\r
-cleanup:\r
- Py_XDECREF(tmp);\r
- return result;\r
-}\r
-\r
-PyDoc_STRVAR(compile_doc,\r
-"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\\r
-\n\\r
-Compile the source string (a Python module, statement or expression)\n\\r
-into a code object that can be executed by the exec statement or eval().\n\\r
-The filename will be used for run-time error messages.\n\\r
-The mode must be 'exec' to compile a module, 'single' to compile a\n\\r
-single (interactive) statement, or 'eval' to compile an expression.\n\\r
-The flags argument, if present, controls which future statements influence\n\\r
-the compilation of the code.\n\\r
-The dont_inherit argument, if non-zero, stops the compilation inheriting\n\\r
-the effects of any future statements in effect in the code calling\n\\r
-compile; if absent or zero these statements do influence the compilation,\n\\r
-in addition to any features explicitly specified.");\r
-\r
-static PyObject *\r
-builtin_dir(PyObject *self, PyObject *args)\r
-{\r
- PyObject *arg = NULL;\r
-\r
- if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))\r
- return NULL;\r
- return PyObject_Dir(arg);\r
-}\r
-\r
-PyDoc_STRVAR(dir_doc,\r
-"dir([object]) -> list of strings\n"\r
-"\n"\r
-"If called without an argument, return the names in the current scope.\n"\r
-"Else, return an alphabetized list of names comprising (some of) the attributes\n"\r
-"of the given object, and of attributes reachable from it.\n"\r
-"If the object supplies a method named __dir__, it will be used; otherwise\n"\r
-"the default dir() logic is used and returns:\n"\r
-" for a module object: the module's attributes.\n"\r
-" for a class object: its attributes, and recursively the attributes\n"\r
-" of its bases.\n"\r
-" for any other object: its attributes, its class's attributes, and\n"\r
-" recursively the attributes of its class's base classes.");\r
-\r
-static PyObject *\r
-builtin_divmod(PyObject *self, PyObject *args)\r
-{\r
- PyObject *v, *w;\r
-\r
- if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))\r
- return NULL;\r
- return PyNumber_Divmod(v, w);\r
-}\r
-\r
-PyDoc_STRVAR(divmod_doc,\r
-"divmod(x, y) -> (quotient, remainder)\n\\r
-\n\\r
-Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");\r
-\r
-\r
-static PyObject *\r
-builtin_eval(PyObject *self, PyObject *args)\r
-{\r
- PyObject *cmd, *result, *tmp = NULL;\r
- PyObject *globals = Py_None, *locals = Py_None;\r
- char *str;\r
- PyCompilerFlags cf;\r
-\r
- if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))\r
- return NULL;\r
- if (locals != Py_None && !PyMapping_Check(locals)) {\r
- PyErr_SetString(PyExc_TypeError, "locals must be a mapping");\r
- return NULL;\r
- }\r
- if (globals != Py_None && !PyDict_Check(globals)) {\r
- PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?\r
- "globals must be a real dict; try eval(expr, {}, mapping)"\r
- : "globals must be a dict");\r
- return NULL;\r
- }\r
- if (globals == Py_None) {\r
- globals = PyEval_GetGlobals();\r
- if (locals == Py_None)\r
- locals = PyEval_GetLocals();\r
- }\r
- else if (locals == Py_None)\r
- locals = globals;\r
-\r
- if (globals == NULL || locals == NULL) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "eval must be given globals and locals "\r
- "when called without a frame");\r
- return NULL;\r
- }\r
-\r
- if (PyDict_GetItemString(globals, "__builtins__") == NULL) {\r
- if (PyDict_SetItemString(globals, "__builtins__",\r
- PyEval_GetBuiltins()) != 0)\r
- return NULL;\r
- }\r
-\r
- if (PyCode_Check(cmd)) {\r
- if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "code object passed to eval() may not contain free variables");\r
- return NULL;\r
- }\r
- return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);\r
- }\r
-\r
- if (!PyString_Check(cmd) &&\r
- !PyUnicode_Check(cmd)) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "eval() arg 1 must be a string or code object");\r
- return NULL;\r
- }\r
- cf.cf_flags = 0;\r
-\r
-#ifdef Py_USING_UNICODE\r
- if (PyUnicode_Check(cmd)) {\r
- tmp = PyUnicode_AsUTF8String(cmd);\r
- if (tmp == NULL)\r
- return NULL;\r
- cmd = tmp;\r
- cf.cf_flags |= PyCF_SOURCE_IS_UTF8;\r
- }\r
-#endif\r
- if (PyString_AsStringAndSize(cmd, &str, NULL)) {\r
- Py_XDECREF(tmp);\r
- return NULL;\r
- }\r
- while (*str == ' ' || *str == '\t')\r
- str++;\r
-\r
- (void)PyEval_MergeCompilerFlags(&cf);\r
- result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);\r
- Py_XDECREF(tmp);\r
- return result;\r
-}\r
-\r
-PyDoc_STRVAR(eval_doc,\r
-"eval(source[, globals[, locals]]) -> value\n\\r
-\n\\r
-Evaluate the source in the context of globals and locals.\n\\r
-The source may be a string representing a Python expression\n\\r
-or a code object as returned by compile().\n\\r
-The globals must be a dictionary and locals can be any mapping,\n\\r
-defaulting to the current globals and locals.\n\\r
-If only globals is given, locals defaults to it.\n");\r
-\r
-\r
-static PyObject *\r
-builtin_execfile(PyObject *self, PyObject *args)\r
-{\r
- char *filename;\r
- PyObject *globals = Py_None, *locals = Py_None;\r
- PyObject *res;\r
- FILE* fp = NULL;\r
- PyCompilerFlags cf;\r
- int exists;\r
-\r
- if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",\r
- 1) < 0)\r
- return NULL;\r
-\r
- if (!PyArg_ParseTuple(args, "s|O!O:execfile",\r
- &filename,\r
- &PyDict_Type, &globals,\r
- &locals))\r
- return NULL;\r
- if (locals != Py_None && !PyMapping_Check(locals)) {\r
- PyErr_SetString(PyExc_TypeError, "locals must be a mapping");\r
- return NULL;\r
- }\r
- if (globals == Py_None) {\r
- globals = PyEval_GetGlobals();\r
- if (locals == Py_None)\r
- locals = PyEval_GetLocals();\r
- }\r
- else if (locals == Py_None)\r
- locals = globals;\r
- if (PyDict_GetItemString(globals, "__builtins__") == NULL) {\r
- if (PyDict_SetItemString(globals, "__builtins__",\r
- PyEval_GetBuiltins()) != 0)\r
- return NULL;\r
- }\r
-\r
- exists = 0;\r
- /* Test for existence or directory. */\r
-#if defined(PLAN9)\r
- {\r
- Dir *d;\r
-\r
- if ((d = dirstat(filename))!=nil) {\r
- if(d->mode & DMDIR)\r
- werrstr("is a directory");\r
- else\r
- exists = 1;\r
- free(d);\r
- }\r
- }\r
-#elif defined(RISCOS)\r
- if (object_exists(filename)) {\r
- if (isdir(filename))\r
- errno = EISDIR;\r
- else\r
- exists = 1;\r
- }\r
-#else /* standard Posix */\r
- {\r
- struct stat s;\r
- if (stat(filename, &s) == 0) {\r
- if (S_ISDIR(s.st_mode))\r
-# if defined(PYOS_OS2) && defined(PYCC_VACPP)\r
- errno = EOS2ERR;\r
-# else\r
- errno = EISDIR;\r
-# endif\r
- else\r
- exists = 1;\r
- }\r
- }\r
-#endif\r
-\r
- if (exists) {\r
- Py_BEGIN_ALLOW_THREADS\r
- fp = fopen(filename, "r" PY_STDIOTEXTMODE);\r
- Py_END_ALLOW_THREADS\r
-\r
- if (fp == NULL) {\r
- exists = 0;\r
- }\r
- }\r
-\r
- if (!exists) {\r
- PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);\r
- return NULL;\r
- }\r
- cf.cf_flags = 0;\r
- if (PyEval_MergeCompilerFlags(&cf))\r
- res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,\r
- locals, 1, &cf);\r
- else\r
- res = PyRun_FileEx(fp, filename, Py_file_input, globals,\r
- locals, 1);\r
- return res;\r
-}\r
-\r
-PyDoc_STRVAR(execfile_doc,\r
-"execfile(filename[, globals[, locals]])\n\\r
-\n\\r
-Read and execute a Python script from a file.\n\\r
-The globals and locals are dictionaries, defaulting to the current\n\\r
-globals and locals. If only globals is given, locals defaults to it.");\r
-\r
-\r
-static PyObject *\r
-builtin_getattr(PyObject *self, PyObject *args)\r
-{\r
- PyObject *v, *result, *dflt = NULL;\r
- PyObject *name;\r
-\r
- if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))\r
- return NULL;\r
-#ifdef Py_USING_UNICODE\r
- if (PyUnicode_Check(name)) {\r
- name = _PyUnicode_AsDefaultEncodedString(name, NULL);\r
- if (name == NULL)\r
- return NULL;\r
- }\r
-#endif\r
-\r
- if (!PyString_Check(name)) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "getattr(): attribute name must be string");\r
- return NULL;\r
- }\r
- result = PyObject_GetAttr(v, name);\r
- if (result == NULL && dflt != NULL &&\r
- PyErr_ExceptionMatches(PyExc_AttributeError))\r
- {\r
- PyErr_Clear();\r
- Py_INCREF(dflt);\r
- result = dflt;\r
- }\r
- return result;\r
-}\r
-\r
-PyDoc_STRVAR(getattr_doc,\r
-"getattr(object, name[, default]) -> value\n\\r
-\n\\r
-Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\\r
-When a default argument is given, it is returned when the attribute doesn't\n\\r
-exist; without it, an exception is raised in that case.");\r
-\r
-\r
-static PyObject *\r
-builtin_globals(PyObject *self)\r
-{\r
- PyObject *d;\r
-\r
- d = PyEval_GetGlobals();\r
- Py_XINCREF(d);\r
- return d;\r
-}\r
-\r
-PyDoc_STRVAR(globals_doc,\r
-"globals() -> dictionary\n\\r
-\n\\r
-Return the dictionary containing the current scope's global variables.");\r
-\r
-\r
-static PyObject *\r
-builtin_hasattr(PyObject *self, PyObject *args)\r
-{\r
- PyObject *v;\r
- PyObject *name;\r
-\r
- if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))\r
- return NULL;\r
-#ifdef Py_USING_UNICODE\r
- if (PyUnicode_Check(name)) {\r
- name = _PyUnicode_AsDefaultEncodedString(name, NULL);\r
- if (name == NULL)\r
- return NULL;\r
- }\r
-#endif\r
-\r
- if (!PyString_Check(name)) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "hasattr(): attribute name must be string");\r
- return NULL;\r
- }\r
- v = PyObject_GetAttr(v, name);\r
- if (v == NULL) {\r
- if (!PyErr_ExceptionMatches(PyExc_Exception))\r
- return NULL;\r
- else {\r
- PyErr_Clear();\r
- Py_INCREF(Py_False);\r
- return Py_False;\r
- }\r
- }\r
- Py_DECREF(v);\r
- Py_INCREF(Py_True);\r
- return Py_True;\r
-}\r
-\r
-PyDoc_STRVAR(hasattr_doc,\r
-"hasattr(object, name) -> bool\n\\r
-\n\\r
-Return whether the object has an attribute with the given name.\n\\r
-(This is done by calling getattr(object, name) and catching exceptions.)");\r
-\r
-\r
-static PyObject *\r
-builtin_id(PyObject *self, PyObject *v)\r
-{\r
- return PyLong_FromVoidPtr(v);\r
-}\r
-\r
-PyDoc_STRVAR(id_doc,\r
-"id(object) -> integer\n\\r
-\n\\r
-Return the identity of an object. This is guaranteed to be unique among\n\\r
-simultaneously existing objects. (Hint: it's the object's memory address.)");\r
-\r
-\r
-static PyObject *\r
-builtin_map(PyObject *self, PyObject *args)\r
-{\r
- typedef struct {\r
- PyObject *it; /* the iterator object */\r
- int saw_StopIteration; /* bool: did the iterator end? */\r
- } sequence;\r
-\r
- PyObject *func, *result;\r
- sequence *seqs = NULL, *sqp;\r
- Py_ssize_t n, len;\r
- register int i, j;\r
-\r
- n = PyTuple_Size(args);\r
- if (n < 2) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "map() requires at least two args");\r
- return NULL;\r
- }\r
-\r
- func = PyTuple_GetItem(args, 0);\r
- n--;\r
-\r
- if (func == Py_None) {\r
- if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "\r
- "use list(...)", 1) < 0)\r
- return NULL;\r
- if (n == 1) {\r
- /* map(None, S) is the same as list(S). */\r
- return PySequence_List(PyTuple_GetItem(args, 1));\r
- }\r
- }\r
-\r
- /* Get space for sequence descriptors. Must NULL out the iterator\r
- * pointers so that jumping to Fail_2 later doesn't see trash.\r
- */\r
- if ((seqs = PyMem_NEW(sequence, n)) == NULL) {\r
- PyErr_NoMemory();\r
- return NULL;\r
- }\r
- for (i = 0; i < n; ++i) {\r
- seqs[i].it = (PyObject*)NULL;\r
- seqs[i].saw_StopIteration = 0;\r
- }\r
-\r
- /* Do a first pass to obtain iterators for the arguments, and set len\r
- * to the largest of their lengths.\r
- */\r
- len = 0;\r
- for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {\r
- PyObject *curseq;\r
- Py_ssize_t curlen;\r
-\r
- /* Get iterator. */\r
- curseq = PyTuple_GetItem(args, i+1);\r
- sqp->it = PyObject_GetIter(curseq);\r
- if (sqp->it == NULL) {\r
- static char errmsg[] =\r
- "argument %d to map() must support iteration";\r
- char errbuf[sizeof(errmsg) + 25];\r
- PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);\r
- PyErr_SetString(PyExc_TypeError, errbuf);\r
- goto Fail_2;\r
- }\r
-\r
- /* Update len. */\r
- curlen = _PyObject_LengthHint(curseq, 8);\r
- if (curlen > len)\r
- len = curlen;\r
- }\r
-\r
- /* Get space for the result list. */\r
- if ((result = (PyObject *) PyList_New(len)) == NULL)\r
- goto Fail_2;\r
-\r
- /* Iterate over the sequences until all have stopped. */\r
- for (i = 0; ; ++i) {\r
- PyObject *alist, *item=NULL, *value;\r
- int numactive = 0;\r
-\r
- if (func == Py_None && n == 1)\r
- alist = NULL;\r
- else if ((alist = PyTuple_New(n)) == NULL)\r
- goto Fail_1;\r
-\r
- for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {\r
- if (sqp->saw_StopIteration) {\r
- Py_INCREF(Py_None);\r
- item = Py_None;\r
- }\r
- else {\r
- item = PyIter_Next(sqp->it);\r
- if (item)\r
- ++numactive;\r
- else {\r
- if (PyErr_Occurred()) {\r
- Py_XDECREF(alist);\r
- goto Fail_1;\r
- }\r
- Py_INCREF(Py_None);\r
- item = Py_None;\r
- sqp->saw_StopIteration = 1;\r
- }\r
- }\r
- if (alist)\r
- PyTuple_SET_ITEM(alist, j, item);\r
- else\r
- break;\r
- }\r
-\r
- if (!alist)\r
- alist = item;\r
-\r
- if (numactive == 0) {\r
- Py_DECREF(alist);\r
- break;\r
- }\r
-\r
- if (func == Py_None)\r
- value = alist;\r
- else {\r
- value = PyEval_CallObject(func, alist);\r
- Py_DECREF(alist);\r
- if (value == NULL)\r
- goto Fail_1;\r
- }\r
- if (i >= len) {\r
- int status = PyList_Append(result, value);\r
- Py_DECREF(value);\r
- if (status < 0)\r
- goto Fail_1;\r
- }\r
- else if (PyList_SetItem(result, i, value) < 0)\r
- goto Fail_1;\r
- }\r
-\r
- if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)\r
- goto Fail_1;\r
-\r
- goto Succeed;\r
-\r
-Fail_1:\r
- Py_DECREF(result);\r
-Fail_2:\r
- result = NULL;\r
-Succeed:\r
- assert(seqs);\r
- for (i = 0; i < n; ++i)\r
- Py_XDECREF(seqs[i].it);\r
- PyMem_DEL(seqs);\r
- return result;\r
-}\r
-\r
-PyDoc_STRVAR(map_doc,\r
-"map(function, sequence[, sequence, ...]) -> list\n\\r
-\n\\r
-Return a list of the results of applying the function to the items of\n\\r
-the argument sequence(s). If more than one sequence is given, the\n\\r
-function is called with an argument list consisting of the corresponding\n\\r
-item of each sequence, substituting None for missing values when not all\n\\r
-sequences have the same length. If the function is None, return a list of\n\\r
-the items of the sequence (or a list of tuples if more than one sequence).");\r
-\r
-\r
-static PyObject *\r
-builtin_next(PyObject *self, PyObject *args)\r
-{\r
- PyObject *it, *res;\r
- PyObject *def = NULL;\r
-\r
- if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))\r
- return NULL;\r
- if (!PyIter_Check(it)) {\r
- PyErr_Format(PyExc_TypeError,\r
- "%.200s object is not an iterator",\r
- it->ob_type->tp_name);\r
- return NULL;\r
- }\r
-\r
- res = (*it->ob_type->tp_iternext)(it);\r
- if (res != NULL) {\r
- return res;\r
- } else if (def != NULL) {\r
- if (PyErr_Occurred()) {\r
- if (!PyErr_ExceptionMatches(PyExc_StopIteration))\r
- return NULL;\r
- PyErr_Clear();\r
- }\r
- Py_INCREF(def);\r
- return def;\r
- } else if (PyErr_Occurred()) {\r
- return NULL;\r
- } else {\r
- PyErr_SetNone(PyExc_StopIteration);\r
- return NULL;\r
- }\r
-}\r
-\r
-PyDoc_STRVAR(next_doc,\r
-"next(iterator[, default])\n\\r
-\n\\r
-Return the next item from the iterator. If default is given and the iterator\n\\r
-is exhausted, it is returned instead of raising StopIteration.");\r
-\r
-\r
-static PyObject *\r
-builtin_setattr(PyObject *self, PyObject *args)\r
-{\r
- PyObject *v;\r
- PyObject *name;\r
- PyObject *value;\r
-\r
- if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))\r
- return NULL;\r
- if (PyObject_SetAttr(v, name, value) != 0)\r
- return NULL;\r
- Py_INCREF(Py_None);\r
- return Py_None;\r
-}\r
-\r
-PyDoc_STRVAR(setattr_doc,\r
-"setattr(object, name, value)\n\\r
-\n\\r
-Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\\r
-``x.y = v''.");\r
-\r
-\r
-static PyObject *\r
-builtin_delattr(PyObject *self, PyObject *args)\r
-{\r
- PyObject *v;\r
- PyObject *name;\r
-\r
- if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))\r
- return NULL;\r
- if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)\r
- return NULL;\r
- Py_INCREF(Py_None);\r
- return Py_None;\r
-}\r
-\r
-PyDoc_STRVAR(delattr_doc,\r
-"delattr(object, name)\n\\r
-\n\\r
-Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\\r
-``del x.y''.");\r
-\r
-\r
-static PyObject *\r
-builtin_hash(PyObject *self, PyObject *v)\r
-{\r
- long x;\r
-\r
- x = PyObject_Hash(v);\r
- if (x == -1)\r
- return NULL;\r
- return PyInt_FromLong(x);\r
-}\r
-\r
-PyDoc_STRVAR(hash_doc,\r
-"hash(object) -> integer\n\\r
-\n\\r
-Return a hash value for the object. Two objects with the same value have\n\\r
-the same hash value. The reverse is not necessarily true, but likely.");\r
-\r
-\r
-static PyObject *\r
-builtin_hex(PyObject *self, PyObject *v)\r
-{\r
- PyNumberMethods *nb;\r
- PyObject *res;\r
-\r
- if ((nb = v->ob_type->tp_as_number) == NULL ||\r
- nb->nb_hex == NULL) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "hex() argument can't be converted to hex");\r
- return NULL;\r
- }\r
- res = (*nb->nb_hex)(v);\r
- if (res && !PyString_Check(res)) {\r
- PyErr_Format(PyExc_TypeError,\r
- "__hex__ returned non-string (type %.200s)",\r
- res->ob_type->tp_name);\r
- Py_DECREF(res);\r
- return NULL;\r
- }\r
- return res;\r
-}\r
-\r
-PyDoc_STRVAR(hex_doc,\r
-"hex(number) -> string\n\\r
-\n\\r
-Return the hexadecimal representation of an integer or long integer.");\r
-\r
-\r
-static PyObject *builtin_raw_input(PyObject *, PyObject *);\r
-\r
-static PyObject *\r
-builtin_input(PyObject *self, PyObject *args)\r
-{\r
- PyObject *line;\r
- char *str;\r
- PyObject *res;\r
- PyObject *globals, *locals;\r
- PyCompilerFlags cf;\r
-\r
- line = builtin_raw_input(self, args);\r
- if (line == NULL)\r
- return line;\r
- if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))\r
- return NULL;\r
- while (*str == ' ' || *str == '\t')\r
- str++;\r
- globals = PyEval_GetGlobals();\r
- locals = PyEval_GetLocals();\r
- if (PyDict_GetItemString(globals, "__builtins__") == NULL) {\r
- if (PyDict_SetItemString(globals, "__builtins__",\r
- PyEval_GetBuiltins()) != 0)\r
- return NULL;\r
- }\r
- cf.cf_flags = 0;\r
- PyEval_MergeCompilerFlags(&cf);\r
- res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);\r
- Py_DECREF(line);\r
- return res;\r
-}\r
-\r
-PyDoc_STRVAR(input_doc,\r
-"input([prompt]) -> value\n\\r
-\n\\r
-Equivalent to eval(raw_input(prompt)).");\r
-\r
-\r
-static PyObject *\r
-builtin_intern(PyObject *self, PyObject *args)\r
-{\r
- PyObject *s;\r
- if (!PyArg_ParseTuple(args, "S:intern", &s))\r
- return NULL;\r
- if (!PyString_CheckExact(s)) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "can't intern subclass of string");\r
- return NULL;\r
- }\r
- Py_INCREF(s);\r
- PyString_InternInPlace(&s);\r
- return s;\r
-}\r
-\r
-PyDoc_STRVAR(intern_doc,\r
-"intern(string) -> string\n\\r
-\n\\r
-``Intern'' the given string. This enters the string in the (global)\n\\r
-table of interned strings whose purpose is to speed up dictionary lookups.\n\\r
-Return the string itself or the previously interned string object with the\n\\r
-same value.");\r
-\r
-\r
-static PyObject *\r
-builtin_iter(PyObject *self, PyObject *args)\r
-{\r
- PyObject *v, *w = NULL;\r
-\r
- if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))\r
- return NULL;\r
- if (w == NULL)\r
- return PyObject_GetIter(v);\r
- if (!PyCallable_Check(v)) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "iter(v, w): v must be callable");\r
- return NULL;\r
- }\r
- return PyCallIter_New(v, w);\r
-}\r
-\r
-PyDoc_STRVAR(iter_doc,\r
-"iter(collection) -> iterator\n\\r
-iter(callable, sentinel) -> iterator\n\\r
-\n\\r
-Get an iterator from an object. In the first form, the argument must\n\\r
-supply its own iterator, or be a sequence.\n\\r
-In the second form, the callable is called until it returns the sentinel.");\r
-\r
-\r
-static PyObject *\r
-builtin_len(PyObject *self, PyObject *v)\r
-{\r
- Py_ssize_t res;\r
-\r
- res = PyObject_Size(v);\r
- if (res < 0 && PyErr_Occurred())\r
- return NULL;\r
- return PyInt_FromSsize_t(res);\r
-}\r
-\r
-PyDoc_STRVAR(len_doc,\r
-"len(object) -> integer\n\\r
-\n\\r
-Return the number of items of a sequence or collection.");\r
-\r
-\r
-static PyObject *\r
-builtin_locals(PyObject *self)\r
-{\r
- PyObject *d;\r
-\r
- d = PyEval_GetLocals();\r
- Py_XINCREF(d);\r
- return d;\r
-}\r
-\r
-PyDoc_STRVAR(locals_doc,\r
-"locals() -> dictionary\n\\r
-\n\\r
-Update and return a dictionary containing the current scope's local variables.");\r
-\r
-\r
-static PyObject *\r
-min_max(PyObject *args, PyObject *kwds, int op)\r
-{\r
- PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;\r
- const char *name = op == Py_LT ? "min" : "max";\r
-\r
- if (PyTuple_Size(args) > 1)\r
- v = args;\r
- else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))\r
- return NULL;\r
-\r
- if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {\r
- keyfunc = PyDict_GetItemString(kwds, "key");\r
- if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {\r
- PyErr_Format(PyExc_TypeError,\r
- "%s() got an unexpected keyword argument", name);\r
- return NULL;\r
- }\r
- Py_INCREF(keyfunc);\r
- }\r
-\r
- it = PyObject_GetIter(v);\r
- if (it == NULL) {\r
- Py_XDECREF(keyfunc);\r
- return NULL;\r
- }\r
-\r
- maxitem = NULL; /* the result */\r
- maxval = NULL; /* the value associated with the result */\r
- while (( item = PyIter_Next(it) )) {\r
- /* get the value from the key function */\r
- if (keyfunc != NULL) {\r
- val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);\r
- if (val == NULL)\r
- goto Fail_it_item;\r
- }\r
- /* no key function; the value is the item */\r
- else {\r
- val = item;\r
- Py_INCREF(val);\r
- }\r
-\r
- /* maximum value and item are unset; set them */\r
- if (maxval == NULL) {\r
- maxitem = item;\r
- maxval = val;\r
- }\r
- /* maximum value and item are set; update them as necessary */\r
- else {\r
- int cmp = PyObject_RichCompareBool(val, maxval, op);\r
- if (cmp < 0)\r
- goto Fail_it_item_and_val;\r
- else if (cmp > 0) {\r
- Py_DECREF(maxval);\r
- Py_DECREF(maxitem);\r
- maxval = val;\r
- maxitem = item;\r
- }\r
- else {\r
- Py_DECREF(item);\r
- Py_DECREF(val);\r
- }\r
- }\r
- }\r
- if (PyErr_Occurred())\r
- goto Fail_it;\r
- if (maxval == NULL) {\r
- PyErr_Format(PyExc_ValueError,\r
- "%s() arg is an empty sequence", name);\r
- assert(maxitem == NULL);\r
- }\r
- else\r
- Py_DECREF(maxval);\r
- Py_DECREF(it);\r
- Py_XDECREF(keyfunc);\r
- return maxitem;\r
-\r
-Fail_it_item_and_val:\r
- Py_DECREF(val);\r
-Fail_it_item:\r
- Py_DECREF(item);\r
-Fail_it:\r
- Py_XDECREF(maxval);\r
- Py_XDECREF(maxitem);\r
- Py_DECREF(it);\r
- Py_XDECREF(keyfunc);\r
- return NULL;\r
-}\r
-\r
-static PyObject *\r
-builtin_min(PyObject *self, PyObject *args, PyObject *kwds)\r
-{\r
- return min_max(args, kwds, Py_LT);\r
-}\r
-\r
-PyDoc_STRVAR(min_doc,\r
-"min(iterable[, key=func]) -> value\n\\r
-min(a, b, c, ...[, key=func]) -> value\n\\r
-\n\\r
-With a single iterable argument, return its smallest item.\n\\r
-With two or more arguments, return the smallest argument.");\r
-\r
-\r
-static PyObject *\r
-builtin_max(PyObject *self, PyObject *args, PyObject *kwds)\r
-{\r
- return min_max(args, kwds, Py_GT);\r
-}\r
-\r
-PyDoc_STRVAR(max_doc,\r
-"max(iterable[, key=func]) -> value\n\\r
-max(a, b, c, ...[, key=func]) -> value\n\\r
-\n\\r
-With a single iterable argument, return its largest item.\n\\r
-With two or more arguments, return the largest argument.");\r
-\r
-\r
-static PyObject *\r
-builtin_oct(PyObject *self, PyObject *v)\r
-{\r
- PyNumberMethods *nb;\r
- PyObject *res;\r
-\r
- if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||\r
- nb->nb_oct == NULL) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "oct() argument can't be converted to oct");\r
- return NULL;\r
- }\r
- res = (*nb->nb_oct)(v);\r
- if (res && !PyString_Check(res)) {\r
- PyErr_Format(PyExc_TypeError,\r
- "__oct__ returned non-string (type %.200s)",\r
- res->ob_type->tp_name);\r
- Py_DECREF(res);\r
- return NULL;\r
- }\r
- return res;\r
-}\r
-\r
-PyDoc_STRVAR(oct_doc,\r
-"oct(number) -> string\n\\r
-\n\\r
-Return the octal representation of an integer or long integer.");\r
-\r
-\r
-static PyObject *\r
-builtin_open(PyObject *self, PyObject *args, PyObject *kwds)\r
-{\r
- return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);\r
-}\r
-\r
-PyDoc_STRVAR(open_doc,\r
-"open(name[, mode[, buffering]]) -> file object\n\\r
-\n\\r
-Open a file using the file() type, returns a file object. This is the\n\\r
-preferred way to open a file. See file.__doc__ for further information.");\r
-\r
-\r
-static PyObject *\r
-builtin_ord(PyObject *self, PyObject* obj)\r
-{\r
- long ord;\r
- Py_ssize_t size;\r
-\r
- if (PyString_Check(obj)) {\r
- size = PyString_GET_SIZE(obj);\r
- if (size == 1) {\r
- ord = (long)((unsigned char)*PyString_AS_STRING(obj));\r
- return PyInt_FromLong(ord);\r
- }\r
- } else if (PyByteArray_Check(obj)) {\r
- size = PyByteArray_GET_SIZE(obj);\r
- if (size == 1) {\r
- ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));\r
- return PyInt_FromLong(ord);\r
- }\r
-\r
-#ifdef Py_USING_UNICODE\r
- } else if (PyUnicode_Check(obj)) {\r
- size = PyUnicode_GET_SIZE(obj);\r
- if (size == 1) {\r
- ord = (long)*PyUnicode_AS_UNICODE(obj);\r
- return PyInt_FromLong(ord);\r
- }\r
-#endif\r
- } else {\r
- PyErr_Format(PyExc_TypeError,\r
- "ord() expected string of length 1, but " \\r
- "%.200s found", obj->ob_type->tp_name);\r
- return NULL;\r
- }\r
-\r
- PyErr_Format(PyExc_TypeError,\r
- "ord() expected a character, "\r
- "but string of length %zd found",\r
- size);\r
- return NULL;\r
-}\r
-\r
-PyDoc_STRVAR(ord_doc,\r
-"ord(c) -> integer\n\\r
-\n\\r
-Return the integer ordinal of a one-character string.");\r
-\r
-\r
-static PyObject *\r
-builtin_pow(PyObject *self, PyObject *args)\r
-{\r
- PyObject *v, *w, *z = Py_None;\r
-\r
- if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))\r
- return NULL;\r
- return PyNumber_Power(v, w, z);\r
-}\r
-\r
-PyDoc_STRVAR(pow_doc,\r
-"pow(x, y[, z]) -> number\n\\r
-\n\\r
-With two arguments, equivalent to x**y. With three arguments,\n\\r
-equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");\r
-\r
-\r
-static PyObject *\r
-builtin_print(PyObject *self, PyObject *args, PyObject *kwds)\r
-{\r
- static char *kwlist[] = {"sep", "end", "file", 0};\r
- static PyObject *dummy_args = NULL;\r
- static PyObject *unicode_newline = NULL, *unicode_space = NULL;\r
- static PyObject *str_newline = NULL, *str_space = NULL;\r
- PyObject *newline, *space;\r
- PyObject *sep = NULL, *end = NULL, *file = NULL;\r
- int i, err, use_unicode = 0;\r
-\r
- if (dummy_args == NULL) {\r
- if (!(dummy_args = PyTuple_New(0)))\r
- return NULL;\r
- }\r
- if (str_newline == NULL) {\r
- str_newline = PyString_FromString("\n");\r
- if (str_newline == NULL)\r
- return NULL;\r
- str_space = PyString_FromString(" ");\r
- if (str_space == NULL) {\r
- Py_CLEAR(str_newline);\r
- return NULL;\r
- }\r
-#ifdef Py_USING_UNICODE\r
- unicode_newline = PyUnicode_FromString("\n");\r
- if (unicode_newline == NULL) {\r
- Py_CLEAR(str_newline);\r
- Py_CLEAR(str_space);\r
- return NULL;\r
- }\r
- unicode_space = PyUnicode_FromString(" ");\r
- if (unicode_space == NULL) {\r
- Py_CLEAR(str_newline);\r
- Py_CLEAR(str_space);\r
- Py_CLEAR(unicode_space);\r
- return NULL;\r
- }\r
-#endif\r
- }\r
- if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",\r
- kwlist, &sep, &end, &file))\r
- return NULL;\r
- if (file == NULL || file == Py_None) {\r
- file = PySys_GetObject("stdout");\r
- /* sys.stdout may be None when FILE* stdout isn't connected */\r
- if (file == Py_None)\r
- Py_RETURN_NONE;\r
- }\r
- if (sep == Py_None) {\r
- sep = NULL;\r
- }\r
- else if (sep) {\r
- if (PyUnicode_Check(sep)) {\r
- use_unicode = 1;\r
- }\r
- else if (!PyString_Check(sep)) {\r
- PyErr_Format(PyExc_TypeError,\r
- "sep must be None, str or unicode, not %.200s",\r
- sep->ob_type->tp_name);\r
- return NULL;\r
- }\r
- }\r
- if (end == Py_None)\r
- end = NULL;\r
- else if (end) {\r
- if (PyUnicode_Check(end)) {\r
- use_unicode = 1;\r
- }\r
- else if (!PyString_Check(end)) {\r
- PyErr_Format(PyExc_TypeError,\r
- "end must be None, str or unicode, not %.200s",\r
- end->ob_type->tp_name);\r
- return NULL;\r
- }\r
- }\r
-\r
- if (!use_unicode) {\r
- for (i = 0; i < PyTuple_Size(args); i++) {\r
- if (PyUnicode_Check(PyTuple_GET_ITEM(args, i))) {\r
- use_unicode = 1;\r
- break;\r
- }\r
- }\r
- }\r
- if (use_unicode) {\r
- newline = unicode_newline;\r
- space = unicode_space;\r
- }\r
- else {\r
- newline = str_newline;\r
- space = str_space;\r
- }\r
-\r
- for (i = 0; i < PyTuple_Size(args); i++) {\r
- if (i > 0) {\r
- if (sep == NULL)\r
- err = PyFile_WriteObject(space, file,\r
- Py_PRINT_RAW);\r
- else\r
- err = PyFile_WriteObject(sep, file,\r
- Py_PRINT_RAW);\r
- if (err)\r
- return NULL;\r
- }\r
- err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,\r
- Py_PRINT_RAW);\r
- if (err)\r
- return NULL;\r
- }\r
-\r
- if (end == NULL)\r
- err = PyFile_WriteObject(newline, file, Py_PRINT_RAW);\r
- else\r
- err = PyFile_WriteObject(end, file, Py_PRINT_RAW);\r
- if (err)\r
- return NULL;\r
-\r
- Py_RETURN_NONE;\r
-}\r
-\r
-PyDoc_STRVAR(print_doc,\r
-"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\\r
-\n\\r
-Prints the values to a stream, or to sys.stdout by default.\n\\r
-Optional keyword arguments:\n\\r
-file: a file-like object (stream); defaults to the current sys.stdout.\n\\r
-sep: string inserted between values, default a space.\n\\r
-end: string appended after the last value, default a newline.");\r
-\r
-\r
-/* Return number of items in range (lo, hi, step), when arguments are\r
- * PyInt or PyLong objects. step > 0 required. Return a value < 0 if\r
- * & only if the true value is too large to fit in a signed long.\r
- * Arguments MUST return 1 with either PyInt_Check() or\r
- * PyLong_Check(). Return -1 when there is an error.\r
- */\r
-static long\r
-get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)\r
-{\r
- /* -------------------------------------------------------------\r
- Algorithm is equal to that of get_len_of_range(), but it operates\r
- on PyObjects (which are assumed to be PyLong or PyInt objects).\r
- ---------------------------------------------------------------*/\r
- long n;\r
- PyObject *diff = NULL;\r
- PyObject *one = NULL;\r
- PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;\r
- /* holds sub-expression evaluations */\r
-\r
- /* if (lo >= hi), return length of 0. */\r
- if (PyObject_Compare(lo, hi) >= 0)\r
- return 0;\r
-\r
- if ((one = PyLong_FromLong(1L)) == NULL)\r
- goto Fail;\r
-\r
- if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)\r
- goto Fail;\r
-\r
- if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)\r
- goto Fail;\r
-\r
- if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)\r
- goto Fail;\r
-\r
- if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)\r
- goto Fail;\r
-\r
- n = PyLong_AsLong(tmp3);\r
- if (PyErr_Occurred()) { /* Check for Overflow */\r
- PyErr_Clear();\r
- goto Fail;\r
- }\r
-\r
- Py_DECREF(tmp3);\r
- Py_DECREF(tmp2);\r
- Py_DECREF(diff);\r
- Py_DECREF(tmp1);\r
- Py_DECREF(one);\r
- return n;\r
-\r
- Fail:\r
- Py_XDECREF(tmp3);\r
- Py_XDECREF(tmp2);\r
- Py_XDECREF(diff);\r
- Py_XDECREF(tmp1);\r
- Py_XDECREF(one);\r
- return -1;\r
-}\r
-\r
-/* Helper function for handle_range_longs. If arg is int or long\r
- object, returns it with incremented reference count. If arg is\r
- float, raises type error. As a last resort, creates a new int by\r
- calling arg type's nb_int method if it is defined. Returns NULL\r
- and sets exception on error.\r
-\r
- Returns a new reference to an int object. */\r
-static PyObject *\r
-get_range_long_argument(PyObject *arg, const char *name)\r
-{\r
- PyObject *v;\r
- PyNumberMethods *nb;\r
- if (PyInt_Check(arg) || PyLong_Check(arg)) {\r
- Py_INCREF(arg);\r
- return arg;\r
- }\r
- if (PyFloat_Check(arg) ||\r
- (nb = Py_TYPE(arg)->tp_as_number) == NULL ||\r
- nb->nb_int == NULL) {\r
- PyErr_Format(PyExc_TypeError,\r
- "range() integer %s argument expected, got %s.",\r
- name, arg->ob_type->tp_name);\r
- return NULL;\r
- }\r
- v = nb->nb_int(arg);\r
- if (v == NULL)\r
- return NULL;\r
- if (PyInt_Check(v) || PyLong_Check(v))\r
- return v;\r
- Py_DECREF(v);\r
- PyErr_SetString(PyExc_TypeError,\r
- "__int__ should return int object");\r
- return NULL;\r
-}\r
-\r
-/* An extension of builtin_range() that handles the case when PyLong\r
- * arguments are given. */\r
-static PyObject *\r
-handle_range_longs(PyObject *self, PyObject *args)\r
-{\r
- PyObject *ilow = NULL;\r
- PyObject *ihigh = NULL;\r
- PyObject *istep = NULL;\r
-\r
- PyObject *low = NULL;\r
- PyObject *high = NULL;\r
- PyObject *step = NULL;\r
-\r
- PyObject *curnum = NULL;\r
- PyObject *v = NULL;\r
- long bign;\r
- Py_ssize_t i, n;\r
- int cmp_result;\r
-\r
- PyObject *zero = PyLong_FromLong(0);\r
-\r
- if (zero == NULL)\r
- return NULL;\r
-\r
- if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {\r
- Py_DECREF(zero);\r
- return NULL;\r
- }\r
-\r
- /* Figure out which way we were called, supply defaults, and be\r
- * sure to incref everything so that the decrefs at the end\r
- * are correct. NB: ilow, ihigh and istep are borrowed references.\r
- */\r
- assert(ilow != NULL);\r
- if (ihigh == NULL) {\r
- /* only 1 arg -- it's the upper limit */\r
- ihigh = ilow;\r
- ilow = NULL;\r
- }\r
-\r
- /* convert ihigh if necessary */\r
- assert(ihigh != NULL);\r
- high = get_range_long_argument(ihigh, "end");\r
- if (high == NULL)\r
- goto Fail;\r
-\r
- /* ihigh correct now; do ilow */\r
- if (ilow == NULL) {\r
- Py_INCREF(zero);\r
- low = zero;\r
- }\r
- else {\r
- low = get_range_long_argument(ilow, "start");\r
- if (low == NULL)\r
- goto Fail;\r
- }\r
-\r
- /* ilow and ihigh correct now; do istep */\r
- if (istep == NULL)\r
- step = PyLong_FromLong(1);\r
- else\r
- step = get_range_long_argument(istep, "step");\r
- if (step == NULL)\r
- goto Fail;\r
-\r
- if (PyObject_Cmp(step, zero, &cmp_result) == -1)\r
- goto Fail;\r
-\r
- if (cmp_result == 0) {\r
- PyErr_SetString(PyExc_ValueError,\r
- "range() step argument must not be zero");\r
- goto Fail;\r
- }\r
-\r
- if (cmp_result > 0)\r
- bign = get_len_of_range_longs(low, high, step);\r
- else {\r
- PyObject *neg_step = PyNumber_Negative(step);\r
- if (neg_step == NULL)\r
- goto Fail;\r
- bign = get_len_of_range_longs(high, low, neg_step);\r
- Py_DECREF(neg_step);\r
- }\r
-\r
- n = (Py_ssize_t)bign;\r
- if (bign < 0 || (long)n != bign) {\r
- PyErr_SetString(PyExc_OverflowError,\r
- "range() result has too many items");\r
- goto Fail;\r
- }\r
-\r
- v = PyList_New(n);\r
- if (v == NULL)\r
- goto Fail;\r
-\r
- curnum = low;\r
- Py_INCREF(curnum);\r
-\r
- for (i = 0; i < n; i++) {\r
- PyObject *w = PyNumber_Long(curnum);\r
- PyObject *tmp_num;\r
- if (w == NULL)\r
- goto Fail;\r
-\r
- PyList_SET_ITEM(v, i, w);\r
-\r
- tmp_num = PyNumber_Add(curnum, step);\r
- if (tmp_num == NULL)\r
- goto Fail;\r
-\r
- Py_DECREF(curnum);\r
- curnum = tmp_num;\r
- }\r
- Py_DECREF(low);\r
- Py_DECREF(high);\r
- Py_DECREF(step);\r
- Py_DECREF(zero);\r
- Py_DECREF(curnum);\r
- return v;\r
-\r
- Fail:\r
- Py_XDECREF(low);\r
- Py_XDECREF(high);\r
- Py_XDECREF(step);\r
- Py_DECREF(zero);\r
- Py_XDECREF(curnum);\r
- Py_XDECREF(v);\r
- return NULL;\r
-}\r
-\r
-/* Return number of items in range/xrange (lo, hi, step). step > 0\r
- * required. Return a value < 0 if & only if the true value is too\r
- * large to fit in a signed long.\r
- */\r
-static long\r
-get_len_of_range(long lo, long hi, long step)\r
-{\r
- /* -------------------------------------------------------------\r
- If lo >= hi, the range is empty.\r
- Else if n values are in the range, the last one is\r
- lo + (n-1)*step, which must be <= hi-1. Rearranging,\r
- n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives\r
- the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so\r
- the RHS is non-negative and so truncation is the same as the\r
- floor. Letting M be the largest positive long, the worst case\r
- for the RHS numerator is hi=M, lo=-M-1, and then\r
- hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough\r
- precision to compute the RHS exactly.\r
- ---------------------------------------------------------------*/\r
- long n = 0;\r
- if (lo < hi) {\r
- unsigned long uhi = (unsigned long)hi;\r
- unsigned long ulo = (unsigned long)lo;\r
- unsigned long diff = uhi - ulo - 1;\r
- n = (long)(diff / (unsigned long)step + 1);\r
- }\r
- return n;\r
-}\r
-\r
-static PyObject *\r
-builtin_range(PyObject *self, PyObject *args)\r
-{\r
- long ilow = 0, ihigh = 0, istep = 1;\r
- long bign;\r
- Py_ssize_t i, n;\r
-\r
- PyObject *v;\r
-\r
- if (PyTuple_Size(args) <= 1) {\r
- if (!PyArg_ParseTuple(args,\r
- "l;range() requires 1-3 int arguments",\r
- &ihigh)) {\r
- PyErr_Clear();\r
- return handle_range_longs(self, args);\r
- }\r
- }\r
- else {\r
- if (!PyArg_ParseTuple(args,\r
- "ll|l;range() requires 1-3 int arguments",\r
- &ilow, &ihigh, &istep)) {\r
- PyErr_Clear();\r
- return handle_range_longs(self, args);\r
- }\r
- }\r
- if (istep == 0) {\r
- PyErr_SetString(PyExc_ValueError,\r
- "range() step argument must not be zero");\r
- return NULL;\r
- }\r
- if (istep > 0)\r
- bign = get_len_of_range(ilow, ihigh, istep);\r
- else\r
- bign = get_len_of_range(ihigh, ilow, -istep);\r
- n = (Py_ssize_t)bign;\r
- if (bign < 0 || (long)n != bign) {\r
- PyErr_SetString(PyExc_OverflowError,\r
- "range() result has too many items");\r
- return NULL;\r
- }\r
- v = PyList_New(n);\r
- if (v == NULL)\r
- return NULL;\r
- for (i = 0; i < n; i++) {\r
- PyObject *w = PyInt_FromLong(ilow);\r
- if (w == NULL) {\r
- Py_DECREF(v);\r
- return NULL;\r
- }\r
- PyList_SET_ITEM(v, i, w);\r
- ilow += istep;\r
- }\r
- return v;\r
-}\r
-\r
-PyDoc_STRVAR(range_doc,\r
-"range(stop) -> list of integers\n\\r
-range(start, stop[, step]) -> list of integers\n\\r
-\n\\r
-Return a list containing an arithmetic progression of integers.\n\\r
-range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\\r
-When step is given, it specifies the increment (or decrement).\n\\r
-For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\\r
-These are exactly the valid indices for a list of 4 elements.");\r
-\r
-\r
-static PyObject *\r
-builtin_raw_input(PyObject *self, PyObject *args)\r
-{\r
- PyObject *v = NULL;\r
- PyObject *fin = PySys_GetObject("stdin");\r
- PyObject *fout = PySys_GetObject("stdout");\r
-\r
- if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))\r
- return NULL;\r
-\r
- if (fin == NULL) {\r
- PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");\r
- return NULL;\r
- }\r
- if (fout == NULL) {\r
- PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");\r
- return NULL;\r
- }\r
- if (PyFile_SoftSpace(fout, 0)) {\r
- if (PyFile_WriteString(" ", fout) != 0)\r
- return NULL;\r
- }\r
- if (PyFile_AsFile(fin) && PyFile_AsFile(fout)\r
- && isatty(fileno(PyFile_AsFile(fin)))\r
- && isatty(fileno(PyFile_AsFile(fout)))) {\r
- PyObject *po;\r
- char *prompt;\r
- char *s;\r
- PyObject *result;\r
- if (v != NULL) {\r
- po = PyObject_Str(v);\r
- if (po == NULL)\r
- return NULL;\r
- prompt = PyString_AsString(po);\r
- if (prompt == NULL)\r
- return NULL;\r
- }\r
- else {\r
- po = NULL;\r
- prompt = "";\r
- }\r
- s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),\r
- prompt);\r
- Py_XDECREF(po);\r
- if (s == NULL) {\r
- if (!PyErr_Occurred())\r
- PyErr_SetNone(PyExc_KeyboardInterrupt);\r
- return NULL;\r
- }\r
- if (*s == '\0') {\r
- PyErr_SetNone(PyExc_EOFError);\r
- result = NULL;\r
- }\r
- else { /* strip trailing '\n' */\r
- size_t len = strlen(s);\r
- if (len > PY_SSIZE_T_MAX) {\r
- PyErr_SetString(PyExc_OverflowError,\r
- "[raw_]input: input too long");\r
- result = NULL;\r
- }\r
- else {\r
- result = PyString_FromStringAndSize(s, len-1);\r
- }\r
- }\r
- PyMem_FREE(s);\r
- return result;\r
- }\r
- if (v != NULL) {\r
- if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)\r
- return NULL;\r
- }\r
- return PyFile_GetLine(fin, -1);\r
-}\r
-\r
-PyDoc_STRVAR(raw_input_doc,\r
-"raw_input([prompt]) -> string\n\\r
-\n\\r
-Read a string from standard input. The trailing newline is stripped.\n\\r
-If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\\r
-On Unix, GNU readline is used if enabled. The prompt string, if given,\n\\r
-is printed without a trailing newline before reading.");\r
-\r
-\r
-static PyObject *\r
-builtin_reduce(PyObject *self, PyObject *args)\r
-{\r
- static PyObject *functools_reduce = NULL;\r
-\r
- if (PyErr_WarnPy3k("reduce() not supported in 3.x; "\r
- "use functools.reduce()", 1) < 0)\r
- return NULL;\r
-\r
- if (functools_reduce == NULL) {\r
- PyObject *functools = PyImport_ImportModule("functools");\r
- if (functools == NULL)\r
- return NULL;\r
- functools_reduce = PyObject_GetAttrString(functools, "reduce");\r
- Py_DECREF(functools);\r
- if (functools_reduce == NULL)\r
- return NULL;\r
- }\r
- return PyObject_Call(functools_reduce, args, NULL);\r
-}\r
-\r
-PyDoc_STRVAR(reduce_doc,\r
-"reduce(function, sequence[, initial]) -> value\n\\r
-\n\\r
-Apply a function of two arguments cumulatively to the items of a sequence,\n\\r
-from left to right, so as to reduce the sequence to a single value.\n\\r
-For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\\r
-((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\\r
-of the sequence in the calculation, and serves as a default when the\n\\r
-sequence is empty.");\r
-\r
-\r
-static PyObject *\r
-builtin_reload(PyObject *self, PyObject *v)\r
-{\r
- if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",\r
- 1) < 0)\r
- return NULL;\r
-\r
- return PyImport_ReloadModule(v);\r
-}\r
-\r
-PyDoc_STRVAR(reload_doc,\r
-"reload(module) -> module\n\\r
-\n\\r
-Reload the module. The module must have been successfully imported before.");\r
-\r
-\r
-static PyObject *\r
-builtin_repr(PyObject *self, PyObject *v)\r
-{\r
- return PyObject_Repr(v);\r
-}\r
-\r
-PyDoc_STRVAR(repr_doc,\r
-"repr(object) -> string\n\\r
-\n\\r
-Return the canonical string representation of the object.\n\\r
-For most object types, eval(repr(object)) == object.");\r
-\r
-\r
-static PyObject *\r
-builtin_round(PyObject *self, PyObject *args, PyObject *kwds)\r
-{\r
- double x;\r
- PyObject *o_ndigits = NULL;\r
- Py_ssize_t ndigits;\r
- static char *kwlist[] = {"number", "ndigits", 0};\r
-\r
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|O:round",\r
- kwlist, &x, &o_ndigits))\r
- return NULL;\r
-\r
- if (o_ndigits == NULL) {\r
- /* second argument defaults to 0 */\r
- ndigits = 0;\r
- }\r
- else {\r
- /* interpret 2nd argument as a Py_ssize_t; clip on overflow */\r
- ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);\r
- if (ndigits == -1 && PyErr_Occurred())\r
- return NULL;\r
- }\r
-\r
- /* nans, infinities and zeros round to themselves */\r
- if (!Py_IS_FINITE(x) || x == 0.0)\r
- return PyFloat_FromDouble(x);\r
-\r
- /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x\r
- always rounds to itself. For ndigits < NDIGITS_MIN, x always\r
- rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */\r
-#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))\r
-#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))\r
- if (ndigits > NDIGITS_MAX)\r
- /* return x */\r
- return PyFloat_FromDouble(x);\r
- else if (ndigits < NDIGITS_MIN)\r
- /* return 0.0, but with sign of x */\r
- return PyFloat_FromDouble(0.0*x);\r
- else\r
- /* finite x, and ndigits is not unreasonably large */\r
- /* _Py_double_round is defined in floatobject.c */\r
- return _Py_double_round(x, (int)ndigits);\r
-#undef NDIGITS_MAX\r
-#undef NDIGITS_MIN\r
-}\r
-\r
-PyDoc_STRVAR(round_doc,\r
-"round(number[, ndigits]) -> floating point number\n\\r
-\n\\r
-Round a number to a given precision in decimal digits (default 0 digits).\n\\r
-This always returns a floating point number. Precision may be negative.");\r
-\r
-static PyObject *\r
-builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)\r
-{\r
- PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;\r
- PyObject *callable;\r
- static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};\r
- int reverse;\r
-\r
- /* args 1-4 should match listsort in Objects/listobject.c */\r
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",\r
- kwlist, &seq, &compare, &keyfunc, &reverse))\r
- return NULL;\r
-\r
- newlist = PySequence_List(seq);\r
- if (newlist == NULL)\r
- return NULL;\r
-\r
- callable = PyObject_GetAttrString(newlist, "sort");\r
- if (callable == NULL) {\r
- Py_DECREF(newlist);\r
- return NULL;\r
- }\r
-\r
- newargs = PyTuple_GetSlice(args, 1, 4);\r
- if (newargs == NULL) {\r
- Py_DECREF(newlist);\r
- Py_DECREF(callable);\r
- return NULL;\r
- }\r
-\r
- v = PyObject_Call(callable, newargs, kwds);\r
- Py_DECREF(newargs);\r
- Py_DECREF(callable);\r
- if (v == NULL) {\r
- Py_DECREF(newlist);\r
- return NULL;\r
- }\r
- Py_DECREF(v);\r
- return newlist;\r
-}\r
-\r
-PyDoc_STRVAR(sorted_doc,\r
-"sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");\r
-\r
-static PyObject *\r
-builtin_vars(PyObject *self, PyObject *args)\r
-{\r
- PyObject *v = NULL;\r
- PyObject *d;\r
-\r
- if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))\r
- return NULL;\r
- if (v == NULL) {\r
- d = PyEval_GetLocals();\r
- if (d == NULL) {\r
- if (!PyErr_Occurred())\r
- PyErr_SetString(PyExc_SystemError,\r
- "vars(): no locals!?");\r
- }\r
- else\r
- Py_INCREF(d);\r
- }\r
- else {\r
- d = PyObject_GetAttrString(v, "__dict__");\r
- if (d == NULL) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "vars() argument must have __dict__ attribute");\r
- return NULL;\r
- }\r
- }\r
- return d;\r
-}\r
-\r
-PyDoc_STRVAR(vars_doc,\r
-"vars([object]) -> dictionary\n\\r
-\n\\r
-Without arguments, equivalent to locals().\n\\r
-With an argument, equivalent to object.__dict__.");\r
-\r
-\r
-static PyObject*\r
-builtin_sum(PyObject *self, PyObject *args)\r
-{\r
- PyObject *seq;\r
- PyObject *result = NULL;\r
- PyObject *temp, *item, *iter;\r
-\r
- if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))\r
- return NULL;\r
-\r
- iter = PyObject_GetIter(seq);\r
- if (iter == NULL)\r
- return NULL;\r
-\r
- if (result == NULL) {\r
- result = PyInt_FromLong(0);\r
- if (result == NULL) {\r
- Py_DECREF(iter);\r
- return NULL;\r
- }\r
- } else {\r
- /* reject string values for 'start' parameter */\r
- if (PyObject_TypeCheck(result, &PyBaseString_Type)) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "sum() can't sum strings [use ''.join(seq) instead]");\r
- Py_DECREF(iter);\r
- return NULL;\r
- }\r
- Py_INCREF(result);\r
- }\r
-\r
-#ifndef SLOW_SUM\r
- /* Fast addition by keeping temporary sums in C instead of new Python objects.\r
- Assumes all inputs are the same type. If the assumption fails, default\r
- to the more general routine.\r
- */\r
- if (PyInt_CheckExact(result)) {\r
- long i_result = PyInt_AS_LONG(result);\r
- Py_DECREF(result);\r
- result = NULL;\r
- while(result == NULL) {\r
- item = PyIter_Next(iter);\r
- if (item == NULL) {\r
- Py_DECREF(iter);\r
- if (PyErr_Occurred())\r
- return NULL;\r
- return PyInt_FromLong(i_result);\r
- }\r
- if (PyInt_CheckExact(item)) {\r
- long b = PyInt_AS_LONG(item);\r
- long x = i_result + b;\r
- if ((x^i_result) >= 0 || (x^b) >= 0) {\r
- i_result = x;\r
- Py_DECREF(item);\r
- continue;\r
- }\r
- }\r
- /* Either overflowed or is not an int. Restore real objects and process normally */\r
- result = PyInt_FromLong(i_result);\r
- temp = PyNumber_Add(result, item);\r
- Py_DECREF(result);\r
- Py_DECREF(item);\r
- result = temp;\r
- if (result == NULL) {\r
- Py_DECREF(iter);\r
- return NULL;\r
- }\r
- }\r
- }\r
-\r
- if (PyFloat_CheckExact(result)) {\r
- double f_result = PyFloat_AS_DOUBLE(result);\r
- Py_DECREF(result);\r
- result = NULL;\r
- while(result == NULL) {\r
- item = PyIter_Next(iter);\r
- if (item == NULL) {\r
- Py_DECREF(iter);\r
- if (PyErr_Occurred())\r
- return NULL;\r
- return PyFloat_FromDouble(f_result);\r
- }\r
- if (PyFloat_CheckExact(item)) {\r
- PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)\r
- f_result += PyFloat_AS_DOUBLE(item);\r
- PyFPE_END_PROTECT(f_result)\r
- Py_DECREF(item);\r
- continue;\r
- }\r
- if (PyInt_CheckExact(item)) {\r
- PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)\r
- f_result += (double)PyInt_AS_LONG(item);\r
- PyFPE_END_PROTECT(f_result)\r
- Py_DECREF(item);\r
- continue;\r
- }\r
- result = PyFloat_FromDouble(f_result);\r
- temp = PyNumber_Add(result, item);\r
- Py_DECREF(result);\r
- Py_DECREF(item);\r
- result = temp;\r
- if (result == NULL) {\r
- Py_DECREF(iter);\r
- return NULL;\r
- }\r
- }\r
- }\r
-#endif\r
-\r
- for(;;) {\r
- item = PyIter_Next(iter);\r
- if (item == NULL) {\r
- /* error, or end-of-sequence */\r
- if (PyErr_Occurred()) {\r
- Py_DECREF(result);\r
- result = NULL;\r
- }\r
- break;\r
- }\r
- /* It's tempting to use PyNumber_InPlaceAdd instead of\r
- PyNumber_Add here, to avoid quadratic running time\r
- when doing 'sum(list_of_lists, [])'. However, this\r
- would produce a change in behaviour: a snippet like\r
-\r
- empty = []\r
- sum([[x] for x in range(10)], empty)\r
-\r
- would change the value of empty. */\r
- temp = PyNumber_Add(result, item);\r
- Py_DECREF(result);\r
- Py_DECREF(item);\r
- result = temp;\r
- if (result == NULL)\r
- break;\r
- }\r
- Py_DECREF(iter);\r
- return result;\r
-}\r
-\r
-PyDoc_STRVAR(sum_doc,\r
-"sum(sequence[, start]) -> value\n\\r
-\n\\r
-Return the sum of a sequence of numbers (NOT strings) plus the value\n\\r
-of parameter 'start' (which defaults to 0). When the sequence is\n\\r
-empty, return start.");\r
-\r
-\r
-static PyObject *\r
-builtin_isinstance(PyObject *self, PyObject *args)\r
-{\r
- PyObject *inst;\r
- PyObject *cls;\r
- int retval;\r
-\r
- if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))\r
- return NULL;\r
-\r
- retval = PyObject_IsInstance(inst, cls);\r
- if (retval < 0)\r
- return NULL;\r
- return PyBool_FromLong(retval);\r
-}\r
-\r
-PyDoc_STRVAR(isinstance_doc,\r
-"isinstance(object, class-or-type-or-tuple) -> bool\n\\r
-\n\\r
-Return whether an object is an instance of a class or of a subclass thereof.\n\\r
-With a type as second argument, return whether that is the object's type.\n\\r
-The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\\r
-isinstance(x, A) or isinstance(x, B) or ... (etc.).");\r
-\r
-\r
-static PyObject *\r
-builtin_issubclass(PyObject *self, PyObject *args)\r
-{\r
- PyObject *derived;\r
- PyObject *cls;\r
- int retval;\r
-\r
- if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))\r
- return NULL;\r
-\r
- retval = PyObject_IsSubclass(derived, cls);\r
- if (retval < 0)\r
- return NULL;\r
- return PyBool_FromLong(retval);\r
-}\r
-\r
-PyDoc_STRVAR(issubclass_doc,\r
-"issubclass(C, B) -> bool\n\\r
-\n\\r
-Return whether class C is a subclass (i.e., a derived class) of class B.\n\\r
-When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\\r
-is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");\r
-\r
-\r
-static PyObject*\r
-builtin_zip(PyObject *self, PyObject *args)\r
-{\r
- PyObject *ret;\r
- const Py_ssize_t itemsize = PySequence_Length(args);\r
- Py_ssize_t i;\r
- PyObject *itlist; /* tuple of iterators */\r
- Py_ssize_t len; /* guess at result length */\r
-\r
- if (itemsize == 0)\r
- return PyList_New(0);\r
-\r
- /* args must be a tuple */\r
- assert(PyTuple_Check(args));\r
-\r
- /* Guess at result length: the shortest of the input lengths.\r
- If some argument refuses to say, we refuse to guess too, lest\r
- an argument like xrange(sys.maxint) lead us astray.*/\r
- len = -1; /* unknown */\r
- for (i = 0; i < itemsize; ++i) {\r
- PyObject *item = PyTuple_GET_ITEM(args, i);\r
- Py_ssize_t thislen = _PyObject_LengthHint(item, -2);\r
- if (thislen < 0) {\r
- if (thislen == -1)\r
- return NULL;\r
- len = -1;\r
- break;\r
- }\r
- else if (len < 0 || thislen < len)\r
- len = thislen;\r
- }\r
-\r
- /* allocate result list */\r
- if (len < 0)\r
- len = 10; /* arbitrary */\r
- if ((ret = PyList_New(len)) == NULL)\r
- return NULL;\r
-\r
- /* obtain iterators */\r
- itlist = PyTuple_New(itemsize);\r
- if (itlist == NULL)\r
- goto Fail_ret;\r
- for (i = 0; i < itemsize; ++i) {\r
- PyObject *item = PyTuple_GET_ITEM(args, i);\r
- PyObject *it = PyObject_GetIter(item);\r
- if (it == NULL) {\r
- if (PyErr_ExceptionMatches(PyExc_TypeError))\r
- PyErr_Format(PyExc_TypeError,\r
- "zip argument #%zd must support iteration",\r
- i+1);\r
- goto Fail_ret_itlist;\r
- }\r
- PyTuple_SET_ITEM(itlist, i, it);\r
- }\r
-\r
- /* build result into ret list */\r
- for (i = 0; ; ++i) {\r
- int j;\r
- PyObject *next = PyTuple_New(itemsize);\r
- if (!next)\r
- goto Fail_ret_itlist;\r
-\r
- for (j = 0; j < itemsize; j++) {\r
- PyObject *it = PyTuple_GET_ITEM(itlist, j);\r
- PyObject *item = PyIter_Next(it);\r
- if (!item) {\r
- if (PyErr_Occurred()) {\r
- Py_DECREF(ret);\r
- ret = NULL;\r
- }\r
- Py_DECREF(next);\r
- Py_DECREF(itlist);\r
- goto Done;\r
- }\r
- PyTuple_SET_ITEM(next, j, item);\r
- }\r
-\r
- if (i < len)\r
- PyList_SET_ITEM(ret, i, next);\r
- else {\r
- int status = PyList_Append(ret, next);\r
- Py_DECREF(next);\r
- ++len;\r
- if (status < 0)\r
- goto Fail_ret_itlist;\r
- }\r
- }\r
-\r
-Done:\r
- if (ret != NULL && i < len) {\r
- /* The list is too big. */\r
- if (PyList_SetSlice(ret, i, len, NULL) < 0)\r
- return NULL;\r
- }\r
- return ret;\r
-\r
-Fail_ret_itlist:\r
- Py_DECREF(itlist);\r
-Fail_ret:\r
- Py_DECREF(ret);\r
- return NULL;\r
-}\r
-\r
-\r
-PyDoc_STRVAR(zip_doc,\r
-"zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\\r
-\n\\r
-Return a list of tuples, where each tuple contains the i-th element\n\\r
-from each of the argument sequences. The returned list is truncated\n\\r
-in length to the length of the shortest argument sequence.");\r
-\r
-\r
-static PyMethodDef builtin_methods[] = {\r
- {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},\r
- {"abs", builtin_abs, METH_O, abs_doc},\r
- {"all", builtin_all, METH_O, all_doc},\r
- {"any", builtin_any, METH_O, any_doc},\r
- {"apply", builtin_apply, METH_VARARGS, apply_doc},\r
- {"bin", builtin_bin, METH_O, bin_doc},\r
- {"callable", builtin_callable, METH_O, callable_doc},\r
- {"chr", builtin_chr, METH_VARARGS, chr_doc},\r
- {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},\r
- {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},\r
- {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},\r
- {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},\r
- {"dir", builtin_dir, METH_VARARGS, dir_doc},\r
- {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},\r
- {"eval", builtin_eval, METH_VARARGS, eval_doc},\r
- {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},\r
- {"filter", builtin_filter, METH_VARARGS, filter_doc},\r
- {"format", builtin_format, METH_VARARGS, format_doc},\r
- {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},\r
- {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},\r
- {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},\r
- {"hash", builtin_hash, METH_O, hash_doc},\r
- {"hex", builtin_hex, METH_O, hex_doc},\r
- {"id", builtin_id, METH_O, id_doc},\r
- {"input", builtin_input, METH_VARARGS, input_doc},\r
- {"intern", builtin_intern, METH_VARARGS, intern_doc},\r
- {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},\r
- {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},\r
- {"iter", builtin_iter, METH_VARARGS, iter_doc},\r
- {"len", builtin_len, METH_O, len_doc},\r
- {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},\r
- {"map", builtin_map, METH_VARARGS, map_doc},\r
- {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},\r
- {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},\r
- {"next", builtin_next, METH_VARARGS, next_doc},\r
- {"oct", builtin_oct, METH_O, oct_doc},\r
- {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},\r
- {"ord", builtin_ord, METH_O, ord_doc},\r
- {"pow", builtin_pow, METH_VARARGS, pow_doc},\r
- {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},\r
- {"range", builtin_range, METH_VARARGS, range_doc},\r
- {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},\r
- {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},\r
- {"reload", builtin_reload, METH_O, reload_doc},\r
- {"repr", builtin_repr, METH_O, repr_doc},\r
- {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},\r
- {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},\r
- {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},\r
- {"sum", builtin_sum, METH_VARARGS, sum_doc},\r
-#ifdef Py_USING_UNICODE\r
- {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},\r
-#endif\r
- {"vars", builtin_vars, METH_VARARGS, vars_doc},\r
- {"zip", builtin_zip, METH_VARARGS, zip_doc},\r
- {NULL, NULL},\r
-};\r
-\r
-PyDoc_STRVAR(builtin_doc,\r
-"Built-in functions, exceptions, and other objects.\n\\r
-\n\\r
-Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");\r
-\r
-PyObject *\r
-_PyBuiltin_Init(void)\r
-{\r
- PyObject *mod, *dict, *debug;\r
- mod = Py_InitModule4("__builtin__", builtin_methods,\r
- builtin_doc, (PyObject *)NULL,\r
- PYTHON_API_VERSION);\r
- if (mod == NULL)\r
- return NULL;\r
- dict = PyModule_GetDict(mod);\r
-\r
-#ifdef Py_TRACE_REFS\r
- /* __builtin__ exposes a number of statically allocated objects\r
- * that, before this code was added in 2.3, never showed up in\r
- * the list of "all objects" maintained by Py_TRACE_REFS. As a\r
- * result, programs leaking references to None and False (etc)\r
- * couldn't be diagnosed by examining sys.getobjects(0).\r
- */\r
-#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)\r
-#else\r
-#define ADD_TO_ALL(OBJECT) (void)0\r
-#endif\r
-\r
-#define SETBUILTIN(NAME, OBJECT) \\r
- if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \\r
- return NULL; \\r
- ADD_TO_ALL(OBJECT)\r
-\r
- SETBUILTIN("None", Py_None);\r
- SETBUILTIN("Ellipsis", Py_Ellipsis);\r
- SETBUILTIN("NotImplemented", Py_NotImplemented);\r
- SETBUILTIN("False", Py_False);\r
- SETBUILTIN("True", Py_True);\r
- SETBUILTIN("basestring", &PyBaseString_Type);\r
- SETBUILTIN("bool", &PyBool_Type);\r
- SETBUILTIN("memoryview", &PyMemoryView_Type);\r
- SETBUILTIN("bytearray", &PyByteArray_Type);\r
- SETBUILTIN("bytes", &PyString_Type);\r
- SETBUILTIN("buffer", &PyBuffer_Type);\r
- SETBUILTIN("classmethod", &PyClassMethod_Type);\r
-#ifndef WITHOUT_COMPLEX\r
- SETBUILTIN("complex", &PyComplex_Type);\r
-#endif\r
- SETBUILTIN("dict", &PyDict_Type);\r
- SETBUILTIN("enumerate", &PyEnum_Type);\r
- SETBUILTIN("file", &PyFile_Type);\r
- SETBUILTIN("float", &PyFloat_Type);\r
- SETBUILTIN("frozenset", &PyFrozenSet_Type);\r
- SETBUILTIN("property", &PyProperty_Type);\r
- SETBUILTIN("int", &PyInt_Type);\r
- SETBUILTIN("list", &PyList_Type);\r
- SETBUILTIN("long", &PyLong_Type);\r
- SETBUILTIN("object", &PyBaseObject_Type);\r
- SETBUILTIN("reversed", &PyReversed_Type);\r
- SETBUILTIN("set", &PySet_Type);\r
- SETBUILTIN("slice", &PySlice_Type);\r
- SETBUILTIN("staticmethod", &PyStaticMethod_Type);\r
- SETBUILTIN("str", &PyString_Type);\r
- SETBUILTIN("super", &PySuper_Type);\r
- SETBUILTIN("tuple", &PyTuple_Type);\r
- SETBUILTIN("type", &PyType_Type);\r
- SETBUILTIN("xrange", &PyRange_Type);\r
-#ifdef Py_USING_UNICODE\r
- SETBUILTIN("unicode", &PyUnicode_Type);\r
-#endif\r
- debug = PyBool_FromLong(Py_OptimizeFlag == 0);\r
- if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {\r
- Py_XDECREF(debug);\r
- return NULL;\r
- }\r
- Py_XDECREF(debug);\r
-\r
- return mod;\r
-#undef ADD_TO_ALL\r
-#undef SETBUILTIN\r
-}\r
-\r
-/* Helper for filter(): filter a tuple through a function */\r
-\r
-static PyObject *\r
-filtertuple(PyObject *func, PyObject *tuple)\r
-{\r
- PyObject *result;\r
- Py_ssize_t i, j;\r
- Py_ssize_t len = PyTuple_Size(tuple);\r
-\r
- if (len == 0) {\r
- if (PyTuple_CheckExact(tuple))\r
- Py_INCREF(tuple);\r
- else\r
- tuple = PyTuple_New(0);\r
- return tuple;\r
- }\r
-\r
- if ((result = PyTuple_New(len)) == NULL)\r
- return NULL;\r
-\r
- for (i = j = 0; i < len; ++i) {\r
- PyObject *item, *good;\r
- int ok;\r
-\r
- if (tuple->ob_type->tp_as_sequence &&\r
- tuple->ob_type->tp_as_sequence->sq_item) {\r
- item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);\r
- if (item == NULL)\r
- goto Fail_1;\r
- } else {\r
- PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");\r
- goto Fail_1;\r
- }\r
- if (func == Py_None) {\r
- Py_INCREF(item);\r
- good = item;\r
- }\r
- else {\r
- PyObject *arg = PyTuple_Pack(1, item);\r
- if (arg == NULL) {\r
- Py_DECREF(item);\r
- goto Fail_1;\r
- }\r
- good = PyEval_CallObject(func, arg);\r
- Py_DECREF(arg);\r
- if (good == NULL) {\r
- Py_DECREF(item);\r
- goto Fail_1;\r
- }\r
- }\r
- ok = PyObject_IsTrue(good);\r
- Py_DECREF(good);\r
- if (ok > 0) {\r
- if (PyTuple_SetItem(result, j++, item) < 0)\r
- goto Fail_1;\r
- }\r
- else {\r
- Py_DECREF(item);\r
- if (ok < 0)\r
- goto Fail_1;\r
- }\r
- }\r
-\r
- if (_PyTuple_Resize(&result, j) < 0)\r
- return NULL;\r
-\r
- return result;\r
-\r
-Fail_1:\r
- Py_DECREF(result);\r
- return NULL;\r
-}\r
-\r
-\r
-/* Helper for filter(): filter a string through a function */\r
-\r
-static PyObject *\r
-filterstring(PyObject *func, PyObject *strobj)\r
-{\r
- PyObject *result;\r
- Py_ssize_t i, j;\r
- Py_ssize_t len = PyString_Size(strobj);\r
- Py_ssize_t outlen = len;\r
-\r
- if (func == Py_None) {\r
- /* If it's a real string we can return the original,\r
- * as no character is ever false and __getitem__\r
- * does return this character. If it's a subclass\r
- * we must go through the __getitem__ loop */\r
- if (PyString_CheckExact(strobj)) {\r
- Py_INCREF(strobj);\r
- return strobj;\r
- }\r
- }\r
- if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)\r
- return NULL;\r
-\r
- for (i = j = 0; i < len; ++i) {\r
- PyObject *item;\r
- int ok;\r
-\r
- item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);\r
- if (item == NULL)\r
- goto Fail_1;\r
- if (func==Py_None) {\r
- ok = 1;\r
- } else {\r
- PyObject *arg, *good;\r
- arg = PyTuple_Pack(1, item);\r
- if (arg == NULL) {\r
- Py_DECREF(item);\r
- goto Fail_1;\r
- }\r
- good = PyEval_CallObject(func, arg);\r
- Py_DECREF(arg);\r
- if (good == NULL) {\r
- Py_DECREF(item);\r
- goto Fail_1;\r
- }\r
- ok = PyObject_IsTrue(good);\r
- Py_DECREF(good);\r
- }\r
- if (ok > 0) {\r
- Py_ssize_t reslen;\r
- if (!PyString_Check(item)) {\r
- PyErr_SetString(PyExc_TypeError, "can't filter str to str:"\r
- " __getitem__ returned different type");\r
- Py_DECREF(item);\r
- goto Fail_1;\r
- }\r
- reslen = PyString_GET_SIZE(item);\r
- if (reslen == 1) {\r
- PyString_AS_STRING(result)[j++] =\r
- PyString_AS_STRING(item)[0];\r
- } else {\r
- /* do we need more space? */\r
- Py_ssize_t need = j;\r
-\r
- /* calculate space requirements while checking for overflow */\r
- if (need > PY_SSIZE_T_MAX - reslen) {\r
- Py_DECREF(item);\r
- goto Fail_1;\r
- }\r
-\r
- need += reslen;\r
-\r
- if (need > PY_SSIZE_T_MAX - len) {\r
- Py_DECREF(item);\r
- goto Fail_1;\r
- }\r
-\r
- need += len;\r
-\r
- if (need <= i) {\r
- Py_DECREF(item);\r
- goto Fail_1;\r
- }\r
-\r
- need = need - i - 1;\r
-\r
- assert(need >= 0);\r
- assert(outlen >= 0);\r
-\r
- if (need > outlen) {\r
- /* overallocate, to avoid reallocations */\r
- if (outlen > PY_SSIZE_T_MAX / 2) {\r
- Py_DECREF(item);\r
- return NULL;\r
- }\r
-\r
- if (need<2*outlen) {\r
- need = 2*outlen;\r
- }\r
- if (_PyString_Resize(&result, need)) {\r
- Py_DECREF(item);\r
- return NULL;\r
- }\r
- outlen = need;\r
- }\r
- memcpy(\r
- PyString_AS_STRING(result) + j,\r
- PyString_AS_STRING(item),\r
- reslen\r
- );\r
- j += reslen;\r
- }\r
- }\r
- Py_DECREF(item);\r
- if (ok < 0)\r
- goto Fail_1;\r
- }\r
-\r
- if (j < outlen)\r
- _PyString_Resize(&result, j);\r
-\r
- return result;\r
-\r
-Fail_1:\r
- Py_DECREF(result);\r
- return NULL;\r
-}\r
-\r
-#ifdef Py_USING_UNICODE\r
-/* Helper for filter(): filter a Unicode object through a function */\r
-\r
-static PyObject *\r
-filterunicode(PyObject *func, PyObject *strobj)\r
-{\r
- PyObject *result;\r
- register Py_ssize_t i, j;\r
- Py_ssize_t len = PyUnicode_GetSize(strobj);\r
- Py_ssize_t outlen = len;\r
-\r
- if (func == Py_None) {\r
- /* If it's a real string we can return the original,\r
- * as no character is ever false and __getitem__\r
- * does return this character. If it's a subclass\r
- * we must go through the __getitem__ loop */\r
- if (PyUnicode_CheckExact(strobj)) {\r
- Py_INCREF(strobj);\r
- return strobj;\r
- }\r
- }\r
- if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)\r
- return NULL;\r
-\r
- for (i = j = 0; i < len; ++i) {\r
- PyObject *item, *arg, *good;\r
- int ok;\r
-\r
- item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);\r
- if (item == NULL)\r
- goto Fail_1;\r
- if (func == Py_None) {\r
- ok = 1;\r
- } else {\r
- arg = PyTuple_Pack(1, item);\r
- if (arg == NULL) {\r
- Py_DECREF(item);\r
- goto Fail_1;\r
- }\r
- good = PyEval_CallObject(func, arg);\r
- Py_DECREF(arg);\r
- if (good == NULL) {\r
- Py_DECREF(item);\r
- goto Fail_1;\r
- }\r
- ok = PyObject_IsTrue(good);\r
- Py_DECREF(good);\r
- }\r
- if (ok > 0) {\r
- Py_ssize_t reslen;\r
- if (!PyUnicode_Check(item)) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "can't filter unicode to unicode:"\r
- " __getitem__ returned different type");\r
- Py_DECREF(item);\r
- goto Fail_1;\r
- }\r
- reslen = PyUnicode_GET_SIZE(item);\r
- if (reslen == 1)\r
- PyUnicode_AS_UNICODE(result)[j++] =\r
- PyUnicode_AS_UNICODE(item)[0];\r
- else {\r
- /* do we need more space? */\r
- Py_ssize_t need = j + reslen + len - i - 1;\r
-\r
- /* check that didnt overflow */\r
- if ((j > PY_SSIZE_T_MAX - reslen) ||\r
- ((j + reslen) > PY_SSIZE_T_MAX - len) ||\r
- ((j + reslen + len) < i) ||\r
- ((j + reslen + len - i) <= 0)) {\r
- Py_DECREF(item);\r
- return NULL;\r
- }\r
-\r
- assert(need >= 0);\r
- assert(outlen >= 0);\r
-\r
- if (need > outlen) {\r
- /* overallocate,\r
- to avoid reallocations */\r
- if (need < 2 * outlen) {\r
- if (outlen > PY_SSIZE_T_MAX / 2) {\r
- Py_DECREF(item);\r
- return NULL;\r
- } else {\r
- need = 2 * outlen;\r
- }\r
- }\r
-\r
- if (PyUnicode_Resize(\r
- &result, need) < 0) {\r
- Py_DECREF(item);\r
- goto Fail_1;\r
- }\r
- outlen = need;\r
- }\r
- memcpy(PyUnicode_AS_UNICODE(result) + j,\r
- PyUnicode_AS_UNICODE(item),\r
- reslen*sizeof(Py_UNICODE));\r
- j += reslen;\r
- }\r
- }\r
- Py_DECREF(item);\r
- if (ok < 0)\r
- goto Fail_1;\r
- }\r
-\r
- if (j < outlen)\r
- PyUnicode_Resize(&result, j);\r
-\r
- return result;\r
-\r
-Fail_1:\r
- Py_DECREF(result);\r
- return NULL;\r
-}\r
-#endif\r