abstract.c revision 6d6c1a35e08b95a83dbe47dbd9e6474daff00354
1/* Abstract Object Interface (many thanks to Jim Fulton) */
2
3
4#include "Python.h"
5#include <ctype.h>
6#include "structmember.h" /* we need the offsetof() macro from there */
7
8#define NEW_STYLE_NUMBER(o) PyType_HasFeature((o)->ob_type, \
9				Py_TPFLAGS_CHECKTYPES)
10
11/* Shorthands to return certain errors */
12
13static PyObject *
14type_error(const char *msg)
15{
16	PyErr_SetString(PyExc_TypeError, msg);
17	return NULL;
18}
19
20static PyObject *
21null_error(void)
22{
23	if (!PyErr_Occurred())
24		PyErr_SetString(PyExc_SystemError,
25				"null argument to internal routine");
26	return NULL;
27}
28
29/* Operations on any object */
30
31int
32PyObject_Cmp(PyObject *o1, PyObject *o2, int *result)
33{
34	int r;
35
36	if (o1 == NULL || o2 == NULL) {
37		null_error();
38		return -1;
39	}
40	r = PyObject_Compare(o1, o2);
41	if (PyErr_Occurred())
42		return -1;
43	*result = r;
44	return 0;
45}
46
47PyObject *
48PyObject_Type(PyObject *o)
49{
50	PyObject *v;
51
52	if (o == NULL)
53		return null_error();
54	v = (PyObject *)o->ob_type;
55	Py_INCREF(v);
56	return v;
57}
58
59int
60PyObject_Size(PyObject *o)
61{
62	PySequenceMethods *m;
63
64	if (o == NULL) {
65		null_error();
66		return -1;
67	}
68
69	m = o->ob_type->tp_as_sequence;
70	if (m && m->sq_length)
71		return m->sq_length(o);
72
73	return PyMapping_Size(o);
74}
75
76#undef PyObject_Length
77int
78PyObject_Length(PyObject *o)
79{
80	return PyObject_Size(o);
81}
82#define PyObject_Length PyObject_Size
83
84PyObject *
85PyObject_GetItem(PyObject *o, PyObject *key)
86{
87	PyMappingMethods *m;
88
89	if (o == NULL || key == NULL)
90		return null_error();
91
92	m = o->ob_type->tp_as_mapping;
93	if (m && m->mp_subscript)
94		return m->mp_subscript(o, key);
95
96	if (o->ob_type->tp_as_sequence) {
97		if (PyInt_Check(key))
98			return PySequence_GetItem(o, PyInt_AsLong(key));
99		else if (PyLong_Check(key)) {
100			long key_value = PyLong_AsLong(key);
101			if (key_value == -1 && PyErr_Occurred())
102				return NULL;
103			return PySequence_GetItem(o, key_value);
104		}
105		return type_error("sequence index must be integer");
106	}
107
108	return type_error("unsubscriptable object");
109}
110
111int
112PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
113{
114	PyMappingMethods *m;
115
116	if (o == NULL || key == NULL || value == NULL) {
117		null_error();
118		return -1;
119	}
120	m = o->ob_type->tp_as_mapping;
121	if (m && m->mp_ass_subscript)
122		return m->mp_ass_subscript(o, key, value);
123
124	if (o->ob_type->tp_as_sequence) {
125		if (PyInt_Check(key))
126			return PySequence_SetItem(o, PyInt_AsLong(key), value);
127		else if (PyLong_Check(key)) {
128			long key_value = PyLong_AsLong(key);
129			if (key_value == -1 && PyErr_Occurred())
130				return -1;
131			return PySequence_SetItem(o, key_value, value);
132		}
133		type_error("sequence index must be integer");
134		return -1;
135	}
136
137	type_error("object does not support item assignment");
138	return -1;
139}
140
141int
142PyObject_DelItem(PyObject *o, PyObject *key)
143{
144	PyMappingMethods *m;
145
146	if (o == NULL || key == NULL) {
147		null_error();
148		return -1;
149	}
150	m = o->ob_type->tp_as_mapping;
151	if (m && m->mp_ass_subscript)
152		return m->mp_ass_subscript(o, key, (PyObject*)NULL);
153
154	if (o->ob_type->tp_as_sequence) {
155		if (PyInt_Check(key))
156			return PySequence_DelItem(o, PyInt_AsLong(key));
157		else if (PyLong_Check(key)) {
158			long key_value = PyLong_AsLong(key);
159			if (key_value == -1 && PyErr_Occurred())
160				return -1;
161			return PySequence_DelItem(o, key_value);
162		}
163		type_error("sequence index must be integer");
164		return -1;
165	}
166
167	type_error("object does not support item deletion");
168	return -1;
169}
170
171int PyObject_AsCharBuffer(PyObject *obj,
172			  const char **buffer,
173			  int *buffer_len)
174{
175	PyBufferProcs *pb;
176	const char *pp;
177	int len;
178
179	if (obj == NULL || buffer == NULL || buffer_len == NULL) {
180		null_error();
181		return -1;
182	}
183	pb = obj->ob_type->tp_as_buffer;
184	if ( pb == NULL ||
185	     pb->bf_getcharbuffer == NULL ||
186	     pb->bf_getsegcount == NULL ) {
187		PyErr_SetString(PyExc_TypeError,
188				"expected a character buffer object");
189		goto onError;
190	}
191	if ( (*pb->bf_getsegcount)(obj,NULL) != 1 ) {
192		PyErr_SetString(PyExc_TypeError,
193				"expected a single-segment buffer object");
194		goto onError;
195	}
196	len = (*pb->bf_getcharbuffer)(obj,0,&pp);
197	if (len < 0)
198		goto onError;
199	*buffer = pp;
200	*buffer_len = len;
201	return 0;
202
203 onError:
204	return -1;
205}
206
207int PyObject_AsReadBuffer(PyObject *obj,
208			  const void **buffer,
209			  int *buffer_len)
210{
211	PyBufferProcs *pb;
212	void *pp;
213	int len;
214
215	if (obj == NULL || buffer == NULL || buffer_len == NULL) {
216		null_error();
217		return -1;
218	}
219	pb = obj->ob_type->tp_as_buffer;
220	if ( pb == NULL ||
221	     pb->bf_getreadbuffer == NULL ||
222	     pb->bf_getsegcount == NULL ) {
223		PyErr_SetString(PyExc_TypeError,
224				"expected a readable buffer object");
225		goto onError;
226	}
227	if ( (*pb->bf_getsegcount)(obj,NULL) != 1 ) {
228		PyErr_SetString(PyExc_TypeError,
229				"expected a single-segment buffer object");
230		goto onError;
231	}
232	len = (*pb->bf_getreadbuffer)(obj,0,&pp);
233	if (len < 0)
234		goto onError;
235	*buffer = pp;
236	*buffer_len = len;
237	return 0;
238
239 onError:
240	return -1;
241}
242
243int PyObject_AsWriteBuffer(PyObject *obj,
244			   void **buffer,
245			   int *buffer_len)
246{
247	PyBufferProcs *pb;
248	void*pp;
249	int len;
250
251	if (obj == NULL || buffer == NULL || buffer_len == NULL) {
252		null_error();
253		return -1;
254	}
255	pb = obj->ob_type->tp_as_buffer;
256	if ( pb == NULL ||
257	     pb->bf_getwritebuffer == NULL ||
258	     pb->bf_getsegcount == NULL ) {
259		PyErr_SetString(PyExc_TypeError,
260				"expected a writeable buffer object");
261		goto onError;
262	}
263	if ( (*pb->bf_getsegcount)(obj,NULL) != 1 ) {
264		PyErr_SetString(PyExc_TypeError,
265				"expected a single-segment buffer object");
266		goto onError;
267	}
268	len = (*pb->bf_getwritebuffer)(obj,0,&pp);
269	if (len < 0)
270		goto onError;
271	*buffer = pp;
272	*buffer_len = len;
273	return 0;
274
275 onError:
276	return -1;
277}
278
279/* Operations on numbers */
280
281int
282PyNumber_Check(PyObject *o)
283{
284	return o && o->ob_type->tp_as_number;
285}
286
287/* Binary operators */
288
289/* New style number protocol support */
290
291#define NB_SLOT(x) offsetof(PyNumberMethods, x)
292#define NB_BINOP(nb_methods, slot) \
293		((binaryfunc*)(& ((char*)nb_methods)[slot] ))
294#define NB_TERNOP(nb_methods, slot) \
295		((ternaryfunc*)(& ((char*)nb_methods)[slot] ))
296
297/*
298  Calling scheme used for binary operations:
299
300  v	w	Action
301  -------------------------------------------------------------------
302  new	new	v.op(v,w), w.op(v,w)
303  new	old	v.op(v,w), coerce(v,w), v.op(v,w)
304  old	new	w.op(v,w), coerce(v,w), v.op(v,w)
305  old	old	coerce(v,w), v.op(v,w)
306
307  Legend:
308  -------
309  * new == new style number
310  * old == old style number
311  * Action indicates the order in which operations are tried until either
312    a valid result is produced or an error occurs.
313
314 */
315
316static PyObject *
317binary_op1(PyObject *v, PyObject *w, const int op_slot)
318{
319	PyObject *x;
320	binaryfunc *slot;
321	if (v->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(v)) {
322		slot = NB_BINOP(v->ob_type->tp_as_number, op_slot);
323		if (*slot) {
324			x = (*slot)(v, w);
325			if (x != Py_NotImplemented) {
326				return x;
327			}
328			Py_DECREF(x); /* can't do it */
329		}
330		if (v->ob_type == w->ob_type) {
331			goto binop_error;
332		}
333	}
334	if (w->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(w)) {
335		slot = NB_BINOP(w->ob_type->tp_as_number, op_slot);
336		if (*slot) {
337			x = (*slot)(v, w);
338			if (x != Py_NotImplemented) {
339				return x;
340			}
341			Py_DECREF(x); /* can't do it */
342		}
343	}
344	if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w)) {
345		int err = PyNumber_CoerceEx(&v, &w);
346		if (err < 0) {
347			return NULL;
348		}
349		if (err == 0) {
350			PyNumberMethods *mv = v->ob_type->tp_as_number;
351			if (mv) {
352				slot = NB_BINOP(mv, op_slot);
353				if (*slot) {
354					PyObject *x = (*slot)(v, w);
355					Py_DECREF(v);
356					Py_DECREF(w);
357					return x;
358				}
359			}
360			/* CoerceEx incremented the reference counts */
361			Py_DECREF(v);
362			Py_DECREF(w);
363		}
364	}
365binop_error:
366	Py_INCREF(Py_NotImplemented);
367	return Py_NotImplemented;
368}
369
370static PyObject *
371binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
372{
373	PyObject *result = binary_op1(v, w, op_slot);
374	if (result == Py_NotImplemented) {
375		Py_DECREF(Py_NotImplemented);
376		PyErr_Format(PyExc_TypeError,
377				"unsupported operand type(s) for %s", op_name);
378		return NULL;
379	}
380	return result;
381}
382
383
384/*
385  Calling scheme used for ternary operations:
386
387  v	w	z	Action
388  -------------------------------------------------------------------
389  new	new	new	v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
390  new	old	new	v.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
391  old	new	new	w.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
392  old	old	new	z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
393  new	new	old	v.op(v,w,z), w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
394  new	old	old	v.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
395  old	new	old	w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
396  old	old	old	coerce(v,w,z), v.op(v,w,z)
397
398  Legend:
399  -------
400  * new == new style number
401  * old == old style number
402  * Action indicates the order in which operations are tried until either
403    a valid result is produced or an error occurs.
404  * coerce(v,w,z) actually does: coerce(v,w), coerce(v,z), coerce(w,z) and
405    only if z != Py_None; if z == Py_None, then it is treated as absent
406    variable and only coerce(v,w) is tried.
407
408 */
409
410static PyObject *
411ternary_op(PyObject *v,
412	   PyObject *w,
413	   PyObject *z,
414	   const int op_slot,
415	   const char *op_name)
416{
417	PyNumberMethods *mv, *mw, *mz;
418	register PyObject *x = NULL;
419	register ternaryfunc *slot;
420
421	mv = v->ob_type->tp_as_number;
422	if (mv != NULL && NEW_STYLE_NUMBER(v)) {
423		/* try v.op(v,w,z) */
424		slot = NB_TERNOP(mv, op_slot);
425		if (*slot) {
426			x = (*slot)(v, w, z);
427			if (x != Py_NotImplemented)
428				return x;
429			/* Can't do it... fall through */
430			Py_DECREF(x);
431		}
432		if (v->ob_type == w->ob_type &&
433				(z == Py_None || z->ob_type == v->ob_type)) {
434			goto ternary_error;
435		}
436	}
437	mw = w->ob_type->tp_as_number;
438	if (mw != NULL && NEW_STYLE_NUMBER(w)) {
439		/* try w.op(v,w,z) */
440		slot = NB_TERNOP(mw,op_slot);
441		if (*slot) {
442			x = (*slot)(v, w, z);
443			if (x != Py_NotImplemented)
444				return x;
445			/* Can't do it... fall through */
446			Py_DECREF(x);
447		}
448		if (NEW_STYLE_NUMBER(v) &&
449				(z == Py_None || z->ob_type == v->ob_type)) {
450			goto ternary_error;
451		}
452	}
453	mz = z->ob_type->tp_as_number;
454	if (mz != NULL && NEW_STYLE_NUMBER(z)) {
455		/* try: z.op(v,w,z) */
456		slot = NB_TERNOP(mz, op_slot);
457		if (*slot) {
458			x = (*slot)(v, w, z);
459			if (x != Py_NotImplemented)
460				return x;
461			/* Can't do it... fall through */
462			Py_DECREF(x);
463		}
464	}
465
466	if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w) ||
467			(z != Py_None && !NEW_STYLE_NUMBER(z))) {
468		/* we have an old style operand, coerce */
469		PyObject *v1, *z1, *w2, *z2;
470		int c;
471
472		c = PyNumber_Coerce(&v, &w);
473		if (c != 0)
474			goto error3;
475
476		/* Special case: if the third argument is None, it is
477		   treated as absent argument and not coerced. */
478		if (z == Py_None) {
479			if (v->ob_type->tp_as_number) {
480				slot = NB_TERNOP(v->ob_type->tp_as_number,
481						 op_slot);
482				if (*slot)
483					x = (*slot)(v, w, z);
484				else
485					c = -1;
486			}
487			else
488				c = -1;
489			goto error2;
490		}
491		v1 = v;
492		z1 = z;
493		c = PyNumber_Coerce(&v1, &z1);
494		if (c != 0)
495			goto error2;
496		w2 = w;
497		z2 = z1;
498		c = PyNumber_Coerce(&w2, &z2);
499		if (c != 0)
500			goto error1;
501
502		if (v1->ob_type->tp_as_number != NULL) {
503			slot = NB_TERNOP(v1->ob_type->tp_as_number,
504					 op_slot);
505			if (*slot)
506				x = (*slot)(v1, w2, z2);
507			else
508				c = -1;
509		}
510		else
511			c = -1;
512
513		Py_DECREF(w2);
514		Py_DECREF(z2);
515	error1:
516		Py_DECREF(v1);
517		Py_DECREF(z1);
518	error2:
519		Py_DECREF(v);
520		Py_DECREF(w);
521	error3:
522		if (c >= 0)
523			return x;
524	}
525
526ternary_error:
527	PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for %s",
528			op_name);
529	return NULL;
530}
531
532#define BINARY_FUNC(func, op, op_name) \
533    PyObject * \
534    func(PyObject *v, PyObject *w) { \
535	    return binary_op(v, w, NB_SLOT(op), op_name); \
536    }
537
538BINARY_FUNC(PyNumber_Or, nb_or, "|")
539BINARY_FUNC(PyNumber_Xor, nb_xor, "^")
540BINARY_FUNC(PyNumber_And, nb_and, "&")
541BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")
542BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")
543BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")
544BINARY_FUNC(PyNumber_Multiply, nb_multiply, "*")
545BINARY_FUNC(PyNumber_Divide, nb_divide, "/")
546BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
547
548PyObject *
549PyNumber_Add(PyObject *v, PyObject *w)
550{
551	PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
552	if (result == Py_NotImplemented) {
553		PySequenceMethods *m = v->ob_type->tp_as_sequence;
554		Py_DECREF(Py_NotImplemented);
555		if (m && m->sq_concat) {
556			result = (*m->sq_concat)(v, w);
557		}
558                else {
559                    PyErr_SetString(PyExc_TypeError,
560                                    "unsupported operand types for +");
561                    result = NULL;
562                }
563	}
564	return result;
565}
566
567PyObject *
568PyNumber_Remainder(PyObject *v, PyObject *w)
569{
570	if (PyString_Check(v))
571		return PyString_Format(v, w);
572	else if (PyUnicode_Check(v))
573		return PyUnicode_Format(v, w);
574	return binary_op(v, w, NB_SLOT(nb_remainder), "%");
575}
576
577PyObject *
578PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
579{
580	return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
581}
582
583/* Binary in-place operators */
584
585/* The in-place operators are defined to fall back to the 'normal',
586   non in-place operations, if the in-place methods are not in place.
587
588   - If the left hand object has the appropriate struct members, and
589     they are filled, call the appropriate function and return the
590     result.  No coercion is done on the arguments; the left-hand object
591     is the one the operation is performed on, and it's up to the
592     function to deal with the right-hand object.
593
594   - Otherwise, in-place modification is not supported. Handle it exactly as
595     a non in-place operation of the same kind.
596
597   */
598
599#define HASINPLACE(t) PyType_HasFeature((t)->ob_type, Py_TPFLAGS_HAVE_INPLACEOPS)
600
601static PyObject *
602binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
603		const char *op_name)
604{
605	PyNumberMethods *mv = v->ob_type->tp_as_number;
606	if (mv != NULL && HASINPLACE(v)) {
607		binaryfunc *slot = NB_BINOP(mv, iop_slot);
608		if (*slot) {
609			PyObject *x = (*slot)(v, w);
610			if (x != Py_NotImplemented) {
611				return x;
612			}
613			Py_DECREF(x);
614		}
615	}
616	return binary_op(v, w, op_slot, op_name);
617}
618
619#define INPLACE_BINOP(func, iop, op, op_name) \
620	PyObject * \
621	func(PyObject *v, PyObject *w) { \
622		return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
623	}
624
625INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
626INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
627INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")
628INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")
629INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")
630INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")
631INPLACE_BINOP(PyNumber_InPlaceDivide, nb_inplace_divide, nb_divide, "/=")
632
633PyObject *
634PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
635{
636	binaryfunc f = NULL;
637
638	if (v->ob_type->tp_as_sequence != NULL) {
639		if (HASINPLACE(v))
640			f = v->ob_type->tp_as_sequence->sq_inplace_concat;
641		if (f == NULL)
642			f = v->ob_type->tp_as_sequence->sq_concat;
643		if (f != NULL)
644			return (*f)(v, w);
645	}
646	return binary_iop(v, w, NB_SLOT(nb_inplace_add), NB_SLOT(nb_add), "+=");
647}
648
649PyObject *
650PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
651{
652	PyObject * (*g)(PyObject *, int) = NULL;
653	if (HASINPLACE(v) && v->ob_type->tp_as_sequence &&
654		(g = v->ob_type->tp_as_sequence->sq_inplace_repeat)) {
655		long n;
656		if (PyInt_Check(w)) {
657			n  = PyInt_AsLong(w);
658		}
659		else if (PyLong_Check(w)) {
660			n = PyLong_AsLong(w);
661			if (n == -1 && PyErr_Occurred())
662				return NULL;
663		}
664		else {
665			return type_error("can't multiply sequence to non-int");
666		}
667		return (*g)(v, (int)n);
668	}
669	return binary_iop(v, w, NB_SLOT(nb_inplace_multiply),
670				NB_SLOT(nb_multiply), "*=");
671}
672
673
674
675PyObject *
676PyNumber_InPlaceRemainder(PyObject *v, PyObject *w)
677{
678	if (PyString_Check(v))
679		return PyString_Format(v, w);
680	else if (PyUnicode_Check(v))
681		return PyUnicode_Format(v, w);
682	else
683		return binary_iop(v, w, NB_SLOT(nb_inplace_remainder),
684					NB_SLOT(nb_remainder), "%=");
685}
686
687
688PyObject *
689PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
690{
691	if (HASINPLACE(v) && v->ob_type->tp_as_number &&
692	    v->ob_type->tp_as_number->nb_inplace_power != NULL) {
693		return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**=");
694	}
695	else {
696		return ternary_op(v, w, z, NB_SLOT(nb_power), "**=");
697	}
698}
699
700
701/* Unary operators and functions */
702
703PyObject *
704PyNumber_Negative(PyObject *o)
705{
706	PyNumberMethods *m;
707
708	if (o == NULL)
709		return null_error();
710	m = o->ob_type->tp_as_number;
711	if (m && m->nb_negative)
712		return (*m->nb_negative)(o);
713
714	return type_error("bad operand type for unary -");
715}
716
717PyObject *
718PyNumber_Positive(PyObject *o)
719{
720	PyNumberMethods *m;
721
722	if (o == NULL)
723		return null_error();
724	m = o->ob_type->tp_as_number;
725	if (m && m->nb_positive)
726		return (*m->nb_positive)(o);
727
728	return type_error("bad operand type for unary +");
729}
730
731PyObject *
732PyNumber_Invert(PyObject *o)
733{
734	PyNumberMethods *m;
735
736	if (o == NULL)
737		return null_error();
738	m = o->ob_type->tp_as_number;
739	if (m && m->nb_invert)
740		return (*m->nb_invert)(o);
741
742	return type_error("bad operand type for unary ~");
743}
744
745PyObject *
746PyNumber_Absolute(PyObject *o)
747{
748	PyNumberMethods *m;
749
750	if (o == NULL)
751		return null_error();
752	m = o->ob_type->tp_as_number;
753	if (m && m->nb_absolute)
754		return m->nb_absolute(o);
755
756	return type_error("bad operand type for abs()");
757}
758
759/* Add a check for embedded NULL-bytes in the argument. */
760static PyObject *
761int_from_string(const char *s, int len)
762{
763	char *end;
764	PyObject *x;
765
766	x = PyInt_FromString((char*)s, &end, 10);
767	if (x == NULL)
768		return NULL;
769	if (end != s + len) {
770		PyErr_SetString(PyExc_ValueError,
771				"null byte in argument for int()");
772		Py_DECREF(x);
773		return NULL;
774	}
775	return x;
776}
777
778PyObject *
779PyNumber_Int(PyObject *o)
780{
781	PyNumberMethods *m;
782	const char *buffer;
783	int buffer_len;
784
785	if (o == NULL)
786		return null_error();
787	if (PyInt_Check(o)) {
788		Py_INCREF(o);
789		return o;
790	}
791	if (PyString_Check(o))
792		return int_from_string(PyString_AS_STRING(o),
793				       PyString_GET_SIZE(o));
794	if (PyUnicode_Check(o))
795		return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o),
796					 PyUnicode_GET_SIZE(o),
797					 10);
798	m = o->ob_type->tp_as_number;
799	if (m && m->nb_int)
800		return m->nb_int(o);
801	if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
802		return int_from_string((char*)buffer, buffer_len);
803
804	return type_error("object can't be converted to int");
805}
806
807/* Add a check for embedded NULL-bytes in the argument. */
808static PyObject *
809long_from_string(const char *s, int len)
810{
811	char *end;
812	PyObject *x;
813
814	x = PyLong_FromString((char*)s, &end, 10);
815	if (x == NULL)
816		return NULL;
817	if (end != s + len) {
818		PyErr_SetString(PyExc_ValueError,
819				"null byte in argument for long()");
820		Py_DECREF(x);
821		return NULL;
822	}
823	return x;
824}
825
826PyObject *
827PyNumber_Long(PyObject *o)
828{
829	PyNumberMethods *m;
830	const char *buffer;
831	int buffer_len;
832
833	if (o == NULL)
834		return null_error();
835	if (PyLong_Check(o)) {
836		Py_INCREF(o);
837		return o;
838	}
839	if (PyString_Check(o))
840		/* need to do extra error checking that PyLong_FromString()
841		 * doesn't do.  In particular long('9.5') must raise an
842		 * exception, not truncate the float.
843		 */
844		return long_from_string(PyString_AS_STRING(o),
845					PyString_GET_SIZE(o));
846	if (PyUnicode_Check(o))
847		/* The above check is done in PyLong_FromUnicode(). */
848		return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o),
849					  PyUnicode_GET_SIZE(o),
850					  10);
851	m = o->ob_type->tp_as_number;
852	if (m && m->nb_long)
853		return m->nb_long(o);
854	if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
855		return long_from_string(buffer, buffer_len);
856
857	return type_error("object can't be converted to long");
858}
859
860PyObject *
861PyNumber_Float(PyObject *o)
862{
863	PyNumberMethods *m;
864
865	if (o == NULL)
866		return null_error();
867	if (PyFloat_Check(o)) {
868		Py_INCREF(o);
869		return o;
870	}
871	if (!PyString_Check(o)) {
872		m = o->ob_type->tp_as_number;
873		if (m && m->nb_float)
874			return m->nb_float(o);
875	}
876	return PyFloat_FromString(o, NULL);
877}
878
879/* Operations on sequences */
880
881int
882PySequence_Check(PyObject *s)
883{
884	return s != NULL && s->ob_type->tp_as_sequence;
885}
886
887int
888PySequence_Size(PyObject *s)
889{
890	PySequenceMethods *m;
891
892	if (s == NULL) {
893		null_error();
894		return -1;
895	}
896
897	m = s->ob_type->tp_as_sequence;
898	if (m && m->sq_length)
899		return m->sq_length(s);
900
901	type_error("len() of unsized object");
902	return -1;
903}
904
905#undef PySequence_Length
906int
907PySequence_Length(PyObject *s)
908{
909	return PySequence_Size(s);
910}
911#define PySequence_Length PySequence_Size
912
913PyObject *
914PySequence_Concat(PyObject *s, PyObject *o)
915{
916	PySequenceMethods *m;
917
918	if (s == NULL || o == NULL)
919		return null_error();
920
921	m = s->ob_type->tp_as_sequence;
922	if (m && m->sq_concat)
923		return m->sq_concat(s, o);
924
925	return type_error("object can't be concatenated");
926}
927
928PyObject *
929PySequence_Repeat(PyObject *o, int count)
930{
931	PySequenceMethods *m;
932
933	if (o == NULL)
934		return null_error();
935
936	m = o->ob_type->tp_as_sequence;
937	if (m && m->sq_repeat)
938		return m->sq_repeat(o, count);
939
940	return type_error("object can't be repeated");
941}
942
943PyObject *
944PySequence_InPlaceConcat(PyObject *s, PyObject *o)
945{
946	PySequenceMethods *m;
947
948	if (s == NULL || o == NULL)
949		return null_error();
950
951	m = s->ob_type->tp_as_sequence;
952	if (m && HASINPLACE(s) && m->sq_inplace_concat)
953		return m->sq_inplace_concat(s, o);
954	if (m && m->sq_concat)
955		return m->sq_concat(s, o);
956
957	return type_error("object can't be concatenated");
958}
959
960PyObject *
961PySequence_InPlaceRepeat(PyObject *o, int count)
962{
963	PySequenceMethods *m;
964
965	if (o == NULL)
966		return null_error();
967
968	m = o->ob_type->tp_as_sequence;
969	if (m && HASINPLACE(o) && m->sq_inplace_repeat)
970		return m->sq_inplace_repeat(o, count);
971	if (m && m->sq_repeat)
972		return m->sq_repeat(o, count);
973
974	return type_error("object can't be repeated");
975}
976
977PyObject *
978PySequence_GetItem(PyObject *s, int i)
979{
980	PySequenceMethods *m;
981
982	if (s == NULL)
983		return null_error();
984
985	m = s->ob_type->tp_as_sequence;
986	if (m && m->sq_item) {
987		if (i < 0) {
988			if (m->sq_length) {
989				int l = (*m->sq_length)(s);
990				if (l < 0)
991					return NULL;
992				i += l;
993			}
994		}
995		return m->sq_item(s, i);
996	}
997
998	return type_error("unindexable object");
999}
1000
1001static PyObject *
1002sliceobj_from_intint(int i, int j)
1003{
1004	PyObject *start, *end, *slice;
1005	start = PyInt_FromLong((long)i);
1006	if (!start)
1007		return NULL;
1008	end = PyInt_FromLong((long)j);
1009	if (!end) {
1010		Py_DECREF(start);
1011		return NULL;
1012	}
1013	slice = PySlice_New(start, end, NULL);
1014	Py_DECREF(start);
1015	Py_DECREF(end);
1016	return slice;
1017}
1018
1019PyObject *
1020PySequence_GetSlice(PyObject *s, int i1, int i2)
1021{
1022	PySequenceMethods *m;
1023	PyMappingMethods *mp;
1024
1025	if (!s) return null_error();
1026
1027	m = s->ob_type->tp_as_sequence;
1028	if (m && m->sq_slice) {
1029		if (i1 < 0 || i2 < 0) {
1030			if (m->sq_length) {
1031				int l = (*m->sq_length)(s);
1032				if (l < 0)
1033					return NULL;
1034				if (i1 < 0)
1035					i1 += l;
1036				if (i2 < 0)
1037					i2 += l;
1038			}
1039		}
1040		return m->sq_slice(s, i1, i2);
1041	} else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_subscript) {
1042		PyObject *res;
1043		PyObject *slice = sliceobj_from_intint(i1, i2);
1044		if (!slice)
1045			return NULL;
1046		res = mp->mp_subscript(s, slice);
1047		Py_DECREF(slice);
1048		return res;
1049	}
1050
1051	return type_error("unsliceable object");
1052}
1053
1054int
1055PySequence_SetItem(PyObject *s, int i, PyObject *o)
1056{
1057	PySequenceMethods *m;
1058
1059	if (s == NULL) {
1060		null_error();
1061		return -1;
1062	}
1063
1064	m = s->ob_type->tp_as_sequence;
1065	if (m && m->sq_ass_item) {
1066		if (i < 0) {
1067			if (m->sq_length) {
1068				int l = (*m->sq_length)(s);
1069				if (l < 0)
1070					return -1;
1071				i += l;
1072			}
1073		}
1074		return m->sq_ass_item(s, i, o);
1075	}
1076
1077	type_error("object doesn't support item assignment");
1078	return -1;
1079}
1080
1081int
1082PySequence_DelItem(PyObject *s, int i)
1083{
1084	PySequenceMethods *m;
1085
1086	if (s == NULL) {
1087		null_error();
1088		return -1;
1089	}
1090
1091	m = s->ob_type->tp_as_sequence;
1092	if (m && m->sq_ass_item) {
1093		if (i < 0) {
1094			if (m->sq_length) {
1095				int l = (*m->sq_length)(s);
1096				if (l < 0)
1097					return -1;
1098				i += l;
1099			}
1100		}
1101		return m->sq_ass_item(s, i, (PyObject *)NULL);
1102	}
1103
1104	type_error("object doesn't support item deletion");
1105	return -1;
1106}
1107
1108int
1109PySequence_SetSlice(PyObject *s, int i1, int i2, PyObject *o)
1110{
1111	PySequenceMethods *m;
1112	PyMappingMethods *mp;
1113
1114	if (s == NULL) {
1115		null_error();
1116		return -1;
1117	}
1118
1119	m = s->ob_type->tp_as_sequence;
1120	if (m && m->sq_ass_slice) {
1121		if (i1 < 0 || i2 < 0) {
1122			if (m->sq_length) {
1123				int l = (*m->sq_length)(s);
1124				if (l < 0)
1125					return -1;
1126				if (i1 < 0)
1127					i1 += l;
1128				if (i2 < 0)
1129					i2 += l;
1130			}
1131		}
1132		return m->sq_ass_slice(s, i1, i2, o);
1133	} else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_ass_subscript) {
1134		int res;
1135		PyObject *slice = sliceobj_from_intint(i1, i2);
1136		if (!slice)
1137			return -1;
1138		res = mp->mp_ass_subscript(s, slice, o);
1139		Py_DECREF(slice);
1140		return res;
1141	}
1142
1143	type_error("object doesn't support slice assignment");
1144	return -1;
1145}
1146
1147int
1148PySequence_DelSlice(PyObject *s, int i1, int i2)
1149{
1150	PySequenceMethods *m;
1151
1152	if (s == NULL) {
1153		null_error();
1154		return -1;
1155	}
1156
1157	m = s->ob_type->tp_as_sequence;
1158	if (m && m->sq_ass_slice) {
1159		if (i1 < 0 || i2 < 0) {
1160			if (m->sq_length) {
1161				int l = (*m->sq_length)(s);
1162				if (l < 0)
1163					return -1;
1164				if (i1 < 0)
1165					i1 += l;
1166				if (i2 < 0)
1167					i2 += l;
1168			}
1169		}
1170		return m->sq_ass_slice(s, i1, i2, (PyObject *)NULL);
1171	}
1172	type_error("object doesn't support slice deletion");
1173	return -1;
1174}
1175
1176PyObject *
1177PySequence_Tuple(PyObject *v)
1178{
1179	PyObject *it;  /* iter(v) */
1180	int n;         /* guess for result tuple size */
1181	PyObject *result;
1182	int j;
1183
1184	if (v == NULL)
1185		return null_error();
1186
1187	/* Special-case the common tuple and list cases, for efficiency. */
1188	if (PyTuple_Check(v)) {
1189		Py_INCREF(v);
1190		return v;
1191	}
1192	if (PyList_Check(v))
1193		return PyList_AsTuple(v);
1194
1195	/* Get iterator. */
1196	it = PyObject_GetIter(v);
1197	if (it == NULL)
1198		return type_error("tuple() argument must support iteration");
1199
1200	/* Guess result size and allocate space. */
1201	n = PySequence_Size(v);
1202	if (n < 0) {
1203		PyErr_Clear();
1204		n = 10;  /* arbitrary */
1205	}
1206	result = PyTuple_New(n);
1207	if (result == NULL)
1208		goto Fail;
1209
1210	/* Fill the tuple. */
1211	for (j = 0; ; ++j) {
1212		PyObject *item = PyIter_Next(it);
1213		if (item == NULL) {
1214			if (PyErr_Occurred())
1215				goto Fail;
1216			break;
1217		}
1218		if (j >= n) {
1219			if (n < 500)
1220				n += 10;
1221			else
1222				n += 100;
1223			if (_PyTuple_Resize(&result, n) != 0) {
1224				Py_DECREF(item);
1225				goto Fail;
1226			}
1227		}
1228		PyTuple_SET_ITEM(result, j, item);
1229	}
1230
1231	/* Cut tuple back if guess was too large. */
1232	if (j < n &&
1233	    _PyTuple_Resize(&result, j) != 0)
1234		goto Fail;
1235
1236	Py_DECREF(it);
1237	return result;
1238
1239Fail:
1240	Py_XDECREF(result);
1241	Py_DECREF(it);
1242	return NULL;
1243}
1244
1245PyObject *
1246PySequence_List(PyObject *v)
1247{
1248	PyObject *it;      /* iter(v) */
1249	PyObject *result;  /* result list */
1250	int n;		   /* guess for result list size */
1251	int i;
1252
1253	if (v == NULL)
1254		return null_error();
1255
1256	/* Special-case list(a_list), for speed. */
1257	if (PyList_Check(v))
1258		return PyList_GetSlice(v, 0, PyList_GET_SIZE(v));
1259
1260	/* Get iterator.  There may be some low-level efficiency to be gained
1261	 * by caching the tp_iternext slot instead of using PyIter_Next()
1262	 * later, but premature optimization is the root etc.
1263	 */
1264	it = PyObject_GetIter(v);
1265	if (it == NULL)
1266		return NULL;
1267
1268	/* Guess a result list size. */
1269	n = -1;	 /* unknown */
1270	if (PySequence_Check(v) &&
1271	    v->ob_type->tp_as_sequence->sq_length) {
1272		n = PySequence_Size(v);
1273		if (n < 0)
1274			PyErr_Clear();
1275	}
1276	if (n < 0)
1277		n = 8;	/* arbitrary */
1278	result = PyList_New(n);
1279	if (result == NULL) {
1280		Py_DECREF(it);
1281		return NULL;
1282	}
1283
1284	/* Run iterator to exhaustion. */
1285	for (i = 0; ; i++) {
1286		PyObject *item = PyIter_Next(it);
1287		if (item == NULL) {
1288			if (PyErr_Occurred()) {
1289				Py_DECREF(result);
1290				result = NULL;
1291			}
1292			break;
1293		}
1294		if (i < n)
1295			PyList_SET_ITEM(result, i, item); /* steals ref */
1296		else {
1297			int status = PyList_Append(result, item);
1298			Py_DECREF(item);  /* append creates a new ref */
1299			if (status < 0) {
1300				Py_DECREF(result);
1301				result = NULL;
1302				break;
1303			}
1304		}
1305	}
1306
1307	/* Cut back result list if initial guess was too large. */
1308	if (i < n && result != NULL) {
1309		if (PyList_SetSlice(result, i, n, (PyObject *)NULL) != 0) {
1310			Py_DECREF(result);
1311			result = NULL;
1312		}
1313	}
1314	Py_DECREF(it);
1315	return result;
1316}
1317
1318PyObject *
1319PySequence_Fast(PyObject *v, const char *m)
1320{
1321	if (v == NULL)
1322		return null_error();
1323
1324	if (PyList_Check(v) || PyTuple_Check(v)) {
1325		Py_INCREF(v);
1326		return v;
1327	}
1328
1329	v = PySequence_Tuple(v);
1330	if (v == NULL && PyErr_ExceptionMatches(PyExc_TypeError))
1331		return type_error(m);
1332
1333	return v;
1334}
1335
1336/* Return # of times o appears in s. */
1337int
1338PySequence_Count(PyObject *s, PyObject *o)
1339{
1340	int n;  /* running count of o hits */
1341	PyObject *it;  /* iter(s) */
1342
1343	if (s == NULL || o == NULL) {
1344		null_error();
1345		return -1;
1346	}
1347
1348	it = PyObject_GetIter(s);
1349	if (it == NULL) {
1350		type_error(".count() requires iterable argument");
1351		return -1;
1352	}
1353
1354	n = 0;
1355	for (;;) {
1356		int cmp;
1357		PyObject *item = PyIter_Next(it);
1358		if (item == NULL) {
1359			if (PyErr_Occurred())
1360				goto Fail;
1361			break;
1362		}
1363		cmp = PyObject_RichCompareBool(o, item, Py_EQ);
1364		Py_DECREF(item);
1365		if (cmp < 0)
1366			goto Fail;
1367		if (cmp > 0) {
1368			if (n == INT_MAX) {
1369				PyErr_SetString(PyExc_OverflowError,
1370				                "count exceeds C int size");
1371				goto Fail;
1372			}
1373			n++;
1374		}
1375	}
1376	Py_DECREF(it);
1377	return n;
1378
1379Fail:
1380	Py_DECREF(it);
1381	return -1;
1382}
1383
1384/* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
1385 * Always uses the iteration protocol, and only Py_EQ comparison.
1386 */
1387int
1388_PySequence_IterContains(PyObject *seq, PyObject *ob)
1389{
1390	int result;
1391	PyObject *it = PyObject_GetIter(seq);
1392	if (it == NULL) {
1393		PyErr_SetString(PyExc_TypeError,
1394			"'in' or 'not in' needs iterable right argument");
1395		return -1;
1396	}
1397
1398	for (;;) {
1399		int cmp;
1400		PyObject *item = PyIter_Next(it);
1401		if (item == NULL) {
1402			result = PyErr_Occurred() ? -1 : 0;
1403			break;
1404		}
1405		cmp = PyObject_RichCompareBool(ob, item, Py_EQ);
1406		Py_DECREF(item);
1407		if (cmp == 0)
1408			continue;
1409		result = cmp > 0 ? 1 : -1;
1410		break;
1411	}
1412	Py_DECREF(it);
1413	return result;
1414}
1415
1416/* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
1417 * Use sq_contains if possible, else defer to _PySequence_IterContains().
1418 */
1419int
1420PySequence_Contains(PyObject *seq, PyObject *ob)
1421{
1422	if (PyType_HasFeature(seq->ob_type, Py_TPFLAGS_HAVE_SEQUENCE_IN)) {
1423		PySequenceMethods *sqm = seq->ob_type->tp_as_sequence;
1424	        if (sqm != NULL && sqm->sq_contains != NULL)
1425			return (*sqm->sq_contains)(seq, ob);
1426	}
1427	return _PySequence_IterContains(seq, ob);
1428}
1429
1430/* Backwards compatibility */
1431#undef PySequence_In
1432int
1433PySequence_In(PyObject *w, PyObject *v)
1434{
1435	return PySequence_Contains(w, v);
1436}
1437
1438int
1439PySequence_Index(PyObject *s, PyObject *o)
1440{
1441	int l, i, cmp, err;
1442	PyObject *item;
1443
1444	if (s == NULL || o == NULL) {
1445		null_error();
1446		return -1;
1447	}
1448
1449	l = PySequence_Size(s);
1450	if (l < 0)
1451		return -1;
1452
1453	for (i = 0; i < l; i++) {
1454		item = PySequence_GetItem(s, i);
1455		if (item == NULL)
1456			return -1;
1457		err = PyObject_Cmp(item, o, &cmp);
1458		Py_DECREF(item);
1459		if (err < 0)
1460			return err;
1461		if (cmp == 0)
1462			return i;
1463	}
1464
1465	PyErr_SetString(PyExc_ValueError, "sequence.index(x): x not in list");
1466	return -1;
1467}
1468
1469/* Operations on mappings */
1470
1471int
1472PyMapping_Check(PyObject *o)
1473{
1474	return o && o->ob_type->tp_as_mapping;
1475}
1476
1477int
1478PyMapping_Size(PyObject *o)
1479{
1480	PyMappingMethods *m;
1481
1482	if (o == NULL) {
1483		null_error();
1484		return -1;
1485	}
1486
1487	m = o->ob_type->tp_as_mapping;
1488	if (m && m->mp_length)
1489		return m->mp_length(o);
1490
1491	type_error("len() of unsized object");
1492	return -1;
1493}
1494
1495#undef PyMapping_Length
1496int
1497PyMapping_Length(PyObject *o)
1498{
1499	return PyMapping_Size(o);
1500}
1501#define PyMapping_Length PyMapping_Size
1502
1503PyObject *
1504PyMapping_GetItemString(PyObject *o, char *key)
1505{
1506	PyObject *okey, *r;
1507
1508	if (key == NULL)
1509		return null_error();
1510
1511	okey = PyString_FromString(key);
1512	if (okey == NULL)
1513		return NULL;
1514	r = PyObject_GetItem(o, okey);
1515	Py_DECREF(okey);
1516	return r;
1517}
1518
1519int
1520PyMapping_SetItemString(PyObject *o, char *key, PyObject *value)
1521{
1522	PyObject *okey;
1523	int r;
1524
1525	if (key == NULL) {
1526		null_error();
1527		return -1;
1528	}
1529
1530	okey = PyString_FromString(key);
1531	if (okey == NULL)
1532		return -1;
1533	r = PyObject_SetItem(o, okey, value);
1534	Py_DECREF(okey);
1535	return r;
1536}
1537
1538int
1539PyMapping_HasKeyString(PyObject *o, char *key)
1540{
1541	PyObject *v;
1542
1543	v = PyMapping_GetItemString(o, key);
1544	if (v) {
1545		Py_DECREF(v);
1546		return 1;
1547	}
1548	PyErr_Clear();
1549	return 0;
1550}
1551
1552int
1553PyMapping_HasKey(PyObject *o, PyObject *key)
1554{
1555	PyObject *v;
1556
1557	v = PyObject_GetItem(o, key);
1558	if (v) {
1559		Py_DECREF(v);
1560		return 1;
1561	}
1562	PyErr_Clear();
1563	return 0;
1564}
1565
1566/* Operations on callable objects */
1567
1568/* XXX PyCallable_Check() is in object.c */
1569
1570PyObject *
1571PyObject_CallObject(PyObject *o, PyObject *a)
1572{
1573	PyObject *r;
1574	PyObject *args = a;
1575
1576	if (args == NULL) {
1577		args = PyTuple_New(0);
1578		if (args == NULL)
1579			return NULL;
1580	}
1581
1582	r = PyEval_CallObject(o, args);
1583
1584	if (args != a) {
1585		Py_DECREF(args);
1586	}
1587
1588	return r;
1589}
1590
1591PyObject *
1592PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw)
1593{
1594        ternaryfunc call;
1595
1596	if ((call = func->ob_type->tp_call) != NULL) {
1597		PyObject *result = (*call)(func, arg, kw);
1598		if (result == NULL && !PyErr_Occurred())
1599			PyErr_SetString(
1600				PyExc_SystemError,
1601				"NULL result without error in PyObject_Call");
1602		return result;
1603	}
1604	PyErr_Format(PyExc_TypeError, "object is not callable: %s",
1605		     PyString_AS_STRING(PyObject_Repr(func)));
1606	return NULL;
1607}
1608
1609PyObject *
1610PyObject_CallFunction(PyObject *callable, char *format, ...)
1611{
1612	va_list va;
1613	PyObject *args, *retval;
1614	va_start(va, format);
1615
1616	if (callable == NULL) {
1617		va_end(va);
1618		return null_error();
1619	}
1620
1621	if (format)
1622		args = Py_VaBuildValue(format, va);
1623	else
1624		args = PyTuple_New(0);
1625
1626	va_end(va);
1627
1628	if (args == NULL)
1629		return NULL;
1630
1631	if (!PyTuple_Check(args)) {
1632		PyObject *a;
1633
1634		a = PyTuple_New(1);
1635		if (a == NULL)
1636			return NULL;
1637		if (PyTuple_SetItem(a, 0, args) < 0)
1638			return NULL;
1639		args = a;
1640	}
1641	retval = PyObject_CallObject(callable, args);
1642
1643	Py_DECREF(args);
1644
1645	return retval;
1646}
1647
1648PyObject *
1649PyObject_CallMethod(PyObject *o, char *name, char *format, ...)
1650{
1651	va_list va;
1652	PyObject *args, *func = 0, *retval;
1653	va_start(va, format);
1654
1655	if (o == NULL || name == NULL) {
1656		va_end(va);
1657		return null_error();
1658	}
1659
1660	func = PyObject_GetAttrString(o, name);
1661	if (func == NULL) {
1662		va_end(va);
1663		PyErr_SetString(PyExc_AttributeError, name);
1664		return 0;
1665	}
1666
1667	if (!PyCallable_Check(func)) {
1668		va_end(va);
1669		return type_error("call of non-callable attribute");
1670	}
1671
1672	if (format && *format)
1673		args = Py_VaBuildValue(format, va);
1674	else
1675		args = PyTuple_New(0);
1676
1677	va_end(va);
1678
1679	if (!args)
1680		return NULL;
1681
1682	if (!PyTuple_Check(args)) {
1683		PyObject *a;
1684
1685		a = PyTuple_New(1);
1686		if (a == NULL)
1687			return NULL;
1688		if (PyTuple_SetItem(a, 0, args) < 0)
1689			return NULL;
1690		args = a;
1691	}
1692
1693	retval = PyObject_CallObject(func, args);
1694
1695	Py_DECREF(args);
1696	Py_DECREF(func);
1697
1698	return retval;
1699}
1700
1701
1702/* isinstance(), issubclass() */
1703
1704static int
1705abstract_issubclass(PyObject *derived, PyObject *cls, int first)
1706{
1707	static PyObject *__bases__ = NULL;
1708	PyObject *bases;
1709	int i, n;
1710	int r = 0;
1711
1712	if (__bases__ == NULL) {
1713		__bases__ = PyString_FromString("__bases__");
1714		if (__bases__ == NULL)
1715			return -1;
1716	}
1717
1718	if (first) {
1719		bases = PyObject_GetAttr(cls, __bases__);
1720		if (bases == NULL || !PyTuple_Check(bases)) {
1721			Py_XDECREF(bases);
1722			PyErr_SetString(PyExc_TypeError,
1723					"issubclass() arg 2 must be a class");
1724			return -1;
1725		}
1726		Py_DECREF(bases);
1727	}
1728
1729	if (derived == cls)
1730		return 1;
1731
1732	bases = PyObject_GetAttr(derived, __bases__);
1733	if (bases == NULL || !PyTuple_Check(bases)) {
1734	        Py_XDECREF(bases);
1735		PyErr_SetString(PyExc_TypeError,
1736				"issubclass() arg 1 must be a class");
1737		return -1;
1738	}
1739
1740	n = PyTuple_GET_SIZE(bases);
1741	for (i = 0; i < n; i++) {
1742		r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls, 0);
1743		if (r != 0)
1744			break;
1745	}
1746
1747	Py_DECREF(bases);
1748
1749	return r;
1750}
1751
1752int
1753PyObject_IsInstance(PyObject *inst, PyObject *cls)
1754{
1755	PyObject *icls;
1756	static PyObject *__class__ = NULL;
1757	int retval = 0;
1758
1759        if (PyClass_Check(cls)) {
1760		if (PyInstance_Check(inst)) {
1761			PyObject *inclass =
1762				(PyObject*)((PyInstanceObject*)inst)->in_class;
1763			retval = PyClass_IsSubclass(inclass, cls);
1764		}
1765	}
1766	else if (PyType_Check(cls)) {
1767		retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
1768	}
1769	else if (!PyInstance_Check(inst)) {
1770		if (__class__ == NULL) {
1771			__class__ = PyString_FromString("__class__");
1772			if (__class__ == NULL)
1773				return -1;
1774		}
1775		icls = PyObject_GetAttr(inst, __class__);
1776		if (icls != NULL) {
1777			retval = abstract_issubclass(icls, cls, 1);
1778			Py_DECREF(icls);
1779			if (retval < 0 &&
1780			    !PyErr_ExceptionMatches(PyExc_TypeError))
1781				return -1;
1782		}
1783		else
1784			retval = -1;
1785	}
1786	else
1787		retval = -1;
1788
1789	if (retval < 0) {
1790		PyErr_SetString(PyExc_TypeError,
1791				"isinstance() arg 2 must be a class or type");
1792	}
1793	return retval;
1794}
1795
1796int
1797PyObject_IsSubclass(PyObject *derived, PyObject *cls)
1798{
1799	int retval;
1800
1801	if (!PyClass_Check(derived) || !PyClass_Check(cls)) {
1802		retval = abstract_issubclass(derived, cls, 1);
1803	}
1804	else {
1805		/* shortcut */
1806	  	if (!(retval = (derived == cls)))
1807			retval = PyClass_IsSubclass(derived, cls);
1808	}
1809
1810	return retval;
1811}
1812
1813PyObject *
1814PyObject_GetIter(PyObject *o)
1815{
1816	PyTypeObject *t = o->ob_type;
1817	getiterfunc f = NULL;
1818	if (PyType_HasFeature(t, Py_TPFLAGS_HAVE_ITER))
1819		f = t->tp_iter;
1820	if (f == NULL) {
1821		if (PySequence_Check(o))
1822			return PySeqIter_New(o);
1823		PyErr_SetString(PyExc_TypeError, "iter() of non-sequence");
1824		return NULL;
1825	}
1826	else {
1827		PyObject *res = (*f)(o);
1828		if (res != NULL && !PyIter_Check(res)) {
1829			PyErr_Format(PyExc_TypeError,
1830				     "iter() returned non-iterator "
1831				     "of type '%.100s'",
1832				     res->ob_type->tp_name);
1833			Py_DECREF(res);
1834			res = NULL;
1835		}
1836		return res;
1837	}
1838}
1839
1840/* Return next item.
1841 * If an error occurs, return NULL.  PyErr_Occurred() will be true.
1842 * If the iteration terminates normally, return NULL and clear the
1843 * PyExc_StopIteration exception (if it was set).  PyErr_Occurred()
1844 * will be false.
1845 * Else return the next object.  PyErr_Occurred() will be false.
1846 */
1847PyObject *
1848PyIter_Next(PyObject *iter)
1849{
1850	PyObject *result;
1851	if (!PyIter_Check(iter)) {
1852		PyErr_Format(PyExc_TypeError,
1853			     "'%.100s' object is not an iterator",
1854			     iter->ob_type->tp_name);
1855		return NULL;
1856	}
1857	result = (*iter->ob_type->tp_iternext)(iter);
1858	if (result == NULL &&
1859	    PyErr_Occurred() &&
1860	    PyErr_ExceptionMatches(PyExc_StopIteration))
1861		PyErr_Clear();
1862	return result;
1863}
1864