bltinmodule.c revision c8b6df90045a3f419e6fab272d93ad4159e54ccc
1/***********************************************************
2Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
3The Netherlands.
4
5                        All Rights Reserved
6
7Permission to use, copy, modify, and distribute this software and its
8documentation for any purpose and without fee is hereby granted,
9provided that the above copyright notice appear in all copies and that
10both that copyright notice and this permission notice appear in
11supporting documentation, and that the names of Stichting Mathematisch
12Centrum or CWI or Corporation for National Research Initiatives or
13CNRI not be used in advertising or publicity pertaining to
14distribution of the software without specific, written prior
15permission.
16
17While CWI is the initial source for this software, a modified version
18is made available by the Corporation for National Research Initiatives
19(CNRI) at the Internet address ftp://ftp.python.org.
20
21STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
22REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
23MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
24CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
25DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
26PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
27TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
28PERFORMANCE OF THIS SOFTWARE.
29
30******************************************************************/
31
32/* Built-in functions */
33
34#include "Python.h"
35
36#include "node.h"
37#include "compile.h"
38#include "eval.h"
39
40#include "mymath.h"
41
42#include <ctype.h>
43
44#ifdef HAVE_UNISTD_H
45#include <unistd.h>
46#endif
47
48/* Forward */
49static PyObject *filterstring Py_PROTO((PyObject *, PyObject *));
50static PyObject *filtertuple  Py_PROTO((PyObject *, PyObject *));
51static PyObject *int_from_string Py_PROTO((PyObject *));
52static PyObject *long_from_string Py_PROTO((PyObject *));
53static PyObject *float_from_string Py_PROTO((PyObject *));
54
55static PyObject *
56builtin___import__(self, args)
57	PyObject *self;
58	PyObject *args;
59{
60	char *name;
61	PyObject *globals = NULL;
62	PyObject *locals = NULL;
63	PyObject *fromlist = NULL;
64
65	if (!PyArg_ParseTuple(args, "s|OOO:__import__",
66			&name, &globals, &locals, &fromlist))
67		return NULL;
68	return PyImport_ImportModule(name);
69}
70
71
72static PyObject *
73builtin_abs(self, args)
74	PyObject *self;
75	PyObject *args;
76{
77	PyObject *v;
78	PyNumberMethods *nm;
79
80	if (!PyArg_ParseTuple(args, "O:abs", &v))
81		return NULL;
82	if ((nm = v->ob_type->tp_as_number) == NULL) {
83		PyErr_SetString(PyExc_TypeError,
84				"abs() requires numeric argument");
85		return NULL;
86	}
87	return (*nm->nb_absolute)(v);
88}
89
90static PyObject *
91builtin_apply(self, args)
92	PyObject *self;
93	PyObject *args;
94{
95	PyObject *func, *alist = NULL, *kwdict = NULL;
96
97	if (!PyArg_ParseTuple(args, "O|OO:apply", &func, &alist, &kwdict))
98		return NULL;
99	if (alist != NULL && !PyTuple_Check(alist)) {
100		PyErr_SetString(PyExc_TypeError,
101				"apply() 2nd argument must be tuple");
102		return NULL;
103	}
104	if (kwdict != NULL && !PyDict_Check(kwdict)) {
105		PyErr_SetString(PyExc_TypeError,
106			   "apply() 3rd argument must be dictionary");
107		return NULL;
108	}
109	return PyEval_CallObjectWithKeywords(func, alist, kwdict);
110}
111
112static PyObject *
113builtin_callable(self, args)
114	PyObject *self;
115	PyObject *args;
116{
117	PyObject *v;
118
119	if (!PyArg_ParseTuple(args, "O:callable", &v))
120		return NULL;
121	return PyInt_FromLong((long)PyCallable_Check(v));
122}
123
124static PyObject *
125builtin_filter(self, args)
126	PyObject *self;
127	PyObject *args;
128{
129	PyObject *func, *seq, *result;
130	PySequenceMethods *sqf;
131	int len;
132	register int i, j;
133
134	if (!PyArg_ParseTuple(args, "OO:filter", &func, &seq))
135		return NULL;
136
137	if (PyString_Check(seq)) {
138		PyObject *r = filterstring(func, seq);
139		return r;
140	}
141
142	if (PyTuple_Check(seq)) {
143		PyObject *r = filtertuple(func, seq);
144		return r;
145	}
146
147	if ((sqf = seq->ob_type->tp_as_sequence) == NULL) {
148		PyErr_SetString(PyExc_TypeError,
149			   "argument 2 to filter() must be a sequence type");
150		goto Fail_2;
151	}
152
153	if ((len = (*sqf->sq_length)(seq)) < 0)
154		goto Fail_2;
155
156	if (PyList_Check(seq) && seq->ob_refcnt == 1) {
157		Py_INCREF(seq);
158		result = seq;
159	}
160	else {
161		if ((result = PyList_New(len)) == NULL)
162			goto Fail_2;
163	}
164
165	for (i = j = 0; ; ++i) {
166		PyObject *item, *good;
167		int ok;
168
169		if ((item = (*sqf->sq_item)(seq, i)) == NULL) {
170			if (i < len)
171				goto Fail_1;
172			if (PyErr_Occurred() == PyExc_IndexError) {
173				PyErr_Clear();
174				break;
175			}
176			goto Fail_1;
177		}
178
179		if (func == Py_None) {
180			good = item;
181			Py_INCREF(good);
182		}
183		else {
184			PyObject *arg = Py_BuildValue("(O)", item);
185			if (arg == NULL)
186				goto Fail_1;
187			good = PyEval_CallObject(func, arg);
188			Py_DECREF(arg);
189			if (good == NULL) {
190				Py_DECREF(item);
191				goto Fail_1;
192			}
193		}
194		ok = PyObject_IsTrue(good);
195		Py_DECREF(good);
196		if (ok) {
197			if (j < len) {
198				if (PyList_SetItem(result, j++, item) < 0)
199					goto Fail_1;
200			}
201			else {
202				j++;
203				if (PyList_Append(result, item) < 0)
204					goto Fail_1;
205			}
206		} else {
207			Py_DECREF(item);
208		}
209	}
210
211
212	if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
213		goto Fail_1;
214
215	return result;
216
217Fail_1:
218	Py_DECREF(result);
219Fail_2:
220	return NULL;
221}
222
223static PyObject *
224builtin_chr(self, args)
225	PyObject *self;
226	PyObject *args;
227{
228	long x;
229	char s[1];
230
231	if (!PyArg_ParseTuple(args, "l:chr", &x))
232		return NULL;
233	if (x < 0 || x >= 256) {
234		PyErr_SetString(PyExc_ValueError,
235				"chr() arg not in range(256)");
236		return NULL;
237	}
238	s[0] = (char)x;
239	return PyString_FromStringAndSize(s, 1);
240}
241
242static PyObject *
243builtin_cmp(self, args)
244	PyObject *self;
245	PyObject *args;
246{
247	PyObject *a, *b;
248	long c;
249
250	if (!PyArg_ParseTuple(args, "OO:cmp", &a, &b))
251		return NULL;
252	c = PyObject_Compare(a, b);
253	if (c && PyErr_Occurred())
254		return NULL;
255	return PyInt_FromLong(c);
256}
257
258static PyObject *
259builtin_coerce(self, args)
260	PyObject *self;
261	PyObject *args;
262{
263	PyObject *v, *w;
264	PyObject *res;
265
266	if (!PyArg_ParseTuple(args, "OO:coerce", &v, &w))
267		return NULL;
268	if (PyNumber_Coerce(&v, &w) < 0)
269		return NULL;
270	res = Py_BuildValue("(OO)", v, w);
271	Py_DECREF(v);
272	Py_DECREF(w);
273	return res;
274}
275
276static PyObject *
277builtin_compile(self, args)
278	PyObject *self;
279	PyObject *args;
280{
281	char *str;
282	char *filename;
283	char *startstr;
284	int start;
285
286	if (!PyArg_ParseTuple(args, "sss:compile", &str, &filename, &startstr))
287		return NULL;
288	if (strcmp(startstr, "exec") == 0)
289		start = Py_file_input;
290	else if (strcmp(startstr, "eval") == 0)
291		start = Py_eval_input;
292	else if (strcmp(startstr, "single") == 0)
293		start = Py_single_input;
294	else {
295		PyErr_SetString(PyExc_ValueError,
296		   "compile() mode must be 'exec' or 'eval' or 'single'");
297		return NULL;
298	}
299	return Py_CompileString(str, filename, start);
300}
301
302#ifndef WITHOUT_COMPLEX
303
304static PyObject *
305builtin_complex(self, args)
306	PyObject *self;
307	PyObject *args;
308{
309	PyObject *r, *i, *tmp;
310	PyNumberMethods *nbr, *nbi = NULL;
311	Py_complex cr, ci;
312	int own_r = 0;
313
314	i = NULL;
315	if (!PyArg_ParseTuple(args, "O|O:complex", &r, &i))
316		return NULL;
317	if ((nbr = r->ob_type->tp_as_number) == NULL ||
318	    nbr->nb_float == NULL ||
319	    (i != NULL &&
320	     ((nbi = i->ob_type->tp_as_number) == NULL ||
321	      nbi->nb_float == NULL))) {
322		PyErr_SetString(PyExc_TypeError,
323			   "complex() argument can't be converted to complex");
324		return NULL;
325	}
326	/* XXX Hack to support classes with __complex__ method */
327	if (PyInstance_Check(r)) {
328		static PyObject *complexstr;
329		PyObject *f;
330		if (complexstr == NULL) {
331			complexstr = PyString_InternFromString("__complex__");
332			if (complexstr == NULL)
333				return NULL;
334		}
335		f = PyObject_GetAttr(r, complexstr);
336		if (f == NULL)
337			PyErr_Clear();
338		else {
339			PyObject *args = Py_BuildValue("()");
340			if (args == NULL)
341				return NULL;
342			r = PyEval_CallObject(f, args);
343			Py_DECREF(args);
344			if (r == NULL)
345				return NULL;
346			own_r = 1;
347		}
348	}
349	if (PyComplex_Check(r)) {
350		cr = ((PyComplexObject*)r)->cval;
351		if (own_r)
352			Py_DECREF(r);
353	}
354	else {
355		tmp = (*nbr->nb_float)(r);
356		if (own_r)
357			Py_DECREF(r);
358		if (tmp == NULL)
359			return NULL;
360		cr.real = PyFloat_AsDouble(tmp);
361		Py_DECREF(tmp);
362		cr.imag = 0.;
363	}
364	if (i == NULL) {
365		ci.real = 0.;
366		ci.imag = 0.;
367	}
368	else if (PyComplex_Check(i))
369		ci = ((PyComplexObject*)i)->cval;
370	else {
371		tmp = (*nbi->nb_float)(i);
372		if (tmp == NULL)
373			return NULL;
374		ci.real = PyFloat_AsDouble(tmp);
375		Py_DECREF(tmp);
376		ci.imag = 0.;
377	}
378	cr.real -= ci.imag;
379	cr.imag += ci.real;
380	return PyComplex_FromCComplex(cr);
381}
382
383#endif
384
385static PyObject *
386builtin_dir(self, args)
387	PyObject *self;
388	PyObject *args;
389{
390	static char *attrlist[] = {"__members__", "__methods__", NULL};
391	PyObject *v = NULL, *l = NULL, *m = NULL;
392	PyObject *d, *x;
393	int i;
394	char **s;
395
396	if (!PyArg_ParseTuple(args, "|O:dir", &v))
397		return NULL;
398	if (v == NULL) {
399		x = PyEval_GetLocals();
400		if (x == NULL)
401			goto error;
402		l = PyMapping_Keys(x);
403		if (l == NULL)
404			goto error;
405	}
406	else {
407		d = PyObject_GetAttrString(v, "__dict__");
408		if (d == NULL)
409			PyErr_Clear();
410		else {
411			l = PyMapping_Keys(d);
412			if (l == NULL)
413				PyErr_Clear();
414			Py_DECREF(d);
415		}
416		if (l == NULL) {
417			l = PyList_New(0);
418			if (l == NULL)
419				goto error;
420		}
421		for (s = attrlist; *s != NULL; s++) {
422			m = PyObject_GetAttrString(v, *s);
423			if (m == NULL) {
424				PyErr_Clear();
425				continue;
426			}
427			for (i = 0; ; i++) {
428				x = PySequence_GetItem(m, i);
429				if (x == NULL) {
430					PyErr_Clear();
431					break;
432				}
433				if (PyList_Append(l, x) != 0) {
434					Py_DECREF(x);
435					Py_DECREF(m);
436					goto error;
437				}
438				Py_DECREF(x);
439			}
440			Py_DECREF(m);
441		}
442	}
443	if (PyList_Sort(l) != 0)
444		goto error;
445	return l;
446  error:
447	Py_XDECREF(l);
448	return NULL;
449}
450
451static PyObject *
452do_divmod(v, w)
453	PyObject *v, *w;
454{
455	PyObject *res;
456
457	if (PyInstance_Check(v) || PyInstance_Check(w))
458		return PyInstance_DoBinOp(v, w, "__divmod__", "__rdivmod__",
459				     do_divmod);
460	if (v->ob_type->tp_as_number == NULL ||
461				w->ob_type->tp_as_number == NULL) {
462		PyErr_SetString(PyExc_TypeError,
463		    "divmod() requires numeric or class instance arguments");
464		return NULL;
465	}
466	if (PyNumber_Coerce(&v, &w) != 0)
467		return NULL;
468	res = (*v->ob_type->tp_as_number->nb_divmod)(v, w);
469	Py_DECREF(v);
470	Py_DECREF(w);
471	return res;
472}
473
474static PyObject *
475builtin_divmod(self, args)
476	PyObject *self;
477	PyObject *args;
478{
479	PyObject *v, *w;
480
481	if (!PyArg_ParseTuple(args, "OO:divmod", &v, &w))
482		return NULL;
483	return do_divmod(v, w);
484}
485
486static PyObject *
487builtin_eval(self, args)
488	PyObject *self;
489	PyObject *args;
490{
491	PyObject *cmd;
492	PyObject *globals = Py_None, *locals = Py_None;
493	char *str;
494
495	if (!PyArg_ParseTuple(args, "O|O!O!:eval",
496			&cmd,
497			&PyDict_Type, &globals,
498			&PyDict_Type, &locals))
499		return NULL;
500	if (globals == Py_None) {
501		globals = PyEval_GetGlobals();
502		if (locals == Py_None)
503			locals = PyEval_GetLocals();
504	}
505	else if (locals == Py_None)
506		locals = globals;
507	if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
508		if (PyDict_SetItemString(globals, "__builtins__",
509					 PyEval_GetBuiltins()) != 0)
510			return NULL;
511	}
512	if (PyCode_Check(cmd))
513		return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
514	if (!PyString_Check(cmd)) {
515		PyErr_SetString(PyExc_TypeError,
516			   "eval() argument 1 must be string or code object");
517		return NULL;
518	}
519	str = PyString_AsString(cmd);
520	if ((int)strlen(str) != PyString_Size(cmd)) {
521		PyErr_SetString(PyExc_ValueError,
522			   "embedded '\\0' in string arg");
523		return NULL;
524	}
525	while (*str == ' ' || *str == '\t')
526		str++;
527	return PyRun_String(str, Py_eval_input, globals, locals);
528}
529
530static PyObject *
531builtin_execfile(self, args)
532	PyObject *self;
533	PyObject *args;
534{
535	char *filename;
536	PyObject *globals = Py_None, *locals = Py_None;
537	PyObject *res;
538	FILE* fp;
539
540	if (!PyArg_ParseTuple(args, "s|O!O!:execfile",
541			&filename,
542			&PyDict_Type, &globals,
543			&PyDict_Type, &locals))
544		return NULL;
545	if (globals == Py_None) {
546		globals = PyEval_GetGlobals();
547		if (locals == Py_None)
548			locals = PyEval_GetLocals();
549	}
550	else if (locals == Py_None)
551		locals = globals;
552	if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
553		if (PyDict_SetItemString(globals, "__builtins__",
554					 PyEval_GetBuiltins()) != 0)
555			return NULL;
556	}
557	Py_BEGIN_ALLOW_THREADS
558	fp = fopen(filename, "r");
559	Py_END_ALLOW_THREADS
560	if (fp == NULL) {
561		PyErr_SetFromErrno(PyExc_IOError);
562		return NULL;
563	}
564	res = PyRun_File(fp, filename, Py_file_input, globals, locals);
565	Py_BEGIN_ALLOW_THREADS
566	fclose(fp);
567	Py_END_ALLOW_THREADS
568	return res;
569}
570
571static PyObject *
572builtin_float(self, args)
573	PyObject *self;
574	PyObject *args;
575{
576	PyObject *v;
577	PyNumberMethods *nb;
578
579	if (!PyArg_ParseTuple(args, "O:float", &v))
580		return NULL;
581	if (PyString_Check(v))
582		return float_from_string(v);
583	if ((nb = v->ob_type->tp_as_number) == NULL ||
584	    nb->nb_float == NULL) {
585		PyErr_SetString(PyExc_TypeError,
586			   "float() argument can't be converted to float");
587		return NULL;
588	}
589	return (*nb->nb_float)(v);
590}
591
592static PyObject *
593builtin_getattr(self, args)
594	PyObject *self;
595	PyObject *args;
596{
597	PyObject *v;
598	PyObject *name;
599
600	if (!PyArg_ParseTuple(args, "OS:getattr", &v, &name))
601		return NULL;
602	return PyObject_GetAttr(v, name);
603}
604
605static PyObject *
606builtin_globals(self, args)
607	PyObject *self;
608	PyObject *args;
609{
610	PyObject *d;
611
612	if (!PyArg_ParseTuple(args, ""))
613		return NULL;
614	d = PyEval_GetGlobals();
615	Py_INCREF(d);
616	return d;
617}
618
619static PyObject *
620builtin_hasattr(self, args)
621	PyObject *self;
622	PyObject *args;
623{
624	PyObject *v;
625	PyObject *name;
626
627	if (!PyArg_ParseTuple(args, "OS:hasattr", &v, &name))
628		return NULL;
629	v = PyObject_GetAttr(v, name);
630	if (v == NULL) {
631		PyErr_Clear();
632		return PyInt_FromLong(0L);
633	}
634	Py_DECREF(v);
635	return PyInt_FromLong(1L);
636}
637
638static PyObject *
639builtin_id(self, args)
640	PyObject *self;
641	PyObject *args;
642{
643	PyObject *v;
644
645	if (!PyArg_ParseTuple(args, "O:id", &v))
646		return NULL;
647	return PyInt_FromLong((long)v);
648}
649
650static PyObject *
651builtin_map(self, args)
652	PyObject *self;
653	PyObject *args;
654{
655	typedef struct {
656		PyObject *seq;
657		PySequenceMethods *sqf;
658		int len;
659	} sequence;
660
661	PyObject *func, *result;
662	sequence *seqs = NULL, *sqp;
663	int n, len;
664	register int i, j;
665
666	n = PyTuple_Size(args);
667	if (n < 2) {
668		PyErr_SetString(PyExc_TypeError,
669				"map() requires at least two args");
670		return NULL;
671	}
672
673	func = PyTuple_GetItem(args, 0);
674	n--;
675
676	if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
677		PyErr_NoMemory();
678		goto Fail_2;
679	}
680
681	for (len = 0, i = 0, sqp = seqs; i < n; ++i, ++sqp) {
682		int curlen;
683
684		if ((sqp->seq = PyTuple_GetItem(args, i + 1)) == NULL)
685			goto Fail_2;
686
687		if (! (sqp->sqf = sqp->seq->ob_type->tp_as_sequence)) {
688			static char errmsg[] =
689			    "argument %d to map() must be a sequence object";
690			char errbuf[sizeof(errmsg) + 25];
691
692			sprintf(errbuf, errmsg, i+2);
693			PyErr_SetString(PyExc_TypeError, errbuf);
694			goto Fail_2;
695		}
696
697		if ((curlen = sqp->len = (*sqp->sqf->sq_length)(sqp->seq)) < 0)
698			goto Fail_2;
699
700		if (curlen > len)
701			len = curlen;
702	}
703
704	if ((result = (PyObject *) PyList_New(len)) == NULL)
705		goto Fail_2;
706
707	/* XXX Special case map(None, single_list) could be more efficient */
708	for (i = 0; ; ++i) {
709		PyObject *alist, *item=NULL, *value;
710		int any = 0;
711
712		if (func == Py_None && n == 1)
713			alist = NULL;
714		else {
715			if ((alist = PyTuple_New(n)) == NULL)
716				goto Fail_1;
717		}
718
719		for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
720			if (sqp->len < 0) {
721				Py_INCREF(Py_None);
722				item = Py_None;
723			}
724			else {
725				item = (*sqp->sqf->sq_item)(sqp->seq, i);
726				if (item == NULL) {
727					if (i < sqp->len)
728						goto Fail_0;
729					if (PyErr_Occurred() ==
730					    PyExc_IndexError) {
731						PyErr_Clear();
732						Py_INCREF(Py_None);
733						item = Py_None;
734						sqp->len = -1;
735					}
736					else {
737						goto Fail_0;
738					}
739				}
740				else
741					any = 1;
742
743			}
744			if (!alist)
745				break;
746			if (PyTuple_SetItem(alist, j, item) < 0) {
747				Py_DECREF(item);
748				goto Fail_0;
749			}
750			continue;
751
752		Fail_0:
753			Py_XDECREF(alist);
754			goto Fail_1;
755		}
756
757		if (!alist)
758			alist = item;
759
760		if (!any) {
761			Py_DECREF(alist);
762			break;
763		}
764
765		if (func == Py_None)
766			value = alist;
767		else {
768			value = PyEval_CallObject(func, alist);
769			Py_DECREF(alist);
770			if (value == NULL)
771				goto Fail_1;
772		}
773		if (i >= len) {
774			if (PyList_Append(result, value) < 0)
775				goto Fail_1;
776		}
777		else {
778			if (PyList_SetItem(result, i, value) < 0)
779				goto Fail_1;
780		}
781	}
782
783	PyMem_DEL(seqs);
784	return result;
785
786Fail_1:
787	Py_DECREF(result);
788Fail_2:
789	if (seqs) PyMem_DEL(seqs);
790	return NULL;
791}
792
793static PyObject *
794builtin_setattr(self, args)
795	PyObject *self;
796	PyObject *args;
797{
798	PyObject *v;
799	PyObject *name;
800	PyObject *value;
801
802	if (!PyArg_ParseTuple(args, "OSO:setattr", &v, &name, &value))
803		return NULL;
804	if (PyObject_SetAttr(v, name, value) != 0)
805		return NULL;
806	Py_INCREF(Py_None);
807	return Py_None;
808}
809
810static PyObject *
811builtin_delattr(self, args)
812	PyObject *self;
813	PyObject *args;
814{
815	PyObject *v;
816	PyObject *name;
817
818	if (!PyArg_ParseTuple(args, "OS:delattr", &v, &name))
819		return NULL;
820	if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
821		return NULL;
822	Py_INCREF(Py_None);
823	return Py_None;
824}
825
826static PyObject *
827builtin_hash(self, args)
828	PyObject *self;
829	PyObject *args;
830{
831	PyObject *v;
832	long x;
833
834	if (!PyArg_ParseTuple(args, "O:hash", &v))
835		return NULL;
836	x = PyObject_Hash(v);
837	if (x == -1)
838		return NULL;
839	return PyInt_FromLong(x);
840}
841
842static PyObject *
843builtin_hex(self, args)
844	PyObject *self;
845	PyObject *args;
846{
847	PyObject *v;
848	PyNumberMethods *nb;
849
850	if (!PyArg_ParseTuple(args, "O:hex", &v))
851		return NULL;
852
853	if ((nb = v->ob_type->tp_as_number) == NULL ||
854	    nb->nb_hex == NULL) {
855		PyErr_SetString(PyExc_TypeError,
856			   "hex() argument can't be converted to hex");
857		return NULL;
858	}
859	return (*nb->nb_hex)(v);
860}
861
862static PyObject *builtin_raw_input Py_PROTO((PyObject *, PyObject *));
863
864static PyObject *
865builtin_input(self, args)
866	PyObject *self;
867	PyObject *args;
868{
869	PyObject *line;
870	char *str;
871	PyObject *res;
872	PyObject *globals, *locals;
873
874	line = builtin_raw_input(self, args);
875	if (line == NULL)
876		return line;
877	if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
878		return NULL;
879	while (*str == ' ' || *str == '\t')
880			str++;
881	globals = PyEval_GetGlobals();
882	locals = PyEval_GetLocals();
883	if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
884		if (PyDict_SetItemString(globals, "__builtins__",
885					 PyEval_GetBuiltins()) != 0)
886			return NULL;
887	}
888	res = PyRun_String(str, Py_eval_input, globals, locals);
889	Py_DECREF(line);
890	return res;
891}
892
893static PyObject *
894builtin_intern(self, args)
895	PyObject *self;
896	PyObject *args;
897{
898	PyObject *s;
899	if (!PyArg_ParseTuple(args, "S", &s))
900		return NULL;
901	Py_INCREF(s);
902	PyString_InternInPlace(&s);
903	return s;
904}
905
906static PyObject *
907builtin_int(self, args)
908	PyObject *self;
909	PyObject *args;
910{
911	PyObject *v;
912	PyNumberMethods *nb;
913
914	if (!PyArg_ParseTuple(args, "O:int", &v))
915		return NULL;
916	if (PyString_Check(v))
917		return int_from_string(v);
918	if ((nb = v->ob_type->tp_as_number) == NULL ||
919	    nb->nb_int == NULL) {
920		PyErr_SetString(PyExc_TypeError,
921			   "int() argument can't be converted to int");
922		return NULL;
923	}
924	return (*nb->nb_int)(v);
925}
926
927static PyObject *
928builtin_len(self, args)
929	PyObject *self;
930	PyObject *args;
931{
932	PyObject *v;
933	long len;
934	PyTypeObject *tp;
935
936	if (!PyArg_ParseTuple(args, "O:len", &v))
937		return NULL;
938	tp = v->ob_type;
939	if (tp->tp_as_sequence != NULL) {
940		len = (*tp->tp_as_sequence->sq_length)(v);
941	}
942	else if (tp->tp_as_mapping != NULL) {
943		len = (*tp->tp_as_mapping->mp_length)(v);
944	}
945	else {
946		PyErr_SetString(PyExc_TypeError, "len() of unsized object");
947		return NULL;
948	}
949	if (len < 0)
950		return NULL;
951	else
952		return PyInt_FromLong(len);
953}
954
955static PyObject *
956builtin_list(self, args)
957	PyObject *self;
958	PyObject *args;
959{
960	PyObject *v;
961	PySequenceMethods *sqf;
962
963	if (!PyArg_ParseTuple(args, "O:list", &v))
964		return NULL;
965	if ((sqf = v->ob_type->tp_as_sequence) != NULL) {
966		int n = (*sqf->sq_length)(v);
967		int i;
968		PyObject *l;
969		if (n < 0)
970			return NULL;
971		l = PyList_New(n);
972		if (l == NULL)
973			return NULL;
974		for (i = 0; i < n; i++) {
975			PyObject *item = (*sqf->sq_item)(v, i);
976			if (item == NULL) {
977				Py_DECREF(l);
978				l = NULL;
979				break;
980			}
981			PyList_SetItem(l, i, item);
982		}
983		/* XXX Should support indefinite-length sequences */
984		return l;
985	}
986	PyErr_SetString(PyExc_TypeError, "list() argument must be a sequence");
987	return NULL;
988}
989
990
991static PyObject *
992builtin_slice(self, args)
993     PyObject *self;
994     PyObject *args;
995{
996  PyObject *start, *stop, *step;
997
998  start = stop = step = NULL;
999
1000  if (!PyArg_ParseTuple(args, "O|OO:slice", &start, &stop, &step))
1001    return NULL;
1002
1003  /*This swapping of stop and start is to maintain compatibility with
1004    the range builtin.*/
1005  if (stop == NULL) {
1006    stop = start;
1007    start = NULL;
1008  }
1009  return PySlice_New(start, stop, step);
1010}
1011
1012static PyObject *
1013builtin_locals(self, args)
1014	PyObject *self;
1015	PyObject *args;
1016{
1017	PyObject *d;
1018
1019	if (!PyArg_ParseTuple(args, ""))
1020		return NULL;
1021	d = PyEval_GetLocals();
1022	Py_INCREF(d);
1023	return d;
1024}
1025
1026static PyObject *
1027builtin_long(self, args)
1028	PyObject *self;
1029	PyObject *args;
1030{
1031	PyObject *v;
1032	PyNumberMethods *nb;
1033
1034	if (!PyArg_ParseTuple(args, "O:long", &v))
1035		return NULL;
1036	if (PyString_Check(v))
1037		return long_from_string(v);
1038	if ((nb = v->ob_type->tp_as_number) == NULL ||
1039	    nb->nb_long == NULL) {
1040		PyErr_SetString(PyExc_TypeError,
1041			   "long() argument can't be converted to long");
1042		return NULL;
1043	}
1044	return (*nb->nb_long)(v);
1045}
1046
1047static PyObject *
1048min_max(args, sign)
1049	PyObject *args;
1050	int sign;
1051{
1052	int i;
1053	PyObject *v, *w, *x;
1054	PySequenceMethods *sq;
1055
1056	if (PyTuple_Size(args) > 1)
1057		v = args;
1058	else if (!PyArg_ParseTuple(args, "O:min/max", &v))
1059		return NULL;
1060	sq = v->ob_type->tp_as_sequence;
1061	if (sq == NULL) {
1062		PyErr_SetString(PyExc_TypeError,
1063				"min() or max() of non-sequence");
1064		return NULL;
1065	}
1066	w = NULL;
1067	for (i = 0; ; i++) {
1068		x = (*sq->sq_item)(v, i); /* Implies INCREF */
1069		if (x == NULL) {
1070			if (PyErr_Occurred() == PyExc_IndexError) {
1071				PyErr_Clear();
1072				break;
1073			}
1074			Py_XDECREF(w);
1075			return NULL;
1076		}
1077		if (w == NULL)
1078			w = x;
1079		else {
1080			int c = PyObject_Compare(x, w);
1081			if (c && PyErr_Occurred()) {
1082				Py_DECREF(x);
1083				Py_XDECREF(w);
1084				return NULL;
1085			}
1086			if (c * sign > 0) {
1087				Py_DECREF(w);
1088				w = x;
1089			}
1090			else
1091				Py_DECREF(x);
1092		}
1093	}
1094	if (w == NULL)
1095		PyErr_SetString(PyExc_ValueError,
1096				"min() or max() of empty sequence");
1097	return w;
1098}
1099
1100static PyObject *
1101builtin_min(self, v)
1102	PyObject *self;
1103	PyObject *v;
1104{
1105	return min_max(v, -1);
1106}
1107
1108static PyObject *
1109builtin_max(self, v)
1110	PyObject *self;
1111	PyObject *v;
1112{
1113	return min_max(v, 1);
1114}
1115
1116static PyObject *
1117builtin_oct(self, args)
1118	PyObject *self;
1119	PyObject *args;
1120{
1121	PyObject *v;
1122	PyNumberMethods *nb;
1123
1124	if (!PyArg_ParseTuple(args, "O:oct", &v))
1125		return NULL;
1126	if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1127	    nb->nb_oct == NULL) {
1128		PyErr_SetString(PyExc_TypeError,
1129			   "oct() argument can't be converted to oct");
1130		return NULL;
1131	}
1132	return (*nb->nb_oct)(v);
1133}
1134
1135static PyObject *
1136builtin_open(self, args)
1137	PyObject *self;
1138	PyObject *args;
1139{
1140	char *name;
1141	char *mode = "r";
1142	int bufsize = -1;
1143	PyObject *f;
1144
1145	if (!PyArg_ParseTuple(args, "s|si:open", &name, &mode, &bufsize))
1146		return NULL;
1147	f = PyFile_FromString(name, mode);
1148	if (f != NULL)
1149		PyFile_SetBufSize(f, bufsize);
1150	return f;
1151}
1152
1153static PyObject *
1154builtin_ord(self, args)
1155	PyObject *self;
1156	PyObject *args;
1157{
1158	char c;
1159
1160	if (!PyArg_ParseTuple(args, "c:ord", &c))
1161		return NULL;
1162	return PyInt_FromLong((long)(c & 0xff));
1163}
1164
1165static PyObject *
1166do_pow(v, w)
1167	PyObject *v, *w;
1168{
1169	PyObject *res;
1170	if (PyInstance_Check(v) || PyInstance_Check(w))
1171		return PyInstance_DoBinOp(v, w, "__pow__", "__rpow__", do_pow);
1172	if (v->ob_type->tp_as_number == NULL ||
1173	    w->ob_type->tp_as_number == NULL) {
1174		PyErr_SetString(PyExc_TypeError,
1175				"pow() requires numeric arguments");
1176		return NULL;
1177	}
1178	if (
1179#ifndef WITHOUT_COMPLEX
1180            !PyComplex_Check(v) &&
1181#endif
1182            PyFloat_Check(w) && PyFloat_AsDouble(v) < 0.0) {
1183		if (!PyErr_Occurred())
1184		    PyErr_SetString(PyExc_ValueError,
1185				    "negative number to float power");
1186		return NULL;
1187	}
1188	if (PyNumber_Coerce(&v, &w) != 0)
1189		return NULL;
1190	res = (*v->ob_type->tp_as_number->nb_power)(v, w, Py_None);
1191	Py_DECREF(v);
1192	Py_DECREF(w);
1193	return res;
1194}
1195
1196static PyObject *
1197builtin_pow(self, args)
1198	PyObject *self;
1199	PyObject *args;
1200{
1201	PyObject *v, *w, *z = Py_None, *res;
1202	PyObject *v1, *z1, *w2, *z2;
1203
1204	if (!PyArg_ParseTuple(args, "OO|O:pow", &v, &w, &z))
1205		return NULL;
1206	if (z == Py_None)
1207		return do_pow(v, w);
1208	/* XXX The ternary version doesn't do class instance coercions */
1209	if (PyInstance_Check(v))
1210		return v->ob_type->tp_as_number->nb_power(v, w, z);
1211	if (v->ob_type->tp_as_number == NULL ||
1212	    z->ob_type->tp_as_number == NULL ||
1213	    w->ob_type->tp_as_number == NULL) {
1214		PyErr_SetString(PyExc_TypeError,
1215				"pow() requires numeric arguments");
1216		return NULL;
1217	}
1218	if (PyNumber_Coerce(&v, &w) != 0)
1219		return NULL;
1220	res = NULL;
1221	v1 = v;
1222	z1 = z;
1223	if (PyNumber_Coerce(&v1, &z1) != 0)
1224		goto error2;
1225	w2 = w;
1226	z2 = z1;
1227 	if (PyNumber_Coerce(&w2, &z2) != 0)
1228		goto error1;
1229	res = (*v1->ob_type->tp_as_number->nb_power)(v1, w2, z2);
1230	Py_DECREF(w2);
1231	Py_DECREF(z2);
1232 error1:
1233	Py_DECREF(v1);
1234	Py_DECREF(z1);
1235 error2:
1236	Py_DECREF(v);
1237	Py_DECREF(w);
1238	return res;
1239}
1240
1241static PyObject *
1242builtin_range(self, args)
1243	PyObject *self;
1244	PyObject *args;
1245{
1246	long ilow = 0, ihigh = 0, istep = 1;
1247	int i, n;
1248	PyObject *v;
1249
1250	if (PyTuple_Size(args) <= 1) {
1251		if (!PyArg_ParseTuple(args,
1252				"l;range() requires 1-3 int arguments",
1253				&ihigh))
1254			return NULL;
1255	}
1256	else {
1257		if (!PyArg_ParseTuple(args,
1258				"ll|l;range() requires 1-3 int arguments",
1259				&ilow, &ihigh, &istep))
1260			return NULL;
1261	}
1262	if (istep == 0) {
1263		PyErr_SetString(PyExc_ValueError, "zero step for range()");
1264		return NULL;
1265	}
1266	/* XXX ought to check overflow of subtraction */
1267	if (istep > 0)
1268		n = (ihigh - ilow + istep - 1) / istep;
1269	else
1270		n = (ihigh - ilow + istep + 1) / istep;
1271	if (n < 0)
1272		n = 0;
1273	v = PyList_New(n);
1274	if (v == NULL)
1275		return NULL;
1276	for (i = 0; i < n; i++) {
1277		PyObject *w = PyInt_FromLong(ilow);
1278		if (w == NULL) {
1279			Py_DECREF(v);
1280			return NULL;
1281		}
1282		PyList_SetItem(v, i, w);
1283		ilow += istep;
1284	}
1285	return v;
1286}
1287
1288static PyObject *
1289builtin_xrange(self, args)
1290	PyObject *self;
1291	PyObject *args;
1292{
1293	long ilow = 0, ihigh = 0, istep = 1;
1294	long n;
1295
1296	if (PyTuple_Size(args) <= 1) {
1297		if (!PyArg_ParseTuple(args,
1298				"l;xrange() requires 1-3 int arguments",
1299				&ihigh))
1300			return NULL;
1301	}
1302	else {
1303		if (!PyArg_ParseTuple(args,
1304				"ll|l;xrange() requires 1-3 int arguments",
1305				&ilow, &ihigh, &istep))
1306			return NULL;
1307	}
1308	if (istep == 0) {
1309		PyErr_SetString(PyExc_ValueError, "zero step for xrange()");
1310		return NULL;
1311	}
1312	/* XXX ought to check overflow of subtraction */
1313	if (istep > 0)
1314		n = (ihigh - ilow + istep - 1) / istep;
1315	else
1316		n = (ihigh - ilow + istep + 1) / istep;
1317	if (n < 0)
1318		n = 0;
1319	return PyRange_New(ilow, n, istep, 1);
1320}
1321
1322extern char *PyOS_Readline Py_PROTO((char *));
1323
1324static PyObject *
1325builtin_raw_input(self, args)
1326	PyObject *self;
1327	PyObject *args;
1328{
1329	PyObject *v = NULL;
1330	PyObject *f;
1331
1332	if (!PyArg_ParseTuple(args, "|O:[raw_]input", &v))
1333		return NULL;
1334	if (PyFile_AsFile(PySys_GetObject("stdin")) == stdin &&
1335	    PyFile_AsFile(PySys_GetObject("stdout")) == stdout &&
1336	    isatty(fileno(stdin)) && isatty(fileno(stdout))) {
1337		PyObject *po;
1338		char *prompt;
1339		char *s;
1340		PyObject *result;
1341		if (v != NULL) {
1342			po = PyObject_Str(v);
1343			if (po == NULL)
1344				return NULL;
1345			prompt = PyString_AsString(po);
1346		}
1347		else {
1348			po = NULL;
1349			prompt = "";
1350		}
1351		s = PyOS_Readline(prompt);
1352		Py_XDECREF(po);
1353		if (s == NULL) {
1354			PyErr_SetNone(PyExc_KeyboardInterrupt);
1355			return NULL;
1356		}
1357		if (*s == '\0') {
1358			PyErr_SetNone(PyExc_EOFError);
1359			result = NULL;
1360		}
1361		else { /* strip trailing '\n' */
1362			result = PyString_FromStringAndSize(s, strlen(s)-1);
1363		}
1364		free(s);
1365		return result;
1366	}
1367	if (v != NULL) {
1368		f = PySys_GetObject("stdout");
1369		if (f == NULL) {
1370			PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1371			return NULL;
1372		}
1373		if (Py_FlushLine() != 0 ||
1374		    PyFile_WriteObject(v, f, Py_PRINT_RAW) != 0)
1375			return NULL;
1376	}
1377	f = PySys_GetObject("stdin");
1378	if (f == NULL) {
1379		PyErr_SetString(PyExc_RuntimeError, "lost sys.stdin");
1380		return NULL;
1381	}
1382	return PyFile_GetLine(f, -1);
1383}
1384
1385static PyObject *
1386builtin_reduce(self, args)
1387	PyObject *self;
1388	PyObject *args;
1389{
1390	PyObject *seq, *func, *result = NULL;
1391	PySequenceMethods *sqf;
1392	register int i;
1393
1394	if (!PyArg_ParseTuple(args, "OO|O:reduce", &func, &seq, &result))
1395		return NULL;
1396	if (result != NULL)
1397		Py_INCREF(result);
1398
1399	if ((sqf = seq->ob_type->tp_as_sequence) == NULL) {
1400		PyErr_SetString(PyExc_TypeError,
1401		    "2nd argument to reduce() must be a sequence object");
1402		return NULL;
1403	}
1404
1405	if ((args = PyTuple_New(2)) == NULL)
1406		goto Fail;
1407
1408	for (i = 0; ; ++i) {
1409		PyObject *op2;
1410
1411		if (args->ob_refcnt > 1) {
1412			Py_DECREF(args);
1413			if ((args = PyTuple_New(2)) == NULL)
1414				goto Fail;
1415		}
1416
1417		if ((op2 = (*sqf->sq_item)(seq, i)) == NULL) {
1418			if (PyErr_Occurred() == PyExc_IndexError) {
1419				PyErr_Clear();
1420				break;
1421			}
1422			goto Fail;
1423		}
1424
1425		if (result == NULL)
1426			result = op2;
1427		else {
1428			PyTuple_SetItem(args, 0, result);
1429			PyTuple_SetItem(args, 1, op2);
1430			if ((result = PyEval_CallObject(func, args)) == NULL)
1431				goto Fail;
1432		}
1433	}
1434
1435	Py_DECREF(args);
1436
1437	if (result == NULL)
1438		PyErr_SetString(PyExc_TypeError,
1439			   "reduce of empty sequence with no initial value");
1440
1441	return result;
1442
1443Fail:
1444	Py_XDECREF(args);
1445	Py_XDECREF(result);
1446	return NULL;
1447}
1448
1449static PyObject *
1450builtin_reload(self, args)
1451	PyObject *self;
1452	PyObject *args;
1453{
1454	PyObject *v;
1455
1456	if (!PyArg_ParseTuple(args, "O:reload", &v))
1457		return NULL;
1458	return PyImport_ReloadModule(v);
1459}
1460
1461static PyObject *
1462builtin_repr(self, args)
1463	PyObject *self;
1464	PyObject *args;
1465{
1466	PyObject *v;
1467
1468	if (!PyArg_ParseTuple(args, "O:repr", &v))
1469		return NULL;
1470	return PyObject_Repr(v);
1471}
1472
1473static PyObject *
1474builtin_round(self, args)
1475	PyObject *self;
1476	PyObject *args;
1477{
1478	double x;
1479	double f;
1480	int ndigits = 0;
1481	int i;
1482
1483	if (!PyArg_ParseTuple(args, "d|i:round", &x, &ndigits))
1484			return NULL;
1485	f = 1.0;
1486	for (i = ndigits; --i >= 0; )
1487		f = f*10.0;
1488	for (i = ndigits; ++i <= 0; )
1489		f = f*0.1;
1490	if (x >= 0.0)
1491		return PyFloat_FromDouble(floor(x*f + 0.5) / f);
1492	else
1493		return PyFloat_FromDouble(ceil(x*f - 0.5) / f);
1494}
1495
1496static PyObject *
1497builtin_str(self, args)
1498	PyObject *self;
1499	PyObject *args;
1500{
1501	PyObject *v;
1502
1503	if (!PyArg_ParseTuple(args, "O:str", &v))
1504		return NULL;
1505	return PyObject_Str(v);
1506}
1507
1508static PyObject *
1509builtin_tuple(self, args)
1510	PyObject *self;
1511	PyObject *args;
1512{
1513	PyObject *v;
1514	PySequenceMethods *sqf;
1515
1516	if (!PyArg_ParseTuple(args, "O:tuple", &v))
1517		return NULL;
1518	if (PyTuple_Check(v)) {
1519		Py_INCREF(v);
1520		return v;
1521	}
1522	if (PyList_Check(v))
1523		return PyList_AsTuple(v);
1524	if (PyString_Check(v)) {
1525		int n = PyString_Size(v);
1526		PyObject *t = PyTuple_New(n);
1527		if (t != NULL) {
1528			int i;
1529			char *p = PyString_AsString(v);
1530			for (i = 0; i < n; i++) {
1531				PyObject *item =
1532					PyString_FromStringAndSize(p+i, 1);
1533				if (item == NULL) {
1534					Py_DECREF(t);
1535					t = NULL;
1536					break;
1537				}
1538				PyTuple_SetItem(t, i, item);
1539			}
1540		}
1541		return t;
1542	}
1543	/* Generic sequence object */
1544	if ((sqf = v->ob_type->tp_as_sequence) != NULL) {
1545		int n = (*sqf->sq_length)(v);
1546		int i;
1547		PyObject *t;
1548		if (n < 0)
1549			return NULL;
1550		t = PyTuple_New(n);
1551		if (t == NULL)
1552			return NULL;
1553		for (i = 0; i < n; i++) {
1554			PyObject *item = (*sqf->sq_item)(v, i);
1555			if (item == NULL) {
1556				Py_DECREF(t);
1557				t = NULL;
1558				break;
1559			}
1560			PyTuple_SetItem(t, i, item);
1561		}
1562		/* XXX Should support indefinite-length sequences */
1563		return t;
1564	}
1565	/* None of the above */
1566	PyErr_SetString(PyExc_TypeError,
1567			"tuple() argument must be a sequence");
1568	return NULL;
1569}
1570
1571static PyObject *
1572builtin_type(self, args)
1573	PyObject *self;
1574	PyObject *args;
1575{
1576	PyObject *v;
1577
1578	if (!PyArg_ParseTuple(args, "O:type", &v))
1579		return NULL;
1580	v = (PyObject *)v->ob_type;
1581	Py_INCREF(v);
1582	return v;
1583}
1584
1585static PyObject *
1586builtin_vars(self, args)
1587	PyObject *self;
1588	PyObject *args;
1589{
1590	PyObject *v = NULL;
1591	PyObject *d;
1592
1593	if (!PyArg_ParseTuple(args, "|O:vars", &v))
1594		return NULL;
1595	if (v == NULL) {
1596		d = PyEval_GetLocals();
1597		if (d == NULL) {
1598			if (!PyErr_Occurred())
1599				PyErr_SetString(PyExc_SystemError,
1600						"no locals!?");
1601		}
1602		else
1603			Py_INCREF(d);
1604	}
1605	else {
1606		d = PyObject_GetAttrString(v, "__dict__");
1607		if (d == NULL) {
1608			PyErr_SetString(PyExc_TypeError,
1609			    "vars() argument must have __dict__ attribute");
1610			return NULL;
1611		}
1612	}
1613	return d;
1614}
1615
1616static PyMethodDef builtin_methods[] = {
1617	{"__import__",	builtin___import__, 1},
1618	{"abs",		builtin_abs, 1},
1619	{"apply",	builtin_apply, 1},
1620	{"callable",	builtin_callable, 1},
1621	{"chr",		builtin_chr, 1},
1622	{"cmp",		builtin_cmp, 1},
1623	{"coerce",	builtin_coerce, 1},
1624	{"compile",	builtin_compile, 1},
1625#ifndef WITHOUT_COMPLEX
1626	{"complex",	builtin_complex, 1},
1627#endif
1628	{"delattr",	builtin_delattr, 1},
1629	{"dir",		builtin_dir, 1},
1630	{"divmod",	builtin_divmod, 1},
1631	{"eval",	builtin_eval, 1},
1632	{"execfile",	builtin_execfile, 1},
1633	{"filter",	builtin_filter, 1},
1634	{"float",	builtin_float, 1},
1635	{"getattr",	builtin_getattr, 1},
1636	{"globals",	builtin_globals, 1},
1637	{"hasattr",	builtin_hasattr, 1},
1638	{"hash",	builtin_hash, 1},
1639	{"hex",		builtin_hex, 1},
1640	{"id",		builtin_id, 1},
1641	{"input",	builtin_input, 1},
1642	{"intern",	builtin_intern, 1},
1643	{"int",		builtin_int, 1},
1644	{"len",		builtin_len, 1},
1645	{"list",	builtin_list, 1},
1646	{"locals",	builtin_locals, 1},
1647	{"long",	builtin_long, 1},
1648	{"map",		builtin_map, 1},
1649	{"max",		builtin_max, 1},
1650	{"min",		builtin_min, 1},
1651	{"oct",		builtin_oct, 1},
1652	{"open",	builtin_open, 1},
1653	{"ord",		builtin_ord, 1},
1654	{"pow",		builtin_pow, 1},
1655	{"range",	builtin_range, 1},
1656	{"raw_input",	builtin_raw_input, 1},
1657	{"reduce",	builtin_reduce, 1},
1658	{"reload",	builtin_reload, 1},
1659	{"repr",	builtin_repr, 1},
1660	{"round",	builtin_round, 1},
1661	{"setattr",	builtin_setattr, 1},
1662	{"slice",       builtin_slice, 1},
1663	{"str",		builtin_str, 1},
1664	{"tuple",	builtin_tuple, 1},
1665	{"type",	builtin_type, 1},
1666	{"vars",	builtin_vars, 1},
1667	{"xrange",	builtin_xrange, 1},
1668	{NULL,		NULL},
1669};
1670
1671static PyObject *builtin_mod;
1672static PyObject *builtin_dict;
1673
1674PyObject *
1675PyBuiltin_GetModule()
1676{
1677	return builtin_mod;
1678}
1679
1680PyObject *
1681PyBuiltin_GetDict()
1682{
1683	return builtin_dict;
1684}
1685
1686/* Predefined exceptions */
1687
1688PyObject *PyExc_AccessError;
1689PyObject *PyExc_AssertionError;
1690PyObject *PyExc_AttributeError;
1691PyObject *PyExc_EOFError;
1692PyObject *PyExc_FloatingPointError;
1693PyObject *PyExc_IOError;
1694PyObject *PyExc_ImportError;
1695PyObject *PyExc_IndexError;
1696PyObject *PyExc_KeyError;
1697PyObject *PyExc_KeyboardInterrupt;
1698PyObject *PyExc_MemoryError;
1699PyObject *PyExc_NameError;
1700PyObject *PyExc_OverflowError;
1701PyObject *PyExc_RuntimeError;
1702PyObject *PyExc_SyntaxError;
1703PyObject *PyExc_SystemError;
1704PyObject *PyExc_SystemExit;
1705PyObject *PyExc_TypeError;
1706PyObject *PyExc_ValueError;
1707PyObject *PyExc_ZeroDivisionError;
1708
1709static PyObject *
1710newstdexception(name)
1711	char *name;
1712{
1713	PyObject *v = PyString_FromString(name);
1714	if (v == NULL || PyDict_SetItemString(builtin_dict, name, v) != 0)
1715		Py_FatalError("no mem for new standard exception");
1716	return v;
1717}
1718
1719static void
1720initerrors()
1721{
1722	PyExc_AccessError = newstdexception("AccessError");
1723	PyExc_AssertionError = newstdexception("AssertionError");
1724	PyExc_AttributeError = newstdexception("AttributeError");
1725	PyExc_EOFError = newstdexception("EOFError");
1726	PyExc_FloatingPointError = newstdexception("FloatingPointError");
1727	PyExc_IOError = newstdexception("IOError");
1728	PyExc_ImportError = newstdexception("ImportError");
1729	PyExc_IndexError = newstdexception("IndexError");
1730	PyExc_KeyError = newstdexception("KeyError");
1731	PyExc_KeyboardInterrupt = newstdexception("KeyboardInterrupt");
1732	PyExc_MemoryError = newstdexception("MemoryError");
1733	PyExc_NameError = newstdexception("NameError");
1734	PyExc_OverflowError = newstdexception("OverflowError");
1735	PyExc_RuntimeError = newstdexception("RuntimeError");
1736	PyExc_SyntaxError = newstdexception("SyntaxError");
1737	PyExc_SystemError = newstdexception("SystemError");
1738	PyExc_SystemExit = newstdexception("SystemExit");
1739	PyExc_TypeError = newstdexception("TypeError");
1740	PyExc_ValueError = newstdexception("ValueError");
1741	PyExc_ZeroDivisionError = newstdexception("ZeroDivisionError");
1742}
1743
1744void
1745PyBuiltin_Init()
1746{
1747	builtin_mod = Py_InitModule("__builtin__", builtin_methods);
1748	builtin_dict = PyModule_GetDict(builtin_mod);
1749	Py_INCREF(builtin_dict);
1750	initerrors();
1751	(void) PyDict_SetItemString(builtin_dict, "None", Py_None);
1752	(void) PyDict_SetItemString(builtin_dict, "Ellipsis", Py_Ellipsis);
1753	(void) PyDict_SetItemString(builtin_dict, "__debug__",
1754			  PyInt_FromLong(Py_OptimizeFlag == 0));
1755	if (PyErr_Occurred())
1756		Py_FatalError(
1757		  "error creating None/Ellipsis/__debug__ in __builtin__");
1758}
1759
1760
1761/* Helper for filter(): filter a tuple through a function */
1762
1763static PyObject *
1764filtertuple(func, tuple)
1765	PyObject *func;
1766	PyObject *tuple;
1767{
1768	PyObject *result;
1769	register int i, j;
1770	int len = PyTuple_Size(tuple);
1771
1772	if (len == 0) {
1773		Py_INCREF(tuple);
1774		return tuple;
1775	}
1776
1777	if ((result = PyTuple_New(len)) == NULL)
1778		return NULL;
1779
1780	for (i = j = 0; i < len; ++i) {
1781		PyObject *item, *good;
1782		int ok;
1783
1784		if ((item = PyTuple_GetItem(tuple, i)) == NULL)
1785			goto Fail_1;
1786		if (func == Py_None) {
1787			Py_INCREF(item);
1788			good = item;
1789		}
1790		else {
1791			PyObject *arg = Py_BuildValue("(O)", item);
1792			if (arg == NULL)
1793				goto Fail_1;
1794			good = PyEval_CallObject(func, arg);
1795			Py_DECREF(arg);
1796			if (good == NULL)
1797				goto Fail_1;
1798		}
1799		ok = PyObject_IsTrue(good);
1800		Py_DECREF(good);
1801		if (ok) {
1802			Py_INCREF(item);
1803			if (PyTuple_SetItem(result, j++, item) < 0)
1804				goto Fail_1;
1805		}
1806	}
1807
1808	if (_PyTuple_Resize(&result, j, 0) < 0)
1809		return NULL;
1810
1811	return result;
1812
1813Fail_1:
1814	Py_DECREF(result);
1815	return NULL;
1816}
1817
1818
1819/* Helper for filter(): filter a string through a function */
1820
1821static PyObject *
1822filterstring(func, strobj)
1823	PyObject *func;
1824	PyObject *strobj;
1825{
1826	PyObject *result;
1827	register int i, j;
1828	int len = PyString_Size(strobj);
1829
1830	if (func == Py_None) {
1831		/* No character is ever false -- share input string */
1832		Py_INCREF(strobj);
1833		return strobj;
1834	}
1835	if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
1836		return NULL;
1837
1838	for (i = j = 0; i < len; ++i) {
1839		PyObject *item, *arg, *good;
1840		int ok;
1841
1842		item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
1843		if (item == NULL)
1844			goto Fail_1;
1845		arg = Py_BuildValue("(O)", item);
1846		Py_DECREF(item);
1847		if (arg == NULL)
1848			goto Fail_1;
1849		good = PyEval_CallObject(func, arg);
1850		Py_DECREF(arg);
1851		if (good == NULL)
1852			goto Fail_1;
1853		ok = PyObject_IsTrue(good);
1854		Py_DECREF(good);
1855		if (ok)
1856			PyString_AS_STRING((PyStringObject *)result)[j++] =
1857				PyString_AS_STRING((PyStringObject *)item)[0];
1858	}
1859
1860	if (j < len && _PyString_Resize(&result, j) < 0)
1861		return NULL;
1862
1863	return result;
1864
1865Fail_1:
1866	Py_DECREF(result);
1867	return NULL;
1868}
1869
1870/* Copied with modifications from stropmodule.c: atoi,atof.atol */
1871
1872static PyObject *
1873int_from_string(v)
1874	PyObject *v;
1875{
1876	extern long PyOS_strtol Py_PROTO((const char *, char **, int));
1877	char *s, *end;
1878	long x;
1879	char buffer[256]; /* For errors */
1880
1881	if (!PyArg_Parse(v, "s", &s))
1882		return NULL;
1883	while (*s && isspace(Py_CHARMASK(*s)))
1884		s++;
1885	if (s[0] == '\0') {
1886		PyErr_SetString(PyExc_ValueError, "empty string for int()");
1887		return NULL;
1888	}
1889	errno = 0;
1890	x = PyOS_strtol(s, &end, 10);
1891	while (*end && isspace(Py_CHARMASK(*end)))
1892		end++;
1893	if (*end != '\0') {
1894		sprintf(buffer, "invalid literal for int(): %.200s", s);
1895		PyErr_SetString(PyExc_ValueError, buffer);
1896		return NULL;
1897	}
1898	else if (errno != 0) {
1899		sprintf(buffer, "int() literal too large: %.200s", s);
1900		PyErr_SetString(PyExc_ValueError, buffer);
1901		return NULL;
1902	}
1903	return PyInt_FromLong(x);
1904}
1905
1906static PyObject *
1907long_from_string(v)
1908	PyObject *v;
1909{
1910	char *s, *end;
1911	PyObject *x;
1912	char buffer[256]; /* For errors */
1913
1914	if (!PyArg_Parse(v, "s", &s))
1915		return NULL;
1916
1917	while (*s && isspace(Py_CHARMASK(*s)))
1918		s++;
1919	if (s[0] == '\0') {
1920		PyErr_SetString(PyExc_ValueError, "empty string for long()");
1921		return NULL;
1922	}
1923	x = PyLong_FromString(s, &end, 10);
1924	if (x == NULL)
1925		return NULL;
1926	while (*end && isspace(Py_CHARMASK(*end)))
1927		end++;
1928	if (*end != '\0') {
1929		sprintf(buffer, "invalid literal for long(): %.200s", s);
1930		PyErr_SetString(PyExc_ValueError, buffer);
1931		Py_DECREF(x);
1932		return NULL;
1933	}
1934	return x;
1935}
1936
1937static PyObject *
1938float_from_string(v)
1939	PyObject *v;
1940{
1941	extern double strtod Py_PROTO((const char *, char **));
1942	char *s, *end;
1943	double x;
1944	char buffer[256]; /* For errors */
1945
1946	if (!PyArg_Parse(v, "s", &s))
1947		return NULL;
1948	while (*s && isspace(Py_CHARMASK(*s)))
1949		s++;
1950	if (s[0] == '\0') {
1951		PyErr_SetString(PyExc_ValueError, "empty string for float()");
1952		return NULL;
1953	}
1954	errno = 0;
1955	PyFPE_START_PROTECT("float_from_string", return 0)
1956	x = strtod(s, &end);
1957	PyFPE_END_PROTECT(x)
1958	while (*end && isspace(Py_CHARMASK(*end)))
1959		end++;
1960	if (*end != '\0') {
1961		sprintf(buffer, "invalid literal for float(): %.200s", s);
1962		PyErr_SetString(PyExc_ValueError, buffer);
1963		return NULL;
1964	}
1965	else if (errno != 0) {
1966		sprintf(buffer, "float() literal too large: %.200s", s);
1967		PyErr_SetString(PyExc_ValueError, buffer);
1968		return NULL;
1969	}
1970	return PyFloat_FromDouble(x);
1971}
1972