PageRenderTime 2855ms CodeModel.GetById 412ms app.highlight 1920ms RepoModel.GetById 128ms app.codeStats 5ms

/Python/bltinmodule.c

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