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