Fix three PyChecker-detected gotchas.
[python/dscho.git] / Objects / classobject.c
blobfa71c4ea3a74fa187150a8f1146d00c8b674f060
2 /* Class object implementation */
4 #include "Python.h"
5 #include "structmember.h"
8 /* Forward */
9 static PyObject *class_lookup(PyClassObject *, PyObject *,
10 PyClassObject **);
11 static PyObject *instance_getattr1(PyInstanceObject *, PyObject *);
12 static PyObject *instance_getattr2(PyInstanceObject *, PyObject *);
14 static PyObject *getattrstr, *setattrstr, *delattrstr;
17 PyObject *
18 PyClass_New(PyObject *bases, PyObject *dict, PyObject *name)
19 /* bases is NULL or tuple of classobjects! */
21 PyClassObject *op, *dummy;
22 static PyObject *docstr, *modstr, *namestr;
23 if (docstr == NULL) {
24 docstr= PyString_InternFromString("__doc__");
25 if (docstr == NULL)
26 return NULL;
28 if (modstr == NULL) {
29 modstr= PyString_InternFromString("__module__");
30 if (modstr == NULL)
31 return NULL;
33 if (namestr == NULL) {
34 namestr= PyString_InternFromString("__name__");
35 if (namestr == NULL)
36 return NULL;
38 if (name == NULL || !PyString_Check(name)) {
39 PyErr_SetString(PyExc_SystemError,
40 "PyClass_New: name must be a string");
41 return NULL;
43 if (dict == NULL || !PyDict_Check(dict)) {
44 PyErr_SetString(PyExc_SystemError,
45 "PyClass_New: dict must be a dictionary");
46 return NULL;
48 if (PyDict_GetItem(dict, docstr) == NULL) {
49 if (PyDict_SetItem(dict, docstr, Py_None) < 0)
50 return NULL;
52 if (PyDict_GetItem(dict, modstr) == NULL) {
53 PyObject *globals = PyEval_GetGlobals();
54 if (globals != NULL) {
55 PyObject *modname = PyDict_GetItem(globals, namestr);
56 if (modname != NULL) {
57 if (PyDict_SetItem(dict, modstr, modname) < 0)
58 return NULL;
62 if (bases == NULL) {
63 bases = PyTuple_New(0);
64 if (bases == NULL)
65 return NULL;
67 else {
68 int i;
69 if (!PyTuple_Check(bases)) {
70 PyErr_SetString(PyExc_SystemError,
71 "PyClass_New: bases must be a tuple");
72 return NULL;
74 i = PyTuple_Size(bases);
75 while (--i >= 0) {
76 if (!PyClass_Check(PyTuple_GetItem(bases, i))) {
77 PyErr_SetString(PyExc_SystemError,
78 "PyClass_New: base must be a class");
79 return NULL;
82 Py_INCREF(bases);
84 op = PyObject_NEW(PyClassObject, &PyClass_Type);
85 if (op == NULL) {
86 Py_DECREF(bases);
87 return NULL;
89 op->cl_bases = bases;
90 Py_INCREF(dict);
91 op->cl_dict = dict;
92 Py_XINCREF(name);
93 op->cl_name = name;
94 if (getattrstr == NULL) {
95 getattrstr = PyString_InternFromString("__getattr__");
96 setattrstr = PyString_InternFromString("__setattr__");
97 delattrstr = PyString_InternFromString("__delattr__");
99 op->cl_getattr = class_lookup(op, getattrstr, &dummy);
100 op->cl_setattr = class_lookup(op, setattrstr, &dummy);
101 op->cl_delattr = class_lookup(op, delattrstr, &dummy);
102 Py_XINCREF(op->cl_getattr);
103 Py_XINCREF(op->cl_setattr);
104 Py_XINCREF(op->cl_delattr);
105 PyObject_GC_Init(op);
106 return (PyObject *) op;
109 /* Class methods */
111 static void
112 class_dealloc(PyClassObject *op)
114 PyObject_GC_Fini(op);
115 Py_DECREF(op->cl_bases);
116 Py_DECREF(op->cl_dict);
117 Py_XDECREF(op->cl_name);
118 Py_XDECREF(op->cl_getattr);
119 Py_XDECREF(op->cl_setattr);
120 Py_XDECREF(op->cl_delattr);
121 op = (PyClassObject *) PyObject_AS_GC(op);
122 PyObject_DEL(op);
125 static PyObject *
126 class_lookup(PyClassObject *cp, PyObject *name, PyClassObject **pclass)
128 int i, n;
129 PyObject *value = PyDict_GetItem(cp->cl_dict, name);
130 if (value != NULL) {
131 *pclass = cp;
132 return value;
134 n = PyTuple_Size(cp->cl_bases);
135 for (i = 0; i < n; i++) {
136 /* XXX What if one of the bases is not a class? */
137 PyObject *v = class_lookup(
138 (PyClassObject *)
139 PyTuple_GetItem(cp->cl_bases, i), name, pclass);
140 if (v != NULL)
141 return v;
143 return NULL;
146 static PyObject *
147 class_getattr(register PyClassObject *op, PyObject *name)
149 register PyObject *v;
150 register char *sname = PyString_AsString(name);
151 PyClassObject *class;
152 if (sname[0] == '_' && sname[1] == '_') {
153 if (strcmp(sname, "__dict__") == 0) {
154 if (PyEval_GetRestricted()) {
155 PyErr_SetString(PyExc_RuntimeError,
156 "class.__dict__ not accessible in restricted mode");
157 return NULL;
159 Py_INCREF(op->cl_dict);
160 return op->cl_dict;
162 if (strcmp(sname, "__bases__") == 0) {
163 Py_INCREF(op->cl_bases);
164 return op->cl_bases;
166 if (strcmp(sname, "__name__") == 0) {
167 if (op->cl_name == NULL)
168 v = Py_None;
169 else
170 v = op->cl_name;
171 Py_INCREF(v);
172 return v;
175 v = class_lookup(op, name, &class);
176 if (v == NULL) {
177 PyErr_Format(PyExc_AttributeError,
178 "class %.50s has no attribute '%.400s'",
179 PyString_AS_STRING(op->cl_name), sname);
180 return NULL;
182 Py_INCREF(v);
183 if (PyFunction_Check(v)) {
184 PyObject *w = PyMethod_New(v, (PyObject *)NULL,
185 (PyObject *)class);
186 Py_DECREF(v);
187 v = w;
189 return v;
192 static void
193 set_slot(PyObject **slot, PyObject *v)
195 PyObject *temp = *slot;
196 Py_XINCREF(v);
197 *slot = v;
198 Py_XDECREF(temp);
201 static void
202 set_attr_slots(PyClassObject *c)
204 PyClassObject *dummy;
206 set_slot(&c->cl_getattr, class_lookup(c, getattrstr, &dummy));
207 set_slot(&c->cl_setattr, class_lookup(c, setattrstr, &dummy));
208 set_slot(&c->cl_delattr, class_lookup(c, delattrstr, &dummy));
211 static char *
212 set_dict(PyClassObject *c, PyObject *v)
214 if (v == NULL || !PyDict_Check(v))
215 return "__dict__ must be a dictionary object";
216 set_slot(&c->cl_dict, v);
217 set_attr_slots(c);
218 return "";
221 static char *
222 set_bases(PyClassObject *c, PyObject *v)
224 int i, n;
226 if (v == NULL || !PyTuple_Check(v))
227 return "__bases__ must be a tuple object";
228 n = PyTuple_Size(v);
229 for (i = 0; i < n; i++) {
230 PyObject *x = PyTuple_GET_ITEM(v, i);
231 if (!PyClass_Check(x))
232 return "__bases__ items must be classes";
233 if (PyClass_IsSubclass(x, (PyObject *)c))
234 return "a __bases__ item causes an inheritance cycle";
236 set_slot(&c->cl_bases, v);
237 set_attr_slots(c);
238 return "";
241 static char *
242 set_name(PyClassObject *c, PyObject *v)
244 if (v == NULL || !PyString_Check(v))
245 return "__name__ must be a string object";
246 if (strlen(PyString_AS_STRING(v)) != (size_t)PyString_GET_SIZE(v))
247 return "__name__ must not contain null bytes";
248 set_slot(&c->cl_name, v);
249 return "";
252 static int
253 class_setattr(PyClassObject *op, PyObject *name, PyObject *v)
255 char *sname;
256 if (PyEval_GetRestricted()) {
257 PyErr_SetString(PyExc_RuntimeError,
258 "classes are read-only in restricted mode");
259 return -1;
261 sname = PyString_AsString(name);
262 if (sname[0] == '_' && sname[1] == '_') {
263 int n = PyString_Size(name);
264 if (sname[n-1] == '_' && sname[n-2] == '_') {
265 char *err = NULL;
266 if (strcmp(sname, "__dict__") == 0)
267 err = set_dict(op, v);
268 else if (strcmp(sname, "__bases__") == 0)
269 err = set_bases(op, v);
270 else if (strcmp(sname, "__name__") == 0)
271 err = set_name(op, v);
272 else if (strcmp(sname, "__getattr__") == 0)
273 set_slot(&op->cl_getattr, v);
274 else if (strcmp(sname, "__setattr__") == 0)
275 set_slot(&op->cl_setattr, v);
276 else if (strcmp(sname, "__delattr__") == 0)
277 set_slot(&op->cl_delattr, v);
278 /* For the last three, we fall through to update the
279 dictionary as well. */
280 if (err != NULL) {
281 if (*err == '\0')
282 return 0;
283 PyErr_SetString(PyExc_TypeError, err);
284 return -1;
288 if (v == NULL) {
289 int rv = PyDict_DelItem(op->cl_dict, name);
290 if (rv < 0)
291 PyErr_Format(PyExc_AttributeError,
292 "class %.50s has no attribute '%.400s'",
293 PyString_AS_STRING(op->cl_name), sname);
294 return rv;
296 else
297 return PyDict_SetItem(op->cl_dict, name, v);
300 static PyObject *
301 class_repr(PyClassObject *op)
303 PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
304 char buf[140];
305 char *name;
306 if (op->cl_name == NULL || !PyString_Check(op->cl_name))
307 name = "?";
308 else
309 name = PyString_AsString(op->cl_name);
310 if (mod == NULL || !PyString_Check(mod))
311 sprintf(buf, "<class ?.%.100s at %p>", name, op);
312 else
313 sprintf(buf, "<class %.50s.%.50s at %p>",
314 PyString_AsString(mod),
315 name, op);
316 return PyString_FromString(buf);
319 static PyObject *
320 class_str(PyClassObject *op)
322 PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
323 PyObject *name = op->cl_name;
324 PyObject *res;
325 int m, n;
327 if (name == NULL || !PyString_Check(name))
328 return class_repr(op);
329 if (mod == NULL || !PyString_Check(mod)) {
330 Py_INCREF(name);
331 return name;
333 m = PyString_Size(mod);
334 n = PyString_Size(name);
335 res = PyString_FromStringAndSize((char *)NULL, m+1+n);
336 if (res != NULL) {
337 char *s = PyString_AsString(res);
338 memcpy(s, PyString_AsString(mod), m);
339 s += m;
340 *s++ = '.';
341 memcpy(s, PyString_AsString(name), n);
343 return res;
346 static int
347 class_traverse(PyClassObject *o, visitproc visit, void *arg)
349 int err;
350 if (o->cl_bases) {
351 err = visit(o->cl_bases, arg);
352 if (err)
353 return err;
355 if (o->cl_dict) {
356 err = visit(o->cl_dict, arg);
357 if (err)
358 return err;
360 if (o->cl_name) {
361 err = visit(o->cl_name, arg);
362 if (err)
363 return err;
365 if (o->cl_getattr) {
366 err = visit(o->cl_getattr, arg);
367 if (err)
368 return err;
370 if (o->cl_setattr) {
371 err = visit(o->cl_setattr, arg);
372 if (err)
373 return err;
375 if (o->cl_delattr) {
376 err = visit(o->cl_delattr, arg);
377 if (err)
378 return err;
380 return 0;
383 PyTypeObject PyClass_Type = {
384 PyObject_HEAD_INIT(&PyType_Type)
386 "class",
387 sizeof(PyClassObject) + PyGC_HEAD_SIZE,
389 (destructor)class_dealloc, /* tp_dealloc */
390 0, /* tp_print */
391 0, /* tp_getattr */
392 0, /* tp_setattr */
393 0, /* tp_compare */
394 (reprfunc)class_repr, /* tp_repr */
395 0, /* tp_as_number */
396 0, /* tp_as_sequence */
397 0, /* tp_as_mapping */
398 0, /* tp_hash */
399 0, /* tp_call */
400 (reprfunc)class_str, /* tp_str */
401 (getattrofunc)class_getattr, /* tp_getattro */
402 (setattrofunc)class_setattr, /* tp_setattro */
403 0, /* tp_as_buffer */
404 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /* tp_flags */
405 0, /* tp_doc */
406 (traverseproc)class_traverse, /* tp_traverse */
410 PyClass_IsSubclass(PyObject *class, PyObject *base)
412 int i, n;
413 PyClassObject *cp;
414 if (class == base)
415 return 1;
416 if (class == NULL || !PyClass_Check(class))
417 return 0;
418 cp = (PyClassObject *)class;
419 n = PyTuple_Size(cp->cl_bases);
420 for (i = 0; i < n; i++) {
421 if (PyClass_IsSubclass(PyTuple_GetItem(cp->cl_bases, i), base))
422 return 1;
424 return 0;
428 /* Instance objects */
430 PyObject *
431 PyInstance_NewRaw(PyObject *klass, PyObject *dict)
433 PyInstanceObject *inst;
435 if (!PyClass_Check(klass)) {
436 PyErr_BadInternalCall();
437 return NULL;
439 if (dict == NULL) {
440 dict = PyDict_New();
441 if (dict == NULL)
442 return NULL;
444 else {
445 if (!PyDict_Check(dict)) {
446 PyErr_BadInternalCall();
447 return NULL;
449 Py_INCREF(dict);
451 inst = PyObject_NEW(PyInstanceObject, &PyInstance_Type);
452 if (inst == NULL) {
453 Py_DECREF(dict);
454 return NULL;
456 inst->in_weakreflist = NULL;
457 Py_INCREF(klass);
458 inst->in_class = (PyClassObject *)klass;
459 inst->in_dict = dict;
460 PyObject_GC_Init(inst);
461 return (PyObject *)inst;
464 PyObject *
465 PyInstance_New(PyObject *klass, PyObject *arg, PyObject *kw)
467 register PyInstanceObject *inst;
468 PyObject *init;
469 static PyObject *initstr;
471 inst = (PyInstanceObject *) PyInstance_NewRaw(klass, NULL);
472 if (inst == NULL)
473 return NULL;
474 if (initstr == NULL)
475 initstr = PyString_InternFromString("__init__");
476 init = instance_getattr2(inst, initstr);
477 if (init == NULL) {
478 if ((arg != NULL && (!PyTuple_Check(arg) ||
479 PyTuple_Size(arg) != 0))
480 || (kw != NULL && (!PyDict_Check(kw) ||
481 PyDict_Size(kw) != 0))) {
482 PyErr_SetString(PyExc_TypeError,
483 "this constructor takes no arguments");
484 Py_DECREF(inst);
485 inst = NULL;
488 else {
489 PyObject *res = PyEval_CallObjectWithKeywords(init, arg, kw);
490 Py_DECREF(init);
491 if (res == NULL) {
492 Py_DECREF(inst);
493 inst = NULL;
495 else {
496 if (res != Py_None) {
497 PyErr_SetString(PyExc_TypeError,
498 "__init__() should return None");
499 Py_DECREF(inst);
500 inst = NULL;
502 Py_DECREF(res);
505 return (PyObject *)inst;
508 /* Instance methods */
510 static void
511 instance_dealloc(register PyInstanceObject *inst)
513 PyObject *error_type, *error_value, *error_traceback;
514 PyObject *del;
515 static PyObject *delstr;
516 #ifdef Py_REF_DEBUG
517 extern long _Py_RefTotal;
518 #endif
520 PyObject_ClearWeakRefs((PyObject *) inst);
522 /* Temporarily resurrect the object. */
523 #ifdef Py_TRACE_REFS
524 #ifndef Py_REF_DEBUG
525 # error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
526 #endif
527 /* much too complicated if Py_TRACE_REFS defined */
528 inst->ob_type = &PyInstance_Type;
529 _Py_NewReference((PyObject *)inst);
530 #ifdef COUNT_ALLOCS
531 /* compensate for boost in _Py_NewReference; note that
532 * _Py_RefTotal was also boosted; we'll knock that down later.
534 inst->ob_type->tp_alloc--;
535 #endif
536 #else /* !Py_TRACE_REFS */
537 /* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
538 Py_INCREF(inst);
539 #endif /* !Py_TRACE_REFS */
541 /* Save the current exception, if any. */
542 PyErr_Fetch(&error_type, &error_value, &error_traceback);
543 /* Execute __del__ method, if any. */
544 if (delstr == NULL)
545 delstr = PyString_InternFromString("__del__");
546 if ((del = instance_getattr2(inst, delstr)) != NULL) {
547 PyObject *res = PyEval_CallObject(del, (PyObject *)NULL);
548 if (res == NULL)
549 PyErr_WriteUnraisable(del);
550 else
551 Py_DECREF(res);
552 Py_DECREF(del);
554 /* Restore the saved exception. */
555 PyErr_Restore(error_type, error_value, error_traceback);
556 /* Undo the temporary resurrection; can't use DECREF here, it would
557 * cause a recursive call.
559 #ifdef Py_REF_DEBUG
560 /* _Py_RefTotal was boosted either by _Py_NewReference or
561 * Py_INCREF above.
563 _Py_RefTotal--;
564 #endif
565 if (--inst->ob_refcnt > 0) {
566 #ifdef COUNT_ALLOCS
567 inst->ob_type->tp_free--;
568 #endif
569 return; /* __del__ added a reference; don't delete now */
571 #ifdef Py_TRACE_REFS
572 _Py_ForgetReference((PyObject *)inst);
573 #ifdef COUNT_ALLOCS
574 /* compensate for increment in _Py_ForgetReference */
575 inst->ob_type->tp_free--;
576 #endif
577 #ifndef WITH_CYCLE_GC
578 inst->ob_type = NULL;
579 #endif
580 #endif
581 PyObject_GC_Fini(inst);
582 Py_DECREF(inst->in_class);
583 Py_XDECREF(inst->in_dict);
584 inst = (PyInstanceObject *) PyObject_AS_GC(inst);
585 PyObject_DEL(inst);
588 static PyObject *
589 instance_getattr1(register PyInstanceObject *inst, PyObject *name)
591 register PyObject *v;
592 register char *sname = PyString_AsString(name);
593 if (sname[0] == '_' && sname[1] == '_') {
594 if (strcmp(sname, "__dict__") == 0) {
595 if (PyEval_GetRestricted()) {
596 PyErr_SetString(PyExc_RuntimeError,
597 "instance.__dict__ not accessible in restricted mode");
598 return NULL;
600 Py_INCREF(inst->in_dict);
601 return inst->in_dict;
603 if (strcmp(sname, "__class__") == 0) {
604 Py_INCREF(inst->in_class);
605 return (PyObject *)inst->in_class;
608 v = instance_getattr2(inst, name);
609 if (v == NULL) {
610 PyErr_Format(PyExc_AttributeError,
611 "%.50s instance has no attribute '%.400s'",
612 PyString_AS_STRING(inst->in_class->cl_name), sname);
614 return v;
617 static PyObject *
618 instance_getattr2(register PyInstanceObject *inst, PyObject *name)
620 register PyObject *v;
621 PyClassObject *class;
622 class = NULL;
623 v = PyDict_GetItem(inst->in_dict, name);
624 if (v == NULL) {
625 v = class_lookup(inst->in_class, name, &class);
626 if (v == NULL)
627 return v;
629 Py_INCREF(v);
630 if (class != NULL) {
631 if (PyFunction_Check(v)) {
632 PyObject *w = PyMethod_New(v, (PyObject *)inst,
633 (PyObject *)class);
634 Py_DECREF(v);
635 v = w;
637 else if (PyMethod_Check(v)) {
638 PyObject *im_class = PyMethod_Class(v);
639 /* Only if classes are compatible */
640 if (PyClass_IsSubclass((PyObject *)class, im_class)) {
641 PyObject *im_func = PyMethod_Function(v);
642 PyObject *w = PyMethod_New(im_func,
643 (PyObject *)inst, im_class);
644 Py_DECREF(v);
645 v = w;
649 return v;
652 static PyObject *
653 instance_getattr(register PyInstanceObject *inst, PyObject *name)
655 register PyObject *func, *res;
656 res = instance_getattr1(inst, name);
657 if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) {
658 PyObject *args;
659 PyErr_Clear();
660 args = Py_BuildValue("(OO)", inst, name);
661 if (args == NULL)
662 return NULL;
663 res = PyEval_CallObject(func, args);
664 Py_DECREF(args);
666 return res;
669 static int
670 instance_setattr1(PyInstanceObject *inst, PyObject *name, PyObject *v)
672 if (v == NULL) {
673 int rv = PyDict_DelItem(inst->in_dict, name);
674 if (rv < 0)
675 PyErr_Format(PyExc_AttributeError,
676 "%.50s instance has no attribute '%.400s'",
677 PyString_AS_STRING(inst->in_class->cl_name),
678 PyString_AS_STRING(name));
679 return rv;
681 else
682 return PyDict_SetItem(inst->in_dict, name, v);
685 static int
686 instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v)
688 PyObject *func, *args, *res, *tmp;
689 char *sname = PyString_AsString(name);
690 if (sname[0] == '_' && sname[1] == '_') {
691 int n = PyString_Size(name);
692 if (sname[n-1] == '_' && sname[n-2] == '_') {
693 if (strcmp(sname, "__dict__") == 0) {
694 if (PyEval_GetRestricted()) {
695 PyErr_SetString(PyExc_RuntimeError,
696 "__dict__ not accessible in restricted mode");
697 return -1;
699 if (v == NULL || !PyDict_Check(v)) {
700 PyErr_SetString(PyExc_TypeError,
701 "__dict__ must be set to a dictionary");
702 return -1;
704 tmp = inst->in_dict;
705 Py_INCREF(v);
706 inst->in_dict = v;
707 Py_DECREF(tmp);
708 return 0;
710 if (strcmp(sname, "__class__") == 0) {
711 if (PyEval_GetRestricted()) {
712 PyErr_SetString(PyExc_RuntimeError,
713 "__class__ not accessible in restricted mode");
714 return -1;
716 if (v == NULL || !PyClass_Check(v)) {
717 PyErr_SetString(PyExc_TypeError,
718 "__class__ must be set to a class");
719 return -1;
721 tmp = (PyObject *)(inst->in_class);
722 Py_INCREF(v);
723 inst->in_class = (PyClassObject *)v;
724 Py_DECREF(tmp);
725 return 0;
729 if (v == NULL)
730 func = inst->in_class->cl_delattr;
731 else
732 func = inst->in_class->cl_setattr;
733 if (func == NULL)
734 return instance_setattr1(inst, name, v);
735 if (v == NULL)
736 args = Py_BuildValue("(OO)", inst, name);
737 else
738 args = Py_BuildValue("(OOO)", inst, name, v);
739 if (args == NULL)
740 return -1;
741 res = PyEval_CallObject(func, args);
742 Py_DECREF(args);
743 if (res == NULL)
744 return -1;
745 Py_DECREF(res);
746 return 0;
749 static PyObject *
750 instance_repr(PyInstanceObject *inst)
752 PyObject *func;
753 PyObject *res;
754 static PyObject *reprstr;
756 if (reprstr == NULL)
757 reprstr = PyString_InternFromString("__repr__");
758 func = instance_getattr(inst, reprstr);
759 if (func == NULL) {
760 char buf[140];
761 PyObject *classname = inst->in_class->cl_name;
762 PyObject *mod = PyDict_GetItemString(
763 inst->in_class->cl_dict, "__module__");
764 char *cname;
765 if (classname != NULL && PyString_Check(classname))
766 cname = PyString_AsString(classname);
767 else
768 cname = "?";
769 PyErr_Clear();
770 if (mod == NULL || !PyString_Check(mod))
771 sprintf(buf, "<?.%.100s instance at %p>",
772 cname, inst);
773 else
774 sprintf(buf, "<%.50s.%.50s instance at %p>",
775 PyString_AsString(mod),
776 cname, inst);
777 return PyString_FromString(buf);
779 res = PyEval_CallObject(func, (PyObject *)NULL);
780 Py_DECREF(func);
781 return res;
784 static long
785 instance_hash(PyInstanceObject *inst)
787 PyObject *func;
788 PyObject *res;
789 long outcome;
790 static PyObject *hashstr, *eqstr, *cmpstr;
792 if (hashstr == NULL)
793 hashstr = PyString_InternFromString("__hash__");
794 func = instance_getattr(inst, hashstr);
795 if (func == NULL) {
796 /* If there is no __eq__ and no __cmp__ method, we hash on the
797 address. If an __eq__ or __cmp__ method exists, there must
798 be a __hash__. */
799 PyErr_Clear();
800 if (eqstr == NULL)
801 eqstr = PyString_InternFromString("__eq__");
802 func = instance_getattr(inst, eqstr);
803 if (func == NULL) {
804 PyErr_Clear();
805 if (cmpstr == NULL)
806 cmpstr = PyString_InternFromString("__cmp__");
807 func = instance_getattr(inst, cmpstr);
808 if (func == NULL) {
809 PyErr_Clear();
810 return _Py_HashPointer(inst);
813 PyErr_SetString(PyExc_TypeError, "unhashable instance");
814 return -1;
816 res = PyEval_CallObject(func, (PyObject *)NULL);
817 Py_DECREF(func);
818 if (res == NULL)
819 return -1;
820 if (PyInt_Check(res)) {
821 outcome = PyInt_AsLong(res);
822 if (outcome == -1)
823 outcome = -2;
825 else {
826 PyErr_SetString(PyExc_TypeError,
827 "__hash__() should return an int");
828 outcome = -1;
830 Py_DECREF(res);
831 return outcome;
834 static int
835 instance_traverse(PyInstanceObject *o, visitproc visit, void *arg)
837 int err;
838 if (o->in_class) {
839 err = visit((PyObject *)(o->in_class), arg);
840 if (err)
841 return err;
843 if (o->in_dict) {
844 err = visit(o->in_dict, arg);
845 if (err)
846 return err;
848 return 0;
851 static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr;
853 static int
854 instance_length(PyInstanceObject *inst)
856 PyObject *func;
857 PyObject *res;
858 int outcome;
860 if (lenstr == NULL)
861 lenstr = PyString_InternFromString("__len__");
862 func = instance_getattr(inst, lenstr);
863 if (func == NULL)
864 return -1;
865 res = PyEval_CallObject(func, (PyObject *)NULL);
866 Py_DECREF(func);
867 if (res == NULL)
868 return -1;
869 if (PyInt_Check(res)) {
870 outcome = PyInt_AsLong(res);
871 if (outcome < 0)
872 PyErr_SetString(PyExc_ValueError,
873 "__len__() should return >= 0");
875 else {
876 PyErr_SetString(PyExc_TypeError,
877 "__len__() should return an int");
878 outcome = -1;
880 Py_DECREF(res);
881 return outcome;
884 static PyObject *
885 instance_subscript(PyInstanceObject *inst, PyObject *key)
887 PyObject *func;
888 PyObject *arg;
889 PyObject *res;
891 if (getitemstr == NULL)
892 getitemstr = PyString_InternFromString("__getitem__");
893 func = instance_getattr(inst, getitemstr);
894 if (func == NULL)
895 return NULL;
896 arg = Py_BuildValue("(O)", key);
897 if (arg == NULL) {
898 Py_DECREF(func);
899 return NULL;
901 res = PyEval_CallObject(func, arg);
902 Py_DECREF(func);
903 Py_DECREF(arg);
904 return res;
907 static int
908 instance_ass_subscript(PyInstanceObject *inst, PyObject *key, PyObject *value)
910 PyObject *func;
911 PyObject *arg;
912 PyObject *res;
914 if (value == NULL) {
915 if (delitemstr == NULL)
916 delitemstr = PyString_InternFromString("__delitem__");
917 func = instance_getattr(inst, delitemstr);
919 else {
920 if (setitemstr == NULL)
921 setitemstr = PyString_InternFromString("__setitem__");
922 func = instance_getattr(inst, setitemstr);
924 if (func == NULL)
925 return -1;
926 if (value == NULL)
927 arg = Py_BuildValue("(O)", key);
928 else
929 arg = Py_BuildValue("(OO)", key, value);
930 if (arg == NULL) {
931 Py_DECREF(func);
932 return -1;
934 res = PyEval_CallObject(func, arg);
935 Py_DECREF(func);
936 Py_DECREF(arg);
937 if (res == NULL)
938 return -1;
939 Py_DECREF(res);
940 return 0;
943 static PyMappingMethods instance_as_mapping = {
944 (inquiry)instance_length, /* mp_length */
945 (binaryfunc)instance_subscript, /* mp_subscript */
946 (objobjargproc)instance_ass_subscript, /* mp_ass_subscript */
949 static PyObject *
950 instance_item(PyInstanceObject *inst, int i)
952 PyObject *func, *arg, *res;
954 if (getitemstr == NULL)
955 getitemstr = PyString_InternFromString("__getitem__");
956 func = instance_getattr(inst, getitemstr);
957 if (func == NULL)
958 return NULL;
959 arg = Py_BuildValue("(i)", i);
960 if (arg == NULL) {
961 Py_DECREF(func);
962 return NULL;
964 res = PyEval_CallObject(func, arg);
965 Py_DECREF(func);
966 Py_DECREF(arg);
967 return res;
970 static PyObject *
971 sliceobj_from_intint(int i, int j)
973 PyObject *start, *end, *res;
975 start = PyInt_FromLong((long)i);
976 if (!start)
977 return NULL;
979 end = PyInt_FromLong((long)j);
980 if (!end) {
981 Py_DECREF(start);
982 return NULL;
984 res = PySlice_New(start, end, NULL);
985 Py_DECREF(start);
986 Py_DECREF(end);
987 return res;
991 static PyObject *
992 instance_slice(PyInstanceObject *inst, int i, int j)
994 PyObject *func, *arg, *res;
995 static PyObject *getslicestr;
997 if (getslicestr == NULL)
998 getslicestr = PyString_InternFromString("__getslice__");
999 func = instance_getattr(inst, getslicestr);
1001 if (func == NULL) {
1002 PyErr_Clear();
1004 if (getitemstr == NULL)
1005 getitemstr = PyString_InternFromString("__getitem__");
1006 func = instance_getattr(inst, getitemstr);
1007 if (func == NULL)
1008 return NULL;
1009 arg = Py_BuildValue("(N)", sliceobj_from_intint(i, j));
1010 } else
1011 arg = Py_BuildValue("(ii)", i, j);
1013 if (arg == NULL) {
1014 Py_DECREF(func);
1015 return NULL;
1017 res = PyEval_CallObject(func, arg);
1018 Py_DECREF(func);
1019 Py_DECREF(arg);
1020 return res;
1023 static int
1024 instance_ass_item(PyInstanceObject *inst, int i, PyObject *item)
1026 PyObject *func, *arg, *res;
1028 if (item == NULL) {
1029 if (delitemstr == NULL)
1030 delitemstr = PyString_InternFromString("__delitem__");
1031 func = instance_getattr(inst, delitemstr);
1033 else {
1034 if (setitemstr == NULL)
1035 setitemstr = PyString_InternFromString("__setitem__");
1036 func = instance_getattr(inst, setitemstr);
1038 if (func == NULL)
1039 return -1;
1040 if (item == NULL)
1041 arg = Py_BuildValue("i", i);
1042 else
1043 arg = Py_BuildValue("(iO)", i, item);
1044 if (arg == NULL) {
1045 Py_DECREF(func);
1046 return -1;
1048 res = PyEval_CallObject(func, arg);
1049 Py_DECREF(func);
1050 Py_DECREF(arg);
1051 if (res == NULL)
1052 return -1;
1053 Py_DECREF(res);
1054 return 0;
1057 static int
1058 instance_ass_slice(PyInstanceObject *inst, int i, int j, PyObject *value)
1060 PyObject *func, *arg, *res;
1061 static PyObject *setslicestr, *delslicestr;
1063 if (value == NULL) {
1064 if (delslicestr == NULL)
1065 delslicestr =
1066 PyString_InternFromString("__delslice__");
1067 func = instance_getattr(inst, delslicestr);
1068 if (func == NULL) {
1069 PyErr_Clear();
1070 if (delitemstr == NULL)
1071 delitemstr =
1072 PyString_InternFromString("__delitem__");
1073 func = instance_getattr(inst, delitemstr);
1074 if (func == NULL)
1075 return -1;
1077 arg = Py_BuildValue("(N)",
1078 sliceobj_from_intint(i, j));
1079 } else
1080 arg = Py_BuildValue("(ii)", i, j);
1082 else {
1083 if (setslicestr == NULL)
1084 setslicestr =
1085 PyString_InternFromString("__setslice__");
1086 func = instance_getattr(inst, setslicestr);
1087 if (func == NULL) {
1088 PyErr_Clear();
1089 if (setitemstr == NULL)
1090 setitemstr =
1091 PyString_InternFromString("__setitem__");
1092 func = instance_getattr(inst, setitemstr);
1093 if (func == NULL)
1094 return -1;
1096 arg = Py_BuildValue("(NO)",
1097 sliceobj_from_intint(i, j), value);
1098 } else
1099 arg = Py_BuildValue("(iiO)", i, j, value);
1101 if (arg == NULL) {
1102 Py_DECREF(func);
1103 return -1;
1105 res = PyEval_CallObject(func, arg);
1106 Py_DECREF(func);
1107 Py_DECREF(arg);
1108 if (res == NULL)
1109 return -1;
1110 Py_DECREF(res);
1111 return 0;
1114 static int instance_contains(PyInstanceObject *inst, PyObject *member)
1116 static PyObject *__contains__;
1117 PyObject *func, *arg, *res;
1118 int ret;
1120 if(__contains__ == NULL) {
1121 __contains__ = PyString_InternFromString("__contains__");
1122 if(__contains__ == NULL)
1123 return -1;
1125 func = instance_getattr(inst, __contains__);
1126 if(func == NULL) {
1127 /* fall back to previous behavior */
1128 int i, cmp_res;
1130 if(!PyErr_ExceptionMatches(PyExc_AttributeError))
1131 return -1;
1132 PyErr_Clear();
1133 for(i=0;;i++) {
1134 PyObject *obj = instance_item(inst, i);
1135 int ret = 0;
1137 if(obj == NULL) {
1138 if(!PyErr_ExceptionMatches(PyExc_IndexError))
1139 return -1;
1140 PyErr_Clear();
1141 return 0;
1143 if(PyObject_Cmp(obj, member, &cmp_res) == -1)
1144 ret = -1;
1145 if(cmp_res == 0)
1146 ret = 1;
1147 Py_DECREF(obj);
1148 if(ret)
1149 return ret;
1152 arg = Py_BuildValue("(O)", member);
1153 if(arg == NULL) {
1154 Py_DECREF(func);
1155 return -1;
1157 res = PyEval_CallObject(func, arg);
1158 Py_DECREF(func);
1159 Py_DECREF(arg);
1160 if(res == NULL)
1161 return -1;
1162 ret = PyObject_IsTrue(res);
1163 Py_DECREF(res);
1164 return ret;
1167 static PySequenceMethods
1168 instance_as_sequence = {
1169 (inquiry)instance_length, /* sq_length */
1170 0, /* sq_concat */
1171 0, /* sq_repeat */
1172 (intargfunc)instance_item, /* sq_item */
1173 (intintargfunc)instance_slice, /* sq_slice */
1174 (intobjargproc)instance_ass_item, /* sq_ass_item */
1175 (intintobjargproc)instance_ass_slice, /* sq_ass_slice */
1176 (objobjproc)instance_contains, /* sq_contains */
1179 static PyObject *
1180 generic_unary_op(PyInstanceObject *self, PyObject *methodname)
1182 PyObject *func, *res;
1184 if ((func = instance_getattr(self, methodname)) == NULL)
1185 return NULL;
1186 res = PyEval_CallObject(func, (PyObject *)NULL);
1187 Py_DECREF(func);
1188 return res;
1191 static PyObject *
1192 generic_binary_op(PyObject *v, PyObject *w, char *opname)
1194 PyObject *result;
1195 PyObject *args;
1196 PyObject *func = PyObject_GetAttrString(v, opname);
1197 if (func == NULL) {
1198 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1199 return NULL;
1200 PyErr_Clear();
1201 Py_INCREF(Py_NotImplemented);
1202 return Py_NotImplemented;
1204 args = Py_BuildValue("(O)", w);
1205 if (args == NULL) {
1206 Py_DECREF(func);
1207 return NULL;
1209 result = PyEval_CallObject(func, args);
1210 Py_DECREF(args);
1211 Py_DECREF(func);
1212 return result;
1216 static PyObject *coerce_obj;
1218 /* Try one half of a binary operator involving a class instance. */
1219 static PyObject *
1220 half_binop(PyObject *v, PyObject *w, char *opname, binaryfunc thisfunc,
1221 int swapped)
1223 PyObject *args;
1224 PyObject *coercefunc;
1225 PyObject *coerced = NULL;
1226 PyObject *v1;
1227 PyObject *result;
1229 if (!PyInstance_Check(v)) {
1230 Py_INCREF(Py_NotImplemented);
1231 return Py_NotImplemented;
1234 if (coerce_obj == NULL) {
1235 coerce_obj = PyString_InternFromString("__coerce__");
1236 if (coerce_obj == NULL)
1237 return NULL;
1239 coercefunc = PyObject_GetAttr(v, coerce_obj);
1240 if (coercefunc == NULL) {
1241 PyErr_Clear();
1242 return generic_binary_op(v, w, opname);
1245 args = Py_BuildValue("(O)", w);
1246 if (args == NULL) {
1247 return NULL;
1249 coerced = PyEval_CallObject(coercefunc, args);
1250 Py_DECREF(args);
1251 Py_DECREF(coercefunc);
1252 if (coerced == NULL) {
1253 return NULL;
1255 if (coerced == Py_None || coerced == Py_NotImplemented) {
1256 Py_DECREF(coerced);
1257 return generic_binary_op(v, w, opname);
1259 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1260 Py_DECREF(coerced);
1261 PyErr_SetString(PyExc_TypeError,
1262 "coercion should return None or 2-tuple");
1263 return NULL;
1265 v1 = PyTuple_GetItem(coerced, 0);
1266 w = PyTuple_GetItem(coerced, 1);
1267 if (v1->ob_type == v->ob_type && PyInstance_Check(v)) {
1268 /* prevent recursion if __coerce__ returns self as the first
1269 * argument */
1270 result = generic_binary_op(v1, w, opname);
1271 } else {
1272 if (swapped)
1273 result = (thisfunc)(w, v1);
1274 else
1275 result = (thisfunc)(v1, w);
1277 Py_DECREF(coerced);
1278 return result;
1281 /* Implement a binary operator involving at least one class instance. */
1282 static PyObject *
1283 do_binop(PyObject *v, PyObject *w, char *opname, char *ropname,
1284 binaryfunc thisfunc)
1286 PyObject *result = half_binop(v, w, opname, thisfunc, 0);
1287 if (result == Py_NotImplemented) {
1288 Py_DECREF(result);
1289 result = half_binop(w, v, ropname, thisfunc, 1);
1291 return result;
1294 static PyObject *
1295 do_binop_inplace(PyObject *v, PyObject *w, char *iopname, char *opname,
1296 char *ropname, binaryfunc thisfunc)
1298 PyObject *result = half_binop(v, w, iopname, thisfunc, 0);
1299 if (result == Py_NotImplemented) {
1300 Py_DECREF(result);
1301 result = do_binop(v, w, opname, ropname, thisfunc);
1303 return result;
1306 static int
1307 instance_coerce(PyObject **pv, PyObject **pw)
1309 PyObject *v = *pv;
1310 PyObject *w = *pw;
1311 PyObject *coercefunc;
1312 PyObject *args;
1313 PyObject *coerced;
1315 if (coerce_obj == NULL) {
1316 coerce_obj = PyString_InternFromString("__coerce__");
1317 if (coerce_obj == NULL)
1318 return -1;
1320 coercefunc = PyObject_GetAttr(v, coerce_obj);
1321 if (coercefunc == NULL) {
1322 /* No __coerce__ method */
1323 PyErr_Clear();
1324 return 1;
1326 /* Has __coerce__ method: call it */
1327 args = Py_BuildValue("(O)", w);
1328 if (args == NULL) {
1329 return -1;
1331 coerced = PyEval_CallObject(coercefunc, args);
1332 Py_DECREF(args);
1333 Py_DECREF(coercefunc);
1334 if (coerced == NULL) {
1335 /* __coerce__ call raised an exception */
1336 return -1;
1338 if (coerced == Py_None || coerced == Py_NotImplemented) {
1339 /* __coerce__ says "I can't do it" */
1340 Py_DECREF(coerced);
1341 return 1;
1343 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1344 /* __coerce__ return value is malformed */
1345 Py_DECREF(coerced);
1346 PyErr_SetString(PyExc_TypeError,
1347 "coercion should return None or 2-tuple");
1348 return -1;
1350 /* __coerce__ returned two new values */
1351 *pv = PyTuple_GetItem(coerced, 0);
1352 *pw = PyTuple_GetItem(coerced, 1);
1353 Py_INCREF(*pv);
1354 Py_INCREF(*pw);
1355 Py_DECREF(coerced);
1356 return 0;
1359 #define UNARY(funcname, methodname) \
1360 static PyObject *funcname(PyInstanceObject *self) { \
1361 static PyObject *o; \
1362 if (o == NULL) o = PyString_InternFromString(methodname); \
1363 return generic_unary_op(self, o); \
1366 #define BINARY(f, m, n) \
1367 static PyObject *f(PyObject *v, PyObject *w) { \
1368 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1371 #define BINARY_INPLACE(f, m, n) \
1372 static PyObject *f(PyObject *v, PyObject *w) { \
1373 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1374 "__r" m "__", n); \
1377 UNARY(instance_neg, "__neg__")
1378 UNARY(instance_pos, "__pos__")
1379 UNARY(instance_abs, "__abs__")
1381 BINARY(instance_or, "or", PyNumber_Or)
1382 BINARY(instance_and, "and", PyNumber_And)
1383 BINARY(instance_xor, "xor", PyNumber_Xor)
1384 BINARY(instance_lshift, "lshift", PyNumber_Lshift)
1385 BINARY(instance_rshift, "rshift", PyNumber_Rshift)
1386 BINARY(instance_add, "add", PyNumber_Add)
1387 BINARY(instance_sub, "sub", PyNumber_Subtract)
1388 BINARY(instance_mul, "mul", PyNumber_Multiply)
1389 BINARY(instance_div, "div", PyNumber_Divide)
1390 BINARY(instance_mod, "mod", PyNumber_Remainder)
1391 BINARY(instance_divmod, "divmod", PyNumber_Divmod)
1393 BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr)
1394 BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor)
1395 BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd)
1396 BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift)
1397 BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift)
1398 BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd)
1399 BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract)
1400 BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply)
1401 BINARY_INPLACE(instance_idiv, "div", PyNumber_InPlaceDivide)
1402 BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder)
1404 /* Try a 3-way comparison, returning an int; v is an instance. Return:
1405 -2 for an exception;
1406 -1 if v < w;
1407 0 if v == w;
1408 1 if v > w;
1409 2 if this particular 3-way comparison is not implemented or undefined.
1411 static int
1412 half_cmp(PyObject *v, PyObject *w)
1414 static PyObject *cmp_obj;
1415 PyObject *args;
1416 PyObject *cmp_func;
1417 PyObject *result;
1418 long l;
1420 assert(PyInstance_Check(v));
1422 if (cmp_obj == NULL) {
1423 cmp_obj = PyString_InternFromString("__cmp__");
1424 if (cmp_obj == NULL)
1425 return -2;
1428 cmp_func = PyObject_GetAttr(v, cmp_obj);
1429 if (cmp_func == NULL) {
1430 PyErr_Clear();
1431 return 2;
1434 args = Py_BuildValue("(O)", w);
1435 if (args == NULL)
1436 return -2;
1438 result = PyEval_CallObject(cmp_func, args);
1439 Py_DECREF(args);
1440 Py_DECREF(cmp_func);
1442 if (result == NULL)
1443 return -2;
1445 if (result == Py_NotImplemented) {
1446 Py_DECREF(result);
1447 return 2;
1450 l = PyInt_AsLong(result);
1451 Py_DECREF(result);
1452 if (l == -1 && PyErr_Occurred()) {
1453 PyErr_SetString(PyExc_TypeError,
1454 "comparison did not return an int");
1455 return -2;
1458 return l < 0 ? -1 : l > 0 ? 1 : 0;
1461 /* Try a 3-way comparison, returning an int; either v or w is an instance.
1462 We first try a coercion. Return:
1463 -2 for an exception;
1464 -1 if v < w;
1465 0 if v == w;
1466 1 if v > w;
1467 2 if this particular 3-way comparison is not implemented or undefined.
1468 THIS IS ONLY CALLED FROM object.c!
1470 static int
1471 instance_compare(PyObject *v, PyObject *w)
1473 int c;
1475 c = PyNumber_CoerceEx(&v, &w);
1476 if (c < 0)
1477 return -2;
1478 if (c == 0) {
1479 /* If neither is now an instance, use regular comparison */
1480 if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
1481 c = PyObject_Compare(v, w);
1482 Py_DECREF(v);
1483 Py_DECREF(w);
1484 if (PyErr_Occurred())
1485 return -2;
1486 return c < 0 ? -1 : c > 0 ? 1 : 0;
1489 else {
1490 /* The coercion didn't do anything.
1491 Treat this the same as returning v and w unchanged. */
1492 Py_INCREF(v);
1493 Py_INCREF(w);
1496 if (PyInstance_Check(v)) {
1497 c = half_cmp(v, w);
1498 if (c <= 1) {
1499 Py_DECREF(v);
1500 Py_DECREF(w);
1501 return c;
1504 if (PyInstance_Check(w)) {
1505 c = half_cmp(w, v);
1506 if (c <= 1) {
1507 Py_DECREF(v);
1508 Py_DECREF(w);
1509 if (c >= -1)
1510 c = -c;
1511 return c;
1514 Py_DECREF(v);
1515 Py_DECREF(w);
1516 return 2;
1519 static int
1520 instance_nonzero(PyInstanceObject *self)
1522 PyObject *func, *res;
1523 long outcome;
1524 static PyObject *nonzerostr;
1526 if (nonzerostr == NULL)
1527 nonzerostr = PyString_InternFromString("__nonzero__");
1528 if ((func = instance_getattr(self, nonzerostr)) == NULL) {
1529 PyErr_Clear();
1530 if (lenstr == NULL)
1531 lenstr = PyString_InternFromString("__len__");
1532 if ((func = instance_getattr(self, lenstr)) == NULL) {
1533 PyErr_Clear();
1534 /* Fall back to the default behavior:
1535 all instances are nonzero */
1536 return 1;
1539 res = PyEval_CallObject(func, (PyObject *)NULL);
1540 Py_DECREF(func);
1541 if (res == NULL)
1542 return -1;
1543 if (!PyInt_Check(res)) {
1544 Py_DECREF(res);
1545 PyErr_SetString(PyExc_TypeError,
1546 "__nonzero__ should return an int");
1547 return -1;
1549 outcome = PyInt_AsLong(res);
1550 Py_DECREF(res);
1551 if (outcome < 0) {
1552 PyErr_SetString(PyExc_ValueError,
1553 "__nonzero__ should return >= 0");
1554 return -1;
1556 return outcome > 0;
1559 UNARY(instance_invert, "__invert__")
1560 UNARY(instance_int, "__int__")
1561 UNARY(instance_long, "__long__")
1562 UNARY(instance_float, "__float__")
1563 UNARY(instance_oct, "__oct__")
1564 UNARY(instance_hex, "__hex__")
1566 static PyObject *
1567 bin_power(PyObject *v, PyObject *w)
1569 return PyNumber_Power(v, w, Py_None);
1572 /* This version is for ternary calls only (z != None) */
1573 static PyObject *
1574 instance_pow(PyObject *v, PyObject *w, PyObject *z)
1576 if (z == Py_None) {
1577 return do_binop(v, w, "__pow__", "__rpow__", bin_power);
1579 else {
1580 PyObject *func;
1581 PyObject *args;
1582 PyObject *result;
1584 /* XXX Doesn't do coercions... */
1585 func = PyObject_GetAttrString(v, "__pow__");
1586 if (func == NULL)
1587 return NULL;
1588 args = Py_BuildValue("(OO)", w, z);
1589 if (args == NULL) {
1590 Py_DECREF(func);
1591 return NULL;
1593 result = PyEval_CallObject(func, args);
1594 Py_DECREF(func);
1595 Py_DECREF(args);
1596 return result;
1600 static PyObject *
1601 bin_inplace_power(PyObject *v, PyObject *w)
1603 return PyNumber_InPlacePower(v, w, Py_None);
1607 static PyObject *
1608 instance_ipow(PyObject *v, PyObject *w, PyObject *z)
1610 if (z == Py_None) {
1611 return do_binop_inplace(v, w, "__ipow__", "__pow__",
1612 "__rpow__", bin_inplace_power);
1614 else {
1615 /* XXX Doesn't do coercions... */
1616 PyObject *func;
1617 PyObject *args;
1618 PyObject *result;
1620 func = PyObject_GetAttrString(v, "__ipow__");
1621 if (func == NULL) {
1622 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1623 return NULL;
1624 PyErr_Clear();
1625 return instance_pow(v, w, z);
1627 args = Py_BuildValue("(OO)", w, z);
1628 if (args == NULL) {
1629 Py_DECREF(func);
1630 return NULL;
1632 result = PyEval_CallObject(func, args);
1633 Py_DECREF(func);
1634 Py_DECREF(args);
1635 return result;
1640 /* Map rich comparison operators to their __xx__ namesakes */
1641 static char *name_op[] = {
1642 "__lt__",
1643 "__le__",
1644 "__eq__",
1645 "__ne__",
1646 "__gt__",
1647 "__ge__",
1650 static PyObject *
1651 half_richcompare(PyObject *v, PyObject *w, int op)
1653 PyObject *name;
1654 PyObject *method;
1655 PyObject *args;
1656 PyObject *res;
1658 assert(PyInstance_Check(v));
1660 name = PyString_InternFromString(name_op[op]);
1661 if (name == NULL)
1662 return NULL;
1664 method = PyObject_GetAttr(v, name);
1665 Py_DECREF(name);
1666 if (method == NULL) {
1667 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1668 return NULL;
1669 PyErr_Clear();
1670 res = Py_NotImplemented;
1671 Py_INCREF(res);
1672 return res;
1675 args = Py_BuildValue("(O)", w);
1676 if (args == NULL) {
1677 Py_DECREF(method);
1678 return NULL;
1681 res = PyEval_CallObject(method, args);
1682 Py_DECREF(args);
1683 Py_DECREF(method);
1685 return res;
1688 /* Map rich comparison operators to their swapped version, e.g. LT --> GT */
1689 static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
1691 static PyObject *
1692 instance_richcompare(PyObject *v, PyObject *w, int op)
1694 PyObject *res;
1696 if (PyInstance_Check(v)) {
1697 res = half_richcompare(v, w, op);
1698 if (res != Py_NotImplemented)
1699 return res;
1700 Py_DECREF(res);
1703 if (PyInstance_Check(w)) {
1704 res = half_richcompare(w, v, swapped_op[op]);
1705 if (res != Py_NotImplemented)
1706 return res;
1707 Py_DECREF(res);
1710 Py_INCREF(Py_NotImplemented);
1711 return Py_NotImplemented;
1715 static PyNumberMethods instance_as_number = {
1716 (binaryfunc)instance_add, /* nb_add */
1717 (binaryfunc)instance_sub, /* nb_subtract */
1718 (binaryfunc)instance_mul, /* nb_multiply */
1719 (binaryfunc)instance_div, /* nb_divide */
1720 (binaryfunc)instance_mod, /* nb_remainder */
1721 (binaryfunc)instance_divmod, /* nb_divmod */
1722 (ternaryfunc)instance_pow, /* nb_power */
1723 (unaryfunc)instance_neg, /* nb_negative */
1724 (unaryfunc)instance_pos, /* nb_positive */
1725 (unaryfunc)instance_abs, /* nb_absolute */
1726 (inquiry)instance_nonzero, /* nb_nonzero */
1727 (unaryfunc)instance_invert, /* nb_invert */
1728 (binaryfunc)instance_lshift, /* nb_lshift */
1729 (binaryfunc)instance_rshift, /* nb_rshift */
1730 (binaryfunc)instance_and, /* nb_and */
1731 (binaryfunc)instance_xor, /* nb_xor */
1732 (binaryfunc)instance_or, /* nb_or */
1733 (coercion)instance_coerce, /* nb_coerce */
1734 (unaryfunc)instance_int, /* nb_int */
1735 (unaryfunc)instance_long, /* nb_long */
1736 (unaryfunc)instance_float, /* nb_float */
1737 (unaryfunc)instance_oct, /* nb_oct */
1738 (unaryfunc)instance_hex, /* nb_hex */
1739 (binaryfunc)instance_iadd, /* nb_inplace_add */
1740 (binaryfunc)instance_isub, /* nb_inplace_subtract */
1741 (binaryfunc)instance_imul, /* nb_inplace_multiply */
1742 (binaryfunc)instance_idiv, /* nb_inplace_divide */
1743 (binaryfunc)instance_imod, /* nb_inplace_remainder */
1744 (ternaryfunc)instance_ipow, /* nb_inplace_power */
1745 (binaryfunc)instance_ilshift, /* nb_inplace_lshift */
1746 (binaryfunc)instance_irshift, /* nb_inplace_rshift */
1747 (binaryfunc)instance_iand, /* nb_inplace_and */
1748 (binaryfunc)instance_ixor, /* nb_inplace_xor */
1749 (binaryfunc)instance_ior, /* nb_inplace_or */
1752 PyTypeObject PyInstance_Type = {
1753 PyObject_HEAD_INIT(&PyType_Type)
1755 "instance",
1756 sizeof(PyInstanceObject) + PyGC_HEAD_SIZE,
1758 (destructor)instance_dealloc, /* tp_dealloc */
1759 0, /* tp_print */
1760 0, /* tp_getattr */
1761 0, /* tp_setattr */
1762 instance_compare, /* tp_compare */
1763 (reprfunc)instance_repr, /* tp_repr */
1764 &instance_as_number, /* tp_as_number */
1765 &instance_as_sequence, /* tp_as_sequence */
1766 &instance_as_mapping, /* tp_as_mapping */
1767 (hashfunc)instance_hash, /* tp_hash */
1768 0, /* tp_call */
1769 0, /* tp_str */
1770 (getattrofunc)instance_getattr, /* tp_getattro */
1771 (setattrofunc)instance_setattr, /* tp_setattro */
1772 0, /* tp_as_buffer */
1773 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC | Py_TPFLAGS_CHECKTYPES,/*tp_flags*/
1774 0, /* tp_doc */
1775 (traverseproc)instance_traverse, /* tp_traverse */
1776 0, /* tp_clear */
1777 instance_richcompare, /* tp_richcompare */
1778 offsetof(PyInstanceObject, in_weakreflist) /* tp_weaklistoffset */
1782 /* Instance method objects are used for two purposes:
1783 (a) as bound instance methods (returned by instancename.methodname)
1784 (b) as unbound methods (returned by ClassName.methodname)
1785 In case (b), im_self is NULL
1788 static PyMethodObject *free_list;
1790 PyObject *
1791 PyMethod_New(PyObject *func, PyObject *self, PyObject *class)
1793 register PyMethodObject *im;
1794 if (!PyCallable_Check(func)) {
1795 PyErr_BadInternalCall();
1796 return NULL;
1798 im = free_list;
1799 if (im != NULL) {
1800 free_list = (PyMethodObject *)(im->im_self);
1801 PyObject_INIT(im, &PyMethod_Type);
1803 else {
1804 im = PyObject_NEW(PyMethodObject, &PyMethod_Type);
1805 if (im == NULL)
1806 return NULL;
1808 im->im_weakreflist = NULL;
1809 Py_INCREF(func);
1810 im->im_func = func;
1811 Py_XINCREF(self);
1812 im->im_self = self;
1813 Py_INCREF(class);
1814 im->im_class = class;
1815 PyObject_GC_Init(im);
1816 return (PyObject *)im;
1819 PyObject *
1820 PyMethod_Function(register PyObject *im)
1822 if (!PyMethod_Check(im)) {
1823 PyErr_BadInternalCall();
1824 return NULL;
1826 return ((PyMethodObject *)im)->im_func;
1829 PyObject *
1830 PyMethod_Self(register PyObject *im)
1832 if (!PyMethod_Check(im)) {
1833 PyErr_BadInternalCall();
1834 return NULL;
1836 return ((PyMethodObject *)im)->im_self;
1839 PyObject *
1840 PyMethod_Class(register PyObject *im)
1842 if (!PyMethod_Check(im)) {
1843 PyErr_BadInternalCall();
1844 return NULL;
1846 return ((PyMethodObject *)im)->im_class;
1849 /* Class method methods */
1851 #define OFF(x) offsetof(PyMethodObject, x)
1853 static struct memberlist instancemethod_memberlist[] = {
1854 {"im_func", T_OBJECT, OFF(im_func)},
1855 {"im_self", T_OBJECT, OFF(im_self)},
1856 {"im_class", T_OBJECT, OFF(im_class)},
1857 /* Dummies that are not handled by getattr() except for __members__ */
1858 {"__doc__", T_INT, 0},
1859 {"__name__", T_INT, 0},
1860 {"__dict__", T_OBJECT, 0},
1861 {NULL} /* Sentinel */
1864 static int
1865 instancemethod_setattro(register PyMethodObject *im, PyObject *name,
1866 PyObject *v)
1868 char *sname = PyString_AsString(name);
1870 PyErr_Format(PyExc_TypeError, "read-only attribute: %s", sname);
1871 return -1;
1875 static PyObject *
1876 instancemethod_getattro(register PyMethodObject *im, PyObject *name)
1878 PyObject *rtn;
1879 char *sname = PyString_AsString(name);
1880 if (sname[0] == '_') {
1881 /* Inherit __name__ and __doc__ from the callable object
1882 implementing the method */
1883 if (strcmp(sname, "__name__") == 0 ||
1884 strcmp(sname, "__doc__") == 0)
1885 return PyObject_GetAttr(im->im_func, name);
1887 if (PyEval_GetRestricted()) {
1888 PyErr_SetString(PyExc_RuntimeError,
1889 "instance-method attributes not accessible in restricted mode");
1890 return NULL;
1892 if (sname[0] == '_' && strcmp(sname, "__dict__") == 0)
1893 return PyObject_GetAttr(im->im_func, name);
1895 rtn = PyMember_Get((char *)im, instancemethod_memberlist, sname);
1896 if (rtn == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
1897 PyErr_Clear();
1898 rtn = PyObject_GetAttr(im->im_func, name);
1900 return rtn;
1903 static void
1904 instancemethod_dealloc(register PyMethodObject *im)
1906 PyObject_ClearWeakRefs((PyObject *)im);
1907 PyObject_GC_Fini(im);
1908 Py_DECREF(im->im_func);
1909 Py_XDECREF(im->im_self);
1910 Py_DECREF(im->im_class);
1911 im->im_self = (PyObject *)free_list;
1912 free_list = im;
1915 static int
1916 instancemethod_compare(PyMethodObject *a, PyMethodObject *b)
1918 if (a->im_self != b->im_self)
1919 return (a->im_self < b->im_self) ? -1 : 1;
1920 return PyObject_Compare(a->im_func, b->im_func);
1923 static PyObject *
1924 instancemethod_repr(PyMethodObject *a)
1926 char buf[240];
1927 PyInstanceObject *self = (PyInstanceObject *)(a->im_self);
1928 PyObject *func = a->im_func;
1929 PyClassObject *class = (PyClassObject *)(a->im_class);
1930 PyObject *fclassname, *iclassname, *funcname;
1931 char *fcname, *icname, *fname;
1932 fclassname = class->cl_name;
1933 if (PyFunction_Check(func)) {
1934 funcname = ((PyFunctionObject *)func)->func_name;
1935 Py_INCREF(funcname);
1937 else {
1938 funcname = PyObject_GetAttrString(func,"__name__");
1939 if (funcname == NULL)
1940 PyErr_Clear();
1942 if (funcname != NULL && PyString_Check(funcname))
1943 fname = PyString_AS_STRING(funcname);
1944 else
1945 fname = "?";
1946 if (fclassname != NULL && PyString_Check(fclassname))
1947 fcname = PyString_AsString(fclassname);
1948 else
1949 fcname = "?";
1950 if (self == NULL)
1951 sprintf(buf, "<unbound method %.100s.%.100s>", fcname, fname);
1952 else {
1953 iclassname = self->in_class->cl_name;
1954 if (iclassname != NULL && PyString_Check(iclassname))
1955 icname = PyString_AsString(iclassname);
1956 else
1957 icname = "?";
1958 sprintf(buf, "<method %.60s.%.60s of %.60s instance at %p>",
1959 fcname, fname, icname, self);
1961 Py_XDECREF(funcname);
1962 return PyString_FromString(buf);
1965 static long
1966 instancemethod_hash(PyMethodObject *a)
1968 long x, y;
1969 if (a->im_self == NULL)
1970 x = PyObject_Hash(Py_None);
1971 else
1972 x = PyObject_Hash(a->im_self);
1973 if (x == -1)
1974 return -1;
1975 y = PyObject_Hash(a->im_func);
1976 if (y == -1)
1977 return -1;
1978 return x ^ y;
1981 static int
1982 instancemethod_traverse(PyMethodObject *im, visitproc visit, void *arg)
1984 int err;
1985 if (im->im_func) {
1986 err = visit(im->im_func, arg);
1987 if (err)
1988 return err;
1990 if (im->im_self) {
1991 err = visit(im->im_self, arg);
1992 if (err)
1993 return err;
1995 if (im->im_class) {
1996 err = visit(im->im_class, arg);
1997 if (err)
1998 return err;
2000 return 0;
2003 PyTypeObject PyMethod_Type = {
2004 PyObject_HEAD_INIT(&PyType_Type)
2006 "instance method",
2007 sizeof(PyMethodObject) + PyGC_HEAD_SIZE,
2009 (destructor)instancemethod_dealloc, /* tp_dealloc */
2010 0, /* tp_print */
2011 0, /* tp_getattr */
2012 0, /* tp_setattr */
2013 (cmpfunc)instancemethod_compare, /* tp_compare */
2014 (reprfunc)instancemethod_repr, /* tp_repr */
2015 0, /* tp_as_number */
2016 0, /* tp_as_sequence */
2017 0, /* tp_as_mapping */
2018 (hashfunc)instancemethod_hash, /* tp_hash */
2019 0, /* tp_call */
2020 0, /* tp_str */
2021 (getattrofunc)instancemethod_getattro, /* tp_getattro */
2022 (setattrofunc)instancemethod_setattro, /* tp_setattro */
2023 0, /* tp_as_buffer */
2024 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC | Py_TPFLAGS_HAVE_WEAKREFS,
2025 0, /* tp_doc */
2026 (traverseproc)instancemethod_traverse, /* tp_traverse */
2027 0, /* tp_clear */
2028 0, /* tp_richcompare */
2029 offsetof(PyMethodObject, im_weakreflist) /* tp_weaklistoffset */
2032 /* Clear out the free list */
2034 void
2035 PyMethod_Fini(void)
2037 while (free_list) {
2038 PyMethodObject *im = free_list;
2039 free_list = (PyMethodObject *)(im->im_self);
2040 im = (PyMethodObject *) PyObject_AS_GC(im);
2041 PyObject_DEL(im);