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