Updated for hfsplus module, new gusi libs.
[python/dscho.git] / Objects / abstract.c
blob59314497bd41231f64a8e6e13138b02f6caf1b74
1 /* Abstract Object Interface (many thanks to Jim Fulton) */
4 #include "Python.h"
5 #include <ctype.h>
6 #include "structmember.h" /* we need the offsetof() macro from there */
7 #include "longintrepr.h"
9 #define NEW_STYLE_NUMBER(o) PyType_HasFeature((o)->ob_type, \
10 Py_TPFLAGS_CHECKTYPES)
12 /* Shorthands to return certain errors */
14 static PyObject *
15 type_error(const char *msg)
17 PyErr_SetString(PyExc_TypeError, msg);
18 return NULL;
21 static PyObject *
22 null_error(void)
24 if (!PyErr_Occurred())
25 PyErr_SetString(PyExc_SystemError,
26 "null argument to internal routine");
27 return NULL;
30 /* Operations on any object */
32 int
33 PyObject_Cmp(PyObject *o1, PyObject *o2, int *result)
35 int r;
37 if (o1 == NULL || o2 == NULL) {
38 null_error();
39 return -1;
41 r = PyObject_Compare(o1, o2);
42 if (PyErr_Occurred())
43 return -1;
44 *result = r;
45 return 0;
48 PyObject *
49 PyObject_Type(PyObject *o)
51 PyObject *v;
53 if (o == NULL)
54 return null_error();
55 v = (PyObject *)o->ob_type;
56 Py_INCREF(v);
57 return v;
60 int
61 PyObject_Size(PyObject *o)
63 PySequenceMethods *m;
65 if (o == NULL) {
66 null_error();
67 return -1;
70 m = o->ob_type->tp_as_sequence;
71 if (m && m->sq_length)
72 return m->sq_length(o);
74 return PyMapping_Size(o);
77 #undef PyObject_Length
78 int
79 PyObject_Length(PyObject *o)
81 return PyObject_Size(o);
83 #define PyObject_Length PyObject_Size
85 PyObject *
86 PyObject_GetItem(PyObject *o, PyObject *key)
88 PyMappingMethods *m;
90 if (o == NULL || key == NULL)
91 return null_error();
93 m = o->ob_type->tp_as_mapping;
94 if (m && m->mp_subscript)
95 return m->mp_subscript(o, key);
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);
106 else if (o->ob_type->tp_as_sequence->sq_item)
107 return type_error("sequence index must be integer");
110 return type_error("unsubscriptable object");
114 PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
116 PyMappingMethods *m;
118 if (o == NULL || key == NULL || value == NULL) {
119 null_error();
120 return -1;
122 m = o->ob_type->tp_as_mapping;
123 if (m && m->mp_ass_subscript)
124 return m->mp_ass_subscript(o, key, value);
126 if (o->ob_type->tp_as_sequence) {
127 if (PyInt_Check(key))
128 return PySequence_SetItem(o, PyInt_AsLong(key), value);
129 else if (PyLong_Check(key)) {
130 long key_value = PyLong_AsLong(key);
131 if (key_value == -1 && PyErr_Occurred())
132 return -1;
133 return PySequence_SetItem(o, key_value, value);
135 else if (o->ob_type->tp_as_sequence->sq_ass_item) {
136 type_error("sequence index must be integer");
137 return -1;
141 type_error("object does not support item assignment");
142 return -1;
146 PyObject_DelItem(PyObject *o, PyObject *key)
148 PyMappingMethods *m;
150 if (o == NULL || key == NULL) {
151 null_error();
152 return -1;
154 m = o->ob_type->tp_as_mapping;
155 if (m && m->mp_ass_subscript)
156 return m->mp_ass_subscript(o, key, (PyObject*)NULL);
158 if (o->ob_type->tp_as_sequence) {
159 if (PyInt_Check(key))
160 return PySequence_DelItem(o, PyInt_AsLong(key));
161 else if (PyLong_Check(key)) {
162 long key_value = PyLong_AsLong(key);
163 if (key_value == -1 && PyErr_Occurred())
164 return -1;
165 return PySequence_DelItem(o, key_value);
167 else if (o->ob_type->tp_as_sequence->sq_ass_item) {
168 type_error("sequence index must be integer");
169 return -1;
173 type_error("object does not support item deletion");
174 return -1;
177 int PyObject_AsCharBuffer(PyObject *obj,
178 const char **buffer,
179 int *buffer_len)
181 PyBufferProcs *pb;
182 const char *pp;
183 int len;
185 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
186 null_error();
187 return -1;
189 pb = obj->ob_type->tp_as_buffer;
190 if (pb == NULL ||
191 pb->bf_getcharbuffer == NULL ||
192 pb->bf_getsegcount == NULL) {
193 PyErr_SetString(PyExc_TypeError,
194 "expected a character buffer object");
195 return -1;
197 if ((*pb->bf_getsegcount)(obj,NULL) != 1) {
198 PyErr_SetString(PyExc_TypeError,
199 "expected a single-segment buffer object");
200 return -1;
202 len = (*pb->bf_getcharbuffer)(obj, 0, &pp);
203 if (len < 0)
204 return -1;
205 *buffer = pp;
206 *buffer_len = len;
207 return 0;
211 PyObject_CheckReadBuffer(PyObject *obj)
213 PyBufferProcs *pb = obj->ob_type->tp_as_buffer;
215 if (pb == NULL ||
216 pb->bf_getreadbuffer == NULL ||
217 pb->bf_getsegcount == NULL ||
218 (*pb->bf_getsegcount)(obj, NULL) != 1)
219 return 0;
220 return 1;
223 int PyObject_AsReadBuffer(PyObject *obj,
224 const void **buffer,
225 int *buffer_len)
227 PyBufferProcs *pb;
228 void *pp;
229 int len;
231 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
232 null_error();
233 return -1;
235 pb = obj->ob_type->tp_as_buffer;
236 if (pb == NULL ||
237 pb->bf_getreadbuffer == NULL ||
238 pb->bf_getsegcount == NULL) {
239 PyErr_SetString(PyExc_TypeError,
240 "expected a readable buffer object");
241 return -1;
243 if ((*pb->bf_getsegcount)(obj, NULL) != 1) {
244 PyErr_SetString(PyExc_TypeError,
245 "expected a single-segment buffer object");
246 return -1;
248 len = (*pb->bf_getreadbuffer)(obj, 0, &pp);
249 if (len < 0)
250 return -1;
251 *buffer = pp;
252 *buffer_len = len;
253 return 0;
256 int PyObject_AsWriteBuffer(PyObject *obj,
257 void **buffer,
258 int *buffer_len)
260 PyBufferProcs *pb;
261 void*pp;
262 int len;
264 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
265 null_error();
266 return -1;
268 pb = obj->ob_type->tp_as_buffer;
269 if (pb == NULL ||
270 pb->bf_getwritebuffer == NULL ||
271 pb->bf_getsegcount == NULL) {
272 PyErr_SetString(PyExc_TypeError,
273 "expected a writeable buffer object");
274 return -1;
276 if ((*pb->bf_getsegcount)(obj, NULL) != 1) {
277 PyErr_SetString(PyExc_TypeError,
278 "expected a single-segment buffer object");
279 return -1;
281 len = (*pb->bf_getwritebuffer)(obj,0,&pp);
282 if (len < 0)
283 return -1;
284 *buffer = pp;
285 *buffer_len = len;
286 return 0;
289 /* Operations on numbers */
292 PyNumber_Check(PyObject *o)
294 return o && o->ob_type->tp_as_number;
297 /* Binary operators */
299 /* New style number protocol support */
301 #define NB_SLOT(x) offsetof(PyNumberMethods, x)
302 #define NB_BINOP(nb_methods, slot) \
303 ((binaryfunc*)(& ((char*)nb_methods)[slot] ))
304 #define NB_TERNOP(nb_methods, slot) \
305 ((ternaryfunc*)(& ((char*)nb_methods)[slot] ))
308 Calling scheme used for binary operations:
310 v w Action
311 -------------------------------------------------------------------
312 new new w.op(v,w)[*], v.op(v,w), w.op(v,w)
313 new old v.op(v,w), coerce(v,w), v.op(v,w)
314 old new w.op(v,w), coerce(v,w), v.op(v,w)
315 old old coerce(v,w), v.op(v,w)
317 [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
318 v->ob_type
320 Legend:
321 -------
322 * new == new style number
323 * old == old style number
324 * Action indicates the order in which operations are tried until either
325 a valid result is produced or an error occurs.
329 static PyObject *
330 binary_op1(PyObject *v, PyObject *w, const int op_slot)
332 PyObject *x;
333 binaryfunc slotv = NULL;
334 binaryfunc slotw = NULL;
336 if (v->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(v))
337 slotv = *NB_BINOP(v->ob_type->tp_as_number, op_slot);
338 if (w->ob_type != v->ob_type &&
339 w->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(w)) {
340 slotw = *NB_BINOP(w->ob_type->tp_as_number, op_slot);
341 if (slotw == slotv)
342 slotw = NULL;
344 if (slotv) {
345 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
346 x = slotw(v, w);
347 if (x != Py_NotImplemented)
348 return x;
349 Py_DECREF(x); /* can't do it */
350 slotw = NULL;
352 x = slotv(v, w);
353 if (x != Py_NotImplemented)
354 return x;
355 Py_DECREF(x); /* can't do it */
357 if (slotw) {
358 x = slotw(v, w);
359 if (x != Py_NotImplemented)
360 return x;
361 Py_DECREF(x); /* can't do it */
363 if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w)) {
364 int err = PyNumber_CoerceEx(&v, &w);
365 if (err < 0) {
366 return NULL;
368 if (err == 0) {
369 PyNumberMethods *mv = v->ob_type->tp_as_number;
370 if (mv) {
371 binaryfunc slot;
372 slot = *NB_BINOP(mv, op_slot);
373 if (slot) {
374 PyObject *x = slot(v, w);
375 Py_DECREF(v);
376 Py_DECREF(w);
377 return x;
380 /* CoerceEx incremented the reference counts */
381 Py_DECREF(v);
382 Py_DECREF(w);
385 Py_INCREF(Py_NotImplemented);
386 return Py_NotImplemented;
389 static PyObject *
390 binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
392 PyObject *result = binary_op1(v, w, op_slot);
393 if (result == Py_NotImplemented) {
394 Py_DECREF(Py_NotImplemented);
395 PyErr_Format(
396 PyExc_TypeError,
397 "unsupported operand type(s) for %s: '%s' and '%s'",
398 op_name,
399 v->ob_type->tp_name,
400 w->ob_type->tp_name);
401 return NULL;
403 return result;
408 Calling scheme used for ternary operations:
410 *** In some cases, w.op is called before v.op; see binary_op1. ***
412 v w z Action
413 -------------------------------------------------------------------
414 new new new v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
415 new old new v.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
416 old new new w.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
417 old old new z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
418 new new old v.op(v,w,z), w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
419 new old old v.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
420 old new old w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
421 old old old coerce(v,w,z), v.op(v,w,z)
423 Legend:
424 -------
425 * new == new style number
426 * old == old style number
427 * Action indicates the order in which operations are tried until either
428 a valid result is produced or an error occurs.
429 * coerce(v,w,z) actually does: coerce(v,w), coerce(v,z), coerce(w,z) and
430 only if z != Py_None; if z == Py_None, then it is treated as absent
431 variable and only coerce(v,w) is tried.
435 static PyObject *
436 ternary_op(PyObject *v,
437 PyObject *w,
438 PyObject *z,
439 const int op_slot,
440 const char *op_name)
442 PyNumberMethods *mv, *mw, *mz;
443 PyObject *x = NULL;
444 ternaryfunc slotv = NULL;
445 ternaryfunc slotw = NULL;
446 ternaryfunc slotz = NULL;
448 mv = v->ob_type->tp_as_number;
449 mw = w->ob_type->tp_as_number;
450 if (mv != NULL && NEW_STYLE_NUMBER(v))
451 slotv = *NB_TERNOP(mv, op_slot);
452 if (w->ob_type != v->ob_type &&
453 mv != NULL && NEW_STYLE_NUMBER(w)) {
454 slotw = *NB_TERNOP(mw, op_slot);
455 if (slotw == slotv)
456 slotw = NULL;
458 if (slotv) {
459 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
460 x = slotw(v, w, z);
461 if (x != Py_NotImplemented)
462 return x;
463 Py_DECREF(x); /* can't do it */
464 slotw = NULL;
466 x = slotv(v, w, z);
467 if (x != Py_NotImplemented)
468 return x;
469 Py_DECREF(x); /* can't do it */
471 if (slotw) {
472 x = slotw(v, w, z);
473 if (x != Py_NotImplemented)
474 return x;
475 Py_DECREF(x); /* can't do it */
477 mz = z->ob_type->tp_as_number;
478 if (mz != NULL && NEW_STYLE_NUMBER(z)) {
479 slotz = *NB_TERNOP(mz, op_slot);
480 if (slotz == slotv || slotz == slotw)
481 slotz = NULL;
482 if (slotz) {
483 x = slotz(v, w, z);
484 if (x != Py_NotImplemented)
485 return x;
486 Py_DECREF(x); /* can't do it */
490 if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w) ||
491 (z != Py_None && !NEW_STYLE_NUMBER(z))) {
492 /* we have an old style operand, coerce */
493 PyObject *v1, *z1, *w2, *z2;
494 int c;
496 c = PyNumber_Coerce(&v, &w);
497 if (c != 0)
498 goto error3;
500 /* Special case: if the third argument is None, it is
501 treated as absent argument and not coerced. */
502 if (z == Py_None) {
503 if (v->ob_type->tp_as_number) {
504 slotz = *NB_TERNOP(v->ob_type->tp_as_number,
505 op_slot);
506 if (slotz)
507 x = slotz(v, w, z);
508 else
509 c = -1;
511 else
512 c = -1;
513 goto error2;
515 v1 = v;
516 z1 = z;
517 c = PyNumber_Coerce(&v1, &z1);
518 if (c != 0)
519 goto error2;
520 w2 = w;
521 z2 = z1;
522 c = PyNumber_Coerce(&w2, &z2);
523 if (c != 0)
524 goto error1;
526 if (v1->ob_type->tp_as_number != NULL) {
527 slotv = *NB_TERNOP(v1->ob_type->tp_as_number,
528 op_slot);
529 if (slotv)
530 x = slotv(v1, w2, z2);
531 else
532 c = -1;
534 else
535 c = -1;
537 Py_DECREF(w2);
538 Py_DECREF(z2);
539 error1:
540 Py_DECREF(v1);
541 Py_DECREF(z1);
542 error2:
543 Py_DECREF(v);
544 Py_DECREF(w);
545 error3:
546 if (c >= 0)
547 return x;
550 if (z == Py_None)
551 PyErr_Format(
552 PyExc_TypeError,
553 "unsupported operand type(s) for ** or pow(): "
554 "'%s' and '%s'",
555 v->ob_type->tp_name,
556 w->ob_type->tp_name);
557 else
558 PyErr_Format(
559 PyExc_TypeError,
560 "unsupported operand type(s) for pow(): "
561 "'%s', '%s', '%s'",
562 v->ob_type->tp_name,
563 w->ob_type->tp_name,
564 z->ob_type->tp_name);
565 return NULL;
568 #define BINARY_FUNC(func, op, op_name) \
569 PyObject * \
570 func(PyObject *v, PyObject *w) { \
571 return binary_op(v, w, NB_SLOT(op), op_name); \
574 BINARY_FUNC(PyNumber_Or, nb_or, "|")
575 BINARY_FUNC(PyNumber_Xor, nb_xor, "^")
576 BINARY_FUNC(PyNumber_And, nb_and, "&")
577 BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")
578 BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")
579 BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")
580 BINARY_FUNC(PyNumber_Multiply, nb_multiply, "*")
581 BINARY_FUNC(PyNumber_Divide, nb_divide, "/")
582 BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
584 PyObject *
585 PyNumber_Add(PyObject *v, PyObject *w)
587 PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
588 if (result == Py_NotImplemented) {
589 PySequenceMethods *m = v->ob_type->tp_as_sequence;
590 Py_DECREF(Py_NotImplemented);
591 if (m && m->sq_concat) {
592 result = (*m->sq_concat)(v, w);
594 else {
595 PyErr_Format(
596 PyExc_TypeError,
597 "unsupported operand types for +: '%s' and '%s'",
598 v->ob_type->tp_name,
599 w->ob_type->tp_name);
600 result = NULL;
603 return result;
606 PyObject *
607 PyNumber_FloorDivide(PyObject *v, PyObject *w)
609 /* XXX tp_flags test */
610 return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
613 PyObject *
614 PyNumber_TrueDivide(PyObject *v, PyObject *w)
616 /* XXX tp_flags test */
617 return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
620 PyObject *
621 PyNumber_Remainder(PyObject *v, PyObject *w)
623 if (PyString_Check(v))
624 return PyString_Format(v, w);
625 #ifdef Py_USING_UNICODE
626 else if (PyUnicode_Check(v))
627 return PyUnicode_Format(v, w);
628 #endif
629 return binary_op(v, w, NB_SLOT(nb_remainder), "%");
632 PyObject *
633 PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
635 return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
638 /* Binary in-place operators */
640 /* The in-place operators are defined to fall back to the 'normal',
641 non in-place operations, if the in-place methods are not in place.
643 - If the left hand object has the appropriate struct members, and
644 they are filled, call the appropriate function and return the
645 result. No coercion is done on the arguments; the left-hand object
646 is the one the operation is performed on, and it's up to the
647 function to deal with the right-hand object.
649 - Otherwise, in-place modification is not supported. Handle it exactly as
650 a non in-place operation of the same kind.
654 #define HASINPLACE(t) PyType_HasFeature((t)->ob_type, Py_TPFLAGS_HAVE_INPLACEOPS)
656 static PyObject *
657 binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
658 const char *op_name)
660 PyNumberMethods *mv = v->ob_type->tp_as_number;
661 if (mv != NULL && HASINPLACE(v)) {
662 binaryfunc *slot = NB_BINOP(mv, iop_slot);
663 if (*slot) {
664 PyObject *x = (*slot)(v, w);
665 if (x != Py_NotImplemented) {
666 return x;
668 Py_DECREF(x);
671 return binary_op(v, w, op_slot, op_name);
674 #define INPLACE_BINOP(func, iop, op, op_name) \
675 PyObject * \
676 func(PyObject *v, PyObject *w) { \
677 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
680 INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
681 INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
682 INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")
683 INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")
684 INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")
685 INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")
686 INPLACE_BINOP(PyNumber_InPlaceDivide, nb_inplace_divide, nb_divide, "/=")
688 PyObject *
689 PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w)
691 /* XXX tp_flags test */
692 return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide),
693 NB_SLOT(nb_floor_divide), "//=");
696 PyObject *
697 PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w)
699 /* XXX tp_flags test */
700 return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide),
701 NB_SLOT(nb_true_divide), "/=");
704 PyObject *
705 PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
707 binaryfunc f = NULL;
709 if (v->ob_type->tp_as_sequence != NULL) {
710 if (HASINPLACE(v))
711 f = v->ob_type->tp_as_sequence->sq_inplace_concat;
712 if (f == NULL)
713 f = v->ob_type->tp_as_sequence->sq_concat;
714 if (f != NULL)
715 return (*f)(v, w);
717 return binary_iop(v, w, NB_SLOT(nb_inplace_add), NB_SLOT(nb_add), "+=");
720 PyObject *
721 PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
723 PyObject * (*g)(PyObject *, int) = NULL;
724 if (HASINPLACE(v) && v->ob_type->tp_as_sequence &&
725 (g = v->ob_type->tp_as_sequence->sq_inplace_repeat)) {
726 long n;
727 if (PyInt_Check(w)) {
728 n = PyInt_AsLong(w);
730 else if (PyLong_Check(w)) {
731 n = PyLong_AsLong(w);
732 if (n == -1 && PyErr_Occurred())
733 return NULL;
735 else {
736 return type_error("can't multiply sequence to non-int");
738 return (*g)(v, (int)n);
740 return binary_iop(v, w, NB_SLOT(nb_inplace_multiply),
741 NB_SLOT(nb_multiply), "*=");
746 PyObject *
747 PyNumber_InPlaceRemainder(PyObject *v, PyObject *w)
749 if (PyString_Check(v))
750 return PyString_Format(v, w);
751 #ifdef Py_USING_UNICODE
752 else if (PyUnicode_Check(v))
753 return PyUnicode_Format(v, w);
754 #endif
755 else
756 return binary_iop(v, w, NB_SLOT(nb_inplace_remainder),
757 NB_SLOT(nb_remainder), "%=");
761 PyObject *
762 PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
764 if (HASINPLACE(v) && v->ob_type->tp_as_number &&
765 v->ob_type->tp_as_number->nb_inplace_power != NULL) {
766 return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**=");
768 else {
769 return ternary_op(v, w, z, NB_SLOT(nb_power), "**=");
774 /* Unary operators and functions */
776 PyObject *
777 PyNumber_Negative(PyObject *o)
779 PyNumberMethods *m;
781 if (o == NULL)
782 return null_error();
783 m = o->ob_type->tp_as_number;
784 if (m && m->nb_negative)
785 return (*m->nb_negative)(o);
787 return type_error("bad operand type for unary -");
790 PyObject *
791 PyNumber_Positive(PyObject *o)
793 PyNumberMethods *m;
795 if (o == NULL)
796 return null_error();
797 m = o->ob_type->tp_as_number;
798 if (m && m->nb_positive)
799 return (*m->nb_positive)(o);
801 return type_error("bad operand type for unary +");
804 PyObject *
805 PyNumber_Invert(PyObject *o)
807 PyNumberMethods *m;
809 if (o == NULL)
810 return null_error();
811 m = o->ob_type->tp_as_number;
812 if (m && m->nb_invert)
813 return (*m->nb_invert)(o);
815 return type_error("bad operand type for unary ~");
818 PyObject *
819 PyNumber_Absolute(PyObject *o)
821 PyNumberMethods *m;
823 if (o == NULL)
824 return null_error();
825 m = o->ob_type->tp_as_number;
826 if (m && m->nb_absolute)
827 return m->nb_absolute(o);
829 return type_error("bad operand type for abs()");
832 /* Add a check for embedded NULL-bytes in the argument. */
833 static PyObject *
834 int_from_string(const char *s, int len)
836 char *end;
837 PyObject *x;
839 x = PyInt_FromString((char*)s, &end, 10);
840 if (x == NULL)
841 return NULL;
842 if (end != s + len) {
843 PyErr_SetString(PyExc_ValueError,
844 "null byte in argument for int()");
845 Py_DECREF(x);
846 return NULL;
848 return x;
851 PyObject *
852 PyNumber_Int(PyObject *o)
854 PyNumberMethods *m;
855 const char *buffer;
856 int buffer_len;
858 if (o == NULL)
859 return null_error();
860 if (PyInt_CheckExact(o)) {
861 Py_INCREF(o);
862 return o;
864 if (PyInt_Check(o)) {
865 PyIntObject *io = (PyIntObject*)o;
866 return PyInt_FromLong(io->ob_ival);
868 if (PyString_Check(o))
869 return int_from_string(PyString_AS_STRING(o),
870 PyString_GET_SIZE(o));
871 #ifdef Py_USING_UNICODE
872 if (PyUnicode_Check(o))
873 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o),
874 PyUnicode_GET_SIZE(o),
875 10);
876 #endif
877 m = o->ob_type->tp_as_number;
878 if (m && m->nb_int)
879 return m->nb_int(o);
880 if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
881 return int_from_string((char*)buffer, buffer_len);
883 return type_error("object can't be converted to int");
886 /* Add a check for embedded NULL-bytes in the argument. */
887 static PyObject *
888 long_from_string(const char *s, int len)
890 char *end;
891 PyObject *x;
893 x = PyLong_FromString((char*)s, &end, 10);
894 if (x == NULL)
895 return NULL;
896 if (end != s + len) {
897 PyErr_SetString(PyExc_ValueError,
898 "null byte in argument for long()");
899 Py_DECREF(x);
900 return NULL;
902 return x;
905 PyObject *
906 PyNumber_Long(PyObject *o)
908 PyNumberMethods *m;
909 const char *buffer;
910 int buffer_len;
912 if (o == NULL)
913 return null_error();
914 if (PyLong_CheckExact(o)) {
915 Py_INCREF(o);
916 return o;
918 if (PyLong_Check(o))
919 return _PyLong_Copy((PyLongObject *)o);
920 if (PyString_Check(o))
921 /* need to do extra error checking that PyLong_FromString()
922 * doesn't do. In particular long('9.5') must raise an
923 * exception, not truncate the float.
925 return long_from_string(PyString_AS_STRING(o),
926 PyString_GET_SIZE(o));
927 #ifdef Py_USING_UNICODE
928 if (PyUnicode_Check(o))
929 /* The above check is done in PyLong_FromUnicode(). */
930 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o),
931 PyUnicode_GET_SIZE(o),
932 10);
933 #endif
934 m = o->ob_type->tp_as_number;
935 if (m && m->nb_long)
936 return m->nb_long(o);
937 if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
938 return long_from_string(buffer, buffer_len);
940 return type_error("object can't be converted to long");
943 PyObject *
944 PyNumber_Float(PyObject *o)
946 PyNumberMethods *m;
948 if (o == NULL)
949 return null_error();
950 if (PyFloat_CheckExact(o)) {
951 Py_INCREF(o);
952 return o;
954 if (PyFloat_Check(o)) {
955 PyFloatObject *po = (PyFloatObject *)o;
956 return PyFloat_FromDouble(po->ob_fval);
958 if (!PyString_Check(o)) {
959 m = o->ob_type->tp_as_number;
960 if (m && m->nb_float)
961 return m->nb_float(o);
963 return PyFloat_FromString(o, NULL);
966 /* Operations on sequences */
969 PySequence_Check(PyObject *s)
971 return s != NULL && s->ob_type->tp_as_sequence &&
972 s->ob_type->tp_as_sequence->sq_item != NULL;
976 PySequence_Size(PyObject *s)
978 PySequenceMethods *m;
980 if (s == NULL) {
981 null_error();
982 return -1;
985 m = s->ob_type->tp_as_sequence;
986 if (m && m->sq_length)
987 return m->sq_length(s);
989 type_error("len() of unsized object");
990 return -1;
993 #undef PySequence_Length
995 PySequence_Length(PyObject *s)
997 return PySequence_Size(s);
999 #define PySequence_Length PySequence_Size
1001 PyObject *
1002 PySequence_Concat(PyObject *s, PyObject *o)
1004 PySequenceMethods *m;
1006 if (s == NULL || o == NULL)
1007 return null_error();
1009 m = s->ob_type->tp_as_sequence;
1010 if (m && m->sq_concat)
1011 return m->sq_concat(s, o);
1013 return type_error("object can't be concatenated");
1016 PyObject *
1017 PySequence_Repeat(PyObject *o, int count)
1019 PySequenceMethods *m;
1021 if (o == NULL)
1022 return null_error();
1024 m = o->ob_type->tp_as_sequence;
1025 if (m && m->sq_repeat)
1026 return m->sq_repeat(o, count);
1028 return type_error("object can't be repeated");
1031 PyObject *
1032 PySequence_InPlaceConcat(PyObject *s, PyObject *o)
1034 PySequenceMethods *m;
1036 if (s == NULL || o == NULL)
1037 return null_error();
1039 m = s->ob_type->tp_as_sequence;
1040 if (m && HASINPLACE(s) && m->sq_inplace_concat)
1041 return m->sq_inplace_concat(s, o);
1042 if (m && m->sq_concat)
1043 return m->sq_concat(s, o);
1045 return type_error("object can't be concatenated");
1048 PyObject *
1049 PySequence_InPlaceRepeat(PyObject *o, int count)
1051 PySequenceMethods *m;
1053 if (o == NULL)
1054 return null_error();
1056 m = o->ob_type->tp_as_sequence;
1057 if (m && HASINPLACE(o) && m->sq_inplace_repeat)
1058 return m->sq_inplace_repeat(o, count);
1059 if (m && m->sq_repeat)
1060 return m->sq_repeat(o, count);
1062 return type_error("object can't be repeated");
1065 PyObject *
1066 PySequence_GetItem(PyObject *s, int i)
1068 PySequenceMethods *m;
1070 if (s == NULL)
1071 return null_error();
1073 m = s->ob_type->tp_as_sequence;
1074 if (m && m->sq_item) {
1075 if (i < 0) {
1076 if (m->sq_length) {
1077 int l = (*m->sq_length)(s);
1078 if (l < 0)
1079 return NULL;
1080 i += l;
1083 return m->sq_item(s, i);
1086 return type_error("unindexable object");
1089 static PyObject *
1090 sliceobj_from_intint(int i, int j)
1092 PyObject *start, *end, *slice;
1093 start = PyInt_FromLong((long)i);
1094 if (!start)
1095 return NULL;
1096 end = PyInt_FromLong((long)j);
1097 if (!end) {
1098 Py_DECREF(start);
1099 return NULL;
1101 slice = PySlice_New(start, end, NULL);
1102 Py_DECREF(start);
1103 Py_DECREF(end);
1104 return slice;
1107 PyObject *
1108 PySequence_GetSlice(PyObject *s, int i1, int i2)
1110 PySequenceMethods *m;
1111 PyMappingMethods *mp;
1113 if (!s) return null_error();
1115 m = s->ob_type->tp_as_sequence;
1116 if (m && m->sq_slice) {
1117 if (i1 < 0 || i2 < 0) {
1118 if (m->sq_length) {
1119 int l = (*m->sq_length)(s);
1120 if (l < 0)
1121 return NULL;
1122 if (i1 < 0)
1123 i1 += l;
1124 if (i2 < 0)
1125 i2 += l;
1128 return m->sq_slice(s, i1, i2);
1129 } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_subscript) {
1130 PyObject *res;
1131 PyObject *slice = sliceobj_from_intint(i1, i2);
1132 if (!slice)
1133 return NULL;
1134 res = mp->mp_subscript(s, slice);
1135 Py_DECREF(slice);
1136 return res;
1139 return type_error("unsliceable object");
1143 PySequence_SetItem(PyObject *s, int i, PyObject *o)
1145 PySequenceMethods *m;
1147 if (s == NULL) {
1148 null_error();
1149 return -1;
1152 m = s->ob_type->tp_as_sequence;
1153 if (m && m->sq_ass_item) {
1154 if (i < 0) {
1155 if (m->sq_length) {
1156 int l = (*m->sq_length)(s);
1157 if (l < 0)
1158 return -1;
1159 i += l;
1162 return m->sq_ass_item(s, i, o);
1165 type_error("object doesn't support item assignment");
1166 return -1;
1170 PySequence_DelItem(PyObject *s, int i)
1172 PySequenceMethods *m;
1174 if (s == NULL) {
1175 null_error();
1176 return -1;
1179 m = s->ob_type->tp_as_sequence;
1180 if (m && m->sq_ass_item) {
1181 if (i < 0) {
1182 if (m->sq_length) {
1183 int l = (*m->sq_length)(s);
1184 if (l < 0)
1185 return -1;
1186 i += l;
1189 return m->sq_ass_item(s, i, (PyObject *)NULL);
1192 type_error("object doesn't support item deletion");
1193 return -1;
1197 PySequence_SetSlice(PyObject *s, int i1, int i2, PyObject *o)
1199 PySequenceMethods *m;
1200 PyMappingMethods *mp;
1202 if (s == NULL) {
1203 null_error();
1204 return -1;
1207 m = s->ob_type->tp_as_sequence;
1208 if (m && m->sq_ass_slice) {
1209 if (i1 < 0 || i2 < 0) {
1210 if (m->sq_length) {
1211 int l = (*m->sq_length)(s);
1212 if (l < 0)
1213 return -1;
1214 if (i1 < 0)
1215 i1 += l;
1216 if (i2 < 0)
1217 i2 += l;
1220 return m->sq_ass_slice(s, i1, i2, o);
1221 } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_ass_subscript) {
1222 int res;
1223 PyObject *slice = sliceobj_from_intint(i1, i2);
1224 if (!slice)
1225 return -1;
1226 res = mp->mp_ass_subscript(s, slice, o);
1227 Py_DECREF(slice);
1228 return res;
1231 type_error("object doesn't support slice assignment");
1232 return -1;
1236 PySequence_DelSlice(PyObject *s, int i1, int i2)
1238 PySequenceMethods *m;
1240 if (s == NULL) {
1241 null_error();
1242 return -1;
1245 m = s->ob_type->tp_as_sequence;
1246 if (m && m->sq_ass_slice) {
1247 if (i1 < 0 || i2 < 0) {
1248 if (m->sq_length) {
1249 int l = (*m->sq_length)(s);
1250 if (l < 0)
1251 return -1;
1252 if (i1 < 0)
1253 i1 += l;
1254 if (i2 < 0)
1255 i2 += l;
1258 return m->sq_ass_slice(s, i1, i2, (PyObject *)NULL);
1260 type_error("object doesn't support slice deletion");
1261 return -1;
1264 PyObject *
1265 PySequence_Tuple(PyObject *v)
1267 PyObject *it; /* iter(v) */
1268 int n; /* guess for result tuple size */
1269 PyObject *result;
1270 int j;
1272 if (v == NULL)
1273 return null_error();
1275 /* Special-case the common tuple and list cases, for efficiency. */
1276 if (PyTuple_CheckExact(v)) {
1277 /* Note that we can't know whether it's safe to return
1278 a tuple *subclass* instance as-is, hence the restriction
1279 to exact tuples here. In contrast, lists always make
1280 a copy, so there's no need for exactness below. */
1281 Py_INCREF(v);
1282 return v;
1284 if (PyList_Check(v))
1285 return PyList_AsTuple(v);
1287 /* Get iterator. */
1288 it = PyObject_GetIter(v);
1289 if (it == NULL)
1290 return NULL;
1292 /* Guess result size and allocate space. */
1293 n = PySequence_Size(v);
1294 if (n < 0) {
1295 PyErr_Clear();
1296 n = 10; /* arbitrary */
1298 result = PyTuple_New(n);
1299 if (result == NULL)
1300 goto Fail;
1302 /* Fill the tuple. */
1303 for (j = 0; ; ++j) {
1304 PyObject *item = PyIter_Next(it);
1305 if (item == NULL) {
1306 if (PyErr_Occurred())
1307 goto Fail;
1308 break;
1310 if (j >= n) {
1311 if (n < 500)
1312 n += 10;
1313 else
1314 n += 100;
1315 if (_PyTuple_Resize(&result, n) != 0) {
1316 Py_DECREF(item);
1317 goto Fail;
1320 PyTuple_SET_ITEM(result, j, item);
1323 /* Cut tuple back if guess was too large. */
1324 if (j < n &&
1325 _PyTuple_Resize(&result, j) != 0)
1326 goto Fail;
1328 Py_DECREF(it);
1329 return result;
1331 Fail:
1332 Py_XDECREF(result);
1333 Py_DECREF(it);
1334 return NULL;
1337 PyObject *
1338 PySequence_List(PyObject *v)
1340 PyObject *it; /* iter(v) */
1341 PyObject *result; /* result list */
1342 int n; /* guess for result list size */
1343 int i;
1345 if (v == NULL)
1346 return null_error();
1348 /* Special-case list(a_list), for speed. */
1349 if (PyList_Check(v))
1350 return PyList_GetSlice(v, 0, PyList_GET_SIZE(v));
1352 /* Get iterator. There may be some low-level efficiency to be gained
1353 * by caching the tp_iternext slot instead of using PyIter_Next()
1354 * later, but premature optimization is the root etc.
1356 it = PyObject_GetIter(v);
1357 if (it == NULL)
1358 return NULL;
1360 /* Guess a result list size. */
1361 n = -1; /* unknown */
1362 if (PySequence_Check(v) &&
1363 v->ob_type->tp_as_sequence->sq_length) {
1364 n = PySequence_Size(v);
1365 if (n < 0)
1366 PyErr_Clear();
1368 if (n < 0)
1369 n = 8; /* arbitrary */
1370 result = PyList_New(n);
1371 if (result == NULL) {
1372 Py_DECREF(it);
1373 return NULL;
1376 /* Run iterator to exhaustion. */
1377 for (i = 0; ; i++) {
1378 PyObject *item = PyIter_Next(it);
1379 if (item == NULL) {
1380 if (PyErr_Occurred()) {
1381 Py_DECREF(result);
1382 result = NULL;
1384 break;
1386 if (i < n)
1387 PyList_SET_ITEM(result, i, item); /* steals ref */
1388 else {
1389 int status = PyList_Append(result, item);
1390 Py_DECREF(item); /* append creates a new ref */
1391 if (status < 0) {
1392 Py_DECREF(result);
1393 result = NULL;
1394 break;
1399 /* Cut back result list if initial guess was too large. */
1400 if (i < n && result != NULL) {
1401 if (PyList_SetSlice(result, i, n, (PyObject *)NULL) != 0) {
1402 Py_DECREF(result);
1403 result = NULL;
1406 Py_DECREF(it);
1407 return result;
1410 PyObject *
1411 PySequence_Fast(PyObject *v, const char *m)
1413 if (v == NULL)
1414 return null_error();
1416 if (PyList_Check(v) || PyTuple_Check(v)) {
1417 Py_INCREF(v);
1418 return v;
1421 v = PySequence_Tuple(v);
1422 if (v == NULL && PyErr_ExceptionMatches(PyExc_TypeError))
1423 return type_error(m);
1425 return v;
1428 /* Iterate over seq. Result depends on the operation:
1429 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
1430 PY_ITERSEARCH_INDEX: 0-based index of first occurence of obj in seq;
1431 set ValueError and return -1 if none found; also return -1 on error.
1432 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
1435 _PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
1437 int n;
1438 int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
1439 PyObject *it; /* iter(seq) */
1441 if (seq == NULL || obj == NULL) {
1442 null_error();
1443 return -1;
1446 it = PyObject_GetIter(seq);
1447 if (it == NULL) {
1448 type_error("iterable argument required");
1449 return -1;
1452 n = wrapped = 0;
1453 for (;;) {
1454 int cmp;
1455 PyObject *item = PyIter_Next(it);
1456 if (item == NULL) {
1457 if (PyErr_Occurred())
1458 goto Fail;
1459 break;
1462 cmp = PyObject_RichCompareBool(obj, item, Py_EQ);
1463 Py_DECREF(item);
1464 if (cmp < 0)
1465 goto Fail;
1466 if (cmp > 0) {
1467 switch (operation) {
1468 case PY_ITERSEARCH_COUNT:
1469 ++n;
1470 if (n <= 0) {
1471 PyErr_SetString(PyExc_OverflowError,
1472 "count exceeds C int size");
1473 goto Fail;
1475 break;
1477 case PY_ITERSEARCH_INDEX:
1478 if (wrapped) {
1479 PyErr_SetString(PyExc_OverflowError,
1480 "index exceeds C int size");
1481 goto Fail;
1483 goto Done;
1485 case PY_ITERSEARCH_CONTAINS:
1486 n = 1;
1487 goto Done;
1489 default:
1490 assert(!"unknown operation");
1494 if (operation == PY_ITERSEARCH_INDEX) {
1495 ++n;
1496 if (n <= 0)
1497 wrapped = 1;
1501 if (operation != PY_ITERSEARCH_INDEX)
1502 goto Done;
1504 PyErr_SetString(PyExc_ValueError,
1505 "sequence.index(x): x not in sequence");
1506 /* fall into failure code */
1507 Fail:
1508 n = -1;
1509 /* fall through */
1510 Done:
1511 Py_DECREF(it);
1512 return n;
1516 /* Return # of times o appears in s. */
1518 PySequence_Count(PyObject *s, PyObject *o)
1520 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
1523 /* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
1524 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
1527 PySequence_Contains(PyObject *seq, PyObject *ob)
1529 if (PyType_HasFeature(seq->ob_type, Py_TPFLAGS_HAVE_SEQUENCE_IN)) {
1530 PySequenceMethods *sqm = seq->ob_type->tp_as_sequence;
1531 if (sqm != NULL && sqm->sq_contains != NULL)
1532 return (*sqm->sq_contains)(seq, ob);
1534 return _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
1537 /* Backwards compatibility */
1538 #undef PySequence_In
1540 PySequence_In(PyObject *w, PyObject *v)
1542 return PySequence_Contains(w, v);
1546 PySequence_Index(PyObject *s, PyObject *o)
1548 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
1551 /* Operations on mappings */
1554 PyMapping_Check(PyObject *o)
1556 return o && o->ob_type->tp_as_mapping &&
1557 o->ob_type->tp_as_mapping->mp_subscript;
1561 PyMapping_Size(PyObject *o)
1563 PyMappingMethods *m;
1565 if (o == NULL) {
1566 null_error();
1567 return -1;
1570 m = o->ob_type->tp_as_mapping;
1571 if (m && m->mp_length)
1572 return m->mp_length(o);
1574 type_error("len() of unsized object");
1575 return -1;
1578 #undef PyMapping_Length
1580 PyMapping_Length(PyObject *o)
1582 return PyMapping_Size(o);
1584 #define PyMapping_Length PyMapping_Size
1586 PyObject *
1587 PyMapping_GetItemString(PyObject *o, char *key)
1589 PyObject *okey, *r;
1591 if (key == NULL)
1592 return null_error();
1594 okey = PyString_FromString(key);
1595 if (okey == NULL)
1596 return NULL;
1597 r = PyObject_GetItem(o, okey);
1598 Py_DECREF(okey);
1599 return r;
1603 PyMapping_SetItemString(PyObject *o, char *key, PyObject *value)
1605 PyObject *okey;
1606 int r;
1608 if (key == NULL) {
1609 null_error();
1610 return -1;
1613 okey = PyString_FromString(key);
1614 if (okey == NULL)
1615 return -1;
1616 r = PyObject_SetItem(o, okey, value);
1617 Py_DECREF(okey);
1618 return r;
1622 PyMapping_HasKeyString(PyObject *o, char *key)
1624 PyObject *v;
1626 v = PyMapping_GetItemString(o, key);
1627 if (v) {
1628 Py_DECREF(v);
1629 return 1;
1631 PyErr_Clear();
1632 return 0;
1636 PyMapping_HasKey(PyObject *o, PyObject *key)
1638 PyObject *v;
1640 v = PyObject_GetItem(o, key);
1641 if (v) {
1642 Py_DECREF(v);
1643 return 1;
1645 PyErr_Clear();
1646 return 0;
1649 /* Operations on callable objects */
1651 /* XXX PyCallable_Check() is in object.c */
1653 PyObject *
1654 PyObject_CallObject(PyObject *o, PyObject *a)
1656 return PyEval_CallObjectWithKeywords(o, a, NULL);
1659 PyObject *
1660 PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw)
1662 ternaryfunc call;
1664 if ((call = func->ob_type->tp_call) != NULL) {
1665 PyObject *result = (*call)(func, arg, kw);
1666 if (result == NULL && !PyErr_Occurred())
1667 PyErr_SetString(
1668 PyExc_SystemError,
1669 "NULL result without error in PyObject_Call");
1670 return result;
1672 PyErr_Format(PyExc_TypeError, "'%s' object is not callable",
1673 func->ob_type->tp_name);
1674 return NULL;
1677 PyObject *
1678 PyObject_CallFunction(PyObject *callable, char *format, ...)
1680 va_list va;
1681 PyObject *args, *retval;
1683 if (callable == NULL)
1684 return null_error();
1686 if (format && *format) {
1687 va_start(va, format);
1688 args = Py_VaBuildValue(format, va);
1689 va_end(va);
1691 else
1692 args = PyTuple_New(0);
1694 if (args == NULL)
1695 return NULL;
1697 if (!PyTuple_Check(args)) {
1698 PyObject *a;
1700 a = PyTuple_New(1);
1701 if (a == NULL)
1702 return NULL;
1703 if (PyTuple_SetItem(a, 0, args) < 0)
1704 return NULL;
1705 args = a;
1707 retval = PyObject_CallObject(callable, args);
1709 Py_DECREF(args);
1711 return retval;
1714 PyObject *
1715 PyObject_CallMethod(PyObject *o, char *name, char *format, ...)
1717 va_list va;
1718 PyObject *args, *func = 0, *retval;
1720 if (o == NULL || name == NULL)
1721 return null_error();
1723 func = PyObject_GetAttrString(o, name);
1724 if (func == NULL) {
1725 PyErr_SetString(PyExc_AttributeError, name);
1726 return 0;
1729 if (!PyCallable_Check(func))
1730 return type_error("call of non-callable attribute");
1732 if (format && *format) {
1733 va_start(va, format);
1734 args = Py_VaBuildValue(format, va);
1735 va_end(va);
1737 else
1738 args = PyTuple_New(0);
1740 if (!args)
1741 return NULL;
1743 if (!PyTuple_Check(args)) {
1744 PyObject *a;
1746 a = PyTuple_New(1);
1747 if (a == NULL)
1748 return NULL;
1749 if (PyTuple_SetItem(a, 0, args) < 0)
1750 return NULL;
1751 args = a;
1754 retval = PyObject_CallObject(func, args);
1756 Py_DECREF(args);
1757 Py_DECREF(func);
1759 return retval;
1763 static PyObject *
1764 objargs_mktuple(va_list va)
1766 int i, n = 0;
1767 va_list countva;
1768 PyObject *result, *tmp;
1770 #ifdef VA_LIST_IS_ARRAY
1771 memcpy(countva, va, sizeof(va_list));
1772 #else
1773 countva = va;
1774 #endif
1776 while (((PyObject *)va_arg(countva, PyObject *)) != NULL)
1777 ++n;
1778 result = PyTuple_New(n);
1779 if (result != NULL && n > 0) {
1780 for (i = 0; i < n; ++i) {
1781 tmp = (PyObject *)va_arg(va, PyObject *);
1782 PyTuple_SET_ITEM(result, i, tmp);
1783 Py_INCREF(tmp);
1786 return result;
1789 PyObject *
1790 PyObject_CallMethodObjArgs(PyObject *callable, PyObject *name, ...)
1792 PyObject *args, *tmp;
1793 va_list vargs;
1795 if (callable == NULL || name == NULL)
1796 return null_error();
1798 callable = PyObject_GetAttr(callable, name);
1799 if (callable == NULL)
1800 return NULL;
1802 /* count the args */
1803 va_start(vargs, name);
1804 args = objargs_mktuple(vargs);
1805 va_end(vargs);
1806 if (args == NULL) {
1807 Py_DECREF(callable);
1808 return NULL;
1810 tmp = PyObject_Call(callable, args, NULL);
1811 Py_DECREF(args);
1812 Py_DECREF(callable);
1814 return tmp;
1817 PyObject *
1818 PyObject_CallFunctionObjArgs(PyObject *callable, ...)
1820 PyObject *args, *tmp;
1821 va_list vargs;
1823 if (callable == NULL)
1824 return null_error();
1826 /* count the args */
1827 va_start(vargs, callable);
1828 args = objargs_mktuple(vargs);
1829 va_end(vargs);
1830 if (args == NULL)
1831 return NULL;
1832 tmp = PyObject_Call(callable, args, NULL);
1833 Py_DECREF(args);
1835 return tmp;
1839 /* isinstance(), issubclass() */
1841 static PyObject *
1842 abstract_get_bases(PyObject *cls)
1844 static PyObject *__bases__ = NULL;
1845 PyObject *bases;
1847 if (__bases__ == NULL) {
1848 __bases__ = PyString_FromString("__bases__");
1849 if (__bases__ == NULL)
1850 return NULL;
1853 bases = PyObject_GetAttr(cls, __bases__);
1854 if (bases == NULL || !PyTuple_Check(bases)) {
1855 Py_XDECREF(bases);
1856 return NULL;
1859 return bases;
1863 static int
1864 abstract_issubclass(PyObject *derived, PyObject *cls)
1866 PyObject *bases;
1867 int i, n;
1868 int r = 0;
1871 if (derived == cls)
1872 return 1;
1874 bases = abstract_get_bases(derived);
1875 if (bases == NULL)
1876 return 0;
1878 n = PyTuple_GET_SIZE(bases);
1879 for (i = 0; i < n; i++) {
1880 r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
1881 if (r != 0)
1882 break;
1885 Py_DECREF(bases);
1887 return r;
1891 PyObject_IsInstance(PyObject *inst, PyObject *cls)
1893 PyObject *icls;
1894 static PyObject *__class__ = NULL;
1895 int retval = 0;
1897 if (PyClass_Check(cls) && PyInstance_Check(inst)) {
1898 PyObject *inclass =
1899 (PyObject*)((PyInstanceObject*)inst)->in_class;
1900 retval = PyClass_IsSubclass(inclass, cls);
1902 else if (PyType_Check(cls)) {
1903 retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
1905 else if (PyTuple_Check(cls)) {
1906 /* Not a general sequence -- that opens up the road to
1907 recursion and stack overflow. */
1908 int i, n;
1910 n = PyTuple_GET_SIZE(cls);
1911 for (i = 0; i < n; i++) {
1912 retval = PyObject_IsInstance(
1913 inst, PyTuple_GET_ITEM(cls, i));
1914 if (retval != 0)
1915 break;
1917 return retval;
1919 else {
1920 PyObject *cls_bases = abstract_get_bases(cls);
1921 if (cls_bases == NULL) {
1922 PyErr_SetString(PyExc_TypeError,
1923 "isinstance() arg 2 must be a class or type");
1924 return -1;
1926 Py_DECREF(cls_bases);
1927 if (__class__ == NULL) {
1928 __class__ = PyString_FromString("__class__");
1929 if (__class__ == NULL)
1930 return -1;
1932 icls = PyObject_GetAttr(inst, __class__);
1933 if (icls == NULL) {
1934 PyErr_Clear();
1935 retval = 0;
1937 else {
1938 retval = abstract_issubclass(icls, cls);
1939 Py_DECREF(icls);
1943 return retval;
1947 PyObject_IsSubclass(PyObject *derived, PyObject *cls)
1949 int retval;
1951 if (!PyClass_Check(derived) || !PyClass_Check(cls)) {
1952 PyObject *derived_bases;
1953 PyObject *cls_bases;
1955 derived_bases = abstract_get_bases(derived);
1956 if (derived_bases == NULL) {
1957 PyErr_SetString(PyExc_TypeError,
1958 "issubclass() arg 1 must be a class");
1959 return -1;
1961 Py_DECREF(derived_bases);
1963 cls_bases = abstract_get_bases(cls);
1964 if (cls_bases == NULL) {
1965 PyErr_SetString(PyExc_TypeError,
1966 "issubclass() arg 2 must be a class");
1967 return -1;
1969 Py_DECREF(cls_bases);
1971 retval = abstract_issubclass(derived, cls);
1973 else {
1974 /* shortcut */
1975 if (!(retval = (derived == cls)))
1976 retval = PyClass_IsSubclass(derived, cls);
1979 return retval;
1982 PyObject *
1983 PyObject_GetIter(PyObject *o)
1985 PyTypeObject *t = o->ob_type;
1986 getiterfunc f = NULL;
1987 if (PyType_HasFeature(t, Py_TPFLAGS_HAVE_ITER))
1988 f = t->tp_iter;
1989 if (f == NULL) {
1990 if (PySequence_Check(o))
1991 return PySeqIter_New(o);
1992 PyErr_SetString(PyExc_TypeError,
1993 "iteration over non-sequence");
1994 return NULL;
1996 else {
1997 PyObject *res = (*f)(o);
1998 if (res != NULL && !PyIter_Check(res)) {
1999 PyErr_Format(PyExc_TypeError,
2000 "iter() returned non-iterator "
2001 "of type '%.100s'",
2002 res->ob_type->tp_name);
2003 Py_DECREF(res);
2004 res = NULL;
2006 return res;
2010 /* Return next item.
2011 * If an error occurs, return NULL. PyErr_Occurred() will be true.
2012 * If the iteration terminates normally, return NULL and clear the
2013 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
2014 * will be false.
2015 * Else return the next object. PyErr_Occurred() will be false.
2017 PyObject *
2018 PyIter_Next(PyObject *iter)
2020 PyObject *result;
2021 if (!PyIter_Check(iter)) {
2022 PyErr_Format(PyExc_TypeError,
2023 "'%.100s' object is not an iterator",
2024 iter->ob_type->tp_name);
2025 return NULL;
2027 result = (*iter->ob_type->tp_iternext)(iter);
2028 if (result == NULL &&
2029 PyErr_Occurred() &&
2030 PyErr_ExceptionMatches(PyExc_StopIteration))
2031 PyErr_Clear();
2032 return result;