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