source: vendor/python/2.5/Objects/classobject.c

Last change on this file was 3225, checked in by bird, 18 years ago

Python 2.5

File size: 60.8 KB
Line 
1
2/* Class object implementation */
3
4#include "Python.h"
5#include "structmember.h"
6
7#define TP_DESCR_GET(t) \
8 (PyType_HasFeature(t, Py_TPFLAGS_HAVE_CLASS) ? (t)->tp_descr_get : NULL)
9
10
11/* Forward */
12static PyObject *class_lookup(PyClassObject *, PyObject *,
13 PyClassObject **);
14static PyObject *instance_getattr1(PyInstanceObject *, PyObject *);
15static PyObject *instance_getattr2(PyInstanceObject *, PyObject *);
16
17static PyObject *getattrstr, *setattrstr, *delattrstr;
18
19
20PyObject *
21PyClass_New(PyObject *bases, PyObject *dict, PyObject *name)
22 /* bases is NULL or tuple of classobjects! */
23{
24 PyClassObject *op, *dummy;
25 static PyObject *docstr, *modstr, *namestr;
26 if (docstr == NULL) {
27 docstr= PyString_InternFromString("__doc__");
28 if (docstr == NULL)
29 return NULL;
30 }
31 if (modstr == NULL) {
32 modstr= PyString_InternFromString("__module__");
33 if (modstr == NULL)
34 return NULL;
35 }
36 if (namestr == NULL) {
37 namestr= PyString_InternFromString("__name__");
38 if (namestr == NULL)
39 return NULL;
40 }
41 if (name == NULL || !PyString_Check(name)) {
42 PyErr_SetString(PyExc_TypeError,
43 "PyClass_New: name must be a string");
44 return NULL;
45 }
46 if (dict == NULL || !PyDict_Check(dict)) {
47 PyErr_SetString(PyExc_TypeError,
48 "PyClass_New: dict must be a dictionary");
49 return NULL;
50 }
51 if (PyDict_GetItem(dict, docstr) == NULL) {
52 if (PyDict_SetItem(dict, docstr, Py_None) < 0)
53 return NULL;
54 }
55 if (PyDict_GetItem(dict, modstr) == NULL) {
56 PyObject *globals = PyEval_GetGlobals();
57 if (globals != NULL) {
58 PyObject *modname = PyDict_GetItem(globals, namestr);
59 if (modname != NULL) {
60 if (PyDict_SetItem(dict, modstr, modname) < 0)
61 return NULL;
62 }
63 }
64 }
65 if (bases == NULL) {
66 bases = PyTuple_New(0);
67 if (bases == NULL)
68 return NULL;
69 }
70 else {
71 Py_ssize_t i, n;
72 PyObject *base;
73 if (!PyTuple_Check(bases)) {
74 PyErr_SetString(PyExc_TypeError,
75 "PyClass_New: bases must be a tuple");
76 return NULL;
77 }
78 n = PyTuple_Size(bases);
79 for (i = 0; i < n; i++) {
80 base = PyTuple_GET_ITEM(bases, i);
81 if (!PyClass_Check(base)) {
82 if (PyCallable_Check(
83 (PyObject *) base->ob_type))
84 return PyObject_CallFunctionObjArgs(
85 (PyObject *) base->ob_type,
86 name, bases, dict, NULL);
87 PyErr_SetString(PyExc_TypeError,
88 "PyClass_New: base must be a class");
89 return NULL;
90 }
91 }
92 Py_INCREF(bases);
93 }
94
95 if (getattrstr == NULL) {
96 getattrstr = PyString_InternFromString("__getattr__");
97 if (getattrstr == NULL)
98 goto alloc_error;
99 setattrstr = PyString_InternFromString("__setattr__");
100 if (setattrstr == NULL)
101 goto alloc_error;
102 delattrstr = PyString_InternFromString("__delattr__");
103 if (delattrstr == NULL)
104 goto alloc_error;
105 }
106
107 op = PyObject_GC_New(PyClassObject, &PyClass_Type);
108 if (op == NULL) {
109alloc_error:
110 Py_DECREF(bases);
111 return NULL;
112 }
113 op->cl_bases = bases;
114 Py_INCREF(dict);
115 op->cl_dict = dict;
116 Py_XINCREF(name);
117 op->cl_name = name;
118
119 op->cl_getattr = class_lookup(op, getattrstr, &dummy);
120 op->cl_setattr = class_lookup(op, setattrstr, &dummy);
121 op->cl_delattr = class_lookup(op, delattrstr, &dummy);
122 Py_XINCREF(op->cl_getattr);
123 Py_XINCREF(op->cl_setattr);
124 Py_XINCREF(op->cl_delattr);
125 _PyObject_GC_TRACK(op);
126 return (PyObject *) op;
127}
128
129PyObject *
130PyMethod_Function(PyObject *im)
131{
132 if (!PyMethod_Check(im)) {
133 PyErr_BadInternalCall();
134 return NULL;
135 }
136 return ((PyMethodObject *)im)->im_func;
137}
138
139PyObject *
140PyMethod_Self(PyObject *im)
141{
142 if (!PyMethod_Check(im)) {
143 PyErr_BadInternalCall();
144 return NULL;
145 }
146 return ((PyMethodObject *)im)->im_self;
147}
148
149PyObject *
150PyMethod_Class(PyObject *im)
151{
152 if (!PyMethod_Check(im)) {
153 PyErr_BadInternalCall();
154 return NULL;
155 }
156 return ((PyMethodObject *)im)->im_class;
157}
158
159PyDoc_STRVAR(class_doc,
160"classobj(name, bases, dict)\n\
161\n\
162Create a class object. The name must be a string; the second argument\n\
163a tuple of classes, and the third a dictionary.");
164
165static PyObject *
166class_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
167{
168 PyObject *name, *bases, *dict;
169 static char *kwlist[] = {"name", "bases", "dict", 0};
170
171 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SOO", kwlist,
172 &name, &bases, &dict))
173 return NULL;
174 return PyClass_New(bases, dict, name);
175}
176
177/* Class methods */
178
179static void
180class_dealloc(PyClassObject *op)
181{
182 _PyObject_GC_UNTRACK(op);
183 Py_DECREF(op->cl_bases);
184 Py_DECREF(op->cl_dict);
185 Py_XDECREF(op->cl_name);
186 Py_XDECREF(op->cl_getattr);
187 Py_XDECREF(op->cl_setattr);
188 Py_XDECREF(op->cl_delattr);
189 PyObject_GC_Del(op);
190}
191
192static PyObject *
193class_lookup(PyClassObject *cp, PyObject *name, PyClassObject **pclass)
194{
195 Py_ssize_t i, n;
196 PyObject *value = PyDict_GetItem(cp->cl_dict, name);
197 if (value != NULL) {
198 *pclass = cp;
199 return value;
200 }
201 n = PyTuple_Size(cp->cl_bases);
202 for (i = 0; i < n; i++) {
203 /* XXX What if one of the bases is not a class? */
204 PyObject *v = class_lookup(
205 (PyClassObject *)
206 PyTuple_GetItem(cp->cl_bases, i), name, pclass);
207 if (v != NULL)
208 return v;
209 }
210 return NULL;
211}
212
213static PyObject *
214class_getattr(register PyClassObject *op, PyObject *name)
215{
216 register PyObject *v;
217 register char *sname = PyString_AsString(name);
218 PyClassObject *klass;
219 descrgetfunc f;
220
221 if (sname[0] == '_' && sname[1] == '_') {
222 if (strcmp(sname, "__dict__") == 0) {
223 if (PyEval_GetRestricted()) {
224 PyErr_SetString(PyExc_RuntimeError,
225 "class.__dict__ not accessible in restricted mode");
226 return NULL;
227 }
228 Py_INCREF(op->cl_dict);
229 return op->cl_dict;
230 }
231 if (strcmp(sname, "__bases__") == 0) {
232 Py_INCREF(op->cl_bases);
233 return op->cl_bases;
234 }
235 if (strcmp(sname, "__name__") == 0) {
236 if (op->cl_name == NULL)
237 v = Py_None;
238 else
239 v = op->cl_name;
240 Py_INCREF(v);
241 return v;
242 }
243 }
244 v = class_lookup(op, name, &klass);
245 if (v == NULL) {
246 PyErr_Format(PyExc_AttributeError,
247 "class %.50s has no attribute '%.400s'",
248 PyString_AS_STRING(op->cl_name), sname);
249 return NULL;
250 }
251 f = TP_DESCR_GET(v->ob_type);
252 if (f == NULL)
253 Py_INCREF(v);
254 else
255 v = f(v, (PyObject *)NULL, (PyObject *)op);
256 return v;
257}
258
259static void
260set_slot(PyObject **slot, PyObject *v)
261{
262 PyObject *temp = *slot;
263 Py_XINCREF(v);
264 *slot = v;
265 Py_XDECREF(temp);
266}
267
268static void
269set_attr_slots(PyClassObject *c)
270{
271 PyClassObject *dummy;
272
273 set_slot(&c->cl_getattr, class_lookup(c, getattrstr, &dummy));
274 set_slot(&c->cl_setattr, class_lookup(c, setattrstr, &dummy));
275 set_slot(&c->cl_delattr, class_lookup(c, delattrstr, &dummy));
276}
277
278static char *
279set_dict(PyClassObject *c, PyObject *v)
280{
281 if (v == NULL || !PyDict_Check(v))
282 return "__dict__ must be a dictionary object";
283 set_slot(&c->cl_dict, v);
284 set_attr_slots(c);
285 return "";
286}
287
288static char *
289set_bases(PyClassObject *c, PyObject *v)
290{
291 Py_ssize_t i, n;
292
293 if (v == NULL || !PyTuple_Check(v))
294 return "__bases__ must be a tuple object";
295 n = PyTuple_Size(v);
296 for (i = 0; i < n; i++) {
297 PyObject *x = PyTuple_GET_ITEM(v, i);
298 if (!PyClass_Check(x))
299 return "__bases__ items must be classes";
300 if (PyClass_IsSubclass(x, (PyObject *)c))
301 return "a __bases__ item causes an inheritance cycle";
302 }
303 set_slot(&c->cl_bases, v);
304 set_attr_slots(c);
305 return "";
306}
307
308static char *
309set_name(PyClassObject *c, PyObject *v)
310{
311 if (v == NULL || !PyString_Check(v))
312 return "__name__ must be a string object";
313 if (strlen(PyString_AS_STRING(v)) != (size_t)PyString_GET_SIZE(v))
314 return "__name__ must not contain null bytes";
315 set_slot(&c->cl_name, v);
316 return "";
317}
318
319static int
320class_setattr(PyClassObject *op, PyObject *name, PyObject *v)
321{
322 char *sname;
323 if (PyEval_GetRestricted()) {
324 PyErr_SetString(PyExc_RuntimeError,
325 "classes are read-only in restricted mode");
326 return -1;
327 }
328 sname = PyString_AsString(name);
329 if (sname[0] == '_' && sname[1] == '_') {
330 Py_ssize_t n = PyString_Size(name);
331 if (sname[n-1] == '_' && sname[n-2] == '_') {
332 char *err = NULL;
333 if (strcmp(sname, "__dict__") == 0)
334 err = set_dict(op, v);
335 else if (strcmp(sname, "__bases__") == 0)
336 err = set_bases(op, v);
337 else if (strcmp(sname, "__name__") == 0)
338 err = set_name(op, v);
339 else if (strcmp(sname, "__getattr__") == 0)
340 set_slot(&op->cl_getattr, v);
341 else if (strcmp(sname, "__setattr__") == 0)
342 set_slot(&op->cl_setattr, v);
343 else if (strcmp(sname, "__delattr__") == 0)
344 set_slot(&op->cl_delattr, v);
345 /* For the last three, we fall through to update the
346 dictionary as well. */
347 if (err != NULL) {
348 if (*err == '\0')
349 return 0;
350 PyErr_SetString(PyExc_TypeError, err);
351 return -1;
352 }
353 }
354 }
355 if (v == NULL) {
356 int rv = PyDict_DelItem(op->cl_dict, name);
357 if (rv < 0)
358 PyErr_Format(PyExc_AttributeError,
359 "class %.50s has no attribute '%.400s'",
360 PyString_AS_STRING(op->cl_name), sname);
361 return rv;
362 }
363 else
364 return PyDict_SetItem(op->cl_dict, name, v);
365}
366
367static PyObject *
368class_repr(PyClassObject *op)
369{
370 PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
371 char *name;
372 if (op->cl_name == NULL || !PyString_Check(op->cl_name))
373 name = "?";
374 else
375 name = PyString_AsString(op->cl_name);
376 if (mod == NULL || !PyString_Check(mod))
377 return PyString_FromFormat("<class ?.%s at %p>", name, op);
378 else
379 return PyString_FromFormat("<class %s.%s at %p>",
380 PyString_AsString(mod),
381 name, op);
382}
383
384static PyObject *
385class_str(PyClassObject *op)
386{
387 PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
388 PyObject *name = op->cl_name;
389 PyObject *res;
390 Py_ssize_t m, n;
391
392 if (name == NULL || !PyString_Check(name))
393 return class_repr(op);
394 if (mod == NULL || !PyString_Check(mod)) {
395 Py_INCREF(name);
396 return name;
397 }
398 m = PyString_GET_SIZE(mod);
399 n = PyString_GET_SIZE(name);
400 res = PyString_FromStringAndSize((char *)NULL, m+1+n);
401 if (res != NULL) {
402 char *s = PyString_AS_STRING(res);
403 memcpy(s, PyString_AS_STRING(mod), m);
404 s += m;
405 *s++ = '.';
406 memcpy(s, PyString_AS_STRING(name), n);
407 }
408 return res;
409}
410
411static int
412class_traverse(PyClassObject *o, visitproc visit, void *arg)
413{
414 Py_VISIT(o->cl_bases);
415 Py_VISIT(o->cl_dict);
416 Py_VISIT(o->cl_name);
417 Py_VISIT(o->cl_getattr);
418 Py_VISIT(o->cl_setattr);
419 Py_VISIT(o->cl_delattr);
420 return 0;
421}
422
423PyTypeObject PyClass_Type = {
424 PyObject_HEAD_INIT(&PyType_Type)
425 0,
426 "classobj",
427 sizeof(PyClassObject),
428 0,
429 (destructor)class_dealloc, /* tp_dealloc */
430 0, /* tp_print */
431 0, /* tp_getattr */
432 0, /* tp_setattr */
433 0, /* tp_compare */
434 (reprfunc)class_repr, /* tp_repr */
435 0, /* tp_as_number */
436 0, /* tp_as_sequence */
437 0, /* tp_as_mapping */
438 0, /* tp_hash */
439 PyInstance_New, /* tp_call */
440 (reprfunc)class_str, /* tp_str */
441 (getattrofunc)class_getattr, /* tp_getattro */
442 (setattrofunc)class_setattr, /* tp_setattro */
443 0, /* tp_as_buffer */
444 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
445 class_doc, /* tp_doc */
446 (traverseproc)class_traverse, /* tp_traverse */
447 0, /* tp_clear */
448 0, /* tp_richcompare */
449 0, /* tp_weaklistoffset */
450 0, /* tp_iter */
451 0, /* tp_iternext */
452 0, /* tp_methods */
453 0, /* tp_members */
454 0, /* tp_getset */
455 0, /* tp_base */
456 0, /* tp_dict */
457 0, /* tp_descr_get */
458 0, /* tp_descr_set */
459 0, /* tp_dictoffset */
460 0, /* tp_init */
461 0, /* tp_alloc */
462 class_new, /* tp_new */
463};
464
465int
466PyClass_IsSubclass(PyObject *klass, PyObject *base)
467{
468 Py_ssize_t i, n;
469 PyClassObject *cp;
470 if (klass == base)
471 return 1;
472 if (PyTuple_Check(base)) {
473 n = PyTuple_GET_SIZE(base);
474 for (i = 0; i < n; i++) {
475 if (PyClass_IsSubclass(klass, PyTuple_GET_ITEM(base, i)))
476 return 1;
477 }
478 return 0;
479 }
480 if (klass == NULL || !PyClass_Check(klass))
481 return 0;
482 cp = (PyClassObject *)klass;
483 n = PyTuple_Size(cp->cl_bases);
484 for (i = 0; i < n; i++) {
485 if (PyClass_IsSubclass(PyTuple_GetItem(cp->cl_bases, i), base))
486 return 1;
487 }
488 return 0;
489}
490
491
492/* Instance objects */
493
494PyObject *
495PyInstance_NewRaw(PyObject *klass, PyObject *dict)
496{
497 PyInstanceObject *inst;
498
499 if (!PyClass_Check(klass)) {
500 PyErr_BadInternalCall();
501 return NULL;
502 }
503 if (dict == NULL) {
504 dict = PyDict_New();
505 if (dict == NULL)
506 return NULL;
507 }
508 else {
509 if (!PyDict_Check(dict)) {
510 PyErr_BadInternalCall();
511 return NULL;
512 }
513 Py_INCREF(dict);
514 }
515 inst = PyObject_GC_New(PyInstanceObject, &PyInstance_Type);
516 if (inst == NULL) {
517 Py_DECREF(dict);
518 return NULL;
519 }
520 inst->in_weakreflist = NULL;
521 Py_INCREF(klass);
522 inst->in_class = (PyClassObject *)klass;
523 inst->in_dict = dict;
524 _PyObject_GC_TRACK(inst);
525 return (PyObject *)inst;
526}
527
528PyObject *
529PyInstance_New(PyObject *klass, PyObject *arg, PyObject *kw)
530{
531 register PyInstanceObject *inst;
532 PyObject *init;
533 static PyObject *initstr;
534
535 if (initstr == NULL) {
536 initstr = PyString_InternFromString("__init__");
537 if (initstr == NULL)
538 return NULL;
539 }
540 inst = (PyInstanceObject *) PyInstance_NewRaw(klass, NULL);
541 if (inst == NULL)
542 return NULL;
543 init = instance_getattr2(inst, initstr);
544 if (init == NULL) {
545 if (PyErr_Occurred()) {
546 Py_DECREF(inst);
547 return NULL;
548 }
549 if ((arg != NULL && (!PyTuple_Check(arg) ||
550 PyTuple_Size(arg) != 0))
551 || (kw != NULL && (!PyDict_Check(kw) ||
552 PyDict_Size(kw) != 0))) {
553 PyErr_SetString(PyExc_TypeError,
554 "this constructor takes no arguments");
555 Py_DECREF(inst);
556 inst = NULL;
557 }
558 }
559 else {
560 PyObject *res = PyEval_CallObjectWithKeywords(init, arg, kw);
561 Py_DECREF(init);
562 if (res == NULL) {
563 Py_DECREF(inst);
564 inst = NULL;
565 }
566 else {
567 if (res != Py_None) {
568 PyErr_SetString(PyExc_TypeError,
569 "__init__() should return None");
570 Py_DECREF(inst);
571 inst = NULL;
572 }
573 Py_DECREF(res);
574 }
575 }
576 return (PyObject *)inst;
577}
578
579/* Instance methods */
580
581PyDoc_STRVAR(instance_doc,
582"instance(class[, dict])\n\
583\n\
584Create an instance without calling its __init__() method.\n\
585The class must be a classic class.\n\
586If present, dict must be a dictionary or None.");
587
588static PyObject *
589instance_new(PyTypeObject* type, PyObject* args, PyObject *kw)
590{
591 PyObject *klass;
592 PyObject *dict = Py_None;
593
594 if (!PyArg_ParseTuple(args, "O!|O:instance",
595 &PyClass_Type, &klass, &dict))
596 return NULL;
597
598 if (dict == Py_None)
599 dict = NULL;
600 else if (!PyDict_Check(dict)) {
601 PyErr_SetString(PyExc_TypeError,
602 "instance() second arg must be dictionary or None");
603 return NULL;
604 }
605 return PyInstance_NewRaw(klass, dict);
606}
607
608
609static void
610instance_dealloc(register PyInstanceObject *inst)
611{
612 PyObject *error_type, *error_value, *error_traceback;
613 PyObject *del;
614 static PyObject *delstr;
615
616 _PyObject_GC_UNTRACK(inst);
617 if (inst->in_weakreflist != NULL)
618 PyObject_ClearWeakRefs((PyObject *) inst);
619
620 /* Temporarily resurrect the object. */
621 assert(inst->ob_type == &PyInstance_Type);
622 assert(inst->ob_refcnt == 0);
623 inst->ob_refcnt = 1;
624
625 /* Save the current exception, if any. */
626 PyErr_Fetch(&error_type, &error_value, &error_traceback);
627 /* Execute __del__ method, if any. */
628 if (delstr == NULL) {
629 delstr = PyString_InternFromString("__del__");
630 if (delstr == NULL)
631 PyErr_WriteUnraisable((PyObject*)inst);
632 }
633 if (delstr && (del = instance_getattr2(inst, delstr)) != NULL) {
634 PyObject *res = PyEval_CallObject(del, (PyObject *)NULL);
635 if (res == NULL)
636 PyErr_WriteUnraisable(del);
637 else
638 Py_DECREF(res);
639 Py_DECREF(del);
640 }
641 /* Restore the saved exception. */
642 PyErr_Restore(error_type, error_value, error_traceback);
643
644 /* Undo the temporary resurrection; can't use DECREF here, it would
645 * cause a recursive call.
646 */
647 assert(inst->ob_refcnt > 0);
648 if (--inst->ob_refcnt == 0) {
649 Py_DECREF(inst->in_class);
650 Py_XDECREF(inst->in_dict);
651 PyObject_GC_Del(inst);
652 }
653 else {
654 Py_ssize_t refcnt = inst->ob_refcnt;
655 /* __del__ resurrected it! Make it look like the original
656 * Py_DECREF never happened.
657 */
658 _Py_NewReference((PyObject *)inst);
659 inst->ob_refcnt = refcnt;
660 _PyObject_GC_TRACK(inst);
661 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
662 * we need to undo that. */
663 _Py_DEC_REFTOTAL;
664 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the
665 * object chain, so no more to do there.
666 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
667 * _Py_NewReference bumped tp_allocs: both of those need to be
668 * undone.
669 */
670#ifdef COUNT_ALLOCS
671 --inst->ob_type->tp_frees;
672 --inst->ob_type->tp_allocs;
673#endif
674 }
675}
676
677static PyObject *
678instance_getattr1(register PyInstanceObject *inst, PyObject *name)
679{
680 register PyObject *v;
681 register char *sname = PyString_AsString(name);
682 if (sname[0] == '_' && sname[1] == '_') {
683 if (strcmp(sname, "__dict__") == 0) {
684 if (PyEval_GetRestricted()) {
685 PyErr_SetString(PyExc_RuntimeError,
686 "instance.__dict__ not accessible in restricted mode");
687 return NULL;
688 }
689 Py_INCREF(inst->in_dict);
690 return inst->in_dict;
691 }
692 if (strcmp(sname, "__class__") == 0) {
693 Py_INCREF(inst->in_class);
694 return (PyObject *)inst->in_class;
695 }
696 }
697 v = instance_getattr2(inst, name);
698 if (v == NULL && !PyErr_Occurred()) {
699 PyErr_Format(PyExc_AttributeError,
700 "%.50s instance has no attribute '%.400s'",
701 PyString_AS_STRING(inst->in_class->cl_name), sname);
702 }
703 return v;
704}
705
706static PyObject *
707instance_getattr2(register PyInstanceObject *inst, PyObject *name)
708{
709 register PyObject *v;
710 PyClassObject *klass;
711 descrgetfunc f;
712
713 v = PyDict_GetItem(inst->in_dict, name);
714 if (v != NULL) {
715 Py_INCREF(v);
716 return v;
717 }
718 v = class_lookup(inst->in_class, name, &klass);
719 if (v != NULL) {
720 Py_INCREF(v);
721 f = TP_DESCR_GET(v->ob_type);
722 if (f != NULL) {
723 PyObject *w = f(v, (PyObject *)inst,
724 (PyObject *)(inst->in_class));
725 Py_DECREF(v);
726 v = w;
727 }
728 }
729 return v;
730}
731
732static PyObject *
733instance_getattr(register PyInstanceObject *inst, PyObject *name)
734{
735 register PyObject *func, *res;
736 res = instance_getattr1(inst, name);
737 if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) {
738 PyObject *args;
739 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
740 return NULL;
741 PyErr_Clear();
742 args = PyTuple_Pack(2, inst, name);
743 if (args == NULL)
744 return NULL;
745 res = PyEval_CallObject(func, args);
746 Py_DECREF(args);
747 }
748 return res;
749}
750
751/* See classobject.h comments: this only does dict lookups, and is always
752 * safe to call.
753 */
754PyObject *
755_PyInstance_Lookup(PyObject *pinst, PyObject *name)
756{
757 PyObject *v;
758 PyClassObject *klass;
759 PyInstanceObject *inst; /* pinst cast to the right type */
760
761 assert(PyInstance_Check(pinst));
762 inst = (PyInstanceObject *)pinst;
763
764 assert(PyString_Check(name));
765
766 v = PyDict_GetItem(inst->in_dict, name);
767 if (v == NULL)
768 v = class_lookup(inst->in_class, name, &klass);
769 return v;
770}
771
772static int
773instance_setattr1(PyInstanceObject *inst, PyObject *name, PyObject *v)
774{
775 if (v == NULL) {
776 int rv = PyDict_DelItem(inst->in_dict, name);
777 if (rv < 0)
778 PyErr_Format(PyExc_AttributeError,
779 "%.50s instance has no attribute '%.400s'",
780 PyString_AS_STRING(inst->in_class->cl_name),
781 PyString_AS_STRING(name));
782 return rv;
783 }
784 else
785 return PyDict_SetItem(inst->in_dict, name, v);
786}
787
788static int
789instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v)
790{
791 PyObject *func, *args, *res, *tmp;
792 char *sname = PyString_AsString(name);
793 if (sname[0] == '_' && sname[1] == '_') {
794 Py_ssize_t n = PyString_Size(name);
795 if (sname[n-1] == '_' && sname[n-2] == '_') {
796 if (strcmp(sname, "__dict__") == 0) {
797 if (PyEval_GetRestricted()) {
798 PyErr_SetString(PyExc_RuntimeError,
799 "__dict__ not accessible in restricted mode");
800 return -1;
801 }
802 if (v == NULL || !PyDict_Check(v)) {
803 PyErr_SetString(PyExc_TypeError,
804 "__dict__ must be set to a dictionary");
805 return -1;
806 }
807 tmp = inst->in_dict;
808 Py_INCREF(v);
809 inst->in_dict = v;
810 Py_DECREF(tmp);
811 return 0;
812 }
813 if (strcmp(sname, "__class__") == 0) {
814 if (PyEval_GetRestricted()) {
815 PyErr_SetString(PyExc_RuntimeError,
816 "__class__ not accessible in restricted mode");
817 return -1;
818 }
819 if (v == NULL || !PyClass_Check(v)) {
820 PyErr_SetString(PyExc_TypeError,
821 "__class__ must be set to a class");
822 return -1;
823 }
824 tmp = (PyObject *)(inst->in_class);
825 Py_INCREF(v);
826 inst->in_class = (PyClassObject *)v;
827 Py_DECREF(tmp);
828 return 0;
829 }
830 }
831 }
832 if (v == NULL)
833 func = inst->in_class->cl_delattr;
834 else
835 func = inst->in_class->cl_setattr;
836 if (func == NULL)
837 return instance_setattr1(inst, name, v);
838 if (v == NULL)
839 args = PyTuple_Pack(2, inst, name);
840 else
841 args = PyTuple_Pack(3, inst, name, v);
842 if (args == NULL)
843 return -1;
844 res = PyEval_CallObject(func, args);
845 Py_DECREF(args);
846 if (res == NULL)
847 return -1;
848 Py_DECREF(res);
849 return 0;
850}
851
852static PyObject *
853instance_repr(PyInstanceObject *inst)
854{
855 PyObject *func;
856 PyObject *res;
857 static PyObject *reprstr;
858
859 if (reprstr == NULL) {
860 reprstr = PyString_InternFromString("__repr__");
861 if (reprstr == NULL)
862 return NULL;
863 }
864 func = instance_getattr(inst, reprstr);
865 if (func == NULL) {
866 PyObject *classname, *mod;
867 char *cname;
868 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
869 return NULL;
870 PyErr_Clear();
871 classname = inst->in_class->cl_name;
872 mod = PyDict_GetItemString(inst->in_class->cl_dict,
873 "__module__");
874 if (classname != NULL && PyString_Check(classname))
875 cname = PyString_AsString(classname);
876 else
877 cname = "?";
878 if (mod == NULL || !PyString_Check(mod))
879 return PyString_FromFormat("<?.%s instance at %p>",
880 cname, inst);
881 else
882 return PyString_FromFormat("<%s.%s instance at %p>",
883 PyString_AsString(mod),
884 cname, inst);
885 }
886 res = PyEval_CallObject(func, (PyObject *)NULL);
887 Py_DECREF(func);
888 return res;
889}
890
891static PyObject *
892instance_str(PyInstanceObject *inst)
893{
894 PyObject *func;
895 PyObject *res;
896 static PyObject *strstr;
897
898 if (strstr == NULL) {
899 strstr = PyString_InternFromString("__str__");
900 if (strstr == NULL)
901 return NULL;
902 }
903 func = instance_getattr(inst, strstr);
904 if (func == NULL) {
905 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
906 return NULL;
907 PyErr_Clear();
908 return instance_repr(inst);
909 }
910 res = PyEval_CallObject(func, (PyObject *)NULL);
911 Py_DECREF(func);
912 return res;
913}
914
915static long
916instance_hash(PyInstanceObject *inst)
917{
918 PyObject *func;
919 PyObject *res;
920 long outcome;
921 static PyObject *hashstr, *eqstr, *cmpstr;
922
923 if (hashstr == NULL) {
924 hashstr = PyString_InternFromString("__hash__");
925 if (hashstr == NULL)
926 return -1;
927 }
928 func = instance_getattr(inst, hashstr);
929 if (func == NULL) {
930 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
931 return -1;
932 PyErr_Clear();
933 /* If there is no __eq__ and no __cmp__ method, we hash on the
934 address. If an __eq__ or __cmp__ method exists, there must
935 be a __hash__. */
936 if (eqstr == NULL) {
937 eqstr = PyString_InternFromString("__eq__");
938 if (eqstr == NULL)
939 return -1;
940 }
941 func = instance_getattr(inst, eqstr);
942 if (func == NULL) {
943 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
944 return -1;
945 PyErr_Clear();
946 if (cmpstr == NULL) {
947 cmpstr = PyString_InternFromString("__cmp__");
948 if (cmpstr == NULL)
949 return -1;
950 }
951 func = instance_getattr(inst, cmpstr);
952 if (func == NULL) {
953 if (!PyErr_ExceptionMatches(
954 PyExc_AttributeError))
955 return -1;
956 PyErr_Clear();
957 return _Py_HashPointer(inst);
958 }
959 }
960 Py_XDECREF(func);
961 PyErr_SetString(PyExc_TypeError, "unhashable instance");
962 return -1;
963 }
964 res = PyEval_CallObject(func, (PyObject *)NULL);
965 Py_DECREF(func);
966 if (res == NULL)
967 return -1;
968 if (PyInt_Check(res) || PyLong_Check(res))
969 /* This already converts a -1 result to -2. */
970 outcome = res->ob_type->tp_hash(res);
971 else {
972 PyErr_SetString(PyExc_TypeError,
973 "__hash__() should return an int");
974 outcome = -1;
975 }
976 Py_DECREF(res);
977 return outcome;
978}
979
980static int
981instance_traverse(PyInstanceObject *o, visitproc visit, void *arg)
982{
983 Py_VISIT(o->in_class);
984 Py_VISIT(o->in_dict);
985 return 0;
986}
987
988static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr;
989static PyObject *iterstr, *nextstr;
990
991static Py_ssize_t
992instance_length(PyInstanceObject *inst)
993{
994 PyObject *func;
995 PyObject *res;
996 Py_ssize_t outcome;
997
998 if (lenstr == NULL) {
999 lenstr = PyString_InternFromString("__len__");
1000 if (lenstr == NULL)
1001 return -1;
1002 }
1003 func = instance_getattr(inst, lenstr);
1004 if (func == NULL)
1005 return -1;
1006 res = PyEval_CallObject(func, (PyObject *)NULL);
1007 Py_DECREF(func);
1008 if (res == NULL)
1009 return -1;
1010 if (PyInt_Check(res)) {
1011 outcome = PyInt_AsSsize_t(res);
1012 if (outcome == -1 && PyErr_Occurred()) {
1013 Py_DECREF(res);
1014 return -1;
1015 }
1016#if SIZEOF_SIZE_T < SIZEOF_INT
1017 /* Overflow check -- range of PyInt is more than C int */
1018 if (outcome != (int)outcome) {
1019 PyErr_SetString(PyExc_OverflowError,
1020 "__len__() should return 0 <= outcome < 2**31");
1021 outcome = -1;
1022 }
1023 else
1024#endif
1025 if (outcome < 0) {
1026 PyErr_SetString(PyExc_ValueError,
1027 "__len__() should return >= 0");
1028 outcome = -1;
1029 }
1030 }
1031 else {
1032 PyErr_SetString(PyExc_TypeError,
1033 "__len__() should return an int");
1034 outcome = -1;
1035 }
1036 Py_DECREF(res);
1037 return outcome;
1038}
1039
1040static PyObject *
1041instance_subscript(PyInstanceObject *inst, PyObject *key)
1042{
1043 PyObject *func;
1044 PyObject *arg;
1045 PyObject *res;
1046
1047 if (getitemstr == NULL) {
1048 getitemstr = PyString_InternFromString("__getitem__");
1049 if (getitemstr == NULL)
1050 return NULL;
1051 }
1052 func = instance_getattr(inst, getitemstr);
1053 if (func == NULL)
1054 return NULL;
1055 arg = PyTuple_Pack(1, key);
1056 if (arg == NULL) {
1057 Py_DECREF(func);
1058 return NULL;
1059 }
1060 res = PyEval_CallObject(func, arg);
1061 Py_DECREF(func);
1062 Py_DECREF(arg);
1063 return res;
1064}
1065
1066static int
1067instance_ass_subscript(PyInstanceObject *inst, PyObject *key, PyObject *value)
1068{
1069 PyObject *func;
1070 PyObject *arg;
1071 PyObject *res;
1072
1073 if (value == NULL) {
1074 if (delitemstr == NULL) {
1075 delitemstr = PyString_InternFromString("__delitem__");
1076 if (delitemstr == NULL)
1077 return -1;
1078 }
1079 func = instance_getattr(inst, delitemstr);
1080 }
1081 else {
1082 if (setitemstr == NULL) {
1083 setitemstr = PyString_InternFromString("__setitem__");
1084 if (setitemstr == NULL)
1085 return -1;
1086 }
1087 func = instance_getattr(inst, setitemstr);
1088 }
1089 if (func == NULL)
1090 return -1;
1091 if (value == NULL)
1092 arg = PyTuple_Pack(1, key);
1093 else
1094 arg = PyTuple_Pack(2, key, value);
1095 if (arg == NULL) {
1096 Py_DECREF(func);
1097 return -1;
1098 }
1099 res = PyEval_CallObject(func, arg);
1100 Py_DECREF(func);
1101 Py_DECREF(arg);
1102 if (res == NULL)
1103 return -1;
1104 Py_DECREF(res);
1105 return 0;
1106}
1107
1108static PyMappingMethods instance_as_mapping = {
1109 (lenfunc)instance_length, /* mp_length */
1110 (binaryfunc)instance_subscript, /* mp_subscript */
1111 (objobjargproc)instance_ass_subscript, /* mp_ass_subscript */
1112};
1113
1114static PyObject *
1115instance_item(PyInstanceObject *inst, Py_ssize_t i)
1116{
1117 PyObject *func, *res;
1118
1119 if (getitemstr == NULL) {
1120 getitemstr = PyString_InternFromString("__getitem__");
1121 if (getitemstr == NULL)
1122 return NULL;
1123 }
1124 func = instance_getattr(inst, getitemstr);
1125 if (func == NULL)
1126 return NULL;
1127 res = PyObject_CallFunction(func, "n", i);
1128 Py_DECREF(func);
1129 return res;
1130}
1131
1132static PyObject *
1133instance_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j)
1134{
1135 PyObject *func, *arg, *res;
1136 static PyObject *getslicestr;
1137
1138 if (getslicestr == NULL) {
1139 getslicestr = PyString_InternFromString("__getslice__");
1140 if (getslicestr == NULL)
1141 return NULL;
1142 }
1143 func = instance_getattr(inst, getslicestr);
1144
1145 if (func == NULL) {
1146 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1147 return NULL;
1148 PyErr_Clear();
1149
1150 if (getitemstr == NULL) {
1151 getitemstr = PyString_InternFromString("__getitem__");
1152 if (getitemstr == NULL)
1153 return NULL;
1154 }
1155 func = instance_getattr(inst, getitemstr);
1156 if (func == NULL)
1157 return NULL;
1158 arg = Py_BuildValue("(N)", _PySlice_FromIndices(i, j));
1159 } else
1160 arg = Py_BuildValue("(nn)", i, j);
1161
1162 if (arg == NULL) {
1163 Py_DECREF(func);
1164 return NULL;
1165 }
1166 res = PyEval_CallObject(func, arg);
1167 Py_DECREF(func);
1168 Py_DECREF(arg);
1169 return res;
1170}
1171
1172static int
1173instance_ass_item(PyInstanceObject *inst, Py_ssize_t i, PyObject *item)
1174{
1175 PyObject *func, *arg, *res;
1176
1177 if (item == NULL) {
1178 if (delitemstr == NULL) {
1179 delitemstr = PyString_InternFromString("__delitem__");
1180 if (delitemstr == NULL)
1181 return -1;
1182 }
1183 func = instance_getattr(inst, delitemstr);
1184 }
1185 else {
1186 if (setitemstr == NULL) {
1187 setitemstr = PyString_InternFromString("__setitem__");
1188 if (setitemstr == NULL)
1189 return -1;
1190 }
1191 func = instance_getattr(inst, setitemstr);
1192 }
1193 if (func == NULL)
1194 return -1;
1195 if (item == NULL)
1196 arg = PyInt_FromSsize_t(i);
1197 else
1198 arg = Py_BuildValue("(nO)", i, item);
1199 if (arg == NULL) {
1200 Py_DECREF(func);
1201 return -1;
1202 }
1203 res = PyEval_CallObject(func, arg);
1204 Py_DECREF(func);
1205 Py_DECREF(arg);
1206 if (res == NULL)
1207 return -1;
1208 Py_DECREF(res);
1209 return 0;
1210}
1211
1212static int
1213instance_ass_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j, PyObject *value)
1214{
1215 PyObject *func, *arg, *res;
1216 static PyObject *setslicestr, *delslicestr;
1217
1218 if (value == NULL) {
1219 if (delslicestr == NULL) {
1220 delslicestr =
1221 PyString_InternFromString("__delslice__");
1222 if (delslicestr == NULL)
1223 return -1;
1224 }
1225 func = instance_getattr(inst, delslicestr);
1226 if (func == NULL) {
1227 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1228 return -1;
1229 PyErr_Clear();
1230 if (delitemstr == NULL) {
1231 delitemstr =
1232 PyString_InternFromString("__delitem__");
1233 if (delitemstr == NULL)
1234 return -1;
1235 }
1236 func = instance_getattr(inst, delitemstr);
1237 if (func == NULL)
1238 return -1;
1239
1240 arg = Py_BuildValue("(N)",
1241 _PySlice_FromIndices(i, j));
1242 } else
1243 arg = Py_BuildValue("(nn)", i, j);
1244 }
1245 else {
1246 if (setslicestr == NULL) {
1247 setslicestr =
1248 PyString_InternFromString("__setslice__");
1249 if (setslicestr == NULL)
1250 return -1;
1251 }
1252 func = instance_getattr(inst, setslicestr);
1253 if (func == NULL) {
1254 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1255 return -1;
1256 PyErr_Clear();
1257 if (setitemstr == NULL) {
1258 setitemstr =
1259 PyString_InternFromString("__setitem__");
1260 if (setitemstr == NULL)
1261 return -1;
1262 }
1263 func = instance_getattr(inst, setitemstr);
1264 if (func == NULL)
1265 return -1;
1266
1267 arg = Py_BuildValue("(NO)",
1268 _PySlice_FromIndices(i, j), value);
1269 } else
1270 arg = Py_BuildValue("(nnO)", i, j, value);
1271 }
1272 if (arg == NULL) {
1273 Py_DECREF(func);
1274 return -1;
1275 }
1276 res = PyEval_CallObject(func, arg);
1277 Py_DECREF(func);
1278 Py_DECREF(arg);
1279 if (res == NULL)
1280 return -1;
1281 Py_DECREF(res);
1282 return 0;
1283}
1284
1285static int
1286instance_contains(PyInstanceObject *inst, PyObject *member)
1287{
1288 static PyObject *__contains__;
1289 PyObject *func;
1290
1291 /* Try __contains__ first.
1292 * If that can't be done, try iterator-based searching.
1293 */
1294
1295 if(__contains__ == NULL) {
1296 __contains__ = PyString_InternFromString("__contains__");
1297 if(__contains__ == NULL)
1298 return -1;
1299 }
1300 func = instance_getattr(inst, __contains__);
1301 if (func) {
1302 PyObject *res;
1303 int ret;
1304 PyObject *arg = PyTuple_Pack(1, member);
1305 if(arg == NULL) {
1306 Py_DECREF(func);
1307 return -1;
1308 }
1309 res = PyEval_CallObject(func, arg);
1310 Py_DECREF(func);
1311 Py_DECREF(arg);
1312 if(res == NULL)
1313 return -1;
1314 ret = PyObject_IsTrue(res);
1315 Py_DECREF(res);
1316 return ret;
1317 }
1318
1319 /* Couldn't find __contains__. */
1320 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
1321 /* Assume the failure was simply due to that there is no
1322 * __contains__ attribute, and try iterating instead.
1323 */
1324 PyErr_Clear();
1325 return _PySequence_IterSearch((PyObject *)inst, member,
1326 PY_ITERSEARCH_CONTAINS) > 0;
1327 }
1328 else
1329 return -1;
1330}
1331
1332static PySequenceMethods
1333instance_as_sequence = {
1334 (lenfunc)instance_length, /* sq_length */
1335 0, /* sq_concat */
1336 0, /* sq_repeat */
1337 (ssizeargfunc)instance_item, /* sq_item */
1338 (ssizessizeargfunc)instance_slice, /* sq_slice */
1339 (ssizeobjargproc)instance_ass_item, /* sq_ass_item */
1340 (ssizessizeobjargproc)instance_ass_slice,/* sq_ass_slice */
1341 (objobjproc)instance_contains, /* sq_contains */
1342};
1343
1344static PyObject *
1345generic_unary_op(PyInstanceObject *self, PyObject *methodname)
1346{
1347 PyObject *func, *res;
1348
1349 if ((func = instance_getattr(self, methodname)) == NULL)
1350 return NULL;
1351 res = PyEval_CallObject(func, (PyObject *)NULL);
1352 Py_DECREF(func);
1353 return res;
1354}
1355
1356static PyObject *
1357generic_binary_op(PyObject *v, PyObject *w, char *opname)
1358{
1359 PyObject *result;
1360 PyObject *args;
1361 PyObject *func = PyObject_GetAttrString(v, opname);
1362 if (func == NULL) {
1363 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1364 return NULL;
1365 PyErr_Clear();
1366 Py_INCREF(Py_NotImplemented);
1367 return Py_NotImplemented;
1368 }
1369 args = PyTuple_Pack(1, w);
1370 if (args == NULL) {
1371 Py_DECREF(func);
1372 return NULL;
1373 }
1374 result = PyEval_CallObject(func, args);
1375 Py_DECREF(args);
1376 Py_DECREF(func);
1377 return result;
1378}
1379
1380
1381static PyObject *coerce_obj;
1382
1383/* Try one half of a binary operator involving a class instance. */
1384static PyObject *
1385half_binop(PyObject *v, PyObject *w, char *opname, binaryfunc thisfunc,
1386 int swapped)
1387{
1388 PyObject *args;
1389 PyObject *coercefunc;
1390 PyObject *coerced = NULL;
1391 PyObject *v1;
1392 PyObject *result;
1393
1394 if (!PyInstance_Check(v)) {
1395 Py_INCREF(Py_NotImplemented);
1396 return Py_NotImplemented;
1397 }
1398
1399 if (coerce_obj == NULL) {
1400 coerce_obj = PyString_InternFromString("__coerce__");
1401 if (coerce_obj == NULL)
1402 return NULL;
1403 }
1404 coercefunc = PyObject_GetAttr(v, coerce_obj);
1405 if (coercefunc == NULL) {
1406 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1407 return NULL;
1408 PyErr_Clear();
1409 return generic_binary_op(v, w, opname);
1410 }
1411
1412 args = PyTuple_Pack(1, w);
1413 if (args == NULL) {
1414 Py_DECREF(coercefunc);
1415 return NULL;
1416 }
1417 coerced = PyEval_CallObject(coercefunc, args);
1418 Py_DECREF(args);
1419 Py_DECREF(coercefunc);
1420 if (coerced == NULL) {
1421 return NULL;
1422 }
1423 if (coerced == Py_None || coerced == Py_NotImplemented) {
1424 Py_DECREF(coerced);
1425 return generic_binary_op(v, w, opname);
1426 }
1427 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1428 Py_DECREF(coerced);
1429 PyErr_SetString(PyExc_TypeError,
1430 "coercion should return None or 2-tuple");
1431 return NULL;
1432 }
1433 v1 = PyTuple_GetItem(coerced, 0);
1434 w = PyTuple_GetItem(coerced, 1);
1435 if (v1->ob_type == v->ob_type && PyInstance_Check(v)) {
1436 /* prevent recursion if __coerce__ returns self as the first
1437 * argument */
1438 result = generic_binary_op(v1, w, opname);
1439 } else {
1440 if (Py_EnterRecursiveCall(" after coercion"))
1441 return NULL;
1442 if (swapped)
1443 result = (thisfunc)(w, v1);
1444 else
1445 result = (thisfunc)(v1, w);
1446 Py_LeaveRecursiveCall();
1447 }
1448 Py_DECREF(coerced);
1449 return result;
1450}
1451
1452/* Implement a binary operator involving at least one class instance. */
1453static PyObject *
1454do_binop(PyObject *v, PyObject *w, char *opname, char *ropname,
1455 binaryfunc thisfunc)
1456{
1457 PyObject *result = half_binop(v, w, opname, thisfunc, 0);
1458 if (result == Py_NotImplemented) {
1459 Py_DECREF(result);
1460 result = half_binop(w, v, ropname, thisfunc, 1);
1461 }
1462 return result;
1463}
1464
1465static PyObject *
1466do_binop_inplace(PyObject *v, PyObject *w, char *iopname, char *opname,
1467 char *ropname, binaryfunc thisfunc)
1468{
1469 PyObject *result = half_binop(v, w, iopname, thisfunc, 0);
1470 if (result == Py_NotImplemented) {
1471 Py_DECREF(result);
1472 result = do_binop(v, w, opname, ropname, thisfunc);
1473 }
1474 return result;
1475}
1476
1477static int
1478instance_coerce(PyObject **pv, PyObject **pw)
1479{
1480 PyObject *v = *pv;
1481 PyObject *w = *pw;
1482 PyObject *coercefunc;
1483 PyObject *args;
1484 PyObject *coerced;
1485
1486 if (coerce_obj == NULL) {
1487 coerce_obj = PyString_InternFromString("__coerce__");
1488 if (coerce_obj == NULL)
1489 return -1;
1490 }
1491 coercefunc = PyObject_GetAttr(v, coerce_obj);
1492 if (coercefunc == NULL) {
1493 /* No __coerce__ method */
1494 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1495 return -1;
1496 PyErr_Clear();
1497 return 1;
1498 }
1499 /* Has __coerce__ method: call it */
1500 args = PyTuple_Pack(1, w);
1501 if (args == NULL) {
1502 return -1;
1503 }
1504 coerced = PyEval_CallObject(coercefunc, args);
1505 Py_DECREF(args);
1506 Py_DECREF(coercefunc);
1507 if (coerced == NULL) {
1508 /* __coerce__ call raised an exception */
1509 return -1;
1510 }
1511 if (coerced == Py_None || coerced == Py_NotImplemented) {
1512 /* __coerce__ says "I can't do it" */
1513 Py_DECREF(coerced);
1514 return 1;
1515 }
1516 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1517 /* __coerce__ return value is malformed */
1518 Py_DECREF(coerced);
1519 PyErr_SetString(PyExc_TypeError,
1520 "coercion should return None or 2-tuple");
1521 return -1;
1522 }
1523 /* __coerce__ returned two new values */
1524 *pv = PyTuple_GetItem(coerced, 0);
1525 *pw = PyTuple_GetItem(coerced, 1);
1526 Py_INCREF(*pv);
1527 Py_INCREF(*pw);
1528 Py_DECREF(coerced);
1529 return 0;
1530}
1531
1532#define UNARY(funcname, methodname) \
1533static PyObject *funcname(PyInstanceObject *self) { \
1534 static PyObject *o; \
1535 if (o == NULL) { o = PyString_InternFromString(methodname); \
1536 if (o == NULL) return NULL; } \
1537 return generic_unary_op(self, o); \
1538}
1539
1540#define BINARY(f, m, n) \
1541static PyObject *f(PyObject *v, PyObject *w) { \
1542 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1543}
1544
1545#define BINARY_INPLACE(f, m, n) \
1546static PyObject *f(PyObject *v, PyObject *w) { \
1547 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1548 "__r" m "__", n); \
1549}
1550
1551UNARY(instance_neg, "__neg__")
1552UNARY(instance_pos, "__pos__")
1553UNARY(instance_abs, "__abs__")
1554
1555BINARY(instance_or, "or", PyNumber_Or)
1556BINARY(instance_and, "and", PyNumber_And)
1557BINARY(instance_xor, "xor", PyNumber_Xor)
1558BINARY(instance_lshift, "lshift", PyNumber_Lshift)
1559BINARY(instance_rshift, "rshift", PyNumber_Rshift)
1560BINARY(instance_add, "add", PyNumber_Add)
1561BINARY(instance_sub, "sub", PyNumber_Subtract)
1562BINARY(instance_mul, "mul", PyNumber_Multiply)
1563BINARY(instance_div, "div", PyNumber_Divide)
1564BINARY(instance_mod, "mod", PyNumber_Remainder)
1565BINARY(instance_divmod, "divmod", PyNumber_Divmod)
1566BINARY(instance_floordiv, "floordiv", PyNumber_FloorDivide)
1567BINARY(instance_truediv, "truediv", PyNumber_TrueDivide)
1568
1569BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr)
1570BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor)
1571BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd)
1572BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift)
1573BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift)
1574BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd)
1575BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract)
1576BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply)
1577BINARY_INPLACE(instance_idiv, "div", PyNumber_InPlaceDivide)
1578BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder)
1579BINARY_INPLACE(instance_ifloordiv, "floordiv", PyNumber_InPlaceFloorDivide)
1580BINARY_INPLACE(instance_itruediv, "truediv", PyNumber_InPlaceTrueDivide)
1581
1582/* Try a 3-way comparison, returning an int; v is an instance. Return:
1583 -2 for an exception;
1584 -1 if v < w;
1585 0 if v == w;
1586 1 if v > w;
1587 2 if this particular 3-way comparison is not implemented or undefined.
1588*/
1589static int
1590half_cmp(PyObject *v, PyObject *w)
1591{
1592 static PyObject *cmp_obj;
1593 PyObject *args;
1594 PyObject *cmp_func;
1595 PyObject *result;
1596 long l;
1597
1598 assert(PyInstance_Check(v));
1599
1600 if (cmp_obj == NULL) {
1601 cmp_obj = PyString_InternFromString("__cmp__");
1602 if (cmp_obj == NULL)
1603 return -2;
1604 }
1605
1606 cmp_func = PyObject_GetAttr(v, cmp_obj);
1607 if (cmp_func == NULL) {
1608 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1609 return -2;
1610 PyErr_Clear();
1611 return 2;
1612 }
1613
1614 args = PyTuple_Pack(1, w);
1615 if (args == NULL) {
1616 Py_DECREF(cmp_func);
1617 return -2;
1618 }
1619
1620 result = PyEval_CallObject(cmp_func, args);
1621 Py_DECREF(args);
1622 Py_DECREF(cmp_func);
1623
1624 if (result == NULL)
1625 return -2;
1626
1627 if (result == Py_NotImplemented) {
1628 Py_DECREF(result);
1629 return 2;
1630 }
1631
1632 l = PyInt_AsLong(result);
1633 Py_DECREF(result);
1634 if (l == -1 && PyErr_Occurred()) {
1635 PyErr_SetString(PyExc_TypeError,
1636 "comparison did not return an int");
1637 return -2;
1638 }
1639
1640 return l < 0 ? -1 : l > 0 ? 1 : 0;
1641}
1642
1643/* Try a 3-way comparison, returning an int; either v or w is an instance.
1644 We first try a coercion. Return:
1645 -2 for an exception;
1646 -1 if v < w;
1647 0 if v == w;
1648 1 if v > w;
1649 2 if this particular 3-way comparison is not implemented or undefined.
1650 THIS IS ONLY CALLED FROM object.c!
1651*/
1652static int
1653instance_compare(PyObject *v, PyObject *w)
1654{
1655 int c;
1656
1657 c = PyNumber_CoerceEx(&v, &w);
1658 if (c < 0)
1659 return -2;
1660 if (c == 0) {
1661 /* If neither is now an instance, use regular comparison */
1662 if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
1663 c = PyObject_Compare(v, w);
1664 Py_DECREF(v);
1665 Py_DECREF(w);
1666 if (PyErr_Occurred())
1667 return -2;
1668 return c < 0 ? -1 : c > 0 ? 1 : 0;
1669 }
1670 }
1671 else {
1672 /* The coercion didn't do anything.
1673 Treat this the same as returning v and w unchanged. */
1674 Py_INCREF(v);
1675 Py_INCREF(w);
1676 }
1677
1678 if (PyInstance_Check(v)) {
1679 c = half_cmp(v, w);
1680 if (c <= 1) {
1681 Py_DECREF(v);
1682 Py_DECREF(w);
1683 return c;
1684 }
1685 }
1686 if (PyInstance_Check(w)) {
1687 c = half_cmp(w, v);
1688 if (c <= 1) {
1689 Py_DECREF(v);
1690 Py_DECREF(w);
1691 if (c >= -1)
1692 c = -c;
1693 return c;
1694 }
1695 }
1696 Py_DECREF(v);
1697 Py_DECREF(w);
1698 return 2;
1699}
1700
1701static int
1702instance_nonzero(PyInstanceObject *self)
1703{
1704 PyObject *func, *res;
1705 long outcome;
1706 static PyObject *nonzerostr;
1707
1708 if (nonzerostr == NULL) {
1709 nonzerostr = PyString_InternFromString("__nonzero__");
1710 if (nonzerostr == NULL)
1711 return -1;
1712 }
1713 if ((func = instance_getattr(self, nonzerostr)) == NULL) {
1714 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1715 return -1;
1716 PyErr_Clear();
1717 if (lenstr == NULL) {
1718 lenstr = PyString_InternFromString("__len__");
1719 if (lenstr == NULL)
1720 return -1;
1721 }
1722 if ((func = instance_getattr(self, lenstr)) == NULL) {
1723 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1724 return -1;
1725 PyErr_Clear();
1726 /* Fall back to the default behavior:
1727 all instances are nonzero */
1728 return 1;
1729 }
1730 }
1731 res = PyEval_CallObject(func, (PyObject *)NULL);
1732 Py_DECREF(func);
1733 if (res == NULL)
1734 return -1;
1735 if (!PyInt_Check(res)) {
1736 Py_DECREF(res);
1737 PyErr_SetString(PyExc_TypeError,
1738 "__nonzero__ should return an int");
1739 return -1;
1740 }
1741 outcome = PyInt_AsLong(res);
1742 Py_DECREF(res);
1743 if (outcome < 0) {
1744 PyErr_SetString(PyExc_ValueError,
1745 "__nonzero__ should return >= 0");
1746 return -1;
1747 }
1748 return outcome > 0;
1749}
1750
1751static PyObject *
1752instance_index(PyInstanceObject *self)
1753{
1754 PyObject *func, *res;
1755 static PyObject *indexstr = NULL;
1756
1757 if (indexstr == NULL) {
1758 indexstr = PyString_InternFromString("__index__");
1759 if (indexstr == NULL)
1760 return NULL;
1761 }
1762 if ((func = instance_getattr(self, indexstr)) == NULL) {
1763 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1764 return NULL;
1765 PyErr_Clear();
1766 PyErr_SetString(PyExc_TypeError,
1767 "object cannot be interpreted as an index");
1768 return NULL;
1769 }
1770 res = PyEval_CallObject(func, (PyObject *)NULL);
1771 Py_DECREF(func);
1772 return res;
1773}
1774
1775
1776UNARY(instance_invert, "__invert__")
1777UNARY(instance_int, "__int__")
1778UNARY(instance_long, "__long__")
1779UNARY(instance_float, "__float__")
1780UNARY(instance_oct, "__oct__")
1781UNARY(instance_hex, "__hex__")
1782
1783static PyObject *
1784bin_power(PyObject *v, PyObject *w)
1785{
1786 return PyNumber_Power(v, w, Py_None);
1787}
1788
1789/* This version is for ternary calls only (z != None) */
1790static PyObject *
1791instance_pow(PyObject *v, PyObject *w, PyObject *z)
1792{
1793 if (z == Py_None) {
1794 return do_binop(v, w, "__pow__", "__rpow__", bin_power);
1795 }
1796 else {
1797 PyObject *func;
1798 PyObject *args;
1799 PyObject *result;
1800
1801 /* XXX Doesn't do coercions... */
1802 func = PyObject_GetAttrString(v, "__pow__");
1803 if (func == NULL)
1804 return NULL;
1805 args = PyTuple_Pack(2, w, z);
1806 if (args == NULL) {
1807 Py_DECREF(func);
1808 return NULL;
1809 }
1810 result = PyEval_CallObject(func, args);
1811 Py_DECREF(func);
1812 Py_DECREF(args);
1813 return result;
1814 }
1815}
1816
1817static PyObject *
1818bin_inplace_power(PyObject *v, PyObject *w)
1819{
1820 return PyNumber_InPlacePower(v, w, Py_None);
1821}
1822
1823
1824static PyObject *
1825instance_ipow(PyObject *v, PyObject *w, PyObject *z)
1826{
1827 if (z == Py_None) {
1828 return do_binop_inplace(v, w, "__ipow__", "__pow__",
1829 "__rpow__", bin_inplace_power);
1830 }
1831 else {
1832 /* XXX Doesn't do coercions... */
1833 PyObject *func;
1834 PyObject *args;
1835 PyObject *result;
1836
1837 func = PyObject_GetAttrString(v, "__ipow__");
1838 if (func == NULL) {
1839 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1840 return NULL;
1841 PyErr_Clear();
1842 return instance_pow(v, w, z);
1843 }
1844 args = PyTuple_Pack(2, w, z);
1845 if (args == NULL) {
1846 Py_DECREF(func);
1847 return NULL;
1848 }
1849 result = PyEval_CallObject(func, args);
1850 Py_DECREF(func);
1851 Py_DECREF(args);
1852 return result;
1853 }
1854}
1855
1856
1857/* Map rich comparison operators to their __xx__ namesakes */
1858#define NAME_OPS 6
1859static PyObject **name_op = NULL;
1860
1861static int
1862init_name_op(void)
1863{
1864 int i;
1865 char *_name_op[] = {
1866 "__lt__",
1867 "__le__",
1868 "__eq__",
1869 "__ne__",
1870 "__gt__",
1871 "__ge__",
1872 };
1873
1874 name_op = (PyObject **)malloc(sizeof(PyObject *) * NAME_OPS);
1875 if (name_op == NULL)
1876 return -1;
1877 for (i = 0; i < NAME_OPS; ++i) {
1878 name_op[i] = PyString_InternFromString(_name_op[i]);
1879 if (name_op[i] == NULL)
1880 return -1;
1881 }
1882 return 0;
1883}
1884
1885static PyObject *
1886half_richcompare(PyObject *v, PyObject *w, int op)
1887{
1888 PyObject *method;
1889 PyObject *args;
1890 PyObject *res;
1891
1892 assert(PyInstance_Check(v));
1893
1894 if (name_op == NULL) {
1895 if (init_name_op() < 0)
1896 return NULL;
1897 }
1898 /* If the instance doesn't define an __getattr__ method, use
1899 instance_getattr2 directly because it will not set an
1900 exception on failure. */
1901 if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL)
1902 method = instance_getattr2((PyInstanceObject *)v,
1903 name_op[op]);
1904 else
1905 method = PyObject_GetAttr(v, name_op[op]);
1906 if (method == NULL) {
1907 if (PyErr_Occurred()) {
1908 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1909 return NULL;
1910 PyErr_Clear();
1911 }
1912 res = Py_NotImplemented;
1913 Py_INCREF(res);
1914 return res;
1915 }
1916
1917 args = PyTuple_Pack(1, w);
1918 if (args == NULL) {
1919 Py_DECREF(method);
1920 return NULL;
1921 }
1922
1923 res = PyEval_CallObject(method, args);
1924 Py_DECREF(args);
1925 Py_DECREF(method);
1926
1927 return res;
1928}
1929
1930static PyObject *
1931instance_richcompare(PyObject *v, PyObject *w, int op)
1932{
1933 PyObject *res;
1934
1935 if (PyInstance_Check(v)) {
1936 res = half_richcompare(v, w, op);
1937 if (res != Py_NotImplemented)
1938 return res;
1939 Py_DECREF(res);
1940 }
1941
1942 if (PyInstance_Check(w)) {
1943 res = half_richcompare(w, v, _Py_SwappedOp[op]);
1944 if (res != Py_NotImplemented)
1945 return res;
1946 Py_DECREF(res);
1947 }
1948
1949 Py_INCREF(Py_NotImplemented);
1950 return Py_NotImplemented;
1951}
1952
1953
1954/* Get the iterator */
1955static PyObject *
1956instance_getiter(PyInstanceObject *self)
1957{
1958 PyObject *func;
1959
1960 if (iterstr == NULL) {
1961 iterstr = PyString_InternFromString("__iter__");
1962 if (iterstr == NULL)
1963 return NULL;
1964 }
1965 if (getitemstr == NULL) {
1966 getitemstr = PyString_InternFromString("__getitem__");
1967 if (getitemstr == NULL)
1968 return NULL;
1969 }
1970
1971 if ((func = instance_getattr(self, iterstr)) != NULL) {
1972 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
1973 Py_DECREF(func);
1974 if (res != NULL && !PyIter_Check(res)) {
1975 PyErr_Format(PyExc_TypeError,
1976 "__iter__ returned non-iterator "
1977 "of type '%.100s'",
1978 res->ob_type->tp_name);
1979 Py_DECREF(res);
1980 res = NULL;
1981 }
1982 return res;
1983 }
1984 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1985 return NULL;
1986 PyErr_Clear();
1987 if ((func = instance_getattr(self, getitemstr)) == NULL) {
1988 PyErr_SetString(PyExc_TypeError,
1989 "iteration over non-sequence");
1990 return NULL;
1991 }
1992 Py_DECREF(func);
1993 return PySeqIter_New((PyObject *)self);
1994}
1995
1996
1997/* Call the iterator's next */
1998static PyObject *
1999instance_iternext(PyInstanceObject *self)
2000{
2001 PyObject *func;
2002
2003 if (nextstr == NULL) {
2004 nextstr = PyString_InternFromString("next");
2005 if (nextstr == NULL)
2006 return NULL;
2007 }
2008
2009 if ((func = instance_getattr(self, nextstr)) != NULL) {
2010 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
2011 Py_DECREF(func);
2012 if (res != NULL) {
2013 return res;
2014 }
2015 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
2016 PyErr_Clear();
2017 return NULL;
2018 }
2019 return NULL;
2020 }
2021 PyErr_SetString(PyExc_TypeError, "instance has no next() method");
2022 return NULL;
2023}
2024
2025static PyObject *
2026instance_call(PyObject *func, PyObject *arg, PyObject *kw)
2027{
2028 PyObject *res, *call = PyObject_GetAttrString(func, "__call__");
2029 if (call == NULL) {
2030 PyInstanceObject *inst = (PyInstanceObject*) func;
2031 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2032 return NULL;
2033 PyErr_Clear();
2034 PyErr_Format(PyExc_AttributeError,
2035 "%.200s instance has no __call__ method",
2036 PyString_AsString(inst->in_class->cl_name));
2037 return NULL;
2038 }
2039 /* We must check and increment the recursion depth here. Scenario:
2040 class A:
2041 pass
2042 A.__call__ = A() # that's right
2043 a = A() # ok
2044 a() # infinite recursion
2045 This bounces between instance_call() and PyObject_Call() without
2046 ever hitting eval_frame() (which has the main recursion check). */
2047 if (Py_EnterRecursiveCall(" in __call__")) {
2048 res = NULL;
2049 }
2050 else {
2051 res = PyObject_Call(call, arg, kw);
2052 Py_LeaveRecursiveCall();
2053 }
2054 Py_DECREF(call);
2055 return res;
2056}
2057
2058
2059static PyNumberMethods instance_as_number = {
2060 instance_add, /* nb_add */
2061 instance_sub, /* nb_subtract */
2062 instance_mul, /* nb_multiply */
2063 instance_div, /* nb_divide */
2064 instance_mod, /* nb_remainder */
2065 instance_divmod, /* nb_divmod */
2066 instance_pow, /* nb_power */
2067 (unaryfunc)instance_neg, /* nb_negative */
2068 (unaryfunc)instance_pos, /* nb_positive */
2069 (unaryfunc)instance_abs, /* nb_absolute */
2070 (inquiry)instance_nonzero, /* nb_nonzero */
2071 (unaryfunc)instance_invert, /* nb_invert */
2072 instance_lshift, /* nb_lshift */
2073 instance_rshift, /* nb_rshift */
2074 instance_and, /* nb_and */
2075 instance_xor, /* nb_xor */
2076 instance_or, /* nb_or */
2077 instance_coerce, /* nb_coerce */
2078 (unaryfunc)instance_int, /* nb_int */
2079 (unaryfunc)instance_long, /* nb_long */
2080 (unaryfunc)instance_float, /* nb_float */
2081 (unaryfunc)instance_oct, /* nb_oct */
2082 (unaryfunc)instance_hex, /* nb_hex */
2083 instance_iadd, /* nb_inplace_add */
2084 instance_isub, /* nb_inplace_subtract */
2085 instance_imul, /* nb_inplace_multiply */
2086 instance_idiv, /* nb_inplace_divide */
2087 instance_imod, /* nb_inplace_remainder */
2088 instance_ipow, /* nb_inplace_power */
2089 instance_ilshift, /* nb_inplace_lshift */
2090 instance_irshift, /* nb_inplace_rshift */
2091 instance_iand, /* nb_inplace_and */
2092 instance_ixor, /* nb_inplace_xor */
2093 instance_ior, /* nb_inplace_or */
2094 instance_floordiv, /* nb_floor_divide */
2095 instance_truediv, /* nb_true_divide */
2096 instance_ifloordiv, /* nb_inplace_floor_divide */
2097 instance_itruediv, /* nb_inplace_true_divide */
2098 (unaryfunc)instance_index, /* nb_index */
2099};
2100
2101PyTypeObject PyInstance_Type = {
2102 PyObject_HEAD_INIT(&PyType_Type)
2103 0,
2104 "instance",
2105 sizeof(PyInstanceObject),
2106 0,
2107 (destructor)instance_dealloc, /* tp_dealloc */
2108 0, /* tp_print */
2109 0, /* tp_getattr */
2110 0, /* tp_setattr */
2111 instance_compare, /* tp_compare */
2112 (reprfunc)instance_repr, /* tp_repr */
2113 &instance_as_number, /* tp_as_number */
2114 &instance_as_sequence, /* tp_as_sequence */
2115 &instance_as_mapping, /* tp_as_mapping */
2116 (hashfunc)instance_hash, /* tp_hash */
2117 instance_call, /* tp_call */
2118 (reprfunc)instance_str, /* tp_str */
2119 (getattrofunc)instance_getattr, /* tp_getattro */
2120 (setattrofunc)instance_setattr, /* tp_setattro */
2121 0, /* tp_as_buffer */
2122 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES,/*tp_flags*/
2123 instance_doc, /* tp_doc */
2124 (traverseproc)instance_traverse, /* tp_traverse */
2125 0, /* tp_clear */
2126 instance_richcompare, /* tp_richcompare */
2127 offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
2128 (getiterfunc)instance_getiter, /* tp_iter */
2129 (iternextfunc)instance_iternext, /* tp_iternext */
2130 0, /* tp_methods */
2131 0, /* tp_members */
2132 0, /* tp_getset */
2133 0, /* tp_base */
2134 0, /* tp_dict */
2135 0, /* tp_descr_get */
2136 0, /* tp_descr_set */
2137 0, /* tp_dictoffset */
2138 0, /* tp_init */
2139 0, /* tp_alloc */
2140 instance_new, /* tp_new */
2141};
2142
2143
2144/* Instance method objects are used for two purposes:
2145 (a) as bound instance methods (returned by instancename.methodname)
2146 (b) as unbound methods (returned by ClassName.methodname)
2147 In case (b), im_self is NULL
2148*/
2149
2150static PyMethodObject *free_list;
2151
2152PyObject *
2153PyMethod_New(PyObject *func, PyObject *self, PyObject *klass)
2154{
2155 register PyMethodObject *im;
2156 if (!PyCallable_Check(func)) {
2157 PyErr_BadInternalCall();
2158 return NULL;
2159 }
2160 im = free_list;
2161 if (im != NULL) {
2162 free_list = (PyMethodObject *)(im->im_self);
2163 PyObject_INIT(im, &PyMethod_Type);
2164 }
2165 else {
2166 im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
2167 if (im == NULL)
2168 return NULL;
2169 }
2170 im->im_weakreflist = NULL;
2171 Py_INCREF(func);
2172 im->im_func = func;
2173 Py_XINCREF(self);
2174 im->im_self = self;
2175 Py_XINCREF(klass);
2176 im->im_class = klass;
2177 _PyObject_GC_TRACK(im);
2178 return (PyObject *)im;
2179}
2180
2181/* Descriptors for PyMethod attributes */
2182
2183/* im_class, im_func and im_self are stored in the PyMethod object */
2184
2185#define OFF(x) offsetof(PyMethodObject, x)
2186
2187static PyMemberDef instancemethod_memberlist[] = {
2188 {"im_class", T_OBJECT, OFF(im_class), READONLY|RESTRICTED,
2189 "the class associated with a method"},
2190 {"im_func", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
2191 "the function (or other callable) implementing a method"},
2192 {"im_self", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
2193 "the instance to which a method is bound; None for unbound methods"},
2194 {NULL} /* Sentinel */
2195};
2196
2197/* Christian Tismer argued convincingly that method attributes should
2198 (nearly) always override function attributes.
2199 The one exception is __doc__; there's a default __doc__ which
2200 should only be used for the class, not for instances */
2201
2202static PyObject *
2203instancemethod_get_doc(PyMethodObject *im, void *context)
2204{
2205 static PyObject *docstr;
2206 if (docstr == NULL) {
2207 docstr= PyString_InternFromString("__doc__");
2208 if (docstr == NULL)
2209 return NULL;
2210 }
2211 return PyObject_GetAttr(im->im_func, docstr);
2212}
2213
2214static PyGetSetDef instancemethod_getset[] = {
2215 {"__doc__", (getter)instancemethod_get_doc, NULL, NULL},
2216 {0}
2217};
2218
2219static PyObject *
2220instancemethod_getattro(PyObject *obj, PyObject *name)
2221{
2222 PyMethodObject *im = (PyMethodObject *)obj;
2223 PyTypeObject *tp = obj->ob_type;
2224 PyObject *descr = NULL;
2225
2226 if (PyType_HasFeature(tp, Py_TPFLAGS_HAVE_CLASS)) {
2227 if (tp->tp_dict == NULL) {
2228 if (PyType_Ready(tp) < 0)
2229 return NULL;
2230 }
2231 descr = _PyType_Lookup(tp, name);
2232 }
2233
2234 if (descr != NULL) {
2235 descrgetfunc f = TP_DESCR_GET(descr->ob_type);
2236 if (f != NULL)
2237 return f(descr, obj, (PyObject *)obj->ob_type);
2238 else {
2239 Py_INCREF(descr);
2240 return descr;
2241 }
2242 }
2243
2244 return PyObject_GetAttr(im->im_func, name);
2245}
2246
2247PyDoc_STRVAR(instancemethod_doc,
2248"instancemethod(function, instance, class)\n\
2249\n\
2250Create an instance method object.");
2251
2252static PyObject *
2253instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw)
2254{
2255 PyObject *func;
2256 PyObject *self;
2257 PyObject *classObj = NULL;
2258
2259 if (!PyArg_UnpackTuple(args, "instancemethod", 2, 3,
2260 &func, &self, &classObj))
2261 return NULL;
2262 if (!PyCallable_Check(func)) {
2263 PyErr_SetString(PyExc_TypeError,
2264 "first argument must be callable");
2265 return NULL;
2266 }
2267 if (self == Py_None)
2268 self = NULL;
2269 if (self == NULL && classObj == NULL) {
2270 PyErr_SetString(PyExc_TypeError,
2271 "unbound methods must have non-NULL im_class");
2272 return NULL;
2273 }
2274
2275 return PyMethod_New(func, self, classObj);
2276}
2277
2278static void
2279instancemethod_dealloc(register PyMethodObject *im)
2280{
2281 _PyObject_GC_UNTRACK(im);
2282 if (im->im_weakreflist != NULL)
2283 PyObject_ClearWeakRefs((PyObject *)im);
2284 Py_DECREF(im->im_func);
2285 Py_XDECREF(im->im_self);
2286 Py_XDECREF(im->im_class);
2287 im->im_self = (PyObject *)free_list;
2288 free_list = im;
2289}
2290
2291static int
2292instancemethod_compare(PyMethodObject *a, PyMethodObject *b)
2293{
2294 int cmp;
2295 cmp = PyObject_Compare(a->im_func, b->im_func);
2296 if (cmp)
2297 return cmp;
2298
2299 if (a->im_self == b->im_self)
2300 return 0;
2301 if (a->im_self == NULL || b->im_self == NULL)
2302 return (a->im_self < b->im_self) ? -1 : 1;
2303 else
2304 return PyObject_Compare(a->im_self, b->im_self);
2305}
2306
2307static PyObject *
2308instancemethod_repr(PyMethodObject *a)
2309{
2310 PyObject *self = a->im_self;
2311 PyObject *func = a->im_func;
2312 PyObject *klass = a->im_class;
2313 PyObject *funcname = NULL, *klassname = NULL, *result = NULL;
2314 char *sfuncname = "?", *sklassname = "?";
2315
2316 funcname = PyObject_GetAttrString(func, "__name__");
2317 if (funcname == NULL) {
2318 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2319 return NULL;
2320 PyErr_Clear();
2321 }
2322 else if (!PyString_Check(funcname)) {
2323 Py_DECREF(funcname);
2324 funcname = NULL;
2325 }
2326 else
2327 sfuncname = PyString_AS_STRING(funcname);
2328 if (klass == NULL)
2329 klassname = NULL;
2330 else {
2331 klassname = PyObject_GetAttrString(klass, "__name__");
2332 if (klassname == NULL) {
2333 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2334 return NULL;
2335 PyErr_Clear();
2336 }
2337 else if (!PyString_Check(klassname)) {
2338 Py_DECREF(klassname);
2339 klassname = NULL;
2340 }
2341 else
2342 sklassname = PyString_AS_STRING(klassname);
2343 }
2344 if (self == NULL)
2345 result = PyString_FromFormat("<unbound method %s.%s>",
2346 sklassname, sfuncname);
2347 else {
2348 /* XXX Shouldn't use repr() here! */
2349 PyObject *selfrepr = PyObject_Repr(self);
2350 if (selfrepr == NULL)
2351 goto fail;
2352 if (!PyString_Check(selfrepr)) {
2353 Py_DECREF(selfrepr);
2354 goto fail;
2355 }
2356 result = PyString_FromFormat("<bound method %s.%s of %s>",
2357 sklassname, sfuncname,
2358 PyString_AS_STRING(selfrepr));
2359 Py_DECREF(selfrepr);
2360 }
2361 fail:
2362 Py_XDECREF(funcname);
2363 Py_XDECREF(klassname);
2364 return result;
2365}
2366
2367static long
2368instancemethod_hash(PyMethodObject *a)
2369{
2370 long x, y;
2371 if (a->im_self == NULL)
2372 x = PyObject_Hash(Py_None);
2373 else
2374 x = PyObject_Hash(a->im_self);
2375 if (x == -1)
2376 return -1;
2377 y = PyObject_Hash(a->im_func);
2378 if (y == -1)
2379 return -1;
2380 x = x ^ y;
2381 if (x == -1)
2382 x = -2;
2383 return x;
2384}
2385
2386static int
2387instancemethod_traverse(PyMethodObject *im, visitproc visit, void *arg)
2388{
2389 Py_VISIT(im->im_func);
2390 Py_VISIT(im->im_self);
2391 Py_VISIT(im->im_class);
2392 return 0;
2393}
2394
2395static void
2396getclassname(PyObject *klass, char *buf, int bufsize)
2397{
2398 PyObject *name;
2399
2400 assert(bufsize > 1);
2401 strcpy(buf, "?"); /* Default outcome */
2402 if (klass == NULL)
2403 return;
2404 name = PyObject_GetAttrString(klass, "__name__");
2405 if (name == NULL) {
2406 /* This function cannot return an exception */
2407 PyErr_Clear();
2408 return;
2409 }
2410 if (PyString_Check(name)) {
2411 strncpy(buf, PyString_AS_STRING(name), bufsize);
2412 buf[bufsize-1] = '\0';
2413 }
2414 Py_DECREF(name);
2415}
2416
2417static void
2418getinstclassname(PyObject *inst, char *buf, int bufsize)
2419{
2420 PyObject *klass;
2421
2422 if (inst == NULL) {
2423 assert(bufsize > 0 && (size_t)bufsize > strlen("nothing"));
2424 strcpy(buf, "nothing");
2425 return;
2426 }
2427
2428 klass = PyObject_GetAttrString(inst, "__class__");
2429 if (klass == NULL) {
2430 /* This function cannot return an exception */
2431 PyErr_Clear();
2432 klass = (PyObject *)(inst->ob_type);
2433 Py_INCREF(klass);
2434 }
2435 getclassname(klass, buf, bufsize);
2436 Py_XDECREF(klass);
2437}
2438
2439static PyObject *
2440instancemethod_call(PyObject *func, PyObject *arg, PyObject *kw)
2441{
2442 PyObject *self = PyMethod_GET_SELF(func);
2443 PyObject *klass = PyMethod_GET_CLASS(func);
2444 PyObject *result;
2445
2446 func = PyMethod_GET_FUNCTION(func);
2447 if (self == NULL) {
2448 /* Unbound methods must be called with an instance of
2449 the class (or a derived class) as first argument */
2450 int ok;
2451 if (PyTuple_Size(arg) >= 1)
2452 self = PyTuple_GET_ITEM(arg, 0);
2453 if (self == NULL)
2454 ok = 0;
2455 else {
2456 ok = PyObject_IsInstance(self, klass);
2457 if (ok < 0)
2458 return NULL;
2459 }
2460 if (!ok) {
2461 char clsbuf[256];
2462 char instbuf[256];
2463 getclassname(klass, clsbuf, sizeof(clsbuf));
2464 getinstclassname(self, instbuf, sizeof(instbuf));
2465 PyErr_Format(PyExc_TypeError,
2466 "unbound method %s%s must be called with "
2467 "%s instance as first argument "
2468 "(got %s%s instead)",
2469 PyEval_GetFuncName(func),
2470 PyEval_GetFuncDesc(func),
2471 clsbuf,
2472 instbuf,
2473 self == NULL ? "" : " instance");
2474 return NULL;
2475 }
2476 Py_INCREF(arg);
2477 }
2478 else {
2479 Py_ssize_t argcount = PyTuple_Size(arg);
2480 PyObject *newarg = PyTuple_New(argcount + 1);
2481 int i;
2482 if (newarg == NULL)
2483 return NULL;
2484 Py_INCREF(self);
2485 PyTuple_SET_ITEM(newarg, 0, self);
2486 for (i = 0; i < argcount; i++) {
2487 PyObject *v = PyTuple_GET_ITEM(arg, i);
2488 Py_XINCREF(v);
2489 PyTuple_SET_ITEM(newarg, i+1, v);
2490 }
2491 arg = newarg;
2492 }
2493 result = PyObject_Call((PyObject *)func, arg, kw);
2494 Py_DECREF(arg);
2495 return result;
2496}
2497
2498static PyObject *
2499instancemethod_descr_get(PyObject *meth, PyObject *obj, PyObject *cls)
2500{
2501 /* Don't rebind an already bound method, or an unbound method
2502 of a class that's not a base class of cls. */
2503
2504 if (PyMethod_GET_SELF(meth) != NULL) {
2505 /* Already bound */
2506 Py_INCREF(meth);
2507 return meth;
2508 }
2509 /* No, it is an unbound method */
2510 if (PyMethod_GET_CLASS(meth) != NULL && cls != NULL) {
2511 /* Do subclass test. If it fails, return meth unchanged. */
2512 int ok = PyObject_IsSubclass(cls, PyMethod_GET_CLASS(meth));
2513 if (ok < 0)
2514 return NULL;
2515 if (!ok) {
2516 Py_INCREF(meth);
2517 return meth;
2518 }
2519 }
2520 /* Bind it to obj */
2521 return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj, cls);
2522}
2523
2524PyTypeObject PyMethod_Type = {
2525 PyObject_HEAD_INIT(&PyType_Type)
2526 0,
2527 "instancemethod",
2528 sizeof(PyMethodObject),
2529 0,
2530 (destructor)instancemethod_dealloc, /* tp_dealloc */
2531 0, /* tp_print */
2532 0, /* tp_getattr */
2533 0, /* tp_setattr */
2534 (cmpfunc)instancemethod_compare, /* tp_compare */
2535 (reprfunc)instancemethod_repr, /* tp_repr */
2536 0, /* tp_as_number */
2537 0, /* tp_as_sequence */
2538 0, /* tp_as_mapping */
2539 (hashfunc)instancemethod_hash, /* tp_hash */
2540 instancemethod_call, /* tp_call */
2541 0, /* tp_str */
2542 instancemethod_getattro, /* tp_getattro */
2543 PyObject_GenericSetAttr, /* tp_setattro */
2544 0, /* tp_as_buffer */
2545 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
2546 instancemethod_doc, /* tp_doc */
2547 (traverseproc)instancemethod_traverse, /* tp_traverse */
2548 0, /* tp_clear */
2549 0, /* tp_richcompare */
2550 offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */
2551 0, /* tp_iter */
2552 0, /* tp_iternext */
2553 0, /* tp_methods */
2554 instancemethod_memberlist, /* tp_members */
2555 instancemethod_getset, /* tp_getset */
2556 0, /* tp_base */
2557 0, /* tp_dict */
2558 instancemethod_descr_get, /* tp_descr_get */
2559 0, /* tp_descr_set */
2560 0, /* tp_dictoffset */
2561 0, /* tp_init */
2562 0, /* tp_alloc */
2563 instancemethod_new, /* tp_new */
2564};
2565
2566/* Clear out the free list */
2567
2568void
2569PyMethod_Fini(void)
2570{
2571 while (free_list) {
2572 PyMethodObject *im = free_list;
2573 free_list = (PyMethodObject *)(im->im_self);
2574 PyObject_GC_Del(im);
2575 }
2576}
Note: See TracBrowser for help on using the repository browser.