PageRenderTime 327ms CodeModel.GetById 101ms app.highlight 173ms RepoModel.GetById 28ms app.codeStats 2ms

/Python/bltinmodule.c

http://unladen-swallow.googlecode.com/
C | 3422 lines | 2905 code | 391 blank | 126 comment | 788 complexity | b632a8d2725a3ea6685f72dcf2483fb7 MD5 | raw file

Large files files are truncated, but you can click here to view the full 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,

Large files files are truncated, but you can click here to view the full file