blob: 5b645787cbf6f64333f6c6a9deb2d19d774e663e [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Class object implementation */
3
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005#include "structmember.h"
Guido van Rossum04691fc1992-08-12 15:35:34 +00006
Raymond Hettinger9376c8b2014-08-01 23:51:51 -07007/* Free list for method objects to save malloc/free overhead
Christian Heimes6075a822008-02-06 12:44:34 +00008 * The im_self element is used to chain the elements.
9 */
10static PyMethodObject *free_list;
11static int numfree = 0;
Christian Heimes5b970ad2008-02-06 13:33:44 +000012#ifndef PyMethod_MAXFREELIST
13#define PyMethod_MAXFREELIST 256
14#endif
Christian Heimes6075a822008-02-06 12:44:34 +000015
Guido van Rossum915f0eb2001-10-17 20:26:38 +000016#define TP_DESCR_GET(t) \
17 (PyType_HasFeature(t, Py_TPFLAGS_HAVE_CLASS) ? (t)->tp_descr_get : NULL)
18
Guido van Rossum52ca98a1994-09-05 07:32:29 +000019/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000020static PyObject *class_lookup(PyClassObject *, PyObject *,
Antoine Pitrouc83ea132010-05-09 14:46:46 +000021 PyClassObject **);
Tim Petersdbd9ba62000-07-09 03:09:57 +000022static PyObject *instance_getattr1(PyInstanceObject *, PyObject *);
23static PyObject *instance_getattr2(PyInstanceObject *, PyObject *);
Guido van Rossum52ca98a1994-09-05 07:32:29 +000024
Guido van Rossuma63eff61998-05-29 21:37:21 +000025static PyObject *getattrstr, *setattrstr, *delattrstr;
26
Fred Drake79912472000-07-09 04:06:11 +000027
Guido van Rossumc0b618a1997-05-02 03:12:38 +000028PyObject *
Fred Drake79912472000-07-09 04:06:11 +000029PyClass_New(PyObject *bases, PyObject *dict, PyObject *name)
30 /* bases is NULL or tuple of classobjects! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000031{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000032 PyClassObject *op, *dummy;
33 static PyObject *docstr, *modstr, *namestr;
34 if (docstr == NULL) {
35 docstr= PyString_InternFromString("__doc__");
36 if (docstr == NULL)
37 return NULL;
38 }
39 if (modstr == NULL) {
40 modstr= PyString_InternFromString("__module__");
41 if (modstr == NULL)
42 return NULL;
43 }
44 if (namestr == NULL) {
45 namestr= PyString_InternFromString("__name__");
46 if (namestr == NULL)
47 return NULL;
48 }
49 if (name == NULL || !PyString_Check(name)) {
50 PyErr_SetString(PyExc_TypeError,
51 "PyClass_New: name must be a string");
52 return NULL;
53 }
54 if (dict == NULL || !PyDict_Check(dict)) {
55 PyErr_SetString(PyExc_TypeError,
56 "PyClass_New: dict must be a dictionary");
57 return NULL;
58 }
59 if (PyDict_GetItem(dict, docstr) == NULL) {
60 if (PyDict_SetItem(dict, docstr, Py_None) < 0)
61 return NULL;
62 }
63 if (PyDict_GetItem(dict, modstr) == NULL) {
64 PyObject *globals = PyEval_GetGlobals();
65 if (globals != NULL) {
66 PyObject *modname = PyDict_GetItem(globals, namestr);
67 if (modname != NULL) {
68 if (PyDict_SetItem(dict, modstr, modname) < 0)
69 return NULL;
70 }
71 }
72 }
73 if (bases == NULL) {
74 bases = PyTuple_New(0);
75 if (bases == NULL)
76 return NULL;
77 }
78 else {
79 Py_ssize_t i, n;
80 PyObject *base;
81 if (!PyTuple_Check(bases)) {
82 PyErr_SetString(PyExc_TypeError,
83 "PyClass_New: bases must be a tuple");
84 return NULL;
85 }
86 n = PyTuple_Size(bases);
87 for (i = 0; i < n; i++) {
88 base = PyTuple_GET_ITEM(bases, i);
89 if (!PyClass_Check(base)) {
90 if (PyCallable_Check(
Benjamin Petersona72d15c2017-09-13 21:20:29 -070091 (PyObject *) Py_TYPE(base)))
Antoine Pitrouc83ea132010-05-09 14:46:46 +000092 return PyObject_CallFunctionObjArgs(
Benjamin Petersona72d15c2017-09-13 21:20:29 -070093 (PyObject *) Py_TYPE(base),
Antoine Pitrouc83ea132010-05-09 14:46:46 +000094 name, bases, dict, NULL);
95 PyErr_SetString(PyExc_TypeError,
96 "PyClass_New: base must be a class");
97 return NULL;
98 }
99 }
100 Py_INCREF(bases);
101 }
Neal Norwitz6cbb7262006-08-19 04:22:33 +0000102
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000103 if (getattrstr == NULL) {
104 getattrstr = PyString_InternFromString("__getattr__");
105 if (getattrstr == NULL)
106 goto alloc_error;
107 setattrstr = PyString_InternFromString("__setattr__");
108 if (setattrstr == NULL)
109 goto alloc_error;
110 delattrstr = PyString_InternFromString("__delattr__");
111 if (delattrstr == NULL)
112 goto alloc_error;
113 }
Neal Norwitz6cbb7262006-08-19 04:22:33 +0000114
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000115 op = PyObject_GC_New(PyClassObject, &PyClass_Type);
116 if (op == NULL) {
Neal Norwitz6cbb7262006-08-19 04:22:33 +0000117alloc_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000118 Py_DECREF(bases);
119 return NULL;
120 }
121 op->cl_bases = bases;
122 Py_INCREF(dict);
123 op->cl_dict = dict;
124 Py_XINCREF(name);
125 op->cl_name = name;
126 op->cl_weakreflist = NULL;
Neal Norwitz6cbb7262006-08-19 04:22:33 +0000127
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000128 op->cl_getattr = class_lookup(op, getattrstr, &dummy);
129 op->cl_setattr = class_lookup(op, setattrstr, &dummy);
130 op->cl_delattr = class_lookup(op, delattrstr, &dummy);
131 Py_XINCREF(op->cl_getattr);
132 Py_XINCREF(op->cl_setattr);
133 Py_XINCREF(op->cl_delattr);
134 _PyObject_GC_TRACK(op);
135 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000136}
137
Guido van Rossumb479dc52001-09-05 22:52:50 +0000138PyObject *
139PyMethod_Function(PyObject *im)
140{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000141 if (!PyMethod_Check(im)) {
142 PyErr_BadInternalCall();
143 return NULL;
144 }
145 return ((PyMethodObject *)im)->im_func;
Guido van Rossumb479dc52001-09-05 22:52:50 +0000146}
147
148PyObject *
149PyMethod_Self(PyObject *im)
150{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000151 if (!PyMethod_Check(im)) {
152 PyErr_BadInternalCall();
153 return NULL;
154 }
155 return ((PyMethodObject *)im)->im_self;
Guido van Rossumb479dc52001-09-05 22:52:50 +0000156}
157
158PyObject *
159PyMethod_Class(PyObject *im)
160{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000161 if (!PyMethod_Check(im)) {
162 PyErr_BadInternalCall();
163 return NULL;
164 }
165 return ((PyMethodObject *)im)->im_class;
Guido van Rossumb479dc52001-09-05 22:52:50 +0000166}
167
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000168PyDoc_STRVAR(class_doc,
169"classobj(name, bases, dict)\n\
170\n\
171Create a class object. The name must be a string; the second argument\n\
172a tuple of classes, and the third a dictionary.");
173
174static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000175class_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
176{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000177 PyObject *name, *bases, *dict;
178 static char *kwlist[] = {"name", "bases", "dict", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000179
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000180 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SOO", kwlist,
181 &name, &bases, &dict))
182 return NULL;
183 return PyClass_New(bases, dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000184}
185
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000186/* Class methods */
187
188static void
Fred Drake79912472000-07-09 04:06:11 +0000189class_dealloc(PyClassObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000190{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000191 _PyObject_GC_UNTRACK(op);
192 if (op->cl_weakreflist != NULL)
193 PyObject_ClearWeakRefs((PyObject *) op);
194 Py_DECREF(op->cl_bases);
195 Py_DECREF(op->cl_dict);
196 Py_XDECREF(op->cl_name);
197 Py_XDECREF(op->cl_getattr);
198 Py_XDECREF(op->cl_setattr);
199 Py_XDECREF(op->cl_delattr);
200 PyObject_GC_Del(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000201}
202
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000203static PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000204class_lookup(PyClassObject *cp, PyObject *name, PyClassObject **pclass)
Guido van Rossum81daa321993-05-20 14:24:46 +0000205{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000206 Py_ssize_t i, n;
207 PyObject *value = PyDict_GetItem(cp->cl_dict, name);
208 if (value != NULL) {
209 *pclass = cp;
210 return value;
211 }
212 n = PyTuple_Size(cp->cl_bases);
213 for (i = 0; i < n; i++) {
214 /* XXX What if one of the bases is not a class? */
215 PyObject *v = class_lookup(
216 (PyClassObject *)
217 PyTuple_GetItem(cp->cl_bases, i), name, pclass);
218 if (v != NULL)
219 return v;
220 }
221 return NULL;
Guido van Rossum81daa321993-05-20 14:24:46 +0000222}
223
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000224static PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000225class_getattr(register PyClassObject *op, PyObject *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000226{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000227 register PyObject *v;
Benjamin Petersondbc52f82012-03-16 10:58:46 -0500228 register char *sname;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000229 PyClassObject *klass;
230 descrgetfunc f;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000231
Benjamin Petersondbc52f82012-03-16 10:58:46 -0500232 if (!PyString_Check(name)) {
233 PyErr_SetString(PyExc_TypeError, "attribute name must be a string");
234 return NULL;
235 }
236
237 sname = PyString_AsString(name);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000238 if (sname[0] == '_' && sname[1] == '_') {
239 if (strcmp(sname, "__dict__") == 0) {
240 if (PyEval_GetRestricted()) {
241 PyErr_SetString(PyExc_RuntimeError,
242 "class.__dict__ not accessible in restricted mode");
243 return NULL;
244 }
245 Py_INCREF(op->cl_dict);
246 return op->cl_dict;
247 }
248 if (strcmp(sname, "__bases__") == 0) {
249 Py_INCREF(op->cl_bases);
250 return op->cl_bases;
251 }
252 if (strcmp(sname, "__name__") == 0) {
253 if (op->cl_name == NULL)
254 v = Py_None;
255 else
256 v = op->cl_name;
257 Py_INCREF(v);
258 return v;
259 }
260 }
261 v = class_lookup(op, name, &klass);
262 if (v == NULL) {
263 PyErr_Format(PyExc_AttributeError,
264 "class %.50s has no attribute '%.400s'",
265 PyString_AS_STRING(op->cl_name), sname);
266 return NULL;
267 }
Benjamin Petersona72d15c2017-09-13 21:20:29 -0700268 f = TP_DESCR_GET(Py_TYPE(v));
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000269 if (f == NULL)
270 Py_INCREF(v);
271 else
272 v = f(v, (PyObject *)NULL, (PyObject *)op);
273 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000274}
275
Guido van Rossuma63eff61998-05-29 21:37:21 +0000276static void
Fred Drake79912472000-07-09 04:06:11 +0000277set_slot(PyObject **slot, PyObject *v)
Guido van Rossuma63eff61998-05-29 21:37:21 +0000278{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000279 PyObject *temp = *slot;
280 Py_XINCREF(v);
281 *slot = v;
282 Py_XDECREF(temp);
Guido van Rossuma63eff61998-05-29 21:37:21 +0000283}
284
Guido van Rossum7ba30431998-07-08 13:34:48 +0000285static void
Fred Drake79912472000-07-09 04:06:11 +0000286set_attr_slots(PyClassObject *c)
Guido van Rossum7ba30431998-07-08 13:34:48 +0000287{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000288 PyClassObject *dummy;
Guido van Rossum7ba30431998-07-08 13:34:48 +0000289
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000290 set_slot(&c->cl_getattr, class_lookup(c, getattrstr, &dummy));
291 set_slot(&c->cl_setattr, class_lookup(c, setattrstr, &dummy));
292 set_slot(&c->cl_delattr, class_lookup(c, delattrstr, &dummy));
Guido van Rossum7ba30431998-07-08 13:34:48 +0000293}
294
Guido van Rossuma63eff61998-05-29 21:37:21 +0000295static char *
Fred Drake79912472000-07-09 04:06:11 +0000296set_dict(PyClassObject *c, PyObject *v)
Guido van Rossuma63eff61998-05-29 21:37:21 +0000297{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000298 if (v == NULL || !PyDict_Check(v))
299 return "__dict__ must be a dictionary object";
300 set_slot(&c->cl_dict, v);
301 set_attr_slots(c);
302 return "";
Guido van Rossuma63eff61998-05-29 21:37:21 +0000303}
304
305static char *
Fred Drake79912472000-07-09 04:06:11 +0000306set_bases(PyClassObject *c, PyObject *v)
Guido van Rossuma63eff61998-05-29 21:37:21 +0000307{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000308 Py_ssize_t i, n;
Guido van Rossuma63eff61998-05-29 21:37:21 +0000309
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000310 if (v == NULL || !PyTuple_Check(v))
311 return "__bases__ must be a tuple object";
312 n = PyTuple_Size(v);
313 for (i = 0; i < n; i++) {
314 PyObject *x = PyTuple_GET_ITEM(v, i);
315 if (!PyClass_Check(x))
316 return "__bases__ items must be classes";
317 if (PyClass_IsSubclass(x, (PyObject *)c))
318 return "a __bases__ item causes an inheritance cycle";
319 }
320 set_slot(&c->cl_bases, v);
321 set_attr_slots(c);
322 return "";
Guido van Rossuma63eff61998-05-29 21:37:21 +0000323}
324
325static char *
Fred Drake79912472000-07-09 04:06:11 +0000326set_name(PyClassObject *c, PyObject *v)
Guido van Rossuma63eff61998-05-29 21:37:21 +0000327{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000328 if (v == NULL || !PyString_Check(v))
329 return "__name__ must be a string object";
330 if (strlen(PyString_AS_STRING(v)) != (size_t)PyString_GET_SIZE(v))
331 return "__name__ must not contain null bytes";
332 set_slot(&c->cl_name, v);
333 return "";
Guido van Rossuma63eff61998-05-29 21:37:21 +0000334}
335
Guido van Rossum94308391991-10-20 20:11:48 +0000336static int
Fred Drake79912472000-07-09 04:06:11 +0000337class_setattr(PyClassObject *op, PyObject *name, PyObject *v)
Guido van Rossum94308391991-10-20 20:11:48 +0000338{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000339 char *sname;
340 if (PyEval_GetRestricted()) {
341 PyErr_SetString(PyExc_RuntimeError,
342 "classes are read-only in restricted mode");
343 return -1;
344 }
Benjamin Petersondbc52f82012-03-16 10:58:46 -0500345 if (!PyString_Check(name)) {
346 PyErr_SetString(PyExc_TypeError, "attribute name must be a string");
347 return -1;
348 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000349 sname = PyString_AsString(name);
350 if (sname[0] == '_' && sname[1] == '_') {
351 Py_ssize_t n = PyString_Size(name);
352 if (sname[n-1] == '_' && sname[n-2] == '_') {
353 char *err = NULL;
354 if (strcmp(sname, "__dict__") == 0)
355 err = set_dict(op, v);
356 else if (strcmp(sname, "__bases__") == 0)
357 err = set_bases(op, v);
358 else if (strcmp(sname, "__name__") == 0)
359 err = set_name(op, v);
360 else if (strcmp(sname, "__getattr__") == 0)
361 set_slot(&op->cl_getattr, v);
362 else if (strcmp(sname, "__setattr__") == 0)
363 set_slot(&op->cl_setattr, v);
364 else if (strcmp(sname, "__delattr__") == 0)
365 set_slot(&op->cl_delattr, v);
366 /* For the last three, we fall through to update the
367 dictionary as well. */
368 if (err != NULL) {
369 if (*err == '\0')
370 return 0;
371 PyErr_SetString(PyExc_TypeError, err);
372 return -1;
373 }
374 }
375 }
376 if (v == NULL) {
377 int rv = PyDict_DelItem(op->cl_dict, name);
378 if (rv < 0)
379 PyErr_Format(PyExc_AttributeError,
380 "class %.50s has no attribute '%.400s'",
381 PyString_AS_STRING(op->cl_name), sname);
382 return rv;
383 }
384 else
385 return PyDict_SetItem(op->cl_dict, name, v);
Guido van Rossum94308391991-10-20 20:11:48 +0000386}
387
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000388static PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000389class_repr(PyClassObject *op)
Guido van Rossum25831651993-05-19 14:50:45 +0000390{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000391 PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
392 char *name;
393 if (op->cl_name == NULL || !PyString_Check(op->cl_name))
394 name = "?";
395 else
396 name = PyString_AsString(op->cl_name);
397 if (mod == NULL || !PyString_Check(mod))
398 return PyString_FromFormat("<class ?.%s at %p>", name, op);
399 else
400 return PyString_FromFormat("<class %s.%s at %p>",
401 PyString_AsString(mod),
402 name, op);
Guido van Rossum25831651993-05-19 14:50:45 +0000403}
404
Guido van Rossum4a2a6211997-10-20 23:26:11 +0000405static PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000406class_str(PyClassObject *op)
Guido van Rossum4a2a6211997-10-20 23:26:11 +0000407{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000408 PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
409 PyObject *name = op->cl_name;
410 PyObject *res;
411 Py_ssize_t m, n;
Guido van Rossum4a2a6211997-10-20 23:26:11 +0000412
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000413 if (name == NULL || !PyString_Check(name))
414 return class_repr(op);
415 if (mod == NULL || !PyString_Check(mod)) {
416 Py_INCREF(name);
417 return name;
418 }
419 m = PyString_GET_SIZE(mod);
420 n = PyString_GET_SIZE(name);
421 res = PyString_FromStringAndSize((char *)NULL, m+1+n);
422 if (res != NULL) {
423 char *s = PyString_AS_STRING(res);
424 memcpy(s, PyString_AS_STRING(mod), m);
425 s += m;
426 *s++ = '.';
427 memcpy(s, PyString_AS_STRING(name), n);
428 }
429 return res;
Guido van Rossum4a2a6211997-10-20 23:26:11 +0000430}
431
Jeremy Hylton8caad492000-06-23 14:18:11 +0000432static int
433class_traverse(PyClassObject *o, visitproc visit, void *arg)
434{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000435 Py_VISIT(o->cl_bases);
436 Py_VISIT(o->cl_dict);
437 Py_VISIT(o->cl_name);
438 Py_VISIT(o->cl_getattr);
439 Py_VISIT(o->cl_setattr);
440 Py_VISIT(o->cl_delattr);
441 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +0000442}
443
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000444PyTypeObject PyClass_Type = {
Benjamin Petersona72d15c2017-09-13 21:20:29 -0700445 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000446 "classobj",
447 sizeof(PyClassObject),
448 0,
449 (destructor)class_dealloc, /* tp_dealloc */
450 0, /* tp_print */
451 0, /* tp_getattr */
452 0, /* tp_setattr */
453 0, /* tp_compare */
454 (reprfunc)class_repr, /* tp_repr */
455 0, /* tp_as_number */
456 0, /* tp_as_sequence */
457 0, /* tp_as_mapping */
458 0, /* tp_hash */
459 PyInstance_New, /* tp_call */
460 (reprfunc)class_str, /* tp_str */
461 (getattrofunc)class_getattr, /* tp_getattro */
462 (setattrofunc)class_setattr, /* tp_setattro */
463 0, /* tp_as_buffer */
464 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
465 class_doc, /* tp_doc */
466 (traverseproc)class_traverse, /* tp_traverse */
467 0, /* tp_clear */
468 0, /* tp_richcompare */
469 offsetof(PyClassObject, cl_weakreflist), /* tp_weaklistoffset */
470 0, /* tp_iter */
471 0, /* tp_iternext */
472 0, /* tp_methods */
473 0, /* tp_members */
474 0, /* tp_getset */
475 0, /* tp_base */
476 0, /* tp_dict */
477 0, /* tp_descr_get */
478 0, /* tp_descr_set */
479 0, /* tp_dictoffset */
480 0, /* tp_init */
481 0, /* tp_alloc */
482 class_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000483};
484
Guido van Rossum81daa321993-05-20 14:24:46 +0000485int
Anthony Baxter377be112006-04-11 06:54:30 +0000486PyClass_IsSubclass(PyObject *klass, PyObject *base)
Guido van Rossum81daa321993-05-20 14:24:46 +0000487{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000488 Py_ssize_t i, n;
489 PyClassObject *cp;
490 if (klass == base)
491 return 1;
492 if (PyTuple_Check(base)) {
493 n = PyTuple_GET_SIZE(base);
494 for (i = 0; i < n; i++) {
495 if (PyClass_IsSubclass(klass, PyTuple_GET_ITEM(base, i)))
496 return 1;
497 }
498 return 0;
499 }
500 if (klass == NULL || !PyClass_Check(klass))
501 return 0;
502 cp = (PyClassObject *)klass;
503 n = PyTuple_Size(cp->cl_bases);
504 for (i = 0; i < n; i++) {
505 if (PyClass_IsSubclass(PyTuple_GetItem(cp->cl_bases, i), base))
506 return 1;
507 }
508 return 0;
Guido van Rossum81daa321993-05-20 14:24:46 +0000509}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000510
Guido van Rossum81daa321993-05-20 14:24:46 +0000511
512/* Instance objects */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000513
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000514PyObject *
Fred Drake5cc2c8c2001-01-28 03:53:08 +0000515PyInstance_NewRaw(PyObject *klass, PyObject *dict)
516{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000517 PyInstanceObject *inst;
Fred Drake5cc2c8c2001-01-28 03:53:08 +0000518
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000519 if (!PyClass_Check(klass)) {
520 PyErr_BadInternalCall();
521 return NULL;
522 }
523 if (dict == NULL) {
524 dict = PyDict_New();
525 if (dict == NULL)
526 return NULL;
527 }
528 else {
529 if (!PyDict_Check(dict)) {
530 PyErr_BadInternalCall();
531 return NULL;
532 }
533 Py_INCREF(dict);
534 }
535 inst = PyObject_GC_New(PyInstanceObject, &PyInstance_Type);
536 if (inst == NULL) {
537 Py_DECREF(dict);
538 return NULL;
539 }
540 inst->in_weakreflist = NULL;
541 Py_INCREF(klass);
542 inst->in_class = (PyClassObject *)klass;
543 inst->in_dict = dict;
544 _PyObject_GC_TRACK(inst);
545 return (PyObject *)inst;
Fred Drake5cc2c8c2001-01-28 03:53:08 +0000546}
547
548PyObject *
549PyInstance_New(PyObject *klass, PyObject *arg, PyObject *kw)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000550{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000551 register PyInstanceObject *inst;
552 PyObject *init;
553 static PyObject *initstr;
Fred Drake5cc2c8c2001-01-28 03:53:08 +0000554
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000555 if (initstr == NULL) {
556 initstr = PyString_InternFromString("__init__");
557 if (initstr == NULL)
558 return NULL;
559 }
560 inst = (PyInstanceObject *) PyInstance_NewRaw(klass, NULL);
561 if (inst == NULL)
562 return NULL;
563 init = instance_getattr2(inst, initstr);
564 if (init == NULL) {
565 if (PyErr_Occurred()) {
566 Py_DECREF(inst);
567 return NULL;
568 }
569 if ((arg != NULL && (!PyTuple_Check(arg) ||
570 PyTuple_Size(arg) != 0))
571 || (kw != NULL && (!PyDict_Check(kw) ||
572 PyDict_Size(kw) != 0))) {
573 PyErr_SetString(PyExc_TypeError,
574 "this constructor takes no arguments");
575 Py_DECREF(inst);
576 inst = NULL;
577 }
578 }
579 else {
580 PyObject *res = PyEval_CallObjectWithKeywords(init, arg, kw);
581 Py_DECREF(init);
582 if (res == NULL) {
583 Py_DECREF(inst);
584 inst = NULL;
585 }
586 else {
587 if (res != Py_None) {
588 PyErr_SetString(PyExc_TypeError,
589 "__init__() should return None");
590 Py_DECREF(inst);
591 inst = NULL;
592 }
593 Py_DECREF(res);
594 }
595 }
596 return (PyObject *)inst;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000597}
598
Guido van Rossum21ed88c1991-04-04 10:42:10 +0000599/* Instance methods */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000600
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000601PyDoc_STRVAR(instance_doc,
602"instance(class[, dict])\n\
603\n\
604Create an instance without calling its __init__() method.\n\
605The class must be a classic class.\n\
606If present, dict must be a dictionary or None.");
607
608static PyObject *
609instance_new(PyTypeObject* type, PyObject* args, PyObject *kw)
610{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000611 PyObject *klass;
612 PyObject *dict = Py_None;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000613
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000614 if (!PyArg_ParseTuple(args, "O!|O:instance",
615 &PyClass_Type, &klass, &dict))
616 return NULL;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000617
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000618 if (dict == Py_None)
619 dict = NULL;
620 else if (!PyDict_Check(dict)) {
621 PyErr_SetString(PyExc_TypeError,
622 "instance() second arg must be dictionary or None");
623 return NULL;
624 }
625 return PyInstance_NewRaw(klass, dict);
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000626}
627
628
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000629static void
Fred Drake79912472000-07-09 04:06:11 +0000630instance_dealloc(register PyInstanceObject *inst)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000631{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000632 PyObject *error_type, *error_value, *error_traceback;
633 PyObject *del;
634 static PyObject *delstr;
Tim Peters34592512002-07-11 06:23:50 +0000635
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000636 _PyObject_GC_UNTRACK(inst);
637 if (inst->in_weakreflist != NULL)
638 PyObject_ClearWeakRefs((PyObject *) inst);
Fred Drake41deb1e2001-02-01 05:27:45 +0000639
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000640 /* Temporarily resurrect the object. */
Benjamin Petersona72d15c2017-09-13 21:20:29 -0700641 assert(Py_TYPE(inst) == &PyInstance_Type);
642 assert(Py_REFCNT(inst) == 0);
643 Py_REFCNT(inst) = 1;
Tim Peters6b184912000-09-17 14:40:17 +0000644
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000645 /* Save the current exception, if any. */
646 PyErr_Fetch(&error_type, &error_value, &error_traceback);
647 /* Execute __del__ method, if any. */
648 if (delstr == NULL) {
649 delstr = PyString_InternFromString("__del__");
650 if (delstr == NULL)
651 PyErr_WriteUnraisable((PyObject*)inst);
652 }
653 if (delstr && (del = instance_getattr2(inst, delstr)) != NULL) {
654 PyObject *res = PyEval_CallObject(del, (PyObject *)NULL);
655 if (res == NULL)
656 PyErr_WriteUnraisable(del);
657 else
658 Py_DECREF(res);
659 Py_DECREF(del);
660 }
661 /* Restore the saved exception. */
662 PyErr_Restore(error_type, error_value, error_traceback);
Tim Peters34592512002-07-11 06:23:50 +0000663
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000664 /* Undo the temporary resurrection; can't use DECREF here, it would
665 * cause a recursive call.
666 */
Benjamin Petersona72d15c2017-09-13 21:20:29 -0700667 assert(Py_REFCNT(inst) > 0);
668 if (--Py_REFCNT(inst) == 0) {
Guido van Rossum9ff1a442008-01-18 20:56:30 +0000669
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000670 /* New weakrefs could be created during the finalizer call.
671 If this occurs, clear them out without calling their
672 finalizers since they might rely on part of the object
673 being finalized that has already been destroyed. */
674 while (inst->in_weakreflist != NULL) {
675 _PyWeakref_ClearRef((PyWeakReference *)
676 (inst->in_weakreflist));
677 }
Guido van Rossum9ff1a442008-01-18 20:56:30 +0000678
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000679 Py_DECREF(inst->in_class);
680 Py_XDECREF(inst->in_dict);
681 PyObject_GC_Del(inst);
682 }
683 else {
Benjamin Petersona72d15c2017-09-13 21:20:29 -0700684 Py_ssize_t refcnt = Py_REFCNT(inst);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000685 /* __del__ resurrected it! Make it look like the original
686 * Py_DECREF never happened.
687 */
688 _Py_NewReference((PyObject *)inst);
Benjamin Petersona72d15c2017-09-13 21:20:29 -0700689 Py_REFCNT(inst) = refcnt;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000690 _PyObject_GC_TRACK(inst);
691 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
692 * we need to undo that. */
693 _Py_DEC_REFTOTAL;
694 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the
695 * object chain, so no more to do there.
696 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
697 * _Py_NewReference bumped tp_allocs: both of those need to be
698 * undone.
699 */
Tim Peters6b184912000-09-17 14:40:17 +0000700#ifdef COUNT_ALLOCS
Benjamin Petersona72d15c2017-09-13 21:20:29 -0700701 --Py_TYPE(inst)->tp_frees;
702 --Py_TYPE(inst)->tp_allocs;
Tim Peters6b184912000-09-17 14:40:17 +0000703#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000704 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000705}
706
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000707static PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000708instance_getattr1(register PyInstanceObject *inst, PyObject *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000709{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000710 register PyObject *v;
Benjamin Petersondbc52f82012-03-16 10:58:46 -0500711 register char *sname;
712
713 if (!PyString_Check(name)) {
714 PyErr_SetString(PyExc_TypeError, "attribute name must be a string");
715 return NULL;
716 }
717
718 sname = PyString_AsString(name);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000719 if (sname[0] == '_' && sname[1] == '_') {
720 if (strcmp(sname, "__dict__") == 0) {
721 if (PyEval_GetRestricted()) {
722 PyErr_SetString(PyExc_RuntimeError,
723 "instance.__dict__ not accessible in restricted mode");
724 return NULL;
725 }
726 Py_INCREF(inst->in_dict);
727 return inst->in_dict;
728 }
729 if (strcmp(sname, "__class__") == 0) {
730 Py_INCREF(inst->in_class);
731 return (PyObject *)inst->in_class;
732 }
733 }
734 v = instance_getattr2(inst, name);
735 if (v == NULL && !PyErr_Occurred()) {
736 PyErr_Format(PyExc_AttributeError,
737 "%.50s instance has no attribute '%.400s'",
738 PyString_AS_STRING(inst->in_class->cl_name), sname);
739 }
740 return v;
Jeremy Hylton9e392e22000-04-26 20:39:20 +0000741}
742
743static PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000744instance_getattr2(register PyInstanceObject *inst, PyObject *name)
Jeremy Hylton9e392e22000-04-26 20:39:20 +0000745{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000746 register PyObject *v;
747 PyClassObject *klass;
748 descrgetfunc f;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000749
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000750 v = PyDict_GetItem(inst->in_dict, name);
751 if (v != NULL) {
752 Py_INCREF(v);
753 return v;
754 }
755 v = class_lookup(inst->in_class, name, &klass);
756 if (v != NULL) {
757 Py_INCREF(v);
Benjamin Petersona72d15c2017-09-13 21:20:29 -0700758 f = TP_DESCR_GET(Py_TYPE(v));
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000759 if (f != NULL) {
760 PyObject *w = f(v, (PyObject *)inst,
761 (PyObject *)(inst->in_class));
762 Py_DECREF(v);
763 v = w;
764 }
765 }
766 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000767}
768
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000769static PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000770instance_getattr(register PyInstanceObject *inst, PyObject *name)
Guido van Rossume7737541994-09-05 07:31:41 +0000771{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000772 register PyObject *func, *res;
773 res = instance_getattr1(inst, name);
774 if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) {
775 PyObject *args;
776 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
777 return NULL;
778 PyErr_Clear();
779 args = PyTuple_Pack(2, inst, name);
780 if (args == NULL)
781 return NULL;
782 res = PyEval_CallObject(func, args);
783 Py_DECREF(args);
784 }
785 return res;
Guido van Rossume7737541994-09-05 07:31:41 +0000786}
787
Tim Petersdf875b92003-04-07 17:51:59 +0000788/* See classobject.h comments: this only does dict lookups, and is always
789 * safe to call.
790 */
791PyObject *
792_PyInstance_Lookup(PyObject *pinst, PyObject *name)
793{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000794 PyObject *v;
795 PyClassObject *klass;
796 PyInstanceObject *inst; /* pinst cast to the right type */
Tim Petersdf875b92003-04-07 17:51:59 +0000797
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000798 assert(PyInstance_Check(pinst));
799 inst = (PyInstanceObject *)pinst;
Tim Petersdf875b92003-04-07 17:51:59 +0000800
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000801 assert(PyString_Check(name));
Tim Petersdf875b92003-04-07 17:51:59 +0000802
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000803 v = PyDict_GetItem(inst->in_dict, name);
804 if (v == NULL)
805 v = class_lookup(inst->in_class, name, &klass);
806 return v;
Tim Petersdf875b92003-04-07 17:51:59 +0000807}
808
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000809static int
Fred Drake79912472000-07-09 04:06:11 +0000810instance_setattr1(PyInstanceObject *inst, PyObject *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000811{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000812 if (v == NULL) {
813 int rv = PyDict_DelItem(inst->in_dict, name);
814 if (rv < 0)
815 PyErr_Format(PyExc_AttributeError,
816 "%.50s instance has no attribute '%.400s'",
817 PyString_AS_STRING(inst->in_class->cl_name),
818 PyString_AS_STRING(name));
819 return rv;
820 }
821 else
822 return PyDict_SetItem(inst->in_dict, name, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000823}
824
Guido van Rossume7737541994-09-05 07:31:41 +0000825static int
Fred Drake79912472000-07-09 04:06:11 +0000826instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v)
Guido van Rossume7737541994-09-05 07:31:41 +0000827{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000828 PyObject *func, *args, *res, *tmp;
Benjamin Petersondbc52f82012-03-16 10:58:46 -0500829 char *sname;
830
831 if (!PyString_Check(name)) {
832 PyErr_SetString(PyExc_TypeError, "attribute name must be a string");
833 return -1;
834 }
835
836 sname = PyString_AsString(name);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000837 if (sname[0] == '_' && sname[1] == '_') {
838 Py_ssize_t n = PyString_Size(name);
839 if (sname[n-1] == '_' && sname[n-2] == '_') {
840 if (strcmp(sname, "__dict__") == 0) {
841 if (PyEval_GetRestricted()) {
842 PyErr_SetString(PyExc_RuntimeError,
843 "__dict__ not accessible in restricted mode");
844 return -1;
845 }
846 if (v == NULL || !PyDict_Check(v)) {
847 PyErr_SetString(PyExc_TypeError,
848 "__dict__ must be set to a dictionary");
849 return -1;
850 }
851 tmp = inst->in_dict;
852 Py_INCREF(v);
853 inst->in_dict = v;
854 Py_DECREF(tmp);
855 return 0;
856 }
857 if (strcmp(sname, "__class__") == 0) {
858 if (PyEval_GetRestricted()) {
859 PyErr_SetString(PyExc_RuntimeError,
860 "__class__ not accessible in restricted mode");
861 return -1;
862 }
863 if (v == NULL || !PyClass_Check(v)) {
864 PyErr_SetString(PyExc_TypeError,
865 "__class__ must be set to a class");
866 return -1;
867 }
868 tmp = (PyObject *)(inst->in_class);
869 Py_INCREF(v);
870 inst->in_class = (PyClassObject *)v;
871 Py_DECREF(tmp);
872 return 0;
873 }
874 }
875 }
876 if (v == NULL)
877 func = inst->in_class->cl_delattr;
878 else
879 func = inst->in_class->cl_setattr;
880 if (func == NULL)
881 return instance_setattr1(inst, name, v);
882 if (v == NULL)
883 args = PyTuple_Pack(2, inst, name);
884 else
885 args = PyTuple_Pack(3, inst, name, v);
886 if (args == NULL)
887 return -1;
888 res = PyEval_CallObject(func, args);
889 Py_DECREF(args);
890 if (res == NULL)
891 return -1;
892 Py_DECREF(res);
893 return 0;
Guido van Rossume7737541994-09-05 07:31:41 +0000894}
895
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000896static PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000897instance_repr(PyInstanceObject *inst)
Guido van Rossum04691fc1992-08-12 15:35:34 +0000898{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000899 PyObject *func;
900 PyObject *res;
901 static PyObject *reprstr;
Guido van Rossum04691fc1992-08-12 15:35:34 +0000902
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000903 if (reprstr == NULL) {
904 reprstr = PyString_InternFromString("__repr__");
905 if (reprstr == NULL)
906 return NULL;
907 }
908 func = instance_getattr(inst, reprstr);
909 if (func == NULL) {
910 PyObject *classname, *mod;
911 char *cname;
912 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
913 return NULL;
914 PyErr_Clear();
915 classname = inst->in_class->cl_name;
916 mod = PyDict_GetItemString(inst->in_class->cl_dict,
917 "__module__");
918 if (classname != NULL && PyString_Check(classname))
919 cname = PyString_AsString(classname);
920 else
921 cname = "?";
922 if (mod == NULL || !PyString_Check(mod))
923 return PyString_FromFormat("<?.%s instance at %p>",
924 cname, inst);
925 else
926 return PyString_FromFormat("<%s.%s instance at %p>",
927 PyString_AsString(mod),
928 cname, inst);
929 }
930 res = PyEval_CallObject(func, (PyObject *)NULL);
931 Py_DECREF(func);
932 return res;
Guido van Rossum04691fc1992-08-12 15:35:34 +0000933}
934
Guido van Rossum82c690f2001-04-30 14:39:18 +0000935static PyObject *
936instance_str(PyInstanceObject *inst)
937{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000938 PyObject *func;
939 PyObject *res;
940 static PyObject *strstr;
Guido van Rossum82c690f2001-04-30 14:39:18 +0000941
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000942 if (strstr == NULL) {
943 strstr = PyString_InternFromString("__str__");
944 if (strstr == NULL)
945 return NULL;
946 }
947 func = instance_getattr(inst, strstr);
948 if (func == NULL) {
949 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
950 return NULL;
951 PyErr_Clear();
952 return instance_repr(inst);
953 }
954 res = PyEval_CallObject(func, (PyObject *)NULL);
955 Py_DECREF(func);
956 return res;
Guido van Rossum82c690f2001-04-30 14:39:18 +0000957}
958
Guido van Rossum9bfef441993-03-29 10:43:31 +0000959static long
Fred Drake79912472000-07-09 04:06:11 +0000960instance_hash(PyInstanceObject *inst)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000961{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000962 PyObject *func;
963 PyObject *res;
964 long outcome;
965 static PyObject *hashstr, *eqstr, *cmpstr;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000966
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000967 if (hashstr == NULL) {
968 hashstr = PyString_InternFromString("__hash__");
969 if (hashstr == NULL)
970 return -1;
971 }
972 func = instance_getattr(inst, hashstr);
973 if (func == NULL) {
974 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
975 return -1;
976 PyErr_Clear();
977 /* If there is no __eq__ and no __cmp__ method, we hash on the
978 address. If an __eq__ or __cmp__ method exists, there must
979 be a __hash__. */
980 if (eqstr == NULL) {
981 eqstr = PyString_InternFromString("__eq__");
982 if (eqstr == NULL)
983 return -1;
984 }
985 func = instance_getattr(inst, eqstr);
986 if (func == NULL) {
987 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
988 return -1;
989 PyErr_Clear();
990 if (cmpstr == NULL) {
991 cmpstr = PyString_InternFromString("__cmp__");
992 if (cmpstr == NULL)
993 return -1;
994 }
995 func = instance_getattr(inst, cmpstr);
996 if (func == NULL) {
997 if (!PyErr_ExceptionMatches(
998 PyExc_AttributeError))
999 return -1;
1000 PyErr_Clear();
1001 return _Py_HashPointer(inst);
1002 }
1003 }
1004 Py_XDECREF(func);
1005 PyErr_SetString(PyExc_TypeError, "unhashable instance");
1006 return -1;
1007 }
1008 res = PyEval_CallObject(func, (PyObject *)NULL);
1009 Py_DECREF(func);
1010 if (res == NULL)
1011 return -1;
1012 if (PyInt_Check(res) || PyLong_Check(res))
1013 /* This already converts a -1 result to -2. */
Benjamin Petersona72d15c2017-09-13 21:20:29 -07001014 outcome = Py_TYPE(res)->tp_hash(res);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001015 else {
1016 PyErr_SetString(PyExc_TypeError,
1017 "__hash__() should return an int");
1018 outcome = -1;
1019 }
1020 Py_DECREF(res);
1021 return outcome;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001022}
1023
Jeremy Hylton8caad492000-06-23 14:18:11 +00001024static int
1025instance_traverse(PyInstanceObject *o, visitproc visit, void *arg)
1026{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001027 Py_VISIT(o->in_class);
1028 Py_VISIT(o->in_dict);
1029 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00001030}
1031
Guido van Rossum213c7a62001-04-23 14:08:49 +00001032static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr;
1033static PyObject *iterstr, *nextstr;
Guido van Rossum2878a691996-08-09 20:53:24 +00001034
Martin v. Löwis18e16552006-02-15 17:27:45 +00001035static Py_ssize_t
Fred Drake79912472000-07-09 04:06:11 +00001036instance_length(PyInstanceObject *inst)
Guido van Rossum04691fc1992-08-12 15:35:34 +00001037{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001038 PyObject *func;
1039 PyObject *res;
1040 Py_ssize_t outcome;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001041
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001042 if (lenstr == NULL) {
1043 lenstr = PyString_InternFromString("__len__");
1044 if (lenstr == NULL)
1045 return -1;
1046 }
1047 func = instance_getattr(inst, lenstr);
1048 if (func == NULL)
1049 return -1;
1050 res = PyEval_CallObject(func, (PyObject *)NULL);
1051 Py_DECREF(func);
1052 if (res == NULL)
1053 return -1;
1054 if (PyInt_Check(res)) {
1055 outcome = PyInt_AsSsize_t(res);
1056 if (outcome == -1 && PyErr_Occurred()) {
1057 Py_DECREF(res);
1058 return -1;
1059 }
Neal Norwitz1872b1c2006-08-12 18:44:06 +00001060#if SIZEOF_SIZE_T < SIZEOF_INT
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001061 /* Overflow check -- range of PyInt is more than C int */
1062 if (outcome != (int)outcome) {
1063 PyErr_SetString(PyExc_OverflowError,
1064 "__len__() should return 0 <= outcome < 2**31");
1065 outcome = -1;
1066 }
1067 else
Guido van Rossumba3e6ec2005-09-19 22:42:41 +00001068#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001069 if (outcome < 0) {
1070 PyErr_SetString(PyExc_ValueError,
1071 "__len__() should return >= 0");
1072 outcome = -1;
1073 }
1074 }
1075 else {
1076 PyErr_SetString(PyExc_TypeError,
1077 "__len__() should return an int");
1078 outcome = -1;
1079 }
1080 Py_DECREF(res);
1081 return outcome;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001082}
1083
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001084static PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001085instance_subscript(PyInstanceObject *inst, PyObject *key)
Guido van Rossum04691fc1992-08-12 15:35:34 +00001086{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001087 PyObject *func;
1088 PyObject *arg;
1089 PyObject *res;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001090
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001091 if (getitemstr == NULL) {
1092 getitemstr = PyString_InternFromString("__getitem__");
1093 if (getitemstr == NULL)
1094 return NULL;
1095 }
1096 func = instance_getattr(inst, getitemstr);
1097 if (func == NULL)
1098 return NULL;
1099 arg = PyTuple_Pack(1, key);
1100 if (arg == NULL) {
1101 Py_DECREF(func);
1102 return NULL;
1103 }
1104 res = PyEval_CallObject(func, arg);
1105 Py_DECREF(func);
1106 Py_DECREF(arg);
1107 return res;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001108}
1109
Guido van Rossum9bfef441993-03-29 10:43:31 +00001110static int
Fred Drake79912472000-07-09 04:06:11 +00001111instance_ass_subscript(PyInstanceObject *inst, PyObject *key, PyObject *value)
Guido van Rossum04691fc1992-08-12 15:35:34 +00001112{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001113 PyObject *func;
1114 PyObject *arg;
1115 PyObject *res;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001116
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001117 if (value == NULL) {
1118 if (delitemstr == NULL) {
1119 delitemstr = PyString_InternFromString("__delitem__");
1120 if (delitemstr == NULL)
1121 return -1;
1122 }
1123 func = instance_getattr(inst, delitemstr);
1124 }
1125 else {
1126 if (setitemstr == NULL) {
1127 setitemstr = PyString_InternFromString("__setitem__");
1128 if (setitemstr == NULL)
1129 return -1;
1130 }
1131 func = instance_getattr(inst, setitemstr);
1132 }
1133 if (func == NULL)
1134 return -1;
1135 if (value == NULL)
1136 arg = PyTuple_Pack(1, key);
1137 else
1138 arg = PyTuple_Pack(2, key, value);
1139 if (arg == NULL) {
1140 Py_DECREF(func);
1141 return -1;
1142 }
1143 res = PyEval_CallObject(func, arg);
1144 Py_DECREF(func);
1145 Py_DECREF(arg);
1146 if (res == NULL)
1147 return -1;
1148 Py_DECREF(res);
1149 return 0;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001150}
1151
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001152static PyMappingMethods instance_as_mapping = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001153 (lenfunc)instance_length, /* mp_length */
1154 (binaryfunc)instance_subscript, /* mp_subscript */
1155 (objobjargproc)instance_ass_subscript, /* mp_ass_subscript */
Guido van Rossum04691fc1992-08-12 15:35:34 +00001156};
1157
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001158static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001159instance_item(PyInstanceObject *inst, Py_ssize_t i)
Guido van Rossum04691fc1992-08-12 15:35:34 +00001160{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001161 PyObject *func, *res;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001162
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001163 if (getitemstr == NULL) {
1164 getitemstr = PyString_InternFromString("__getitem__");
1165 if (getitemstr == NULL)
1166 return NULL;
1167 }
1168 func = instance_getattr(inst, getitemstr);
1169 if (func == NULL)
1170 return NULL;
1171 res = PyObject_CallFunction(func, "n", i);
1172 Py_DECREF(func);
1173 return res;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001174}
1175
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001176static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001177instance_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j)
Guido van Rossum04691fc1992-08-12 15:35:34 +00001178{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001179 PyObject *func, *arg, *res;
1180 static PyObject *getslicestr;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001181
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001182 if (getslicestr == NULL) {
1183 getslicestr = PyString_InternFromString("__getslice__");
1184 if (getslicestr == NULL)
1185 return NULL;
1186 }
1187 func = instance_getattr(inst, getslicestr);
Thomas Wouters1d75a792000-08-17 22:37:32 +00001188
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001189 if (func == NULL) {
1190 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1191 return NULL;
1192 PyErr_Clear();
Thomas Wouters1d75a792000-08-17 22:37:32 +00001193
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001194 if (getitemstr == NULL) {
1195 getitemstr = PyString_InternFromString("__getitem__");
1196 if (getitemstr == NULL)
1197 return NULL;
1198 }
1199 func = instance_getattr(inst, getitemstr);
1200 if (func == NULL)
1201 return NULL;
1202 arg = Py_BuildValue("(N)", _PySlice_FromIndices(i, j));
1203 }
1204 else {
1205 if (PyErr_WarnPy3k("in 3.x, __getslice__ has been removed; "
1206 "use __getitem__", 1) < 0) {
1207 Py_DECREF(func);
1208 return NULL;
1209 }
1210 arg = Py_BuildValue("(nn)", i, j);
1211 }
Tim Peters34592512002-07-11 06:23:50 +00001212
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001213 if (arg == NULL) {
1214 Py_DECREF(func);
1215 return NULL;
1216 }
1217 res = PyEval_CallObject(func, arg);
1218 Py_DECREF(func);
1219 Py_DECREF(arg);
1220 return res;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001221}
1222
1223static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001224instance_ass_item(PyInstanceObject *inst, Py_ssize_t i, PyObject *item)
Guido van Rossum04691fc1992-08-12 15:35:34 +00001225{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001226 PyObject *func, *arg, *res;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001227
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001228 if (item == NULL) {
1229 if (delitemstr == NULL) {
1230 delitemstr = PyString_InternFromString("__delitem__");
1231 if (delitemstr == NULL)
1232 return -1;
1233 }
1234 func = instance_getattr(inst, delitemstr);
1235 }
1236 else {
1237 if (setitemstr == NULL) {
1238 setitemstr = PyString_InternFromString("__setitem__");
1239 if (setitemstr == NULL)
1240 return -1;
1241 }
1242 func = instance_getattr(inst, setitemstr);
1243 }
1244 if (func == NULL)
1245 return -1;
1246 if (item == NULL)
Benjamin Petersona7b09762011-10-15 13:43:21 -04001247 arg = Py_BuildValue("(n)", i);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001248 else
1249 arg = Py_BuildValue("(nO)", i, item);
1250 if (arg == NULL) {
1251 Py_DECREF(func);
1252 return -1;
1253 }
1254 res = PyEval_CallObject(func, arg);
1255 Py_DECREF(func);
1256 Py_DECREF(arg);
1257 if (res == NULL)
1258 return -1;
1259 Py_DECREF(res);
1260 return 0;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001261}
1262
1263static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001264instance_ass_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Guido van Rossum04691fc1992-08-12 15:35:34 +00001265{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001266 PyObject *func, *arg, *res;
1267 static PyObject *setslicestr, *delslicestr;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001268
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001269 if (value == NULL) {
1270 if (delslicestr == NULL) {
1271 delslicestr =
1272 PyString_InternFromString("__delslice__");
1273 if (delslicestr == NULL)
1274 return -1;
1275 }
1276 func = instance_getattr(inst, delslicestr);
1277 if (func == NULL) {
1278 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1279 return -1;
1280 PyErr_Clear();
1281 if (delitemstr == NULL) {
1282 delitemstr =
1283 PyString_InternFromString("__delitem__");
1284 if (delitemstr == NULL)
1285 return -1;
1286 }
1287 func = instance_getattr(inst, delitemstr);
1288 if (func == NULL)
1289 return -1;
Thomas Wouters1d75a792000-08-17 22:37:32 +00001290
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001291 arg = Py_BuildValue("(N)",
1292 _PySlice_FromIndices(i, j));
1293 }
1294 else {
1295 if (PyErr_WarnPy3k("in 3.x, __delslice__ has been "
1296 "removed; use __delitem__", 1) < 0) {
1297 Py_DECREF(func);
1298 return -1;
1299 }
1300 arg = Py_BuildValue("(nn)", i, j);
1301 }
1302 }
1303 else {
1304 if (setslicestr == NULL) {
1305 setslicestr =
1306 PyString_InternFromString("__setslice__");
1307 if (setslicestr == NULL)
1308 return -1;
1309 }
1310 func = instance_getattr(inst, setslicestr);
1311 if (func == NULL) {
1312 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1313 return -1;
1314 PyErr_Clear();
1315 if (setitemstr == NULL) {
1316 setitemstr =
1317 PyString_InternFromString("__setitem__");
1318 if (setitemstr == NULL)
1319 return -1;
1320 }
1321 func = instance_getattr(inst, setitemstr);
1322 if (func == NULL)
1323 return -1;
Thomas Wouters1d75a792000-08-17 22:37:32 +00001324
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001325 arg = Py_BuildValue("(NO)",
1326 _PySlice_FromIndices(i, j), value);
1327 }
1328 else {
1329 if (PyErr_WarnPy3k("in 3.x, __setslice__ has been "
1330 "removed; use __setitem__", 1) < 0) {
1331 Py_DECREF(func);
1332 return -1;
1333 }
1334 arg = Py_BuildValue("(nnO)", i, j, value);
1335 }
1336 }
1337 if (arg == NULL) {
1338 Py_DECREF(func);
1339 return -1;
1340 }
1341 res = PyEval_CallObject(func, arg);
1342 Py_DECREF(func);
1343 Py_DECREF(arg);
1344 if (res == NULL)
1345 return -1;
1346 Py_DECREF(res);
1347 return 0;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001348}
1349
Tim Peterscb8d3682001-05-05 21:05:01 +00001350static int
1351instance_contains(PyInstanceObject *inst, PyObject *member)
Guido van Rossumee28c3a2000-02-28 15:03:15 +00001352{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001353 static PyObject *__contains__;
1354 PyObject *func;
Tim Peterscb8d3682001-05-05 21:05:01 +00001355
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001356 /* Try __contains__ first.
1357 * If that can't be done, try iterator-based searching.
1358 */
Guido van Rossumee28c3a2000-02-28 15:03:15 +00001359
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001360 if(__contains__ == NULL) {
1361 __contains__ = PyString_InternFromString("__contains__");
1362 if(__contains__ == NULL)
1363 return -1;
1364 }
1365 func = instance_getattr(inst, __contains__);
1366 if (func) {
1367 PyObject *res;
1368 int ret;
1369 PyObject *arg = PyTuple_Pack(1, member);
1370 if(arg == NULL) {
1371 Py_DECREF(func);
1372 return -1;
1373 }
1374 res = PyEval_CallObject(func, arg);
1375 Py_DECREF(func);
1376 Py_DECREF(arg);
1377 if(res == NULL)
1378 return -1;
1379 ret = PyObject_IsTrue(res);
1380 Py_DECREF(res);
1381 return ret;
1382 }
Tim Peterscb8d3682001-05-05 21:05:01 +00001383
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001384 /* Couldn't find __contains__. */
1385 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
1386 Py_ssize_t rc;
1387 /* Assume the failure was simply due to that there is no
1388 * __contains__ attribute, and try iterating instead.
1389 */
1390 PyErr_Clear();
1391 rc = _PySequence_IterSearch((PyObject *)inst, member,
1392 PY_ITERSEARCH_CONTAINS);
1393 if (rc >= 0)
1394 return rc > 0;
1395 }
1396 return -1;
Guido van Rossumee28c3a2000-02-28 15:03:15 +00001397}
1398
Fred Drake79912472000-07-09 04:06:11 +00001399static PySequenceMethods
1400instance_as_sequence = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001401 (lenfunc)instance_length, /* sq_length */
1402 0, /* sq_concat */
1403 0, /* sq_repeat */
1404 (ssizeargfunc)instance_item, /* sq_item */
1405 (ssizessizeargfunc)instance_slice, /* sq_slice */
1406 (ssizeobjargproc)instance_ass_item, /* sq_ass_item */
1407 (ssizessizeobjargproc)instance_ass_slice,/* sq_ass_slice */
1408 (objobjproc)instance_contains, /* sq_contains */
Guido van Rossum04691fc1992-08-12 15:35:34 +00001409};
1410
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001411static PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001412generic_unary_op(PyInstanceObject *self, PyObject *methodname)
Guido van Rossum04691fc1992-08-12 15:35:34 +00001413{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001414 PyObject *func, *res;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001415
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001416 if ((func = instance_getattr(self, methodname)) == NULL)
1417 return NULL;
1418 res = PyEval_CallObject(func, (PyObject *)NULL);
1419 Py_DECREF(func);
1420 return res;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001421}
1422
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001423static PyObject *
1424generic_binary_op(PyObject *v, PyObject *w, char *opname)
Guido van Rossum03093a21994-09-28 15:51:32 +00001425{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001426 PyObject *result;
1427 PyObject *args;
1428 PyObject *func = PyObject_GetAttrString(v, opname);
1429 if (func == NULL) {
1430 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1431 return NULL;
1432 PyErr_Clear();
1433 Py_INCREF(Py_NotImplemented);
1434 return Py_NotImplemented;
1435 }
1436 args = PyTuple_Pack(1, w);
1437 if (args == NULL) {
1438 Py_DECREF(func);
1439 return NULL;
1440 }
1441 result = PyEval_CallObject(func, args);
1442 Py_DECREF(args);
1443 Py_DECREF(func);
1444 return result;
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001445}
1446
1447
1448static PyObject *coerce_obj;
1449
1450/* Try one half of a binary operator involving a class instance. */
1451static PyObject *
Tim Peters34592512002-07-11 06:23:50 +00001452half_binop(PyObject *v, PyObject *w, char *opname, binaryfunc thisfunc,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001453 int swapped)
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001454{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001455 PyObject *args;
1456 PyObject *coercefunc;
1457 PyObject *coerced = NULL;
1458 PyObject *v1;
1459 PyObject *result;
Tim Peters34592512002-07-11 06:23:50 +00001460
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001461 if (!PyInstance_Check(v)) {
1462 Py_INCREF(Py_NotImplemented);
1463 return Py_NotImplemented;
1464 }
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001465
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001466 if (coerce_obj == NULL) {
1467 coerce_obj = PyString_InternFromString("__coerce__");
1468 if (coerce_obj == NULL)
1469 return NULL;
1470 }
1471 coercefunc = PyObject_GetAttr(v, coerce_obj);
1472 if (coercefunc == NULL) {
1473 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1474 return NULL;
1475 PyErr_Clear();
1476 return generic_binary_op(v, w, opname);
1477 }
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001478
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001479 args = PyTuple_Pack(1, w);
1480 if (args == NULL) {
1481 Py_DECREF(coercefunc);
1482 return NULL;
1483 }
1484 coerced = PyEval_CallObject(coercefunc, args);
1485 Py_DECREF(args);
1486 Py_DECREF(coercefunc);
1487 if (coerced == NULL) {
1488 return NULL;
1489 }
1490 if (coerced == Py_None || coerced == Py_NotImplemented) {
1491 Py_DECREF(coerced);
1492 return generic_binary_op(v, w, opname);
1493 }
1494 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1495 Py_DECREF(coerced);
1496 PyErr_SetString(PyExc_TypeError,
1497 "coercion should return None or 2-tuple");
1498 return NULL;
1499 }
1500 v1 = PyTuple_GetItem(coerced, 0);
1501 w = PyTuple_GetItem(coerced, 1);
Benjamin Petersona72d15c2017-09-13 21:20:29 -07001502 if (Py_TYPE(v1) == Py_TYPE(v) && PyInstance_Check(v)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001503 /* prevent recursion if __coerce__ returns self as the first
1504 * argument */
1505 result = generic_binary_op(v1, w, opname);
1506 } else {
1507 if (Py_EnterRecursiveCall(" after coercion"))
1508 return NULL;
1509 if (swapped)
1510 result = (thisfunc)(w, v1);
1511 else
1512 result = (thisfunc)(v1, w);
1513 Py_LeaveRecursiveCall();
1514 }
1515 Py_DECREF(coerced);
1516 return result;
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001517}
1518
1519/* Implement a binary operator involving at least one class instance. */
1520static PyObject *
1521do_binop(PyObject *v, PyObject *w, char *opname, char *ropname,
1522 binaryfunc thisfunc)
1523{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001524 PyObject *result = half_binop(v, w, opname, thisfunc, 0);
1525 if (result == Py_NotImplemented) {
1526 Py_DECREF(result);
1527 result = half_binop(w, v, ropname, thisfunc, 1);
1528 }
1529 return result;
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001530}
1531
1532static PyObject *
1533do_binop_inplace(PyObject *v, PyObject *w, char *iopname, char *opname,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001534 char *ropname, binaryfunc thisfunc)
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001535{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001536 PyObject *result = half_binop(v, w, iopname, thisfunc, 0);
1537 if (result == Py_NotImplemented) {
1538 Py_DECREF(result);
1539 result = do_binop(v, w, opname, ropname, thisfunc);
1540 }
1541 return result;
Guido van Rossum03093a21994-09-28 15:51:32 +00001542}
1543
Guido van Rossum879c5811995-01-10 15:24:06 +00001544static int
Fred Drake79912472000-07-09 04:06:11 +00001545instance_coerce(PyObject **pv, PyObject **pw)
Guido van Rossum879c5811995-01-10 15:24:06 +00001546{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001547 PyObject *v = *pv;
1548 PyObject *w = *pw;
1549 PyObject *coercefunc;
1550 PyObject *args;
1551 PyObject *coerced;
Guido van Rossum879c5811995-01-10 15:24:06 +00001552
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001553 if (coerce_obj == NULL) {
1554 coerce_obj = PyString_InternFromString("__coerce__");
1555 if (coerce_obj == NULL)
1556 return -1;
1557 }
1558 coercefunc = PyObject_GetAttr(v, coerce_obj);
1559 if (coercefunc == NULL) {
1560 /* No __coerce__ method */
1561 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1562 return -1;
1563 PyErr_Clear();
1564 return 1;
1565 }
1566 /* Has __coerce__ method: call it */
1567 args = PyTuple_Pack(1, w);
1568 if (args == NULL) {
1569 return -1;
1570 }
1571 coerced = PyEval_CallObject(coercefunc, args);
1572 Py_DECREF(args);
1573 Py_DECREF(coercefunc);
1574 if (coerced == NULL) {
1575 /* __coerce__ call raised an exception */
1576 return -1;
1577 }
1578 if (coerced == Py_None || coerced == Py_NotImplemented) {
1579 /* __coerce__ says "I can't do it" */
1580 Py_DECREF(coerced);
1581 return 1;
1582 }
1583 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1584 /* __coerce__ return value is malformed */
1585 Py_DECREF(coerced);
1586 PyErr_SetString(PyExc_TypeError,
1587 "coercion should return None or 2-tuple");
1588 return -1;
1589 }
1590 /* __coerce__ returned two new values */
1591 *pv = PyTuple_GetItem(coerced, 0);
1592 *pw = PyTuple_GetItem(coerced, 1);
1593 Py_INCREF(*pv);
1594 Py_INCREF(*pw);
1595 Py_DECREF(coerced);
1596 return 0;
Guido van Rossum879c5811995-01-10 15:24:06 +00001597}
1598
Guido van Rossum04691fc1992-08-12 15:35:34 +00001599#define UNARY(funcname, methodname) \
Thomas Woutersc3073522000-07-23 22:09:59 +00001600static PyObject *funcname(PyInstanceObject *self) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001601 static PyObject *o; \
1602 if (o == NULL) { o = PyString_InternFromString(methodname); \
1603 if (o == NULL) return NULL; } \
1604 return generic_unary_op(self, o); \
Guido van Rossum04691fc1992-08-12 15:35:34 +00001605}
1606
Kristján Valur Jónssonabe1d482007-05-07 16:46:54 +00001607/* unary function with a fallback */
1608#define UNARY_FB(funcname, methodname, funcname_fb) \
1609static PyObject *funcname(PyInstanceObject *self) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001610 static PyObject *o; \
1611 if (o == NULL) { o = PyString_InternFromString(methodname); \
1612 if (o == NULL) return NULL; } \
1613 if (PyObject_HasAttr((PyObject*)self, o)) \
1614 return generic_unary_op(self, o); \
1615 else \
1616 return funcname_fb(self); \
Kristján Valur Jónssonabe1d482007-05-07 16:46:54 +00001617}
1618
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001619#define BINARY(f, m, n) \
1620static PyObject *f(PyObject *v, PyObject *w) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001621 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001622}
1623
1624#define BINARY_INPLACE(f, m, n) \
1625static PyObject *f(PyObject *v, PyObject *w) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001626 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1627 "__r" m "__", n); \
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001628}
1629
Guido van Rossum04691fc1992-08-12 15:35:34 +00001630UNARY(instance_neg, "__neg__")
1631UNARY(instance_pos, "__pos__")
1632UNARY(instance_abs, "__abs__")
1633
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001634BINARY(instance_or, "or", PyNumber_Or)
1635BINARY(instance_and, "and", PyNumber_And)
1636BINARY(instance_xor, "xor", PyNumber_Xor)
1637BINARY(instance_lshift, "lshift", PyNumber_Lshift)
1638BINARY(instance_rshift, "rshift", PyNumber_Rshift)
1639BINARY(instance_add, "add", PyNumber_Add)
1640BINARY(instance_sub, "sub", PyNumber_Subtract)
1641BINARY(instance_mul, "mul", PyNumber_Multiply)
1642BINARY(instance_div, "div", PyNumber_Divide)
1643BINARY(instance_mod, "mod", PyNumber_Remainder)
1644BINARY(instance_divmod, "divmod", PyNumber_Divmod)
Guido van Rossum4668b002001-08-08 05:00:18 +00001645BINARY(instance_floordiv, "floordiv", PyNumber_FloorDivide)
1646BINARY(instance_truediv, "truediv", PyNumber_TrueDivide)
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001647
1648BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr)
1649BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor)
1650BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd)
1651BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift)
1652BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift)
1653BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd)
1654BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract)
1655BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply)
1656BINARY_INPLACE(instance_idiv, "div", PyNumber_InPlaceDivide)
1657BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder)
Guido van Rossum4668b002001-08-08 05:00:18 +00001658BINARY_INPLACE(instance_ifloordiv, "floordiv", PyNumber_InPlaceFloorDivide)
1659BINARY_INPLACE(instance_itruediv, "truediv", PyNumber_InPlaceTrueDivide)
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001660
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001661/* Try a 3-way comparison, returning an int; v is an instance. Return:
1662 -2 for an exception;
1663 -1 if v < w;
1664 0 if v == w;
1665 1 if v > w;
1666 2 if this particular 3-way comparison is not implemented or undefined.
1667*/
1668static int
1669half_cmp(PyObject *v, PyObject *w)
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001670{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001671 static PyObject *cmp_obj;
1672 PyObject *args;
1673 PyObject *cmp_func;
1674 PyObject *result;
1675 long l;
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001676
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001677 assert(PyInstance_Check(v));
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001678
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001679 if (cmp_obj == NULL) {
1680 cmp_obj = PyString_InternFromString("__cmp__");
1681 if (cmp_obj == NULL)
1682 return -2;
1683 }
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001684
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001685 cmp_func = PyObject_GetAttr(v, cmp_obj);
1686 if (cmp_func == NULL) {
1687 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1688 return -2;
1689 PyErr_Clear();
1690 return 2;
1691 }
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001692
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001693 args = PyTuple_Pack(1, w);
1694 if (args == NULL) {
1695 Py_DECREF(cmp_func);
1696 return -2;
1697 }
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001698
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001699 result = PyEval_CallObject(cmp_func, args);
1700 Py_DECREF(args);
1701 Py_DECREF(cmp_func);
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001702
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001703 if (result == NULL)
1704 return -2;
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001705
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001706 if (result == Py_NotImplemented) {
1707 Py_DECREF(result);
1708 return 2;
1709 }
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001710
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001711 l = PyInt_AsLong(result);
1712 Py_DECREF(result);
1713 if (l == -1 && PyErr_Occurred()) {
1714 PyErr_SetString(PyExc_TypeError,
1715 "comparison did not return an int");
1716 return -2;
1717 }
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001718
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001719 return l < 0 ? -1 : l > 0 ? 1 : 0;
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001720}
1721
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001722/* Try a 3-way comparison, returning an int; either v or w is an instance.
1723 We first try a coercion. Return:
1724 -2 for an exception;
1725 -1 if v < w;
1726 0 if v == w;
1727 1 if v > w;
1728 2 if this particular 3-way comparison is not implemented or undefined.
1729 THIS IS ONLY CALLED FROM object.c!
1730*/
1731static int
1732instance_compare(PyObject *v, PyObject *w)
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001733{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001734 int c;
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001735
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001736 c = PyNumber_CoerceEx(&v, &w);
1737 if (c < 0)
1738 return -2;
1739 if (c == 0) {
1740 /* If neither is now an instance, use regular comparison */
1741 if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
1742 c = PyObject_Compare(v, w);
1743 Py_DECREF(v);
1744 Py_DECREF(w);
1745 if (PyErr_Occurred())
1746 return -2;
1747 return c < 0 ? -1 : c > 0 ? 1 : 0;
1748 }
1749 }
1750 else {
1751 /* The coercion didn't do anything.
1752 Treat this the same as returning v and w unchanged. */
1753 Py_INCREF(v);
1754 Py_INCREF(w);
1755 }
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001756
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001757 if (PyInstance_Check(v)) {
1758 c = half_cmp(v, w);
1759 if (c <= 1) {
1760 Py_DECREF(v);
1761 Py_DECREF(w);
1762 return c;
1763 }
1764 }
1765 if (PyInstance_Check(w)) {
1766 c = half_cmp(w, v);
1767 if (c <= 1) {
1768 Py_DECREF(v);
1769 Py_DECREF(w);
1770 if (c >= -1)
1771 c = -c;
1772 return c;
1773 }
1774 }
1775 Py_DECREF(v);
1776 Py_DECREF(w);
1777 return 2;
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001778}
1779
Guido van Rossum9bfef441993-03-29 10:43:31 +00001780static int
Fred Drake79912472000-07-09 04:06:11 +00001781instance_nonzero(PyInstanceObject *self)
Guido van Rossum04691fc1992-08-12 15:35:34 +00001782{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001783 PyObject *func, *res;
1784 long outcome;
1785 static PyObject *nonzerostr;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001786
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001787 if (nonzerostr == NULL) {
1788 nonzerostr = PyString_InternFromString("__nonzero__");
1789 if (nonzerostr == NULL)
1790 return -1;
1791 }
1792 if ((func = instance_getattr(self, nonzerostr)) == NULL) {
1793 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1794 return -1;
1795 PyErr_Clear();
1796 if (lenstr == NULL) {
1797 lenstr = PyString_InternFromString("__len__");
1798 if (lenstr == NULL)
1799 return -1;
1800 }
1801 if ((func = instance_getattr(self, lenstr)) == NULL) {
1802 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1803 return -1;
1804 PyErr_Clear();
1805 /* Fall back to the default behavior:
1806 all instances are nonzero */
1807 return 1;
1808 }
1809 }
1810 res = PyEval_CallObject(func, (PyObject *)NULL);
1811 Py_DECREF(func);
1812 if (res == NULL)
1813 return -1;
1814 if (!PyInt_Check(res)) {
1815 Py_DECREF(res);
1816 PyErr_SetString(PyExc_TypeError,
1817 "__nonzero__ should return an int");
1818 return -1;
1819 }
1820 outcome = PyInt_AsLong(res);
1821 Py_DECREF(res);
1822 if (outcome < 0) {
1823 PyErr_SetString(PyExc_ValueError,
1824 "__nonzero__ should return >= 0");
1825 return -1;
1826 }
1827 return outcome > 0;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001828}
1829
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001830static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001831instance_index(PyInstanceObject *self)
1832{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001833 PyObject *func, *res;
1834 static PyObject *indexstr = NULL;
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001835
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001836 if (indexstr == NULL) {
1837 indexstr = PyString_InternFromString("__index__");
1838 if (indexstr == NULL)
1839 return NULL;
1840 }
1841 if ((func = instance_getattr(self, indexstr)) == NULL) {
1842 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1843 return NULL;
1844 PyErr_Clear();
1845 PyErr_SetString(PyExc_TypeError,
1846 "object cannot be interpreted as an index");
1847 return NULL;
1848 }
1849 res = PyEval_CallObject(func, (PyObject *)NULL);
1850 Py_DECREF(func);
1851 return res;
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001852}
1853
1854
Guido van Rossum04691fc1992-08-12 15:35:34 +00001855UNARY(instance_invert, "__invert__")
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001856UNARY(_instance_trunc, "__trunc__")
1857
1858static PyObject *
1859instance_int(PyInstanceObject *self)
1860{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001861 PyObject *truncated;
1862 static PyObject *int_name;
1863 if (int_name == NULL) {
1864 int_name = PyString_InternFromString("__int__");
1865 if (int_name == NULL)
1866 return NULL;
1867 }
1868 if (PyObject_HasAttr((PyObject*)self, int_name))
1869 return generic_unary_op(self, int_name);
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001870
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001871 truncated = _instance_trunc(self);
1872 /* __trunc__ is specified to return an Integral type, but
1873 int() needs to return an int. */
1874 return _PyNumber_ConvertIntegralToInt(
1875 truncated,
1876 "__trunc__ returned non-Integral (type %.200s)");
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001877}
1878
Kristján Valur Jónssonabe1d482007-05-07 16:46:54 +00001879UNARY_FB(instance_long, "__long__", instance_int)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001880UNARY(instance_float, "__float__")
1881UNARY(instance_oct, "__oct__")
1882UNARY(instance_hex, "__hex__")
1883
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001884static PyObject *
1885bin_power(PyObject *v, PyObject *w)
1886{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001887 return PyNumber_Power(v, w, Py_None);
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001888}
1889
Guido van Rossum03093a21994-09-28 15:51:32 +00001890/* This version is for ternary calls only (z != None) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001891static PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001892instance_pow(PyObject *v, PyObject *w, PyObject *z)
Tim Peters34592512002-07-11 06:23:50 +00001893{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001894 if (z == Py_None) {
1895 return do_binop(v, w, "__pow__", "__rpow__", bin_power);
1896 }
1897 else {
1898 PyObject *func;
1899 PyObject *args;
1900 PyObject *result;
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001901
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001902 /* XXX Doesn't do coercions... */
1903 func = PyObject_GetAttrString(v, "__pow__");
1904 if (func == NULL)
1905 return NULL;
1906 args = PyTuple_Pack(2, w, z);
1907 if (args == NULL) {
1908 Py_DECREF(func);
1909 return NULL;
1910 }
1911 result = PyEval_CallObject(func, args);
1912 Py_DECREF(func);
1913 Py_DECREF(args);
1914 return result;
1915 }
Guido van Rossum03093a21994-09-28 15:51:32 +00001916}
1917
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001918static PyObject *
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001919bin_inplace_power(PyObject *v, PyObject *w)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001920{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001921 return PyNumber_InPlacePower(v, w, Py_None);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001922}
1923
1924
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001925static PyObject *
1926instance_ipow(PyObject *v, PyObject *w, PyObject *z)
1927{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001928 if (z == Py_None) {
1929 return do_binop_inplace(v, w, "__ipow__", "__pow__",
1930 "__rpow__", bin_inplace_power);
1931 }
1932 else {
1933 /* XXX Doesn't do coercions... */
1934 PyObject *func;
1935 PyObject *args;
1936 PyObject *result;
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001937
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001938 func = PyObject_GetAttrString(v, "__ipow__");
1939 if (func == NULL) {
1940 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1941 return NULL;
1942 PyErr_Clear();
1943 return instance_pow(v, w, z);
1944 }
1945 args = PyTuple_Pack(2, w, z);
1946 if (args == NULL) {
1947 Py_DECREF(func);
1948 return NULL;
1949 }
1950 result = PyEval_CallObject(func, args);
1951 Py_DECREF(func);
1952 Py_DECREF(args);
1953 return result;
1954 }
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001955}
1956
1957
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001958/* Map rich comparison operators to their __xx__ namesakes */
Jeremy Hylton1b0feb42001-05-11 14:48:41 +00001959#define NAME_OPS 6
1960static PyObject **name_op = NULL;
1961
Tim Peters34592512002-07-11 06:23:50 +00001962static int
Guido van Rossum0ba9e3a2001-05-22 02:33:08 +00001963init_name_op(void)
Jeremy Hylton1b0feb42001-05-11 14:48:41 +00001964{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001965 int i;
1966 char *_name_op[] = {
1967 "__lt__",
1968 "__le__",
1969 "__eq__",
1970 "__ne__",
1971 "__gt__",
1972 "__ge__",
1973 };
Jeremy Hylton1b0feb42001-05-11 14:48:41 +00001974
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001975 name_op = (PyObject **)malloc(sizeof(PyObject *) * NAME_OPS);
1976 if (name_op == NULL)
1977 return -1;
1978 for (i = 0; i < NAME_OPS; ++i) {
1979 name_op[i] = PyString_InternFromString(_name_op[i]);
1980 if (name_op[i] == NULL)
1981 return -1;
1982 }
1983 return 0;
Jeremy Hylton1b0feb42001-05-11 14:48:41 +00001984}
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001985
1986static PyObject *
1987half_richcompare(PyObject *v, PyObject *w, int op)
1988{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001989 PyObject *method;
1990 PyObject *args;
1991 PyObject *res;
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001992
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001993 assert(PyInstance_Check(v));
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001994
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001995 if (name_op == NULL) {
1996 if (init_name_op() < 0)
1997 return NULL;
1998 }
1999 /* If the instance doesn't define an __getattr__ method, use
2000 instance_getattr2 directly because it will not set an
2001 exception on failure. */
2002 if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL)
2003 method = instance_getattr2((PyInstanceObject *)v,
2004 name_op[op]);
2005 else
2006 method = PyObject_GetAttr(v, name_op[op]);
2007 if (method == NULL) {
2008 if (PyErr_Occurred()) {
2009 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2010 return NULL;
2011 PyErr_Clear();
2012 }
2013 res = Py_NotImplemented;
2014 Py_INCREF(res);
2015 return res;
2016 }
Guido van Rossum8998b4f2001-01-17 15:28:20 +00002017
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002018 args = PyTuple_Pack(1, w);
2019 if (args == NULL) {
2020 Py_DECREF(method);
2021 return NULL;
2022 }
Guido van Rossum8998b4f2001-01-17 15:28:20 +00002023
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002024 res = PyEval_CallObject(method, args);
2025 Py_DECREF(args);
2026 Py_DECREF(method);
Guido van Rossum8998b4f2001-01-17 15:28:20 +00002027
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002028 return res;
Guido van Rossum8998b4f2001-01-17 15:28:20 +00002029}
2030
Guido van Rossum8998b4f2001-01-17 15:28:20 +00002031static PyObject *
2032instance_richcompare(PyObject *v, PyObject *w, int op)
2033{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002034 PyObject *res;
Guido van Rossum8998b4f2001-01-17 15:28:20 +00002035
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002036 if (PyInstance_Check(v)) {
2037 res = half_richcompare(v, w, op);
2038 if (res != Py_NotImplemented)
2039 return res;
2040 Py_DECREF(res);
2041 }
Guido van Rossum8998b4f2001-01-17 15:28:20 +00002042
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002043 if (PyInstance_Check(w)) {
2044 res = half_richcompare(w, v, _Py_SwappedOp[op]);
2045 if (res != Py_NotImplemented)
2046 return res;
2047 Py_DECREF(res);
2048 }
Guido van Rossum8998b4f2001-01-17 15:28:20 +00002049
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002050 Py_INCREF(Py_NotImplemented);
2051 return Py_NotImplemented;
Guido van Rossum8998b4f2001-01-17 15:28:20 +00002052}
2053
Neil Schemenauer29bfc072001-01-04 01:43:46 +00002054
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002055/* Get the iterator */
2056static PyObject *
2057instance_getiter(PyInstanceObject *self)
2058{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002059 PyObject *func;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002060
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002061 if (iterstr == NULL) {
2062 iterstr = PyString_InternFromString("__iter__");
2063 if (iterstr == NULL)
2064 return NULL;
2065 }
2066 if (getitemstr == NULL) {
2067 getitemstr = PyString_InternFromString("__getitem__");
2068 if (getitemstr == NULL)
2069 return NULL;
2070 }
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002071
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002072 if ((func = instance_getattr(self, iterstr)) != NULL) {
2073 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
2074 Py_DECREF(func);
2075 if (res != NULL && !PyIter_Check(res)) {
2076 PyErr_Format(PyExc_TypeError,
2077 "__iter__ returned non-iterator "
2078 "of type '%.100s'",
Benjamin Petersona72d15c2017-09-13 21:20:29 -07002079 Py_TYPE(res)->tp_name);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002080 Py_DECREF(res);
2081 res = NULL;
2082 }
2083 return res;
2084 }
2085 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2086 return NULL;
2087 PyErr_Clear();
2088 if ((func = instance_getattr(self, getitemstr)) == NULL) {
2089 PyErr_SetString(PyExc_TypeError,
2090 "iteration over non-sequence");
2091 return NULL;
2092 }
2093 Py_DECREF(func);
2094 return PySeqIter_New((PyObject *)self);
Guido van Rossum213c7a62001-04-23 14:08:49 +00002095}
2096
2097
2098/* Call the iterator's next */
2099static PyObject *
2100instance_iternext(PyInstanceObject *self)
2101{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002102 PyObject *func;
Guido van Rossum213c7a62001-04-23 14:08:49 +00002103
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002104 if (nextstr == NULL) {
2105 nextstr = PyString_InternFromString("next");
2106 if (nextstr == NULL)
2107 return NULL;
2108 }
Guido van Rossum213c7a62001-04-23 14:08:49 +00002109
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002110 if ((func = instance_getattr(self, nextstr)) != NULL) {
2111 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
2112 Py_DECREF(func);
2113 if (res != NULL) {
2114 return res;
2115 }
2116 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
2117 PyErr_Clear();
2118 return NULL;
2119 }
2120 return NULL;
2121 }
2122 PyErr_SetString(PyExc_TypeError, "instance has no next() method");
2123 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002124}
2125
Tim Peters6d6c1a32001-08-02 04:15:00 +00002126static PyObject *
2127instance_call(PyObject *func, PyObject *arg, PyObject *kw)
2128{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002129 PyObject *res, *call = PyObject_GetAttrString(func, "__call__");
2130 if (call == NULL) {
2131 PyInstanceObject *inst = (PyInstanceObject*) func;
2132 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2133 return NULL;
2134 PyErr_Clear();
2135 PyErr_Format(PyExc_AttributeError,
2136 "%.200s instance has no __call__ method",
2137 PyString_AsString(inst->in_class->cl_name));
2138 return NULL;
2139 }
2140 /* We must check and increment the recursion depth here. Scenario:
2141 class A:
2142 pass
2143 A.__call__ = A() # that's right
2144 a = A() # ok
2145 a() # infinite recursion
2146 This bounces between instance_call() and PyObject_Call() without
2147 ever hitting eval_frame() (which has the main recursion check). */
2148 if (Py_EnterRecursiveCall(" in __call__")) {
2149 res = NULL;
2150 }
2151 else {
2152 res = PyObject_Call(call, arg, kw);
2153 Py_LeaveRecursiveCall();
2154 }
2155 Py_DECREF(call);
2156 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002157}
2158
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002159
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002160static PyNumberMethods instance_as_number = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002161 instance_add, /* nb_add */
2162 instance_sub, /* nb_subtract */
2163 instance_mul, /* nb_multiply */
2164 instance_div, /* nb_divide */
2165 instance_mod, /* nb_remainder */
2166 instance_divmod, /* nb_divmod */
2167 instance_pow, /* nb_power */
2168 (unaryfunc)instance_neg, /* nb_negative */
2169 (unaryfunc)instance_pos, /* nb_positive */
2170 (unaryfunc)instance_abs, /* nb_absolute */
2171 (inquiry)instance_nonzero, /* nb_nonzero */
2172 (unaryfunc)instance_invert, /* nb_invert */
2173 instance_lshift, /* nb_lshift */
2174 instance_rshift, /* nb_rshift */
2175 instance_and, /* nb_and */
2176 instance_xor, /* nb_xor */
2177 instance_or, /* nb_or */
2178 instance_coerce, /* nb_coerce */
2179 (unaryfunc)instance_int, /* nb_int */
2180 (unaryfunc)instance_long, /* nb_long */
2181 (unaryfunc)instance_float, /* nb_float */
2182 (unaryfunc)instance_oct, /* nb_oct */
2183 (unaryfunc)instance_hex, /* nb_hex */
2184 instance_iadd, /* nb_inplace_add */
2185 instance_isub, /* nb_inplace_subtract */
2186 instance_imul, /* nb_inplace_multiply */
2187 instance_idiv, /* nb_inplace_divide */
2188 instance_imod, /* nb_inplace_remainder */
2189 instance_ipow, /* nb_inplace_power */
2190 instance_ilshift, /* nb_inplace_lshift */
2191 instance_irshift, /* nb_inplace_rshift */
2192 instance_iand, /* nb_inplace_and */
2193 instance_ixor, /* nb_inplace_xor */
2194 instance_ior, /* nb_inplace_or */
2195 instance_floordiv, /* nb_floor_divide */
2196 instance_truediv, /* nb_true_divide */
2197 instance_ifloordiv, /* nb_inplace_floor_divide */
2198 instance_itruediv, /* nb_inplace_true_divide */
2199 (unaryfunc)instance_index, /* nb_index */
Guido van Rossum04691fc1992-08-12 15:35:34 +00002200};
2201
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002202PyTypeObject PyInstance_Type = {
Benjamin Petersona72d15c2017-09-13 21:20:29 -07002203 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002204 "instance",
2205 sizeof(PyInstanceObject),
2206 0,
2207 (destructor)instance_dealloc, /* tp_dealloc */
2208 0, /* tp_print */
2209 0, /* tp_getattr */
2210 0, /* tp_setattr */
2211 instance_compare, /* tp_compare */
2212 (reprfunc)instance_repr, /* tp_repr */
2213 &instance_as_number, /* tp_as_number */
2214 &instance_as_sequence, /* tp_as_sequence */
2215 &instance_as_mapping, /* tp_as_mapping */
2216 (hashfunc)instance_hash, /* tp_hash */
2217 instance_call, /* tp_call */
2218 (reprfunc)instance_str, /* tp_str */
2219 (getattrofunc)instance_getattr, /* tp_getattro */
2220 (setattrofunc)instance_setattr, /* tp_setattro */
2221 0, /* tp_as_buffer */
2222 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES,/*tp_flags*/
2223 instance_doc, /* tp_doc */
2224 (traverseproc)instance_traverse, /* tp_traverse */
2225 0, /* tp_clear */
2226 instance_richcompare, /* tp_richcompare */
2227 offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
2228 (getiterfunc)instance_getiter, /* tp_iter */
2229 (iternextfunc)instance_iternext, /* tp_iternext */
2230 0, /* tp_methods */
2231 0, /* tp_members */
2232 0, /* tp_getset */
2233 0, /* tp_base */
2234 0, /* tp_dict */
2235 0, /* tp_descr_get */
2236 0, /* tp_descr_set */
2237 0, /* tp_dictoffset */
2238 0, /* tp_init */
2239 0, /* tp_alloc */
2240 instance_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002241};
2242
2243
Guido van Rossum81daa321993-05-20 14:24:46 +00002244/* Instance method objects are used for two purposes:
2245 (a) as bound instance methods (returned by instancename.methodname)
2246 (b) as unbound methods (returned by ClassName.methodname)
2247 In case (b), im_self is NULL
2248*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002249
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002250PyObject *
Anthony Baxter377be112006-04-11 06:54:30 +00002251PyMethod_New(PyObject *func, PyObject *self, PyObject *klass)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002252{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002253 register PyMethodObject *im;
2254 im = free_list;
2255 if (im != NULL) {
2256 free_list = (PyMethodObject *)(im->im_self);
Martin Panter646b5282016-06-21 23:58:05 +00002257 (void)PyObject_INIT(im, &PyMethod_Type);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002258 numfree--;
2259 }
2260 else {
2261 im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
2262 if (im == NULL)
2263 return NULL;
2264 }
2265 im->im_weakreflist = NULL;
2266 Py_INCREF(func);
2267 im->im_func = func;
2268 Py_XINCREF(self);
2269 im->im_self = self;
2270 Py_XINCREF(klass);
2271 im->im_class = klass;
2272 _PyObject_GC_TRACK(im);
2273 return (PyObject *)im;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002274}
2275
Guido van Rossumf0b35e12001-09-18 03:53:24 +00002276/* Descriptors for PyMethod attributes */
2277
2278/* im_class, im_func and im_self are stored in the PyMethod object */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002279
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002280#define OFF(x) offsetof(PyMethodObject, x)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002281
Guido van Rossum6f799372001-09-20 20:46:19 +00002282static PyMemberDef instancemethod_memberlist[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002283 {"im_class", T_OBJECT, OFF(im_class), READONLY|RESTRICTED,
2284 "the class associated with a method"},
2285 {"im_func", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
2286 "the function (or other callable) implementing a method"},
2287 {"__func__", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
2288 "the function (or other callable) implementing a method"},
2289 {"im_self", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
2290 "the instance to which a method is bound; None for unbound methods"},
2291 {"__self__", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
2292 "the instance to which a method is bound; None for unbound methods"},
2293 {NULL} /* Sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00002294};
2295
Guido van Rossumbaf0f8f2003-11-22 23:55:50 +00002296/* Christian Tismer argued convincingly that method attributes should
2297 (nearly) always override function attributes.
2298 The one exception is __doc__; there's a default __doc__ which
2299 should only be used for the class, not for instances */
2300
2301static PyObject *
2302instancemethod_get_doc(PyMethodObject *im, void *context)
2303{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002304 static PyObject *docstr;
2305 if (docstr == NULL) {
2306 docstr= PyString_InternFromString("__doc__");
2307 if (docstr == NULL)
2308 return NULL;
2309 }
2310 return PyObject_GetAttr(im->im_func, docstr);
Guido van Rossumbaf0f8f2003-11-22 23:55:50 +00002311}
2312
2313static PyGetSetDef instancemethod_getset[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002314 {"__doc__", (getter)instancemethod_get_doc, NULL, NULL},
2315 {0}
Guido van Rossumbaf0f8f2003-11-22 23:55:50 +00002316};
Guido van Rossumf0b35e12001-09-18 03:53:24 +00002317
2318static PyObject *
2319instancemethod_getattro(PyObject *obj, PyObject *name)
2320{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002321 PyMethodObject *im = (PyMethodObject *)obj;
Benjamin Petersona72d15c2017-09-13 21:20:29 -07002322 PyTypeObject *tp = Py_TYPE(obj);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002323 PyObject *descr = NULL;
Guido van Rossumf0b35e12001-09-18 03:53:24 +00002324
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002325 if (PyType_HasFeature(tp, Py_TPFLAGS_HAVE_CLASS)) {
2326 if (tp->tp_dict == NULL) {
2327 if (PyType_Ready(tp) < 0)
2328 return NULL;
2329 }
2330 descr = _PyType_Lookup(tp, name);
2331 }
Guido van Rossumf0b35e12001-09-18 03:53:24 +00002332
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002333 if (descr != NULL) {
Benjamin Petersona72d15c2017-09-13 21:20:29 -07002334 descrgetfunc f = TP_DESCR_GET(Py_TYPE(descr));
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002335 if (f != NULL)
Benjamin Petersona72d15c2017-09-13 21:20:29 -07002336 return f(descr, obj, (PyObject *)Py_TYPE(obj));
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002337 else {
2338 Py_INCREF(descr);
2339 return descr;
2340 }
2341 }
Guido van Rossumf0b35e12001-09-18 03:53:24 +00002342
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002343 return PyObject_GetAttr(im->im_func, name);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002344}
2345
Guido van Rossumbea18cc2002-06-14 20:41:17 +00002346PyDoc_STRVAR(instancemethod_doc,
2347"instancemethod(function, instance, class)\n\
2348\n\
2349Create an instance method object.");
2350
2351static PyObject *
2352instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw)
2353{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002354 PyObject *func;
2355 PyObject *self;
2356 PyObject *classObj = NULL;
Guido van Rossumbea18cc2002-06-14 20:41:17 +00002357
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002358 if (!_PyArg_NoKeywords("instancemethod", kw))
2359 return NULL;
2360 if (!PyArg_UnpackTuple(args, "instancemethod", 2, 3,
2361 &func, &self, &classObj))
2362 return NULL;
2363 if (!PyCallable_Check(func)) {
2364 PyErr_SetString(PyExc_TypeError,
2365 "first argument must be callable");
2366 return NULL;
2367 }
2368 if (self == Py_None)
2369 self = NULL;
2370 if (self == NULL && classObj == NULL) {
2371 PyErr_SetString(PyExc_TypeError,
2372 "unbound methods must have non-NULL im_class");
2373 return NULL;
2374 }
Michael W. Hudsone2749cb2005-03-30 16:32:10 +00002375
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002376 return PyMethod_New(func, self, classObj);
Guido van Rossumbea18cc2002-06-14 20:41:17 +00002377}
2378
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002379static void
Fred Drake79912472000-07-09 04:06:11 +00002380instancemethod_dealloc(register PyMethodObject *im)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002381{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002382 _PyObject_GC_UNTRACK(im);
2383 if (im->im_weakreflist != NULL)
2384 PyObject_ClearWeakRefs((PyObject *)im);
2385 Py_DECREF(im->im_func);
2386 Py_XDECREF(im->im_self);
2387 Py_XDECREF(im->im_class);
2388 if (numfree < PyMethod_MAXFREELIST) {
2389 im->im_self = (PyObject *)free_list;
2390 free_list = im;
2391 numfree++;
2392 }
2393 else {
2394 PyObject_GC_Del(im);
2395 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002396}
2397
Guido van Rossumebc8c511992-09-03 20:39:51 +00002398static int
Fred Drake79912472000-07-09 04:06:11 +00002399instancemethod_compare(PyMethodObject *a, PyMethodObject *b)
Guido van Rossumebc8c511992-09-03 20:39:51 +00002400{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002401 int cmp;
2402 cmp = PyObject_Compare(a->im_func, b->im_func);
2403 if (cmp)
2404 return cmp;
Armin Rigofd01d792006-06-08 10:56:24 +00002405
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002406 if (a->im_self == b->im_self)
2407 return 0;
2408 if (a->im_self == NULL || b->im_self == NULL)
2409 return (a->im_self < b->im_self) ? -1 : 1;
2410 else
2411 return PyObject_Compare(a->im_self, b->im_self);
Guido van Rossumebc8c511992-09-03 20:39:51 +00002412}
2413
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002414static PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002415instancemethod_repr(PyMethodObject *a)
Guido van Rossum25831651993-05-19 14:50:45 +00002416{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002417 PyObject *self = a->im_self;
2418 PyObject *func = a->im_func;
2419 PyObject *klass = a->im_class;
2420 PyObject *funcname = NULL, *klassname = NULL, *result = NULL;
2421 char *sfuncname = "?", *sklassname = "?";
Tim Peters6d6c1a32001-08-02 04:15:00 +00002422
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002423 funcname = PyObject_GetAttrString(func, "__name__");
2424 if (funcname == NULL) {
2425 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2426 return NULL;
2427 PyErr_Clear();
2428 }
2429 else if (!PyString_Check(funcname)) {
2430 Py_DECREF(funcname);
2431 funcname = NULL;
2432 }
2433 else
2434 sfuncname = PyString_AS_STRING(funcname);
2435 if (klass == NULL)
2436 klassname = NULL;
2437 else {
2438 klassname = PyObject_GetAttrString(klass, "__name__");
2439 if (klassname == NULL) {
2440 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2441 return NULL;
2442 PyErr_Clear();
2443 }
2444 else if (!PyString_Check(klassname)) {
2445 Py_DECREF(klassname);
2446 klassname = NULL;
2447 }
2448 else
2449 sklassname = PyString_AS_STRING(klassname);
2450 }
2451 if (self == NULL)
2452 result = PyString_FromFormat("<unbound method %s.%s>",
2453 sklassname, sfuncname);
2454 else {
2455 /* XXX Shouldn't use repr() here! */
2456 PyObject *selfrepr = PyObject_Repr(self);
2457 if (selfrepr == NULL)
2458 goto fail;
2459 if (!PyString_Check(selfrepr)) {
2460 Py_DECREF(selfrepr);
2461 goto fail;
2462 }
2463 result = PyString_FromFormat("<bound method %s.%s of %s>",
2464 sklassname, sfuncname,
2465 PyString_AS_STRING(selfrepr));
2466 Py_DECREF(selfrepr);
2467 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002468 fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002469 Py_XDECREF(funcname);
2470 Py_XDECREF(klassname);
2471 return result;
Guido van Rossum25831651993-05-19 14:50:45 +00002472}
2473
Guido van Rossum9bfef441993-03-29 10:43:31 +00002474static long
Fred Drake79912472000-07-09 04:06:11 +00002475instancemethod_hash(PyMethodObject *a)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002476{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002477 long x, y;
2478 if (a->im_self == NULL)
2479 x = PyObject_Hash(Py_None);
2480 else
2481 x = PyObject_Hash(a->im_self);
2482 if (x == -1)
2483 return -1;
2484 y = PyObject_Hash(a->im_func);
2485 if (y == -1)
2486 return -1;
2487 x = x ^ y;
2488 if (x == -1)
2489 x = -2;
2490 return x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002491}
2492
Jeremy Hylton8caad492000-06-23 14:18:11 +00002493static int
2494instancemethod_traverse(PyMethodObject *im, visitproc visit, void *arg)
2495{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002496 Py_VISIT(im->im_func);
2497 Py_VISIT(im->im_self);
2498 Py_VISIT(im->im_class);
2499 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002500}
2501
Guido van Rossum45ec02a2002-08-19 21:43:18 +00002502static void
Anthony Baxter377be112006-04-11 06:54:30 +00002503getclassname(PyObject *klass, char *buf, int bufsize)
Guido van Rossuma15dece2001-08-24 18:48:27 +00002504{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002505 PyObject *name;
Guido van Rossuma15dece2001-08-24 18:48:27 +00002506
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002507 assert(bufsize > 1);
2508 strcpy(buf, "?"); /* Default outcome */
2509 if (klass == NULL)
2510 return;
2511 name = PyObject_GetAttrString(klass, "__name__");
2512 if (name == NULL) {
2513 /* This function cannot return an exception */
2514 PyErr_Clear();
2515 return;
2516 }
2517 if (PyString_Check(name)) {
2518 strncpy(buf, PyString_AS_STRING(name), bufsize);
2519 buf[bufsize-1] = '\0';
2520 }
2521 Py_DECREF(name);
Guido van Rossuma15dece2001-08-24 18:48:27 +00002522}
2523
Guido van Rossum45ec02a2002-08-19 21:43:18 +00002524static void
2525getinstclassname(PyObject *inst, char *buf, int bufsize)
Guido van Rossuma15dece2001-08-24 18:48:27 +00002526{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002527 PyObject *klass;
Guido van Rossuma15dece2001-08-24 18:48:27 +00002528
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002529 if (inst == NULL) {
2530 assert(bufsize > 0 && (size_t)bufsize > strlen("nothing"));
2531 strcpy(buf, "nothing");
2532 return;
2533 }
Guido van Rossuma15dece2001-08-24 18:48:27 +00002534
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002535 klass = PyObject_GetAttrString(inst, "__class__");
2536 if (klass == NULL) {
2537 /* This function cannot return an exception */
2538 PyErr_Clear();
Benjamin Petersona72d15c2017-09-13 21:20:29 -07002539 klass = (PyObject *)Py_TYPE(inst);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002540 Py_INCREF(klass);
2541 }
2542 getclassname(klass, buf, bufsize);
2543 Py_XDECREF(klass);
Guido van Rossuma15dece2001-08-24 18:48:27 +00002544}
2545
Tim Peters6d6c1a32001-08-02 04:15:00 +00002546static PyObject *
2547instancemethod_call(PyObject *func, PyObject *arg, PyObject *kw)
2548{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002549 PyObject *self = PyMethod_GET_SELF(func);
2550 PyObject *klass = PyMethod_GET_CLASS(func);
2551 PyObject *result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002552
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002553 func = PyMethod_GET_FUNCTION(func);
2554 if (self == NULL) {
2555 /* Unbound methods must be called with an instance of
2556 the class (or a derived class) as first argument */
2557 int ok;
2558 if (PyTuple_Size(arg) >= 1)
2559 self = PyTuple_GET_ITEM(arg, 0);
2560 if (self == NULL)
2561 ok = 0;
2562 else {
2563 ok = PyObject_IsInstance(self, klass);
2564 if (ok < 0)
2565 return NULL;
2566 }
2567 if (!ok) {
2568 char clsbuf[256];
2569 char instbuf[256];
2570 getclassname(klass, clsbuf, sizeof(clsbuf));
2571 getinstclassname(self, instbuf, sizeof(instbuf));
2572 PyErr_Format(PyExc_TypeError,
2573 "unbound method %s%s must be called with "
2574 "%s instance as first argument "
2575 "(got %s%s instead)",
2576 PyEval_GetFuncName(func),
2577 PyEval_GetFuncDesc(func),
2578 clsbuf,
2579 instbuf,
2580 self == NULL ? "" : " instance");
2581 return NULL;
2582 }
2583 Py_INCREF(arg);
2584 }
2585 else {
2586 Py_ssize_t argcount = PyTuple_Size(arg);
2587 PyObject *newarg = PyTuple_New(argcount + 1);
2588 int i;
2589 if (newarg == NULL)
2590 return NULL;
2591 Py_INCREF(self);
2592 PyTuple_SET_ITEM(newarg, 0, self);
2593 for (i = 0; i < argcount; i++) {
2594 PyObject *v = PyTuple_GET_ITEM(arg, i);
2595 Py_XINCREF(v);
2596 PyTuple_SET_ITEM(newarg, i+1, v);
2597 }
2598 arg = newarg;
2599 }
2600 result = PyObject_Call((PyObject *)func, arg, kw);
2601 Py_DECREF(arg);
2602 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002603}
2604
Guido van Rossum23cc2b42001-08-15 17:52:31 +00002605static PyObject *
Guido van Rossum6bae46d2003-02-11 18:43:00 +00002606instancemethod_descr_get(PyObject *meth, PyObject *obj, PyObject *cls)
Guido van Rossum23cc2b42001-08-15 17:52:31 +00002607{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002608 /* Don't rebind an already bound method, or an unbound method
2609 of a class that's not a base class of cls. */
Guido van Rossum6bae46d2003-02-11 18:43:00 +00002610
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002611 if (PyMethod_GET_SELF(meth) != NULL) {
2612 /* Already bound */
2613 Py_INCREF(meth);
2614 return meth;
2615 }
2616 /* No, it is an unbound method */
2617 if (PyMethod_GET_CLASS(meth) != NULL && cls != NULL) {
2618 /* Do subclass test. If it fails, return meth unchanged. */
2619 int ok = PyObject_IsSubclass(cls, PyMethod_GET_CLASS(meth));
2620 if (ok < 0)
2621 return NULL;
2622 if (!ok) {
2623 Py_INCREF(meth);
2624 return meth;
2625 }
2626 }
2627 /* Bind it to obj */
2628 return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj, cls);
Guido van Rossum23cc2b42001-08-15 17:52:31 +00002629}
2630
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002631PyTypeObject PyMethod_Type = {
Benjamin Petersona72d15c2017-09-13 21:20:29 -07002632 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002633 "instancemethod",
2634 sizeof(PyMethodObject),
2635 0,
2636 (destructor)instancemethod_dealloc, /* tp_dealloc */
2637 0, /* tp_print */
2638 0, /* tp_getattr */
2639 0, /* tp_setattr */
2640 (cmpfunc)instancemethod_compare, /* tp_compare */
2641 (reprfunc)instancemethod_repr, /* tp_repr */
2642 0, /* tp_as_number */
2643 0, /* tp_as_sequence */
2644 0, /* tp_as_mapping */
2645 (hashfunc)instancemethod_hash, /* tp_hash */
2646 instancemethod_call, /* tp_call */
2647 0, /* tp_str */
2648 instancemethod_getattro, /* tp_getattro */
2649 PyObject_GenericSetAttr, /* tp_setattro */
2650 0, /* tp_as_buffer */
2651 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
2652 instancemethod_doc, /* tp_doc */
2653 (traverseproc)instancemethod_traverse, /* tp_traverse */
2654 0, /* tp_clear */
2655 0, /* tp_richcompare */
2656 offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */
2657 0, /* tp_iter */
2658 0, /* tp_iternext */
2659 0, /* tp_methods */
2660 instancemethod_memberlist, /* tp_members */
2661 instancemethod_getset, /* tp_getset */
2662 0, /* tp_base */
2663 0, /* tp_dict */
2664 instancemethod_descr_get, /* tp_descr_get */
2665 0, /* tp_descr_set */
2666 0, /* tp_dictoffset */
2667 0, /* tp_init */
2668 0, /* tp_alloc */
2669 instancemethod_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002670};
Guido van Rossuma0d349f1997-08-05 02:06:53 +00002671
2672/* Clear out the free list */
2673
Christian Heimes3b718a72008-02-14 12:47:33 +00002674int
2675PyMethod_ClearFreeList(void)
Guido van Rossuma0d349f1997-08-05 02:06:53 +00002676{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002677 int freelist_size = numfree;
2678
2679 while (free_list) {
2680 PyMethodObject *im = free_list;
2681 free_list = (PyMethodObject *)(im->im_self);
2682 PyObject_GC_Del(im);
2683 numfree--;
2684 }
2685 assert(numfree == 0);
2686 return freelist_size;
Christian Heimes3b718a72008-02-14 12:47:33 +00002687}
2688
2689void
2690PyMethod_Fini(void)
2691{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002692 (void)PyMethod_ClearFreeList();
Guido van Rossuma0d349f1997-08-05 02:06:53 +00002693}