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