bltinmodule.c revision b01a7fa5f8208fb5c767964e63b44f0a02814f62
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_ImportModuleEx(name, globals, locals, fromlist);
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_ExceptionMatches(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_ExceptionMatches(
730						PyExc_IndexError))
731					{
732						PyErr_Clear();
733						Py_INCREF(Py_None);
734						item = Py_None;
735						sqp->len = -1;
736					}
737					else {
738						goto Fail_0;
739					}
740				}
741				else
742					any = 1;
743
744			}
745			if (!alist)
746				break;
747			if (PyTuple_SetItem(alist, j, item) < 0) {
748				Py_DECREF(item);
749				goto Fail_0;
750			}
751			continue;
752
753		Fail_0:
754			Py_XDECREF(alist);
755			goto Fail_1;
756		}
757
758		if (!alist)
759			alist = item;
760
761		if (!any) {
762			Py_DECREF(alist);
763			break;
764		}
765
766		if (func == Py_None)
767			value = alist;
768		else {
769			value = PyEval_CallObject(func, alist);
770			Py_DECREF(alist);
771			if (value == NULL)
772				goto Fail_1;
773		}
774		if (i >= len) {
775			if (PyList_Append(result, value) < 0)
776				goto Fail_1;
777		}
778		else {
779			if (PyList_SetItem(result, i, value) < 0)
780				goto Fail_1;
781		}
782	}
783
784	PyMem_DEL(seqs);
785	return result;
786
787Fail_1:
788	Py_DECREF(result);
789Fail_2:
790	if (seqs) PyMem_DEL(seqs);
791	return NULL;
792}
793
794static PyObject *
795builtin_setattr(self, args)
796	PyObject *self;
797	PyObject *args;
798{
799	PyObject *v;
800	PyObject *name;
801	PyObject *value;
802
803	if (!PyArg_ParseTuple(args, "OSO:setattr", &v, &name, &value))
804		return NULL;
805	if (PyObject_SetAttr(v, name, value) != 0)
806		return NULL;
807	Py_INCREF(Py_None);
808	return Py_None;
809}
810
811static PyObject *
812builtin_delattr(self, args)
813	PyObject *self;
814	PyObject *args;
815{
816	PyObject *v;
817	PyObject *name;
818
819	if (!PyArg_ParseTuple(args, "OS:delattr", &v, &name))
820		return NULL;
821	if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
822		return NULL;
823	Py_INCREF(Py_None);
824	return Py_None;
825}
826
827static PyObject *
828builtin_hash(self, args)
829	PyObject *self;
830	PyObject *args;
831{
832	PyObject *v;
833	long x;
834
835	if (!PyArg_ParseTuple(args, "O:hash", &v))
836		return NULL;
837	x = PyObject_Hash(v);
838	if (x == -1)
839		return NULL;
840	return PyInt_FromLong(x);
841}
842
843static PyObject *
844builtin_hex(self, args)
845	PyObject *self;
846	PyObject *args;
847{
848	PyObject *v;
849	PyNumberMethods *nb;
850
851	if (!PyArg_ParseTuple(args, "O:hex", &v))
852		return NULL;
853
854	if ((nb = v->ob_type->tp_as_number) == NULL ||
855	    nb->nb_hex == NULL) {
856		PyErr_SetString(PyExc_TypeError,
857			   "hex() argument can't be converted to hex");
858		return NULL;
859	}
860	return (*nb->nb_hex)(v);
861}
862
863static PyObject *builtin_raw_input Py_PROTO((PyObject *, PyObject *));
864
865static PyObject *
866builtin_input(self, args)
867	PyObject *self;
868	PyObject *args;
869{
870	PyObject *line;
871	char *str;
872	PyObject *res;
873	PyObject *globals, *locals;
874
875	line = builtin_raw_input(self, args);
876	if (line == NULL)
877		return line;
878	if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
879		return NULL;
880	while (*str == ' ' || *str == '\t')
881			str++;
882	globals = PyEval_GetGlobals();
883	locals = PyEval_GetLocals();
884	if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
885		if (PyDict_SetItemString(globals, "__builtins__",
886					 PyEval_GetBuiltins()) != 0)
887			return NULL;
888	}
889	res = PyRun_String(str, Py_eval_input, globals, locals);
890	Py_DECREF(line);
891	return res;
892}
893
894static PyObject *
895builtin_intern(self, args)
896	PyObject *self;
897	PyObject *args;
898{
899	PyObject *s;
900	if (!PyArg_ParseTuple(args, "S", &s))
901		return NULL;
902	Py_INCREF(s);
903	PyString_InternInPlace(&s);
904	return s;
905}
906
907static PyObject *
908builtin_int(self, args)
909	PyObject *self;
910	PyObject *args;
911{
912	PyObject *v;
913	PyNumberMethods *nb;
914
915	if (!PyArg_ParseTuple(args, "O:int", &v))
916		return NULL;
917	if (PyString_Check(v))
918		return int_from_string(v);
919	if ((nb = v->ob_type->tp_as_number) == NULL ||
920	    nb->nb_int == NULL) {
921		PyErr_SetString(PyExc_TypeError,
922			   "int() argument can't be converted to int");
923		return NULL;
924	}
925	return (*nb->nb_int)(v);
926}
927
928static PyObject *
929builtin_len(self, args)
930	PyObject *self;
931	PyObject *args;
932{
933	PyObject *v;
934	long len;
935	PyTypeObject *tp;
936
937	if (!PyArg_ParseTuple(args, "O:len", &v))
938		return NULL;
939	tp = v->ob_type;
940	if (tp->tp_as_sequence != NULL) {
941		len = (*tp->tp_as_sequence->sq_length)(v);
942	}
943	else if (tp->tp_as_mapping != NULL) {
944		len = (*tp->tp_as_mapping->mp_length)(v);
945	}
946	else {
947		PyErr_SetString(PyExc_TypeError, "len() of unsized object");
948		return NULL;
949	}
950	if (len < 0)
951		return NULL;
952	else
953		return PyInt_FromLong(len);
954}
955
956static PyObject *
957builtin_list(self, args)
958	PyObject *self;
959	PyObject *args;
960{
961	PyObject *v;
962	PySequenceMethods *sqf;
963
964	if (!PyArg_ParseTuple(args, "O:list", &v))
965		return NULL;
966	if ((sqf = v->ob_type->tp_as_sequence) != NULL) {
967		int n = (*sqf->sq_length)(v);
968		int i;
969		PyObject *l;
970		if (n < 0)
971			return NULL;
972		l = PyList_New(n);
973		if (l == NULL)
974			return NULL;
975		for (i = 0; i < n; i++) {
976			PyObject *item = (*sqf->sq_item)(v, i);
977			if (item == NULL) {
978				Py_DECREF(l);
979				l = NULL;
980				break;
981			}
982			PyList_SetItem(l, i, item);
983		}
984		/* XXX Should support indefinite-length sequences */
985		return l;
986	}
987	PyErr_SetString(PyExc_TypeError, "list() argument must be a sequence");
988	return NULL;
989}
990
991
992static PyObject *
993builtin_slice(self, args)
994     PyObject *self;
995     PyObject *args;
996{
997  PyObject *start, *stop, *step;
998
999  start = stop = step = NULL;
1000
1001  if (!PyArg_ParseTuple(args, "O|OO:slice", &start, &stop, &step))
1002    return NULL;
1003
1004  /*This swapping of stop and start is to maintain compatibility with
1005    the range builtin.*/
1006  if (stop == NULL) {
1007    stop = start;
1008    start = NULL;
1009  }
1010  return PySlice_New(start, stop, step);
1011}
1012
1013static PyObject *
1014builtin_locals(self, args)
1015	PyObject *self;
1016	PyObject *args;
1017{
1018	PyObject *d;
1019
1020	if (!PyArg_ParseTuple(args, ""))
1021		return NULL;
1022	d = PyEval_GetLocals();
1023	Py_INCREF(d);
1024	return d;
1025}
1026
1027static PyObject *
1028builtin_long(self, args)
1029	PyObject *self;
1030	PyObject *args;
1031{
1032	PyObject *v;
1033	PyNumberMethods *nb;
1034
1035	if (!PyArg_ParseTuple(args, "O:long", &v))
1036		return NULL;
1037	if (PyString_Check(v))
1038		return long_from_string(v);
1039	if ((nb = v->ob_type->tp_as_number) == NULL ||
1040	    nb->nb_long == NULL) {
1041		PyErr_SetString(PyExc_TypeError,
1042			   "long() argument can't be converted to long");
1043		return NULL;
1044	}
1045	return (*nb->nb_long)(v);
1046}
1047
1048static PyObject *
1049min_max(args, sign)
1050	PyObject *args;
1051	int sign;
1052{
1053	int i;
1054	PyObject *v, *w, *x;
1055	PySequenceMethods *sq;
1056
1057	if (PyTuple_Size(args) > 1)
1058		v = args;
1059	else if (!PyArg_ParseTuple(args, "O:min/max", &v))
1060		return NULL;
1061	sq = v->ob_type->tp_as_sequence;
1062	if (sq == NULL) {
1063		PyErr_SetString(PyExc_TypeError,
1064				"min() or max() of non-sequence");
1065		return NULL;
1066	}
1067	w = NULL;
1068	for (i = 0; ; i++) {
1069		x = (*sq->sq_item)(v, i); /* Implies INCREF */
1070		if (x == NULL) {
1071			if (PyErr_ExceptionMatches(PyExc_IndexError)) {
1072				PyErr_Clear();
1073				break;
1074			}
1075			Py_XDECREF(w);
1076			return NULL;
1077		}
1078		if (w == NULL)
1079			w = x;
1080		else {
1081			int c = PyObject_Compare(x, w);
1082			if (c && PyErr_Occurred()) {
1083				Py_DECREF(x);
1084				Py_XDECREF(w);
1085				return NULL;
1086			}
1087			if (c * sign > 0) {
1088				Py_DECREF(w);
1089				w = x;
1090			}
1091			else
1092				Py_DECREF(x);
1093		}
1094	}
1095	if (w == NULL)
1096		PyErr_SetString(PyExc_ValueError,
1097				"min() or max() of empty sequence");
1098	return w;
1099}
1100
1101static PyObject *
1102builtin_min(self, v)
1103	PyObject *self;
1104	PyObject *v;
1105{
1106	return min_max(v, -1);
1107}
1108
1109static PyObject *
1110builtin_max(self, v)
1111	PyObject *self;
1112	PyObject *v;
1113{
1114	return min_max(v, 1);
1115}
1116
1117static PyObject *
1118builtin_oct(self, args)
1119	PyObject *self;
1120	PyObject *args;
1121{
1122	PyObject *v;
1123	PyNumberMethods *nb;
1124
1125	if (!PyArg_ParseTuple(args, "O:oct", &v))
1126		return NULL;
1127	if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1128	    nb->nb_oct == NULL) {
1129		PyErr_SetString(PyExc_TypeError,
1130			   "oct() argument can't be converted to oct");
1131		return NULL;
1132	}
1133	return (*nb->nb_oct)(v);
1134}
1135
1136static PyObject *
1137builtin_open(self, args)
1138	PyObject *self;
1139	PyObject *args;
1140{
1141	char *name;
1142	char *mode = "r";
1143	int bufsize = -1;
1144	PyObject *f;
1145
1146	if (!PyArg_ParseTuple(args, "s|si:open", &name, &mode, &bufsize))
1147		return NULL;
1148	f = PyFile_FromString(name, mode);
1149	if (f != NULL)
1150		PyFile_SetBufSize(f, bufsize);
1151	return f;
1152}
1153
1154static PyObject *
1155builtin_ord(self, args)
1156	PyObject *self;
1157	PyObject *args;
1158{
1159	char c;
1160
1161	if (!PyArg_ParseTuple(args, "c:ord", &c))
1162		return NULL;
1163	return PyInt_FromLong((long)(c & 0xff));
1164}
1165
1166static PyObject *
1167do_pow(v, w)
1168	PyObject *v, *w;
1169{
1170	PyObject *res;
1171	if (PyInstance_Check(v) || PyInstance_Check(w))
1172		return PyInstance_DoBinOp(v, w, "__pow__", "__rpow__", do_pow);
1173	if (v->ob_type->tp_as_number == NULL ||
1174	    w->ob_type->tp_as_number == NULL) {
1175		PyErr_SetString(PyExc_TypeError,
1176				"pow() requires numeric arguments");
1177		return NULL;
1178	}
1179	if (
1180#ifndef WITHOUT_COMPLEX
1181            !PyComplex_Check(v) &&
1182#endif
1183            PyFloat_Check(w) && PyFloat_AsDouble(v) < 0.0) {
1184		if (!PyErr_Occurred())
1185		    PyErr_SetString(PyExc_ValueError,
1186				    "negative number to float power");
1187		return NULL;
1188	}
1189	if (PyNumber_Coerce(&v, &w) != 0)
1190		return NULL;
1191	res = (*v->ob_type->tp_as_number->nb_power)(v, w, Py_None);
1192	Py_DECREF(v);
1193	Py_DECREF(w);
1194	return res;
1195}
1196
1197static PyObject *
1198builtin_pow(self, args)
1199	PyObject *self;
1200	PyObject *args;
1201{
1202	PyObject *v, *w, *z = Py_None, *res;
1203	PyObject *v1, *z1, *w2, *z2;
1204
1205	if (!PyArg_ParseTuple(args, "OO|O:pow", &v, &w, &z))
1206		return NULL;
1207	if (z == Py_None)
1208		return do_pow(v, w);
1209	/* XXX The ternary version doesn't do class instance coercions */
1210	if (PyInstance_Check(v))
1211		return v->ob_type->tp_as_number->nb_power(v, w, z);
1212	if (v->ob_type->tp_as_number == NULL ||
1213	    z->ob_type->tp_as_number == NULL ||
1214	    w->ob_type->tp_as_number == NULL) {
1215		PyErr_SetString(PyExc_TypeError,
1216				"pow() requires numeric arguments");
1217		return NULL;
1218	}
1219	if (PyNumber_Coerce(&v, &w) != 0)
1220		return NULL;
1221	res = NULL;
1222	v1 = v;
1223	z1 = z;
1224	if (PyNumber_Coerce(&v1, &z1) != 0)
1225		goto error2;
1226	w2 = w;
1227	z2 = z1;
1228 	if (PyNumber_Coerce(&w2, &z2) != 0)
1229		goto error1;
1230	res = (*v1->ob_type->tp_as_number->nb_power)(v1, w2, z2);
1231	Py_DECREF(w2);
1232	Py_DECREF(z2);
1233 error1:
1234	Py_DECREF(v1);
1235	Py_DECREF(z1);
1236 error2:
1237	Py_DECREF(v);
1238	Py_DECREF(w);
1239	return res;
1240}
1241
1242static PyObject *
1243builtin_range(self, args)
1244	PyObject *self;
1245	PyObject *args;
1246{
1247	long ilow = 0, ihigh = 0, istep = 1;
1248	int i, n;
1249	PyObject *v;
1250
1251	if (PyTuple_Size(args) <= 1) {
1252		if (!PyArg_ParseTuple(args,
1253				"l;range() requires 1-3 int arguments",
1254				&ihigh))
1255			return NULL;
1256	}
1257	else {
1258		if (!PyArg_ParseTuple(args,
1259				"ll|l;range() requires 1-3 int arguments",
1260				&ilow, &ihigh, &istep))
1261			return NULL;
1262	}
1263	if (istep == 0) {
1264		PyErr_SetString(PyExc_ValueError, "zero step for range()");
1265		return NULL;
1266	}
1267	/* XXX ought to check overflow of subtraction */
1268	if (istep > 0)
1269		n = (ihigh - ilow + istep - 1) / istep;
1270	else
1271		n = (ihigh - ilow + istep + 1) / istep;
1272	if (n < 0)
1273		n = 0;
1274	v = PyList_New(n);
1275	if (v == NULL)
1276		return NULL;
1277	for (i = 0; i < n; i++) {
1278		PyObject *w = PyInt_FromLong(ilow);
1279		if (w == NULL) {
1280			Py_DECREF(v);
1281			return NULL;
1282		}
1283		PyList_SetItem(v, i, w);
1284		ilow += istep;
1285	}
1286	return v;
1287}
1288
1289static PyObject *
1290builtin_xrange(self, args)
1291	PyObject *self;
1292	PyObject *args;
1293{
1294	long ilow = 0, ihigh = 0, istep = 1;
1295	long n;
1296
1297	if (PyTuple_Size(args) <= 1) {
1298		if (!PyArg_ParseTuple(args,
1299				"l;xrange() requires 1-3 int arguments",
1300				&ihigh))
1301			return NULL;
1302	}
1303	else {
1304		if (!PyArg_ParseTuple(args,
1305				"ll|l;xrange() requires 1-3 int arguments",
1306				&ilow, &ihigh, &istep))
1307			return NULL;
1308	}
1309	if (istep == 0) {
1310		PyErr_SetString(PyExc_ValueError, "zero step for xrange()");
1311		return NULL;
1312	}
1313	/* XXX ought to check overflow of subtraction */
1314	if (istep > 0)
1315		n = (ihigh - ilow + istep - 1) / istep;
1316	else
1317		n = (ihigh - ilow + istep + 1) / istep;
1318	if (n < 0)
1319		n = 0;
1320	return PyRange_New(ilow, n, istep, 1);
1321}
1322
1323extern char *PyOS_Readline Py_PROTO((char *));
1324
1325static PyObject *
1326builtin_raw_input(self, args)
1327	PyObject *self;
1328	PyObject *args;
1329{
1330	PyObject *v = NULL;
1331	PyObject *f;
1332
1333	if (!PyArg_ParseTuple(args, "|O:[raw_]input", &v))
1334		return NULL;
1335	if (PyFile_AsFile(PySys_GetObject("stdin")) == stdin &&
1336	    PyFile_AsFile(PySys_GetObject("stdout")) == stdout &&
1337	    isatty(fileno(stdin)) && isatty(fileno(stdout))) {
1338		PyObject *po;
1339		char *prompt;
1340		char *s;
1341		PyObject *result;
1342		if (v != NULL) {
1343			po = PyObject_Str(v);
1344			if (po == NULL)
1345				return NULL;
1346			prompt = PyString_AsString(po);
1347		}
1348		else {
1349			po = NULL;
1350			prompt = "";
1351		}
1352		s = PyOS_Readline(prompt);
1353		Py_XDECREF(po);
1354		if (s == NULL) {
1355			PyErr_SetNone(PyExc_KeyboardInterrupt);
1356			return NULL;
1357		}
1358		if (*s == '\0') {
1359			PyErr_SetNone(PyExc_EOFError);
1360			result = NULL;
1361		}
1362		else { /* strip trailing '\n' */
1363			result = PyString_FromStringAndSize(s, strlen(s)-1);
1364		}
1365		free(s);
1366		return result;
1367	}
1368	if (v != NULL) {
1369		f = PySys_GetObject("stdout");
1370		if (f == NULL) {
1371			PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1372			return NULL;
1373		}
1374		if (Py_FlushLine() != 0 ||
1375		    PyFile_WriteObject(v, f, Py_PRINT_RAW) != 0)
1376			return NULL;
1377	}
1378	f = PySys_GetObject("stdin");
1379	if (f == NULL) {
1380		PyErr_SetString(PyExc_RuntimeError, "lost sys.stdin");
1381		return NULL;
1382	}
1383	return PyFile_GetLine(f, -1);
1384}
1385
1386static PyObject *
1387builtin_reduce(self, args)
1388	PyObject *self;
1389	PyObject *args;
1390{
1391	PyObject *seq, *func, *result = NULL;
1392	PySequenceMethods *sqf;
1393	register int i;
1394
1395	if (!PyArg_ParseTuple(args, "OO|O:reduce", &func, &seq, &result))
1396		return NULL;
1397	if (result != NULL)
1398		Py_INCREF(result);
1399
1400	if ((sqf = seq->ob_type->tp_as_sequence) == NULL) {
1401		PyErr_SetString(PyExc_TypeError,
1402		    "2nd argument to reduce() must be a sequence object");
1403		return NULL;
1404	}
1405
1406	if ((args = PyTuple_New(2)) == NULL)
1407		goto Fail;
1408
1409	for (i = 0; ; ++i) {
1410		PyObject *op2;
1411
1412		if (args->ob_refcnt > 1) {
1413			Py_DECREF(args);
1414			if ((args = PyTuple_New(2)) == NULL)
1415				goto Fail;
1416		}
1417
1418		if ((op2 = (*sqf->sq_item)(seq, i)) == NULL) {
1419			if (PyErr_ExceptionMatches(PyExc_IndexError)) {
1420				PyErr_Clear();
1421				break;
1422			}
1423			goto Fail;
1424		}
1425
1426		if (result == NULL)
1427			result = op2;
1428		else {
1429			PyTuple_SetItem(args, 0, result);
1430			PyTuple_SetItem(args, 1, op2);
1431			if ((result = PyEval_CallObject(func, args)) == NULL)
1432				goto Fail;
1433		}
1434	}
1435
1436	Py_DECREF(args);
1437
1438	if (result == NULL)
1439		PyErr_SetString(PyExc_TypeError,
1440			   "reduce of empty sequence with no initial value");
1441
1442	return result;
1443
1444Fail:
1445	Py_XDECREF(args);
1446	Py_XDECREF(result);
1447	return NULL;
1448}
1449
1450static PyObject *
1451builtin_reload(self, args)
1452	PyObject *self;
1453	PyObject *args;
1454{
1455	PyObject *v;
1456
1457	if (!PyArg_ParseTuple(args, "O:reload", &v))
1458		return NULL;
1459	return PyImport_ReloadModule(v);
1460}
1461
1462static PyObject *
1463builtin_repr(self, args)
1464	PyObject *self;
1465	PyObject *args;
1466{
1467	PyObject *v;
1468
1469	if (!PyArg_ParseTuple(args, "O:repr", &v))
1470		return NULL;
1471	return PyObject_Repr(v);
1472}
1473
1474static PyObject *
1475builtin_round(self, args)
1476	PyObject *self;
1477	PyObject *args;
1478{
1479	double x;
1480	double f;
1481	int ndigits = 0;
1482	int i;
1483
1484	if (!PyArg_ParseTuple(args, "d|i:round", &x, &ndigits))
1485			return NULL;
1486	f = 1.0;
1487	for (i = ndigits; --i >= 0; )
1488		f = f*10.0;
1489	for (i = ndigits; ++i <= 0; )
1490		f = f*0.1;
1491	if (x >= 0.0)
1492		return PyFloat_FromDouble(floor(x*f + 0.5) / f);
1493	else
1494		return PyFloat_FromDouble(ceil(x*f - 0.5) / f);
1495}
1496
1497static PyObject *
1498builtin_str(self, args)
1499	PyObject *self;
1500	PyObject *args;
1501{
1502	PyObject *v;
1503
1504	if (!PyArg_ParseTuple(args, "O:str", &v))
1505		return NULL;
1506	return PyObject_Str(v);
1507}
1508
1509static PyObject *
1510builtin_tuple(self, args)
1511	PyObject *self;
1512	PyObject *args;
1513{
1514	PyObject *v;
1515	PySequenceMethods *sqf;
1516
1517	if (!PyArg_ParseTuple(args, "O:tuple", &v))
1518		return NULL;
1519	if (PyTuple_Check(v)) {
1520		Py_INCREF(v);
1521		return v;
1522	}
1523	if (PyList_Check(v))
1524		return PyList_AsTuple(v);
1525	if (PyString_Check(v)) {
1526		int n = PyString_Size(v);
1527		PyObject *t = PyTuple_New(n);
1528		if (t != NULL) {
1529			int i;
1530			char *p = PyString_AsString(v);
1531			for (i = 0; i < n; i++) {
1532				PyObject *item =
1533					PyString_FromStringAndSize(p+i, 1);
1534				if (item == NULL) {
1535					Py_DECREF(t);
1536					t = NULL;
1537					break;
1538				}
1539				PyTuple_SetItem(t, i, item);
1540			}
1541		}
1542		return t;
1543	}
1544	/* Generic sequence object */
1545	if ((sqf = v->ob_type->tp_as_sequence) != NULL) {
1546		int n = (*sqf->sq_length)(v);
1547		int i;
1548		PyObject *t;
1549		if (n < 0)
1550			return NULL;
1551		t = PyTuple_New(n);
1552		if (t == NULL)
1553			return NULL;
1554		for (i = 0; i < n; i++) {
1555			PyObject *item = (*sqf->sq_item)(v, i);
1556			if (item == NULL) {
1557				Py_DECREF(t);
1558				t = NULL;
1559				break;
1560			}
1561			PyTuple_SetItem(t, i, item);
1562		}
1563		/* XXX Should support indefinite-length sequences */
1564		return t;
1565	}
1566	/* None of the above */
1567	PyErr_SetString(PyExc_TypeError,
1568			"tuple() argument must be a sequence");
1569	return NULL;
1570}
1571
1572static PyObject *
1573builtin_type(self, args)
1574	PyObject *self;
1575	PyObject *args;
1576{
1577	PyObject *v;
1578
1579	if (!PyArg_ParseTuple(args, "O:type", &v))
1580		return NULL;
1581	v = (PyObject *)v->ob_type;
1582	Py_INCREF(v);
1583	return v;
1584}
1585
1586static PyObject *
1587builtin_vars(self, args)
1588	PyObject *self;
1589	PyObject *args;
1590{
1591	PyObject *v = NULL;
1592	PyObject *d;
1593
1594	if (!PyArg_ParseTuple(args, "|O:vars", &v))
1595		return NULL;
1596	if (v == NULL) {
1597		d = PyEval_GetLocals();
1598		if (d == NULL) {
1599			if (!PyErr_Occurred())
1600				PyErr_SetString(PyExc_SystemError,
1601						"no locals!?");
1602		}
1603		else
1604			Py_INCREF(d);
1605	}
1606	else {
1607		d = PyObject_GetAttrString(v, "__dict__");
1608		if (d == NULL) {
1609			PyErr_SetString(PyExc_TypeError,
1610			    "vars() argument must have __dict__ attribute");
1611			return NULL;
1612		}
1613	}
1614	return d;
1615}
1616
1617static PyObject *
1618builtin_isinstance(self, args)
1619     PyObject *self;
1620     PyObject *args;
1621{
1622	PyObject *inst;
1623	PyObject *cls;
1624	int retval;
1625
1626	if (!PyArg_ParseTuple(args, "OO", &inst, &cls))
1627		return NULL;
1628	if (!PyClass_Check(cls)) {
1629		PyErr_SetString(PyExc_TypeError,
1630				"second argument must be a class");
1631		return NULL;
1632	}
1633
1634	if (!PyInstance_Check(inst))
1635		retval = 0;
1636	else {
1637		PyObject *inclass =
1638			(PyObject*)((PyInstanceObject*)inst)->in_class;
1639		retval = PyClass_IsSubclass(inclass, cls);
1640	}
1641	return PyInt_FromLong(retval);
1642}
1643
1644
1645static PyObject *
1646builtin_issubclass(self, args)
1647     PyObject *self;
1648     PyObject *args;
1649{
1650	PyObject *derived;
1651	PyObject *cls;
1652	int retval;
1653
1654	if (!PyArg_ParseTuple(args, "OO", &derived, &cls))
1655		return NULL;
1656	if (!PyClass_Check(derived) || !PyClass_Check(cls)) {
1657		PyErr_SetString(PyExc_TypeError, "arguments must be classes");
1658		return NULL;
1659	}
1660	/* shortcut */
1661	if (!(retval = (derived == cls)))
1662		retval = PyClass_IsSubclass(derived, cls);
1663
1664	return PyInt_FromLong(retval);
1665}
1666
1667
1668static PyMethodDef builtin_methods[] = {
1669	{"__import__",	builtin___import__, 1},
1670	{"abs",		builtin_abs, 1},
1671	{"apply",	builtin_apply, 1},
1672	{"callable",	builtin_callable, 1},
1673	{"chr",		builtin_chr, 1},
1674	{"cmp",		builtin_cmp, 1},
1675	{"coerce",	builtin_coerce, 1},
1676	{"compile",	builtin_compile, 1},
1677#ifndef WITHOUT_COMPLEX
1678	{"complex",	builtin_complex, 1},
1679#endif
1680	{"delattr",	builtin_delattr, 1},
1681	{"dir",		builtin_dir, 1},
1682	{"divmod",	builtin_divmod, 1},
1683	{"eval",	builtin_eval, 1},
1684	{"execfile",	builtin_execfile, 1},
1685	{"filter",	builtin_filter, 1},
1686	{"float",	builtin_float, 1},
1687	{"getattr",	builtin_getattr, 1},
1688	{"globals",	builtin_globals, 1},
1689	{"hasattr",	builtin_hasattr, 1},
1690	{"hash",	builtin_hash, 1},
1691	{"hex",		builtin_hex, 1},
1692	{"id",		builtin_id, 1},
1693	{"input",	builtin_input, 1},
1694	{"intern",	builtin_intern, 1},
1695	{"int",		builtin_int, 1},
1696	{"isinstance",  builtin_isinstance, 1},
1697	{"issubclass",  builtin_issubclass, 1},
1698	{"len",		builtin_len, 1},
1699	{"list",	builtin_list, 1},
1700	{"locals",	builtin_locals, 1},
1701	{"long",	builtin_long, 1},
1702	{"map",		builtin_map, 1},
1703	{"max",		builtin_max, 1},
1704	{"min",		builtin_min, 1},
1705	{"oct",		builtin_oct, 1},
1706	{"open",	builtin_open, 1},
1707	{"ord",		builtin_ord, 1},
1708	{"pow",		builtin_pow, 1},
1709	{"range",	builtin_range, 1},
1710	{"raw_input",	builtin_raw_input, 1},
1711	{"reduce",	builtin_reduce, 1},
1712	{"reload",	builtin_reload, 1},
1713	{"repr",	builtin_repr, 1},
1714	{"round",	builtin_round, 1},
1715	{"setattr",	builtin_setattr, 1},
1716	{"slice",       builtin_slice, 1},
1717	{"str",		builtin_str, 1},
1718	{"tuple",	builtin_tuple, 1},
1719	{"type",	builtin_type, 1},
1720	{"vars",	builtin_vars, 1},
1721	{"xrange",	builtin_xrange, 1},
1722	{NULL,		NULL},
1723};
1724
1725/* Predefined exceptions */
1726
1727PyObject *PyExc_Exception;
1728PyObject *PyExc_StandardError;
1729PyObject *PyExc_ArithmeticError;
1730PyObject *PyExc_LookupError;
1731
1732PyObject *PyExc_AssertionError;
1733PyObject *PyExc_AttributeError;
1734PyObject *PyExc_EOFError;
1735PyObject *PyExc_FloatingPointError;
1736PyObject *PyExc_IOError;
1737PyObject *PyExc_ImportError;
1738PyObject *PyExc_IndexError;
1739PyObject *PyExc_KeyError;
1740PyObject *PyExc_KeyboardInterrupt;
1741PyObject *PyExc_MemoryError;
1742PyObject *PyExc_NameError;
1743PyObject *PyExc_OverflowError;
1744PyObject *PyExc_RuntimeError;
1745PyObject *PyExc_SyntaxError;
1746PyObject *PyExc_SystemError;
1747PyObject *PyExc_SystemExit;
1748PyObject *PyExc_TypeError;
1749PyObject *PyExc_ValueError;
1750PyObject *PyExc_ZeroDivisionError;
1751
1752PyObject *PyExc_MemoryErrorInst;
1753
1754static struct
1755{
1756	char* name;
1757	PyObject** exc;
1758	int leaf_exc;
1759}
1760bltin_exc[] = {
1761	{"Exception",          &PyExc_Exception,          0},
1762	{"StandardError",      &PyExc_StandardError,      0},
1763	{"ArithmeticError",    &PyExc_ArithmeticError,    0},
1764	{"LookupError",        &PyExc_LookupError,        0},
1765	{"AssertionError",     &PyExc_AssertionError,     1},
1766	{"AttributeError",     &PyExc_AttributeError,     1},
1767	{"EOFError",           &PyExc_EOFError,           1},
1768	{"FloatingPointError", &PyExc_FloatingPointError, 1},
1769	{"IOError",            &PyExc_IOError,            1},
1770	{"ImportError",        &PyExc_ImportError,        1},
1771	{"IndexError",         &PyExc_IndexError,         1},
1772	{"KeyError",           &PyExc_KeyError,           1},
1773	{"KeyboardInterrupt",  &PyExc_KeyboardInterrupt,  1},
1774	{"MemoryError",        &PyExc_MemoryError,        1},
1775	{"NameError",          &PyExc_NameError,          1},
1776	{"OverflowError",      &PyExc_OverflowError,      1},
1777	{"RuntimeError",       &PyExc_RuntimeError,       1},
1778	{"SyntaxError",        &PyExc_SyntaxError,        1},
1779	{"SystemError",        &PyExc_SystemError,        1},
1780	{"SystemExit",         &PyExc_SystemExit,         1},
1781	{"TypeError",          &PyExc_TypeError,          1},
1782	{"ValueError",         &PyExc_ValueError,         1},
1783	{"ZeroDivisionError",  &PyExc_ZeroDivisionError,  1},
1784	{NULL, NULL}
1785};
1786
1787
1788/* import exceptions module to extract class exceptions */
1789static void
1790init_class_exc(dict)
1791	PyObject *dict;
1792{
1793	int i;
1794	PyObject *m = PyImport_ImportModule("exceptions");
1795	PyObject *d;
1796	PyObject *args;
1797
1798	if (m == NULL ||
1799	    (d = PyModule_GetDict(m)) == NULL)
1800	{
1801		PyObject *f = PySys_GetObject("stderr");
1802		if (Py_VerboseFlag) {
1803			PyFile_WriteString(
1804				"'import exceptions' failed; traceback:\n", f);
1805			PyErr_Print();
1806		}
1807		else {
1808			PyFile_WriteString(
1809		      "'import exceptions' failed; use -v for traceback\n", f);
1810			PyErr_Clear();
1811		}
1812		PyFile_WriteString("defaulting to old style exceptions\n", f);
1813		return;
1814	}
1815	for (i = 0; bltin_exc[i].name; i++) {
1816		/* dig the exception out of the module */
1817		PyObject *exc = PyDict_GetItemString(d, bltin_exc[i].name);
1818		if (!exc)
1819		     Py_FatalError("built-in exception cannot be initialized");
1820
1821		Py_XDECREF(*bltin_exc[i].exc);
1822
1823		/* squirrel away a pointer to the exception */
1824		Py_INCREF(exc);
1825		*bltin_exc[i].exc = exc;
1826
1827		/* and insert the name in the __builtin__ module */
1828		PyDict_SetItemString(dict, bltin_exc[i].name, exc);
1829	}
1830
1831	/* we need one pre-allocated instance */
1832	args = Py_BuildValue("()");
1833	if (args) {
1834		PyExc_MemoryErrorInst =
1835			PyEval_CallObject(PyExc_MemoryError, args);
1836		Py_DECREF(args);
1837	}
1838
1839	/* we're done with the exceptions module */
1840	Py_DECREF(m);
1841
1842	if (PyErr_Occurred())
1843		Py_FatalError("can't instantiate standard exceptions");
1844}
1845
1846
1847static void
1848fini_instances()
1849{
1850	Py_XDECREF(PyExc_MemoryErrorInst);
1851	PyExc_MemoryErrorInst = NULL;
1852}
1853
1854
1855static PyObject *
1856newstdexception(dict, name)
1857	PyObject *dict;
1858	char *name;
1859{
1860	PyObject *v = PyString_FromString(name);
1861	if (v == NULL || PyDict_SetItemString(dict, name, v) != 0)
1862		Py_FatalError("no mem for new standard exception");
1863	return v;
1864}
1865
1866static void
1867initerrors(dict)
1868	PyObject *dict;
1869{
1870	int i;
1871	int exccnt = 0;
1872	for (i = 0; bltin_exc[i].name; i++, exccnt++) {
1873		if (bltin_exc[i].leaf_exc)
1874			*bltin_exc[i].exc =
1875				newstdexception(dict, bltin_exc[i].name);
1876	}
1877
1878	/* This is kind of bogus because we special case the three new
1879	   exceptions to be nearly forward compatible.  But this means we
1880	   hard code knowledge about exceptions.py into C here.  I don't
1881	   have a better solution, though
1882	*/
1883	PyExc_LookupError = PyTuple_New(2);
1884	Py_INCREF(PyExc_IndexError);
1885	PyTuple_SET_ITEM(PyExc_LookupError, 0, PyExc_IndexError);
1886	Py_INCREF(PyExc_KeyError);
1887	PyTuple_SET_ITEM(PyExc_LookupError, 1, PyExc_KeyError);
1888	PyDict_SetItemString(dict, "LookupError", PyExc_LookupError);
1889
1890	PyExc_ArithmeticError = PyTuple_New(3);
1891	Py_INCREF(PyExc_OverflowError);
1892	PyTuple_SET_ITEM(PyExc_ArithmeticError, 0, PyExc_OverflowError);
1893	Py_INCREF(PyExc_ZeroDivisionError);
1894	PyTuple_SET_ITEM(PyExc_ArithmeticError, 1, PyExc_ZeroDivisionError);
1895	Py_INCREF(PyExc_FloatingPointError);
1896	PyTuple_SET_ITEM(PyExc_ArithmeticError, 2, PyExc_FloatingPointError);
1897	PyDict_SetItemString(dict, "ArithmeticError", PyExc_ArithmeticError);
1898
1899	PyExc_StandardError = PyTuple_New(exccnt-2);
1900	for (i = 2; bltin_exc[i].name; i++) {
1901		PyObject *exc = *bltin_exc[i].exc;
1902		Py_INCREF(exc);
1903		PyTuple_SET_ITEM(PyExc_StandardError, i-2, exc);
1904	}
1905	PyDict_SetItemString(dict, "StandardError", PyExc_StandardError);
1906
1907	/* Exception is treated differently; for now, it's == StandardError */
1908	PyExc_Exception = PyExc_StandardError;
1909	Py_INCREF(PyExc_Exception);
1910	PyDict_SetItemString(dict, "Exception", PyExc_Exception);
1911
1912	if (PyErr_Occurred())
1913	      Py_FatalError("Could not initialize built-in string exceptions");
1914}
1915
1916static void
1917finierrors()
1918{
1919	int i;
1920	for (i = 0; bltin_exc[i].name; i++) {
1921		PyObject *exc = *bltin_exc[i].exc;
1922		Py_XDECREF(exc);
1923		*bltin_exc[i].exc = NULL;
1924	}
1925}
1926
1927PyObject *
1928_PyBuiltin_Init_1()
1929{
1930	PyObject *mod, *dict;
1931	mod = Py_InitModule("__builtin__", builtin_methods);
1932	if (mod == NULL)
1933		return NULL;
1934	dict = PyModule_GetDict(mod);
1935	initerrors(dict);
1936	if (PyDict_SetItemString(dict, "None", Py_None) < 0)
1937		return NULL;
1938	if (PyDict_SetItemString(dict, "Ellipsis", Py_Ellipsis) < 0)
1939		return NULL;
1940	if (PyDict_SetItemString(dict, "__debug__",
1941			  PyInt_FromLong(Py_OptimizeFlag == 0)) < 0)
1942		return NULL;
1943
1944	return mod;
1945}
1946
1947void
1948_PyBuiltin_Init_2(dict)
1949	PyObject *dict;
1950{
1951	/* if Python was started with -X, initialize the class exceptions */
1952	if (Py_UseClassExceptionsFlag)
1953		init_class_exc(dict);
1954}
1955
1956
1957void
1958_PyBuiltin_Fini_1()
1959{
1960	fini_instances();
1961}
1962
1963
1964void
1965_PyBuiltin_Fini_2()
1966{
1967	finierrors();
1968}
1969
1970
1971/* Helper for filter(): filter a tuple through a function */
1972
1973static PyObject *
1974filtertuple(func, tuple)
1975	PyObject *func;
1976	PyObject *tuple;
1977{
1978	PyObject *result;
1979	register int i, j;
1980	int len = PyTuple_Size(tuple);
1981
1982	if (len == 0) {
1983		Py_INCREF(tuple);
1984		return tuple;
1985	}
1986
1987	if ((result = PyTuple_New(len)) == NULL)
1988		return NULL;
1989
1990	for (i = j = 0; i < len; ++i) {
1991		PyObject *item, *good;
1992		int ok;
1993
1994		if ((item = PyTuple_GetItem(tuple, i)) == NULL)
1995			goto Fail_1;
1996		if (func == Py_None) {
1997			Py_INCREF(item);
1998			good = item;
1999		}
2000		else {
2001			PyObject *arg = Py_BuildValue("(O)", item);
2002			if (arg == NULL)
2003				goto Fail_1;
2004			good = PyEval_CallObject(func, arg);
2005			Py_DECREF(arg);
2006			if (good == NULL)
2007				goto Fail_1;
2008		}
2009		ok = PyObject_IsTrue(good);
2010		Py_DECREF(good);
2011		if (ok) {
2012			Py_INCREF(item);
2013			if (PyTuple_SetItem(result, j++, item) < 0)
2014				goto Fail_1;
2015		}
2016	}
2017
2018	if (_PyTuple_Resize(&result, j, 0) < 0)
2019		return NULL;
2020
2021	return result;
2022
2023Fail_1:
2024	Py_DECREF(result);
2025	return NULL;
2026}
2027
2028
2029/* Helper for filter(): filter a string through a function */
2030
2031static PyObject *
2032filterstring(func, strobj)
2033	PyObject *func;
2034	PyObject *strobj;
2035{
2036	PyObject *result;
2037	register int i, j;
2038	int len = PyString_Size(strobj);
2039
2040	if (func == Py_None) {
2041		/* No character is ever false -- share input string */
2042		Py_INCREF(strobj);
2043		return strobj;
2044	}
2045	if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2046		return NULL;
2047
2048	for (i = j = 0; i < len; ++i) {
2049		PyObject *item, *arg, *good;
2050		int ok;
2051
2052		item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2053		if (item == NULL)
2054			goto Fail_1;
2055		arg = Py_BuildValue("(O)", item);
2056		Py_DECREF(item);
2057		if (arg == NULL)
2058			goto Fail_1;
2059		good = PyEval_CallObject(func, arg);
2060		Py_DECREF(arg);
2061		if (good == NULL)
2062			goto Fail_1;
2063		ok = PyObject_IsTrue(good);
2064		Py_DECREF(good);
2065		if (ok)
2066			PyString_AS_STRING((PyStringObject *)result)[j++] =
2067				PyString_AS_STRING((PyStringObject *)item)[0];
2068	}
2069
2070	if (j < len && _PyString_Resize(&result, j) < 0)
2071		return NULL;
2072
2073	return result;
2074
2075Fail_1:
2076	Py_DECREF(result);
2077	return NULL;
2078}
2079
2080/* Copied with modifications from stropmodule.c: atoi,atof.atol */
2081
2082static PyObject *
2083int_from_string(v)
2084	PyObject *v;
2085{
2086	extern long PyOS_strtol Py_PROTO((const char *, char **, int));
2087	char *s, *end;
2088	long x;
2089	char buffer[256]; /* For errors */
2090
2091	if (!PyArg_Parse(v, "s", &s))
2092		return NULL;
2093	while (*s && isspace(Py_CHARMASK(*s)))
2094		s++;
2095	if (s[0] == '\0') {
2096		PyErr_SetString(PyExc_ValueError, "empty string for int()");
2097		return NULL;
2098	}
2099	errno = 0;
2100	x = PyOS_strtol(s, &end, 10);
2101	while (*end && isspace(Py_CHARMASK(*end)))
2102		end++;
2103	if (*end != '\0') {
2104		sprintf(buffer, "invalid literal for int(): %.200s", s);
2105		PyErr_SetString(PyExc_ValueError, buffer);
2106		return NULL;
2107	}
2108	else if (errno != 0) {
2109		sprintf(buffer, "int() literal too large: %.200s", s);
2110		PyErr_SetString(PyExc_ValueError, buffer);
2111		return NULL;
2112	}
2113	return PyInt_FromLong(x);
2114}
2115
2116static PyObject *
2117long_from_string(v)
2118	PyObject *v;
2119{
2120	char *s, *end;
2121	PyObject *x;
2122	char buffer[256]; /* For errors */
2123
2124	if (!PyArg_Parse(v, "s", &s))
2125		return NULL;
2126
2127	while (*s && isspace(Py_CHARMASK(*s)))
2128		s++;
2129	if (s[0] == '\0') {
2130		PyErr_SetString(PyExc_ValueError, "empty string for long()");
2131		return NULL;
2132	}
2133	x = PyLong_FromString(s, &end, 10);
2134	if (x == NULL)
2135		return NULL;
2136	while (*end && isspace(Py_CHARMASK(*end)))
2137		end++;
2138	if (*end != '\0') {
2139		sprintf(buffer, "invalid literal for long(): %.200s", s);
2140		PyErr_SetString(PyExc_ValueError, buffer);
2141		Py_DECREF(x);
2142		return NULL;
2143	}
2144	return x;
2145}
2146
2147static PyObject *
2148float_from_string(v)
2149	PyObject *v;
2150{
2151	extern double strtod Py_PROTO((const char *, char **));
2152	char *s, *end;
2153	double x;
2154	char buffer[256]; /* For errors */
2155
2156	if (!PyArg_Parse(v, "s", &s))
2157		return NULL;
2158	while (*s && isspace(Py_CHARMASK(*s)))
2159		s++;
2160	if (s[0] == '\0') {
2161		PyErr_SetString(PyExc_ValueError, "empty string for float()");
2162		return NULL;
2163	}
2164	errno = 0;
2165	PyFPE_START_PROTECT("float_from_string", return 0)
2166	x = strtod(s, &end);
2167	PyFPE_END_PROTECT(x)
2168	while (*end && isspace(Py_CHARMASK(*end)))
2169		end++;
2170	if (*end != '\0') {
2171		sprintf(buffer, "invalid literal for float(): %.200s", s);
2172		PyErr_SetString(PyExc_ValueError, buffer);
2173		return NULL;
2174	}
2175	else if (errno != 0) {
2176		sprintf(buffer, "float() literal too large: %.200s", s);
2177		PyErr_SetString(PyExc_ValueError, buffer);
2178		return NULL;
2179	}
2180	return PyFloat_FromDouble(x);
2181}
2182