History

add hg and python

cinap_lenrek committed 15 years ago

Commit 4bb9e221 parent 987265c3706 files · +1228772 −-233Browse files

Showing the changes to sys/src/cmd/python/Objects/classobject.c (1 of 3706 files). Show all

Unified · Split

sys/src/cmd/python/Objects/classobject.c+2580−0
@@ -0,0 +1,2580 @@
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 */
12+static PyObject *class_lookup(PyClassObject *, PyObject *,
13+ PyClassObject **);
14+static PyObject *instance_getattr1(PyInstanceObject *, PyObject *);
15+static PyObject *instance_getattr2(PyInstanceObject *, PyObject *);
16+
17+static PyObject *getattrstr, *setattrstr, *delattrstr;
18+
19+
20+PyObject *
21+PyClass_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) {
109+alloc_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+
129+PyObject *
130+PyMethod_Function(PyObject *im)
131+{
132+ if (!PyMethod_Check(im)) {
133+ PyErr_BadInternalCall();
134+ return NULL;
135+ }
136+ return ((PyMethodObject *)im)->im_func;
137+}
138+
139+PyObject *
140+PyMethod_Self(PyObject *im)
141+{
142+ if (!PyMethod_Check(im)) {
143+ PyErr_BadInternalCall();
144+ return NULL;
145+ }
146+ return ((PyMethodObject *)im)->im_self;
147+}
148+
149+PyObject *
150+PyMethod_Class(PyObject *im)
151+{
152+ if (!PyMethod_Check(im)) {
153+ PyErr_BadInternalCall();
154+ return NULL;
155+ }
156+ return ((PyMethodObject *)im)->im_class;
157+}
158+
159+PyDoc_STRVAR(class_doc,
160+"classobj(name, bases, dict)\n\
161+\n\
162+Create a class object. The name must be a string; the second argument\n\
163+a tuple of classes, and the third a dictionary.");
164+
165+static PyObject *
166+class_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+
179+static void
180+class_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+
192+static PyObject *
193+class_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+
213+static PyObject *
214+class_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+
259+static void
260+set_slot(PyObject **slot, PyObject *v)
261+{
262+ PyObject *temp = *slot;
263+ Py_XINCREF(v);
264+ *slot = v;
265+ Py_XDECREF(temp);
266+}
267+
268+static void
269+set_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+
278+static char *
279+set_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+
288+static char *
289+set_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+
308+static char *
309+set_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+
319+static int
320+class_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+
367+static PyObject *
368+class_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+
384+static PyObject *
385+class_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+
411+static int
412+class_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+
423+PyTypeObject 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+
465+int
466+PyClass_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+
494+PyObject *
495+PyInstance_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+
528+PyObject *
529+PyInstance_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+
581+PyDoc_STRVAR(instance_doc,
582+"instance(class[, dict])\n\
583+\n\
584+Create an instance without calling its __init__() method.\n\
585+The class must be a classic class.\n\
586+If present, dict must be a dictionary or None.");
587+
588+static PyObject *
589+instance_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+
609+static void
610+instance_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+
677+static PyObject *
678+instance_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+
706+static PyObject *
707+instance_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+
732+static PyObject *
733+instance_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+ */
754+PyObject *
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+
772+static int
773+instance_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+
788+static int
789+instance_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+
852+static PyObject *
853+instance_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+
891+static PyObject *
892+instance_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+
915+static long
916+instance_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+
980+static int
981+instance_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+
988+static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr;
989+static PyObject *iterstr, *nextstr;
990+
991+static Py_ssize_t
992+instance_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+
1040+static PyObject *
1041+instance_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+
1066+static int
1067+instance_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+
1108+static 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+
1114+static PyObject *
1115+instance_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+
1132+static PyObject *
1133+instance_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+
1172+static int
1173+instance_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+
1212+static int
1213+instance_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+
1285+static int
1286+instance_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+ Py_ssize_t rc;
1322+ /* Assume the failure was simply due to that there is no
1323+ * __contains__ attribute, and try iterating instead.
1324+ */
1325+ PyErr_Clear();
1326+ rc = _PySequence_IterSearch((PyObject *)inst, member,
1327+ PY_ITERSEARCH_CONTAINS);
1328+ if (rc >= 0)
1329+ return rc > 0;
1330+ }
1331+ return -1;
1332+}
1333+
1334+static PySequenceMethods
1335+instance_as_sequence = {
1336+ (lenfunc)instance_length, /* sq_length */
1337+ 0, /* sq_concat */
1338+ 0, /* sq_repeat */
1339+ (ssizeargfunc)instance_item, /* sq_item */
1340+ (ssizessizeargfunc)instance_slice, /* sq_slice */
1341+ (ssizeobjargproc)instance_ass_item, /* sq_ass_item */
1342+ (ssizessizeobjargproc)instance_ass_slice,/* sq_ass_slice */
1343+ (objobjproc)instance_contains, /* sq_contains */
1344+};
1345+
1346+static PyObject *
1347+generic_unary_op(PyInstanceObject *self, PyObject *methodname)
1348+{
1349+ PyObject *func, *res;
1350+
1351+ if ((func = instance_getattr(self, methodname)) == NULL)
1352+ return NULL;
1353+ res = PyEval_CallObject(func, (PyObject *)NULL);
1354+ Py_DECREF(func);
1355+ return res;
1356+}
1357+
1358+static PyObject *
1359+generic_binary_op(PyObject *v, PyObject *w, char *opname)
1360+{
1361+ PyObject *result;
1362+ PyObject *args;
1363+ PyObject *func = PyObject_GetAttrString(v, opname);
1364+ if (func == NULL) {
1365+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1366+ return NULL;
1367+ PyErr_Clear();
1368+ Py_INCREF(Py_NotImplemented);
1369+ return Py_NotImplemented;
1370+ }
1371+ args = PyTuple_Pack(1, w);
1372+ if (args == NULL) {
1373+ Py_DECREF(func);
1374+ return NULL;
1375+ }
1376+ result = PyEval_CallObject(func, args);
1377+ Py_DECREF(args);
1378+ Py_DECREF(func);
1379+ return result;
1380+}
1381+
1382+
1383+static PyObject *coerce_obj;
1384+
1385+/* Try one half of a binary operator involving a class instance. */
1386+static PyObject *
1387+half_binop(PyObject *v, PyObject *w, char *opname, binaryfunc thisfunc,
1388+ int swapped)
1389+{
1390+ PyObject *args;
1391+ PyObject *coercefunc;
1392+ PyObject *coerced = NULL;
1393+ PyObject *v1;
1394+ PyObject *result;
1395+
1396+ if (!PyInstance_Check(v)) {
1397+ Py_INCREF(Py_NotImplemented);
1398+ return Py_NotImplemented;
1399+ }
1400+
1401+ if (coerce_obj == NULL) {
1402+ coerce_obj = PyString_InternFromString("__coerce__");
1403+ if (coerce_obj == NULL)
1404+ return NULL;
1405+ }
1406+ coercefunc = PyObject_GetAttr(v, coerce_obj);
1407+ if (coercefunc == NULL) {
1408+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1409+ return NULL;
1410+ PyErr_Clear();
1411+ return generic_binary_op(v, w, opname);
1412+ }
1413+
1414+ args = PyTuple_Pack(1, w);
1415+ if (args == NULL) {
1416+ Py_DECREF(coercefunc);
1417+ return NULL;
1418+ }
1419+ coerced = PyEval_CallObject(coercefunc, args);
1420+ Py_DECREF(args);
1421+ Py_DECREF(coercefunc);
1422+ if (coerced == NULL) {
1423+ return NULL;
1424+ }
1425+ if (coerced == Py_None || coerced == Py_NotImplemented) {
1426+ Py_DECREF(coerced);
1427+ return generic_binary_op(v, w, opname);
1428+ }
1429+ if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1430+ Py_DECREF(coerced);
1431+ PyErr_SetString(PyExc_TypeError,
1432+ "coercion should return None or 2-tuple");
1433+ return NULL;
1434+ }
1435+ v1 = PyTuple_GetItem(coerced, 0);
1436+ w = PyTuple_GetItem(coerced, 1);
1437+ if (v1->ob_type == v->ob_type && PyInstance_Check(v)) {
1438+ /* prevent recursion if __coerce__ returns self as the first
1439+ * argument */
1440+ result = generic_binary_op(v1, w, opname);
1441+ } else {
1442+ if (Py_EnterRecursiveCall(" after coercion"))
1443+ return NULL;
1444+ if (swapped)
1445+ result = (thisfunc)(w, v1);
1446+ else
1447+ result = (thisfunc)(v1, w);
1448+ Py_LeaveRecursiveCall();
1449+ }
1450+ Py_DECREF(coerced);
1451+ return result;
1452+}
1453+
1454+/* Implement a binary operator involving at least one class instance. */
1455+static PyObject *
1456+do_binop(PyObject *v, PyObject *w, char *opname, char *ropname,
1457+ binaryfunc thisfunc)
1458+{
1459+ PyObject *result = half_binop(v, w, opname, thisfunc, 0);
1460+ if (result == Py_NotImplemented) {
1461+ Py_DECREF(result);
1462+ result = half_binop(w, v, ropname, thisfunc, 1);
1463+ }
1464+ return result;
1465+}
1466+
1467+static PyObject *
1468+do_binop_inplace(PyObject *v, PyObject *w, char *iopname, char *opname,
1469+ char *ropname, binaryfunc thisfunc)
1470+{
1471+ PyObject *result = half_binop(v, w, iopname, thisfunc, 0);
1472+ if (result == Py_NotImplemented) {
1473+ Py_DECREF(result);
1474+ result = do_binop(v, w, opname, ropname, thisfunc);
1475+ }
1476+ return result;
1477+}
1478+
1479+static int
1480+instance_coerce(PyObject **pv, PyObject **pw)
1481+{
1482+ PyObject *v = *pv;
1483+ PyObject *w = *pw;
1484+ PyObject *coercefunc;
1485+ PyObject *args;
1486+ PyObject *coerced;
1487+
1488+ if (coerce_obj == NULL) {
1489+ coerce_obj = PyString_InternFromString("__coerce__");
1490+ if (coerce_obj == NULL)
1491+ return -1;
1492+ }
1493+ coercefunc = PyObject_GetAttr(v, coerce_obj);
1494+ if (coercefunc == NULL) {
1495+ /* No __coerce__ method */
1496+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1497+ return -1;
1498+ PyErr_Clear();
1499+ return 1;
1500+ }
1501+ /* Has __coerce__ method: call it */
1502+ args = PyTuple_Pack(1, w);
1503+ if (args == NULL) {
1504+ return -1;
1505+ }
1506+ coerced = PyEval_CallObject(coercefunc, args);
1507+ Py_DECREF(args);
1508+ Py_DECREF(coercefunc);
1509+ if (coerced == NULL) {
1510+ /* __coerce__ call raised an exception */
1511+ return -1;
1512+ }
1513+ if (coerced == Py_None || coerced == Py_NotImplemented) {
1514+ /* __coerce__ says "I can't do it" */
1515+ Py_DECREF(coerced);
1516+ return 1;
1517+ }
1518+ if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1519+ /* __coerce__ return value is malformed */
1520+ Py_DECREF(coerced);
1521+ PyErr_SetString(PyExc_TypeError,
1522+ "coercion should return None or 2-tuple");
1523+ return -1;
1524+ }
1525+ /* __coerce__ returned two new values */
1526+ *pv = PyTuple_GetItem(coerced, 0);
1527+ *pw = PyTuple_GetItem(coerced, 1);
1528+ Py_INCREF(*pv);
1529+ Py_INCREF(*pw);
1530+ Py_DECREF(coerced);
1531+ return 0;
1532+}
1533+
1534+#define UNARY(funcname, methodname) \
1535+static PyObject *funcname(PyInstanceObject *self) { \
1536+ static PyObject *o; \
1537+ if (o == NULL) { o = PyString_InternFromString(methodname); \
1538+ if (o == NULL) return NULL; } \
1539+ return generic_unary_op(self, o); \
1540+}
1541+
1542+#define BINARY(f, m, n) \
1543+static PyObject *f(PyObject *v, PyObject *w) { \
1544+ return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1545+}
1546+
1547+#define BINARY_INPLACE(f, m, n) \
1548+static PyObject *f(PyObject *v, PyObject *w) { \
1549+ return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1550+ "__r" m "__", n); \
1551+}
1552+
1553+UNARY(instance_neg, "__neg__")
1554+UNARY(instance_pos, "__pos__")
1555+UNARY(instance_abs, "__abs__")
1556+
1557+BINARY(instance_or, "or", PyNumber_Or)
1558+BINARY(instance_and, "and", PyNumber_And)
1559+BINARY(instance_xor, "xor", PyNumber_Xor)
1560+BINARY(instance_lshift, "lshift", PyNumber_Lshift)
1561+BINARY(instance_rshift, "rshift", PyNumber_Rshift)
1562+BINARY(instance_add, "add", PyNumber_Add)
1563+BINARY(instance_sub, "sub", PyNumber_Subtract)
1564+BINARY(instance_mul, "mul", PyNumber_Multiply)
1565+BINARY(instance_div, "div", PyNumber_Divide)
1566+BINARY(instance_mod, "mod", PyNumber_Remainder)
1567+BINARY(instance_divmod, "divmod", PyNumber_Divmod)
1568+BINARY(instance_floordiv, "floordiv", PyNumber_FloorDivide)
1569+BINARY(instance_truediv, "truediv", PyNumber_TrueDivide)
1570+
1571+BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr)
1572+BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor)
1573+BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd)
1574+BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift)
1575+BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift)
1576+BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd)
1577+BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract)
1578+BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply)
1579+BINARY_INPLACE(instance_idiv, "div", PyNumber_InPlaceDivide)
1580+BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder)
1581+BINARY_INPLACE(instance_ifloordiv, "floordiv", PyNumber_InPlaceFloorDivide)
1582+BINARY_INPLACE(instance_itruediv, "truediv", PyNumber_InPlaceTrueDivide)
1583+
1584+/* Try a 3-way comparison, returning an int; v is an instance. Return:
1585+ -2 for an exception;
1586+ -1 if v < w;
1587+ 0 if v == w;
1588+ 1 if v > w;
1589+ 2 if this particular 3-way comparison is not implemented or undefined.
1590+*/
1591+static int
1592+half_cmp(PyObject *v, PyObject *w)
1593+{
1594+ static PyObject *cmp_obj;
1595+ PyObject *args;
1596+ PyObject *cmp_func;
1597+ PyObject *result;
1598+ long l;
1599+
1600+ assert(PyInstance_Check(v));
1601+
1602+ if (cmp_obj == NULL) {
1603+ cmp_obj = PyString_InternFromString("__cmp__");
1604+ if (cmp_obj == NULL)
1605+ return -2;
1606+ }
1607+
1608+ cmp_func = PyObject_GetAttr(v, cmp_obj);
1609+ if (cmp_func == NULL) {
1610+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1611+ return -2;
1612+ PyErr_Clear();
1613+ return 2;
1614+ }
1615+
1616+ args = PyTuple_Pack(1, w);
1617+ if (args == NULL) {
1618+ Py_DECREF(cmp_func);
1619+ return -2;
1620+ }
1621+
1622+ result = PyEval_CallObject(cmp_func, args);
1623+ Py_DECREF(args);
1624+ Py_DECREF(cmp_func);
1625+
1626+ if (result == NULL)
1627+ return -2;
1628+
1629+ if (result == Py_NotImplemented) {
1630+ Py_DECREF(result);
1631+ return 2;
1632+ }
1633+
1634+ l = PyInt_AsLong(result);
1635+ Py_DECREF(result);
1636+ if (l == -1 && PyErr_Occurred()) {
1637+ PyErr_SetString(PyExc_TypeError,
1638+ "comparison did not return an int");
1639+ return -2;
1640+ }
1641+
1642+ return l < 0 ? -1 : l > 0 ? 1 : 0;
1643+}
1644+
1645+/* Try a 3-way comparison, returning an int; either v or w is an instance.
1646+ We first try a coercion. Return:
1647+ -2 for an exception;
1648+ -1 if v < w;
1649+ 0 if v == w;
1650+ 1 if v > w;
1651+ 2 if this particular 3-way comparison is not implemented or undefined.
1652+ THIS IS ONLY CALLED FROM object.c!
1653+*/
1654+static int
1655+instance_compare(PyObject *v, PyObject *w)
1656+{
1657+ int c;
1658+
1659+ c = PyNumber_CoerceEx(&v, &w);
1660+ if (c < 0)
1661+ return -2;
1662+ if (c == 0) {
1663+ /* If neither is now an instance, use regular comparison */
1664+ if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
1665+ c = PyObject_Compare(v, w);
1666+ Py_DECREF(v);
1667+ Py_DECREF(w);
1668+ if (PyErr_Occurred())
1669+ return -2;
1670+ return c < 0 ? -1 : c > 0 ? 1 : 0;
1671+ }
1672+ }
1673+ else {
1674+ /* The coercion didn't do anything.
1675+ Treat this the same as returning v and w unchanged. */
1676+ Py_INCREF(v);
1677+ Py_INCREF(w);
1678+ }
1679+
1680+ if (PyInstance_Check(v)) {
1681+ c = half_cmp(v, w);
1682+ if (c <= 1) {
1683+ Py_DECREF(v);
1684+ Py_DECREF(w);
1685+ return c;
1686+ }
1687+ }
1688+ if (PyInstance_Check(w)) {
1689+ c = half_cmp(w, v);
1690+ if (c <= 1) {
1691+ Py_DECREF(v);
1692+ Py_DECREF(w);
1693+ if (c >= -1)
1694+ c = -c;
1695+ return c;
1696+ }
1697+ }
1698+ Py_DECREF(v);
1699+ Py_DECREF(w);
1700+ return 2;
1701+}
1702+
1703+static int
1704+instance_nonzero(PyInstanceObject *self)
1705+{
1706+ PyObject *func, *res;
1707+ long outcome;
1708+ static PyObject *nonzerostr;
1709+
1710+ if (nonzerostr == NULL) {
1711+ nonzerostr = PyString_InternFromString("__nonzero__");
1712+ if (nonzerostr == NULL)
1713+ return -1;
1714+ }
1715+ if ((func = instance_getattr(self, nonzerostr)) == NULL) {
1716+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1717+ return -1;
1718+ PyErr_Clear();
1719+ if (lenstr == NULL) {
1720+ lenstr = PyString_InternFromString("__len__");
1721+ if (lenstr == NULL)
1722+ return -1;
1723+ }
1724+ if ((func = instance_getattr(self, lenstr)) == NULL) {
1725+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1726+ return -1;
1727+ PyErr_Clear();
1728+ /* Fall back to the default behavior:
1729+ all instances are nonzero */
1730+ return 1;
1731+ }
1732+ }
1733+ res = PyEval_CallObject(func, (PyObject *)NULL);
1734+ Py_DECREF(func);
1735+ if (res == NULL)
1736+ return -1;
1737+ if (!PyInt_Check(res)) {
1738+ Py_DECREF(res);
1739+ PyErr_SetString(PyExc_TypeError,
1740+ "__nonzero__ should return an int");
1741+ return -1;
1742+ }
1743+ outcome = PyInt_AsLong(res);
1744+ Py_DECREF(res);
1745+ if (outcome < 0) {
1746+ PyErr_SetString(PyExc_ValueError,
1747+ "__nonzero__ should return >= 0");
1748+ return -1;
1749+ }
1750+ return outcome > 0;
1751+}
1752+
1753+static PyObject *
1754+instance_index(PyInstanceObject *self)
1755+{
1756+ PyObject *func, *res;
1757+ static PyObject *indexstr = NULL;
1758+
1759+ if (indexstr == NULL) {
1760+ indexstr = PyString_InternFromString("__index__");
1761+ if (indexstr == NULL)
1762+ return NULL;
1763+ }
1764+ if ((func = instance_getattr(self, indexstr)) == NULL) {
1765+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1766+ return NULL;
1767+ PyErr_Clear();
1768+ PyErr_SetString(PyExc_TypeError,
1769+ "object cannot be interpreted as an index");
1770+ return NULL;
1771+ }
1772+ res = PyEval_CallObject(func, (PyObject *)NULL);
1773+ Py_DECREF(func);
1774+ return res;
1775+}
1776+
1777+
1778+UNARY(instance_invert, "__invert__")
1779+UNARY(instance_int, "__int__")
1780+UNARY(instance_long, "__long__")
1781+UNARY(instance_float, "__float__")
1782+UNARY(instance_oct, "__oct__")
1783+UNARY(instance_hex, "__hex__")
1784+
1785+static PyObject *
1786+bin_power(PyObject *v, PyObject *w)
1787+{
1788+ return PyNumber_Power(v, w, Py_None);
1789+}
1790+
1791+/* This version is for ternary calls only (z != None) */
1792+static PyObject *
1793+instance_pow(PyObject *v, PyObject *w, PyObject *z)
1794+{
1795+ if (z == Py_None) {
1796+ return do_binop(v, w, "__pow__", "__rpow__", bin_power);
1797+ }
1798+ else {
1799+ PyObject *func;
1800+ PyObject *args;
1801+ PyObject *result;
1802+
1803+ /* XXX Doesn't do coercions... */
1804+ func = PyObject_GetAttrString(v, "__pow__");
1805+ if (func == NULL)
1806+ return NULL;
1807+ args = PyTuple_Pack(2, w, z);
1808+ if (args == NULL) {
1809+ Py_DECREF(func);
1810+ return NULL;
1811+ }
1812+ result = PyEval_CallObject(func, args);
1813+ Py_DECREF(func);
1814+ Py_DECREF(args);
1815+ return result;
1816+ }
1817+}
1818+
1819+static PyObject *
1820+bin_inplace_power(PyObject *v, PyObject *w)
1821+{
1822+ return PyNumber_InPlacePower(v, w, Py_None);
1823+}
1824+
1825+
1826+static PyObject *
1827+instance_ipow(PyObject *v, PyObject *w, PyObject *z)
1828+{
1829+ if (z == Py_None) {
1830+ return do_binop_inplace(v, w, "__ipow__", "__pow__",
1831+ "__rpow__", bin_inplace_power);
1832+ }
1833+ else {
1834+ /* XXX Doesn't do coercions... */
1835+ PyObject *func;
1836+ PyObject *args;
1837+ PyObject *result;
1838+
1839+ func = PyObject_GetAttrString(v, "__ipow__");
1840+ if (func == NULL) {
1841+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1842+ return NULL;
1843+ PyErr_Clear();
1844+ return instance_pow(v, w, z);
1845+ }
1846+ args = PyTuple_Pack(2, w, z);
1847+ if (args == NULL) {
1848+ Py_DECREF(func);
1849+ return NULL;
1850+ }
1851+ result = PyEval_CallObject(func, args);
1852+ Py_DECREF(func);
1853+ Py_DECREF(args);
1854+ return result;
1855+ }
1856+}
1857+
1858+
1859+/* Map rich comparison operators to their __xx__ namesakes */
1860+#define NAME_OPS 6
1861+static PyObject **name_op = NULL;
1862+
1863+static int
1864+init_name_op(void)
1865+{
1866+ int i;
1867+ char *_name_op[] = {
1868+ "__lt__",
1869+ "__le__",
1870+ "__eq__",
1871+ "__ne__",
1872+ "__gt__",
1873+ "__ge__",
1874+ };
1875+
1876+ name_op = (PyObject **)malloc(sizeof(PyObject *) * NAME_OPS);
1877+ if (name_op == NULL)
1878+ return -1;
1879+ for (i = 0; i < NAME_OPS; ++i) {
1880+ name_op[i] = PyString_InternFromString(_name_op[i]);
1881+ if (name_op[i] == NULL)
1882+ return -1;
1883+ }
1884+ return 0;
1885+}
1886+
1887+static PyObject *
1888+half_richcompare(PyObject *v, PyObject *w, int op)
1889+{
1890+ PyObject *method;
1891+ PyObject *args;
1892+ PyObject *res;
1893+
1894+ assert(PyInstance_Check(v));
1895+
1896+ if (name_op == NULL) {
1897+ if (init_name_op() < 0)
1898+ return NULL;
1899+ }
1900+ /* If the instance doesn't define an __getattr__ method, use
1901+ instance_getattr2 directly because it will not set an
1902+ exception on failure. */
1903+ if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL)
1904+ method = instance_getattr2((PyInstanceObject *)v,
1905+ name_op[op]);
1906+ else
1907+ method = PyObject_GetAttr(v, name_op[op]);
1908+ if (method == NULL) {
1909+ if (PyErr_Occurred()) {
1910+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1911+ return NULL;
1912+ PyErr_Clear();
1913+ }
1914+ res = Py_NotImplemented;
1915+ Py_INCREF(res);
1916+ return res;
1917+ }
1918+
1919+ args = PyTuple_Pack(1, w);
1920+ if (args == NULL) {
1921+ Py_DECREF(method);
1922+ return NULL;
1923+ }
1924+
1925+ res = PyEval_CallObject(method, args);
1926+ Py_DECREF(args);
1927+ Py_DECREF(method);
1928+
1929+ return res;
1930+}
1931+
1932+static PyObject *
1933+instance_richcompare(PyObject *v, PyObject *w, int op)
1934+{
1935+ PyObject *res;
1936+
1937+ if (PyInstance_Check(v)) {
1938+ res = half_richcompare(v, w, op);
1939+ if (res != Py_NotImplemented)
1940+ return res;
1941+ Py_DECREF(res);
1942+ }
1943+
1944+ if (PyInstance_Check(w)) {
1945+ res = half_richcompare(w, v, _Py_SwappedOp[op]);
1946+ if (res != Py_NotImplemented)
1947+ return res;
1948+ Py_DECREF(res);
1949+ }
1950+
1951+ Py_INCREF(Py_NotImplemented);
1952+ return Py_NotImplemented;
1953+}
1954+
1955+
1956+/* Get the iterator */
1957+static PyObject *
1958+instance_getiter(PyInstanceObject *self)
1959+{
1960+ PyObject *func;
1961+
1962+ if (iterstr == NULL) {
1963+ iterstr = PyString_InternFromString("__iter__");
1964+ if (iterstr == NULL)
1965+ return NULL;
1966+ }
1967+ if (getitemstr == NULL) {
1968+ getitemstr = PyString_InternFromString("__getitem__");
1969+ if (getitemstr == NULL)
1970+ return NULL;
1971+ }
1972+
1973+ if ((func = instance_getattr(self, iterstr)) != NULL) {
1974+ PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
1975+ Py_DECREF(func);
1976+ if (res != NULL && !PyIter_Check(res)) {
1977+ PyErr_Format(PyExc_TypeError,
1978+ "__iter__ returned non-iterator "
1979+ "of type '%.100s'",
1980+ res->ob_type->tp_name);
1981+ Py_DECREF(res);
1982+ res = NULL;
1983+ }
1984+ return res;
1985+ }
1986+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1987+ return NULL;
1988+ PyErr_Clear();
1989+ if ((func = instance_getattr(self, getitemstr)) == NULL) {
1990+ PyErr_SetString(PyExc_TypeError,
1991+ "iteration over non-sequence");
1992+ return NULL;
1993+ }
1994+ Py_DECREF(func);
1995+ return PySeqIter_New((PyObject *)self);
1996+}
1997+
1998+
1999+/* Call the iterator's next */
2000+static PyObject *
2001+instance_iternext(PyInstanceObject *self)
2002+{
2003+ PyObject *func;
2004+
2005+ if (nextstr == NULL) {
2006+ nextstr = PyString_InternFromString("next");
2007+ if (nextstr == NULL)
2008+ return NULL;
2009+ }
2010+
2011+ if ((func = instance_getattr(self, nextstr)) != NULL) {
2012+ PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
2013+ Py_DECREF(func);
2014+ if (res != NULL) {
2015+ return res;
2016+ }
2017+ if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
2018+ PyErr_Clear();
2019+ return NULL;
2020+ }
2021+ return NULL;
2022+ }
2023+ PyErr_SetString(PyExc_TypeError, "instance has no next() method");
2024+ return NULL;
2025+}
2026+
2027+static PyObject *
2028+instance_call(PyObject *func, PyObject *arg, PyObject *kw)
2029+{
2030+ PyObject *res, *call = PyObject_GetAttrString(func, "__call__");
2031+ if (call == NULL) {
2032+ PyInstanceObject *inst = (PyInstanceObject*) func;
2033+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2034+ return NULL;
2035+ PyErr_Clear();
2036+ PyErr_Format(PyExc_AttributeError,
2037+ "%.200s instance has no __call__ method",
2038+ PyString_AsString(inst->in_class->cl_name));
2039+ return NULL;
2040+ }
2041+ /* We must check and increment the recursion depth here. Scenario:
2042+ class A:
2043+ pass
2044+ A.__call__ = A() # that's right
2045+ a = A() # ok
2046+ a() # infinite recursion
2047+ This bounces between instance_call() and PyObject_Call() without
2048+ ever hitting eval_frame() (which has the main recursion check). */
2049+ if (Py_EnterRecursiveCall(" in __call__")) {
2050+ res = NULL;
2051+ }
2052+ else {
2053+ res = PyObject_Call(call, arg, kw);
2054+ Py_LeaveRecursiveCall();
2055+ }
2056+ Py_DECREF(call);
2057+ return res;
2058+}
2059+
2060+
2061+static PyNumberMethods instance_as_number = {
2062+ instance_add, /* nb_add */
2063+ instance_sub, /* nb_subtract */
2064+ instance_mul, /* nb_multiply */
2065+ instance_div, /* nb_divide */
2066+ instance_mod, /* nb_remainder */
2067+ instance_divmod, /* nb_divmod */
2068+ instance_pow, /* nb_power */
2069+ (unaryfunc)instance_neg, /* nb_negative */
2070+ (unaryfunc)instance_pos, /* nb_positive */
2071+ (unaryfunc)instance_abs, /* nb_absolute */
2072+ (inquiry)instance_nonzero, /* nb_nonzero */
2073+ (unaryfunc)instance_invert, /* nb_invert */
2074+ instance_lshift, /* nb_lshift */
2075+ instance_rshift, /* nb_rshift */
2076+ instance_and, /* nb_and */
2077+ instance_xor, /* nb_xor */
2078+ instance_or, /* nb_or */
2079+ instance_coerce, /* nb_coerce */
2080+ (unaryfunc)instance_int, /* nb_int */
2081+ (unaryfunc)instance_long, /* nb_long */
2082+ (unaryfunc)instance_float, /* nb_float */
2083+ (unaryfunc)instance_oct, /* nb_oct */
2084+ (unaryfunc)instance_hex, /* nb_hex */
2085+ instance_iadd, /* nb_inplace_add */
2086+ instance_isub, /* nb_inplace_subtract */
2087+ instance_imul, /* nb_inplace_multiply */
2088+ instance_idiv, /* nb_inplace_divide */
2089+ instance_imod, /* nb_inplace_remainder */
2090+ instance_ipow, /* nb_inplace_power */
2091+ instance_ilshift, /* nb_inplace_lshift */
2092+ instance_irshift, /* nb_inplace_rshift */
2093+ instance_iand, /* nb_inplace_and */
2094+ instance_ixor, /* nb_inplace_xor */
2095+ instance_ior, /* nb_inplace_or */
2096+ instance_floordiv, /* nb_floor_divide */
2097+ instance_truediv, /* nb_true_divide */
2098+ instance_ifloordiv, /* nb_inplace_floor_divide */
2099+ instance_itruediv, /* nb_inplace_true_divide */
2100+ (unaryfunc)instance_index, /* nb_index */
2101+};
2102+
2103+PyTypeObject PyInstance_Type = {
2104+ PyObject_HEAD_INIT(&PyType_Type)
2105+ 0,
2106+ "instance",
2107+ sizeof(PyInstanceObject),
2108+ 0,
2109+ (destructor)instance_dealloc, /* tp_dealloc */
2110+ 0, /* tp_print */
2111+ 0, /* tp_getattr */
2112+ 0, /* tp_setattr */
2113+ instance_compare, /* tp_compare */
2114+ (reprfunc)instance_repr, /* tp_repr */
2115+ &instance_as_number, /* tp_as_number */
2116+ &instance_as_sequence, /* tp_as_sequence */
2117+ &instance_as_mapping, /* tp_as_mapping */
2118+ (hashfunc)instance_hash, /* tp_hash */
2119+ instance_call, /* tp_call */
2120+ (reprfunc)instance_str, /* tp_str */
2121+ (getattrofunc)instance_getattr, /* tp_getattro */
2122+ (setattrofunc)instance_setattr, /* tp_setattro */
2123+ 0, /* tp_as_buffer */
2124+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES,/*tp_flags*/
2125+ instance_doc, /* tp_doc */
2126+ (traverseproc)instance_traverse, /* tp_traverse */
2127+ 0, /* tp_clear */
2128+ instance_richcompare, /* tp_richcompare */
2129+ offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
2130+ (getiterfunc)instance_getiter, /* tp_iter */
2131+ (iternextfunc)instance_iternext, /* tp_iternext */
2132+ 0, /* tp_methods */
2133+ 0, /* tp_members */
2134+ 0, /* tp_getset */
2135+ 0, /* tp_base */
2136+ 0, /* tp_dict */
2137+ 0, /* tp_descr_get */
2138+ 0, /* tp_descr_set */
2139+ 0, /* tp_dictoffset */
2140+ 0, /* tp_init */
2141+ 0, /* tp_alloc */
2142+ instance_new, /* tp_new */
2143+};
2144+
2145+
2146+/* Instance method objects are used for two purposes:
2147+ (a) as bound instance methods (returned by instancename.methodname)
2148+ (b) as unbound methods (returned by ClassName.methodname)
2149+ In case (b), im_self is NULL
2150+*/
2151+
2152+static PyMethodObject *free_list;
2153+
2154+PyObject *
2155+PyMethod_New(PyObject *func, PyObject *self, PyObject *klass)
2156+{
2157+ register PyMethodObject *im;
2158+ if (!PyCallable_Check(func)) {
2159+ PyErr_BadInternalCall();
2160+ return NULL;
2161+ }
2162+ im = free_list;
2163+ if (im != NULL) {
2164+ free_list = (PyMethodObject *)(im->im_self);
2165+ PyObject_INIT(im, &PyMethod_Type);
2166+ }
2167+ else {
2168+ im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
2169+ if (im == NULL)
2170+ return NULL;
2171+ }
2172+ im->im_weakreflist = NULL;
2173+ Py_INCREF(func);
2174+ im->im_func = func;
2175+ Py_XINCREF(self);
2176+ im->im_self = self;
2177+ Py_XINCREF(klass);
2178+ im->im_class = klass;
2179+ _PyObject_GC_TRACK(im);
2180+ return (PyObject *)im;
2181+}
2182+
2183+/* Descriptors for PyMethod attributes */
2184+
2185+/* im_class, im_func and im_self are stored in the PyMethod object */
2186+
2187+#define OFF(x) offsetof(PyMethodObject, x)
2188+
2189+static PyMemberDef instancemethod_memberlist[] = {
2190+ {"im_class", T_OBJECT, OFF(im_class), READONLY|RESTRICTED,
2191+ "the class associated with a method"},
2192+ {"im_func", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
2193+ "the function (or other callable) implementing a method"},
2194+ {"im_self", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
2195+ "the instance to which a method is bound; None for unbound methods"},
2196+ {NULL} /* Sentinel */
2197+};
2198+
2199+/* Christian Tismer argued convincingly that method attributes should
2200+ (nearly) always override function attributes.
2201+ The one exception is __doc__; there's a default __doc__ which
2202+ should only be used for the class, not for instances */
2203+
2204+static PyObject *
2205+instancemethod_get_doc(PyMethodObject *im, void *context)
2206+{
2207+ static PyObject *docstr;
2208+ if (docstr == NULL) {
2209+ docstr= PyString_InternFromString("__doc__");
2210+ if (docstr == NULL)
2211+ return NULL;
2212+ }
2213+ return PyObject_GetAttr(im->im_func, docstr);
2214+}
2215+
2216+static PyGetSetDef instancemethod_getset[] = {
2217+ {"__doc__", (getter)instancemethod_get_doc, NULL, NULL},
2218+ {0}
2219+};
2220+
2221+static PyObject *
2222+instancemethod_getattro(PyObject *obj, PyObject *name)
2223+{
2224+ PyMethodObject *im = (PyMethodObject *)obj;
2225+ PyTypeObject *tp = obj->ob_type;
2226+ PyObject *descr = NULL;
2227+
2228+ if (PyType_HasFeature(tp, Py_TPFLAGS_HAVE_CLASS)) {
2229+ if (tp->tp_dict == NULL) {
2230+ if (PyType_Ready(tp) < 0)
2231+ return NULL;
2232+ }
2233+ descr = _PyType_Lookup(tp, name);
2234+ }
2235+
2236+ if (descr != NULL) {
2237+ descrgetfunc f = TP_DESCR_GET(descr->ob_type);
2238+ if (f != NULL)
2239+ return f(descr, obj, (PyObject *)obj->ob_type);
2240+ else {
2241+ Py_INCREF(descr);
2242+ return descr;
2243+ }
2244+ }
2245+
2246+ return PyObject_GetAttr(im->im_func, name);
2247+}
2248+
2249+PyDoc_STRVAR(instancemethod_doc,
2250+"instancemethod(function, instance, class)\n\
2251+\n\
2252+Create an instance method object.");
2253+
2254+static PyObject *
2255+instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw)
2256+{
2257+ PyObject *func;
2258+ PyObject *self;
2259+ PyObject *classObj = NULL;
2260+
2261+ if (!_PyArg_NoKeywords("instancemethod", kw))
2262+ return NULL;
2263+ if (!PyArg_UnpackTuple(args, "instancemethod", 2, 3,
2264+ &func, &self, &classObj))
2265+ return NULL;
2266+ if (!PyCallable_Check(func)) {
2267+ PyErr_SetString(PyExc_TypeError,
2268+ "first argument must be callable");
2269+ return NULL;
2270+ }
2271+ if (self == Py_None)
2272+ self = NULL;
2273+ if (self == NULL && classObj == NULL) {
2274+ PyErr_SetString(PyExc_TypeError,
2275+ "unbound methods must have non-NULL im_class");
2276+ return NULL;
2277+ }
2278+
2279+ return PyMethod_New(func, self, classObj);
2280+}
2281+
2282+static void
2283+instancemethod_dealloc(register PyMethodObject *im)
2284+{
2285+ _PyObject_GC_UNTRACK(im);
2286+ if (im->im_weakreflist != NULL)
2287+ PyObject_ClearWeakRefs((PyObject *)im);
2288+ Py_DECREF(im->im_func);
2289+ Py_XDECREF(im->im_self);
2290+ Py_XDECREF(im->im_class);
2291+ im->im_self = (PyObject *)free_list;
2292+ free_list = im;
2293+}
2294+
2295+static int
2296+instancemethod_compare(PyMethodObject *a, PyMethodObject *b)
2297+{
2298+ int cmp;
2299+ cmp = PyObject_Compare(a->im_func, b->im_func);
2300+ if (cmp)
2301+ return cmp;
2302+
2303+ if (a->im_self == b->im_self)
2304+ return 0;
2305+ if (a->im_self == NULL || b->im_self == NULL)
2306+ return (a->im_self < b->im_self) ? -1 : 1;
2307+ else
2308+ return PyObject_Compare(a->im_self, b->im_self);
2309+}
2310+
2311+static PyObject *
2312+instancemethod_repr(PyMethodObject *a)
2313+{
2314+ PyObject *self = a->im_self;
2315+ PyObject *func = a->im_func;
2316+ PyObject *klass = a->im_class;
2317+ PyObject *funcname = NULL, *klassname = NULL, *result = NULL;
2318+ char *sfuncname = "?", *sklassname = "?";
2319+
2320+ funcname = PyObject_GetAttrString(func, "__name__");
2321+ if (funcname == NULL) {
2322+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2323+ return NULL;
2324+ PyErr_Clear();
2325+ }
2326+ else if (!PyString_Check(funcname)) {
2327+ Py_DECREF(funcname);
2328+ funcname = NULL;
2329+ }
2330+ else
2331+ sfuncname = PyString_AS_STRING(funcname);
2332+ if (klass == NULL)
2333+ klassname = NULL;
2334+ else {
2335+ klassname = PyObject_GetAttrString(klass, "__name__");
2336+ if (klassname == NULL) {
2337+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2338+ return NULL;
2339+ PyErr_Clear();
2340+ }
2341+ else if (!PyString_Check(klassname)) {
2342+ Py_DECREF(klassname);
2343+ klassname = NULL;
2344+ }
2345+ else
2346+ sklassname = PyString_AS_STRING(klassname);
2347+ }
2348+ if (self == NULL)
2349+ result = PyString_FromFormat("<unbound method %s.%s>",
2350+ sklassname, sfuncname);
2351+ else {
2352+ /* XXX Shouldn't use repr() here! */
2353+ PyObject *selfrepr = PyObject_Repr(self);
2354+ if (selfrepr == NULL)
2355+ goto fail;
2356+ if (!PyString_Check(selfrepr)) {
2357+ Py_DECREF(selfrepr);
2358+ goto fail;
2359+ }
2360+ result = PyString_FromFormat("<bound method %s.%s of %s>",
2361+ sklassname, sfuncname,
2362+ PyString_AS_STRING(selfrepr));
2363+ Py_DECREF(selfrepr);
2364+ }
2365+ fail:
2366+ Py_XDECREF(funcname);
2367+ Py_XDECREF(klassname);
2368+ return result;
2369+}
2370+
2371+static long
2372+instancemethod_hash(PyMethodObject *a)
2373+{
2374+ long x, y;
2375+ if (a->im_self == NULL)
2376+ x = PyObject_Hash(Py_None);
2377+ else
2378+ x = PyObject_Hash(a->im_self);
2379+ if (x == -1)
2380+ return -1;
2381+ y = PyObject_Hash(a->im_func);
2382+ if (y == -1)
2383+ return -1;
2384+ x = x ^ y;
2385+ if (x == -1)
2386+ x = -2;
2387+ return x;
2388+}
2389+
2390+static int
2391+instancemethod_traverse(PyMethodObject *im, visitproc visit, void *arg)
2392+{
2393+ Py_VISIT(im->im_func);
2394+ Py_VISIT(im->im_self);
2395+ Py_VISIT(im->im_class);
2396+ return 0;
2397+}
2398+
2399+static void
2400+getclassname(PyObject *klass, char *buf, int bufsize)
2401+{
2402+ PyObject *name;
2403+
2404+ assert(bufsize > 1);
2405+ strcpy(buf, "?"); /* Default outcome */
2406+ if (klass == NULL)
2407+ return;
2408+ name = PyObject_GetAttrString(klass, "__name__");
2409+ if (name == NULL) {
2410+ /* This function cannot return an exception */
2411+ PyErr_Clear();
2412+ return;
2413+ }
2414+ if (PyString_Check(name)) {
2415+ strncpy(buf, PyString_AS_STRING(name), bufsize);
2416+ buf[bufsize-1] = '\0';
2417+ }
2418+ Py_DECREF(name);
2419+}
2420+
2421+static void
2422+getinstclassname(PyObject *inst, char *buf, int bufsize)
2423+{
2424+ PyObject *klass;
2425+
2426+ if (inst == NULL) {
2427+ assert(bufsize > 0 && (size_t)bufsize > strlen("nothing"));
2428+ strcpy(buf, "nothing");
2429+ return;
2430+ }
2431+
2432+ klass = PyObject_GetAttrString(inst, "__class__");
2433+ if (klass == NULL) {
2434+ /* This function cannot return an exception */
2435+ PyErr_Clear();
2436+ klass = (PyObject *)(inst->ob_type);
2437+ Py_INCREF(klass);
2438+ }
2439+ getclassname(klass, buf, bufsize);
2440+ Py_XDECREF(klass);
2441+}
2442+
2443+static PyObject *
2444+instancemethod_call(PyObject *func, PyObject *arg, PyObject *kw)
2445+{
2446+ PyObject *self = PyMethod_GET_SELF(func);
2447+ PyObject *klass = PyMethod_GET_CLASS(func);
2448+ PyObject *result;
2449+
2450+ func = PyMethod_GET_FUNCTION(func);
2451+ if (self == NULL) {
2452+ /* Unbound methods must be called with an instance of
2453+ the class (or a derived class) as first argument */
2454+ int ok;
2455+ if (PyTuple_Size(arg) >= 1)
2456+ self = PyTuple_GET_ITEM(arg, 0);
2457+ if (self == NULL)
2458+ ok = 0;
2459+ else {
2460+ ok = PyObject_IsInstance(self, klass);
2461+ if (ok < 0)
2462+ return NULL;
2463+ }
2464+ if (!ok) {
2465+ char clsbuf[256];
2466+ char instbuf[256];
2467+ getclassname(klass, clsbuf, sizeof(clsbuf));
2468+ getinstclassname(self, instbuf, sizeof(instbuf));
2469+ PyErr_Format(PyExc_TypeError,
2470+ "unbound method %s%s must be called with "
2471+ "%s instance as first argument "
2472+ "(got %s%s instead)",
2473+ PyEval_GetFuncName(func),
2474+ PyEval_GetFuncDesc(func),
2475+ clsbuf,
2476+ instbuf,
2477+ self == NULL ? "" : " instance");
2478+ return NULL;
2479+ }
2480+ Py_INCREF(arg);
2481+ }
2482+ else {
2483+ Py_ssize_t argcount = PyTuple_Size(arg);
2484+ PyObject *newarg = PyTuple_New(argcount + 1);
2485+ int i;
2486+ if (newarg == NULL)
2487+ return NULL;
2488+ Py_INCREF(self);
2489+ PyTuple_SET_ITEM(newarg, 0, self);
2490+ for (i = 0; i < argcount; i++) {
2491+ PyObject *v = PyTuple_GET_ITEM(arg, i);
2492+ Py_XINCREF(v);
2493+ PyTuple_SET_ITEM(newarg, i+1, v);
2494+ }
2495+ arg = newarg;
2496+ }
2497+ result = PyObject_Call((PyObject *)func, arg, kw);
2498+ Py_DECREF(arg);
2499+ return result;
2500+}
2501+
2502+static PyObject *
2503+instancemethod_descr_get(PyObject *meth, PyObject *obj, PyObject *cls)
2504+{
2505+ /* Don't rebind an already bound method, or an unbound method
2506+ of a class that's not a base class of cls. */
2507+
2508+ if (PyMethod_GET_SELF(meth) != NULL) {
2509+ /* Already bound */
2510+ Py_INCREF(meth);
2511+ return meth;
2512+ }
2513+ /* No, it is an unbound method */
2514+ if (PyMethod_GET_CLASS(meth) != NULL && cls != NULL) {
2515+ /* Do subclass test. If it fails, return meth unchanged. */
2516+ int ok = PyObject_IsSubclass(cls, PyMethod_GET_CLASS(meth));
2517+ if (ok < 0)
2518+ return NULL;
2519+ if (!ok) {
2520+ Py_INCREF(meth);
2521+ return meth;
2522+ }
2523+ }
2524+ /* Bind it to obj */
2525+ return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj, cls);
2526+}
2527+
2528+PyTypeObject PyMethod_Type = {
2529+ PyObject_HEAD_INIT(&PyType_Type)
2530+ 0,
2531+ "instancemethod",
2532+ sizeof(PyMethodObject),
2533+ 0,
2534+ (destructor)instancemethod_dealloc, /* tp_dealloc */
2535+ 0, /* tp_print */
2536+ 0, /* tp_getattr */
2537+ 0, /* tp_setattr */
2538+ (cmpfunc)instancemethod_compare, /* tp_compare */
2539+ (reprfunc)instancemethod_repr, /* tp_repr */
2540+ 0, /* tp_as_number */
2541+ 0, /* tp_as_sequence */
2542+ 0, /* tp_as_mapping */
2543+ (hashfunc)instancemethod_hash, /* tp_hash */
2544+ instancemethod_call, /* tp_call */
2545+ 0, /* tp_str */
2546+ instancemethod_getattro, /* tp_getattro */
2547+ PyObject_GenericSetAttr, /* tp_setattro */
2548+ 0, /* tp_as_buffer */
2549+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
2550+ instancemethod_doc, /* tp_doc */
2551+ (traverseproc)instancemethod_traverse, /* tp_traverse */
2552+ 0, /* tp_clear */
2553+ 0, /* tp_richcompare */
2554+ offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */
2555+ 0, /* tp_iter */
2556+ 0, /* tp_iternext */
2557+ 0, /* tp_methods */
2558+ instancemethod_memberlist, /* tp_members */
2559+ instancemethod_getset, /* tp_getset */
2560+ 0, /* tp_base */
2561+ 0, /* tp_dict */
2562+ instancemethod_descr_get, /* tp_descr_get */
2563+ 0, /* tp_descr_set */
2564+ 0, /* tp_dictoffset */
2565+ 0, /* tp_init */
2566+ 0, /* tp_alloc */
2567+ instancemethod_new, /* tp_new */
2568+};
2569+
2570+/* Clear out the free list */
2571+
2572+void
2573+PyMethod_Fini(void)
2574+{
2575+ while (free_list) {
2576+ PyMethodObject *im = free_list;
2577+ free_list = (PyMethodObject *)(im->im_self);
2578+ PyObject_GC_Del(im);
2579+ }
2580+}

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t