blob: 89d2d4f98138703c819ff0386b12a42575a7b6f6 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
Guido van Rossum6f799372001-09-20 20:46:19 +00008static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00009 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
10 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
11 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000017 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
18 {0}
19};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000020
Guido van Rossumc0b618a1997-05-02 03:12:38 +000021static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000022type_name(PyTypeObject *type, void *context)
23{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +000024 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +000025
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000026 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +000027 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +000028
Georg Brandlc255c7b2006-02-20 22:27:28 +000029 Py_INCREF(et->ht_name);
30 return et->ht_name;
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000031 }
32 else {
33 s = strrchr(type->tp_name, '.');
34 if (s == NULL)
35 s = type->tp_name;
36 else
37 s++;
38 return PyString_FromString(s);
39 }
Guido van Rossumc3542212001-08-16 09:18:56 +000040}
41
Michael W. Hudson98bbc492002-11-26 14:47:27 +000042static int
43type_set_name(PyTypeObject *type, PyObject *value, void *context)
44{
Guido van Rossume5c691a2003-03-07 15:13:17 +000045 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000046
47 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
48 PyErr_Format(PyExc_TypeError,
49 "can't set %s.__name__", type->tp_name);
50 return -1;
51 }
52 if (!value) {
53 PyErr_Format(PyExc_TypeError,
54 "can't delete %s.__name__", type->tp_name);
55 return -1;
56 }
57 if (!PyString_Check(value)) {
58 PyErr_Format(PyExc_TypeError,
59 "can only assign string to %s.__name__, not '%s'",
60 type->tp_name, value->ob_type->tp_name);
61 return -1;
62 }
Tim Petersea7f75d2002-12-07 21:39:16 +000063 if (strlen(PyString_AS_STRING(value))
Michael W. Hudson98bbc492002-11-26 14:47:27 +000064 != (size_t)PyString_GET_SIZE(value)) {
65 PyErr_Format(PyExc_ValueError,
66 "__name__ must not contain null bytes");
67 return -1;
68 }
69
Guido van Rossume5c691a2003-03-07 15:13:17 +000070 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000071
72 Py_INCREF(value);
73
Georg Brandlc255c7b2006-02-20 22:27:28 +000074 Py_DECREF(et->ht_name);
75 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000076
77 type->tp_name = PyString_AS_STRING(value);
78
79 return 0;
80}
81
Guido van Rossumc3542212001-08-16 09:18:56 +000082static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000083type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000084{
Guido van Rossumc3542212001-08-16 09:18:56 +000085 PyObject *mod;
86 char *s;
87
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000088 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
89 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Anthony Baxter3ecdb252004-06-11 14:41:18 +000090 if (!mod) {
91 PyErr_Format(PyExc_AttributeError, "__module__");
92 return 0;
93 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000094 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +000095 return mod;
96 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000097 else {
98 s = strrchr(type->tp_name, '.');
99 if (s != NULL)
100 return PyString_FromStringAndSize(
Armin Rigo7ccbca92006-10-04 12:17:45 +0000101 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000102 return PyString_FromString("__builtin__");
103 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000104}
105
Guido van Rossum3926a632001-09-25 16:25:58 +0000106static int
107type_set_module(PyTypeObject *type, PyObject *value, void *context)
108{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000109 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000110 PyErr_Format(PyExc_TypeError,
111 "can't set %s.__module__", type->tp_name);
112 return -1;
113 }
114 if (!value) {
115 PyErr_Format(PyExc_TypeError,
116 "can't delete %s.__module__", type->tp_name);
117 return -1;
118 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000119
Guido van Rossum3926a632001-09-25 16:25:58 +0000120 return PyDict_SetItemString(type->tp_dict, "__module__", value);
121}
122
Tim Peters6d6c1a32001-08-02 04:15:00 +0000123static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000124type_get_bases(PyTypeObject *type, void *context)
125{
126 Py_INCREF(type->tp_bases);
127 return type->tp_bases;
128}
129
130static PyTypeObject *best_base(PyObject *);
131static int mro_internal(PyTypeObject *);
132static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
133static int add_subclass(PyTypeObject*, PyTypeObject*);
134static void remove_subclass(PyTypeObject *, PyTypeObject *);
135static void update_all_slots(PyTypeObject *);
136
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000137typedef int (*update_callback)(PyTypeObject *, void *);
138static int update_subclasses(PyTypeObject *type, PyObject *name,
139 update_callback callback, void *data);
140static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
141 update_callback callback, void *data);
142
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000143static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000144mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000145{
146 PyTypeObject *subclass;
147 PyObject *ref, *subclasses, *old_mro;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000148 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000149
150 subclasses = type->tp_subclasses;
151 if (subclasses == NULL)
152 return 0;
153 assert(PyList_Check(subclasses));
154 n = PyList_GET_SIZE(subclasses);
155 for (i = 0; i < n; i++) {
156 ref = PyList_GET_ITEM(subclasses, i);
157 assert(PyWeakref_CheckRef(ref));
158 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
159 assert(subclass != NULL);
160 if ((PyObject *)subclass == Py_None)
161 continue;
162 assert(PyType_Check(subclass));
163 old_mro = subclass->tp_mro;
164 if (mro_internal(subclass) < 0) {
165 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000166 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000167 }
168 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000169 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000170 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000171 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000172 if (!tuple)
173 return -1;
174 if (PyList_Append(temp, tuple) < 0)
175 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000176 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000177 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000178 if (mro_subclasses(subclass, temp) < 0)
179 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000180 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000181 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000182}
183
184static int
185type_set_bases(PyTypeObject *type, PyObject *value, void *context)
186{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000187 Py_ssize_t i;
188 int r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000189 PyObject *ob, *temp;
Armin Rigoc0ba52d2007-04-19 14:44:48 +0000190 PyTypeObject *new_base, *old_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000191 PyObject *old_bases, *old_mro;
192
193 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
194 PyErr_Format(PyExc_TypeError,
195 "can't set %s.__bases__", type->tp_name);
196 return -1;
197 }
198 if (!value) {
199 PyErr_Format(PyExc_TypeError,
200 "can't delete %s.__bases__", type->tp_name);
201 return -1;
202 }
203 if (!PyTuple_Check(value)) {
204 PyErr_Format(PyExc_TypeError,
205 "can only assign tuple to %s.__bases__, not %s",
206 type->tp_name, value->ob_type->tp_name);
207 return -1;
208 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000209 if (PyTuple_GET_SIZE(value) == 0) {
210 PyErr_Format(PyExc_TypeError,
211 "can only assign non-empty tuple to %s.__bases__, not ()",
212 type->tp_name);
213 return -1;
214 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000215 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
216 ob = PyTuple_GET_ITEM(value, i);
217 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
218 PyErr_Format(
219 PyExc_TypeError,
220 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
221 type->tp_name, ob->ob_type->tp_name);
222 return -1;
223 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000224 if (PyType_Check(ob)) {
225 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
226 PyErr_SetString(PyExc_TypeError,
227 "a __bases__ item causes an inheritance cycle");
228 return -1;
229 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000230 }
231 }
232
233 new_base = best_base(value);
234
235 if (!new_base) {
236 return -1;
237 }
238
239 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
240 return -1;
241
242 Py_INCREF(new_base);
243 Py_INCREF(value);
244
245 old_bases = type->tp_bases;
246 old_base = type->tp_base;
247 old_mro = type->tp_mro;
248
249 type->tp_bases = value;
250 type->tp_base = new_base;
251
252 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000253 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000254 }
255
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000256 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000257 if (!temp)
258 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000259
260 r = mro_subclasses(type, temp);
261
262 if (r < 0) {
263 for (i = 0; i < PyList_Size(temp); i++) {
264 PyTypeObject* cls;
265 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000266 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
267 "", 2, 2, &cls, &mro);
Armin Rigo796fc992007-04-19 14:56:48 +0000268 Py_INCREF(mro);
269 ob = cls->tp_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000270 cls->tp_mro = mro;
Armin Rigo796fc992007-04-19 14:56:48 +0000271 Py_DECREF(ob);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000272 }
273 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000274 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000275 }
276
277 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000278
279 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000280 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000281 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000282 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000283
284 /* for now, sod that: just remove from all old_bases,
285 add to all new_bases */
286
287 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
288 ob = PyTuple_GET_ITEM(old_bases, i);
289 if (PyType_Check(ob)) {
290 remove_subclass(
291 (PyTypeObject*)ob, type);
292 }
293 }
294
295 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
296 ob = PyTuple_GET_ITEM(value, i);
297 if (PyType_Check(ob)) {
298 if (add_subclass((PyTypeObject*)ob, type) < 0)
299 r = -1;
300 }
301 }
302
303 update_all_slots(type);
304
305 Py_DECREF(old_bases);
306 Py_DECREF(old_base);
307 Py_DECREF(old_mro);
308
309 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000310
311 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000312 Py_DECREF(type->tp_bases);
313 Py_DECREF(type->tp_base);
314 if (type->tp_mro != old_mro) {
315 Py_DECREF(type->tp_mro);
316 }
317
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000318 type->tp_bases = old_bases;
319 type->tp_base = old_base;
320 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000321
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000322 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000323}
324
325static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000326type_dict(PyTypeObject *type, void *context)
327{
328 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000329 Py_INCREF(Py_None);
330 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000331 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000332 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000333}
334
Tim Peters24008312002-03-17 18:56:20 +0000335static PyObject *
336type_get_doc(PyTypeObject *type, void *context)
337{
338 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000339 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000340 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000341 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000342 if (result == NULL) {
343 result = Py_None;
344 Py_INCREF(result);
345 }
346 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000347 result = result->ob_type->tp_descr_get(result, NULL,
348 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000349 }
350 else {
351 Py_INCREF(result);
352 }
Tim Peters24008312002-03-17 18:56:20 +0000353 return result;
354}
355
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000356static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000357 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
358 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000359 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000360 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000361 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000362 {0}
363};
364
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000365static int
366type_compare(PyObject *v, PyObject *w)
367{
368 /* This is called with type objects only. So we
369 can just compare the addresses. */
370 Py_uintptr_t vv = (Py_uintptr_t)v;
371 Py_uintptr_t ww = (Py_uintptr_t)w;
372 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
373}
374
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000375static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000376type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000377{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000378 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000379 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000380
381 mod = type_module(type, NULL);
382 if (mod == NULL)
383 PyErr_Clear();
384 else if (!PyString_Check(mod)) {
385 Py_DECREF(mod);
386 mod = NULL;
387 }
388 name = type_name(type, NULL);
389 if (name == NULL)
390 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000391
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000392 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
393 kind = "class";
394 else
395 kind = "type";
396
Barry Warsaw7ce36942001-08-24 18:34:26 +0000397 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000398 rtn = PyString_FromFormat("<%s '%s.%s'>",
399 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000400 PyString_AS_STRING(mod),
401 PyString_AS_STRING(name));
402 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000403 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000404 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000405
Guido van Rossumc3542212001-08-16 09:18:56 +0000406 Py_XDECREF(mod);
407 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000408 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000409}
410
Tim Peters6d6c1a32001-08-02 04:15:00 +0000411static PyObject *
412type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
413{
414 PyObject *obj;
415
416 if (type->tp_new == NULL) {
417 PyErr_Format(PyExc_TypeError,
418 "cannot create '%.100s' instances",
419 type->tp_name);
420 return NULL;
421 }
422
Tim Peters3f996e72001-09-13 19:18:27 +0000423 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000424 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000425 /* Ugly exception: when the call was type(something),
426 don't call tp_init on the result. */
427 if (type == &PyType_Type &&
428 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
429 (kwds == NULL ||
430 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
431 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000432 /* If the returned object is not an instance of type,
433 it won't be initialized. */
434 if (!PyType_IsSubtype(obj->ob_type, type))
435 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000436 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000437 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
438 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000439 type->tp_init(obj, args, kwds) < 0) {
440 Py_DECREF(obj);
441 obj = NULL;
442 }
443 }
444 return obj;
445}
446
447PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000448PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000449{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000450 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000451 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
452 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000453
454 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000455 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000456 else
Anthony Baxtera6286212006-04-11 07:42:36 +0000457 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000458
Neil Schemenauerc806c882001-08-29 23:54:54 +0000459 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000460 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000461
Neil Schemenauerc806c882001-08-29 23:54:54 +0000462 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000463
Tim Peters6d6c1a32001-08-02 04:15:00 +0000464 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
465 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000466
Tim Peters6d6c1a32001-08-02 04:15:00 +0000467 if (type->tp_itemsize == 0)
468 PyObject_INIT(obj, type);
469 else
470 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000471
Tim Peters6d6c1a32001-08-02 04:15:00 +0000472 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000473 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000474 return obj;
475}
476
477PyObject *
478PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
479{
480 return type->tp_alloc(type, 0);
481}
482
Guido van Rossum9475a232001-10-05 20:51:39 +0000483/* Helpers for subtyping */
484
485static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000486traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
487{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000488 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000489 PyMemberDef *mp;
490
491 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000492 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000493 for (i = 0; i < n; i++, mp++) {
494 if (mp->type == T_OBJECT_EX) {
495 char *addr = (char *)self + mp->offset;
496 PyObject *obj = *(PyObject **)addr;
497 if (obj != NULL) {
498 int err = visit(obj, arg);
499 if (err)
500 return err;
501 }
502 }
503 }
504 return 0;
505}
506
507static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000508subtype_traverse(PyObject *self, visitproc visit, void *arg)
509{
510 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000511 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000512
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000513 /* Find the nearest base with a different tp_traverse,
514 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000515 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000516 base = type;
517 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
518 if (base->ob_size) {
519 int err = traverse_slots(base, self, visit, arg);
520 if (err)
521 return err;
522 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000523 base = base->tp_base;
524 assert(base);
525 }
526
527 if (type->tp_dictoffset != base->tp_dictoffset) {
528 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Woutersc6e55062006-04-15 21:47:09 +0000529 if (dictptr && *dictptr)
530 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000531 }
532
Thomas Woutersc6e55062006-04-15 21:47:09 +0000533 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000534 /* For a heaptype, the instances count as references
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000535 to the type. Traverse the type so the collector
Guido van Rossuma3862092002-06-10 15:24:42 +0000536 can find cycles involving this link. */
Thomas Woutersc6e55062006-04-15 21:47:09 +0000537 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000538
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000539 if (basetraverse)
540 return basetraverse(self, visit, arg);
541 return 0;
542}
543
544static void
545clear_slots(PyTypeObject *type, PyObject *self)
546{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000547 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000548 PyMemberDef *mp;
549
550 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000551 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000552 for (i = 0; i < n; i++, mp++) {
553 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
554 char *addr = (char *)self + mp->offset;
555 PyObject *obj = *(PyObject **)addr;
556 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000557 *(PyObject **)addr = NULL;
Thomas Woutersedf17d82006-04-15 17:28:34 +0000558 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000559 }
560 }
561 }
562}
563
564static int
565subtype_clear(PyObject *self)
566{
567 PyTypeObject *type, *base;
568 inquiry baseclear;
569
570 /* Find the nearest base with a different tp_clear
571 and clear slots while we're at it */
572 type = self->ob_type;
573 base = type;
574 while ((baseclear = base->tp_clear) == subtype_clear) {
575 if (base->ob_size)
576 clear_slots(base, self);
577 base = base->tp_base;
578 assert(base);
579 }
580
Guido van Rossuma3862092002-06-10 15:24:42 +0000581 /* There's no need to clear the instance dict (if any);
582 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000583
584 if (baseclear)
585 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000586 return 0;
587}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000588
589static void
590subtype_dealloc(PyObject *self)
591{
Guido van Rossum14227b42001-12-06 02:35:58 +0000592 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000593 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000594
Guido van Rossum22b13872002-08-06 21:41:44 +0000595 /* Extract the type; we expect it to be a heap type */
596 type = self->ob_type;
597 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000598
Guido van Rossum22b13872002-08-06 21:41:44 +0000599 /* Test whether the type has GC exactly once */
600
601 if (!PyType_IS_GC(type)) {
602 /* It's really rare to find a dynamic type that doesn't have
603 GC; it can only happen when deriving from 'object' and not
604 adding any slots or instance variables. This allows
605 certain simplifications: there's no need to call
606 clear_slots(), or DECREF the dict, or clear weakrefs. */
607
608 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000609 if (type->tp_del) {
610 type->tp_del(self);
611 if (self->ob_refcnt > 0)
612 return;
613 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000614
615 /* Find the nearest base with a different tp_dealloc */
616 base = type;
617 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
618 assert(base->ob_size == 0);
619 base = base->tp_base;
620 assert(base);
621 }
622
623 /* Call the base tp_dealloc() */
624 assert(basedealloc);
625 basedealloc(self);
626
627 /* Can't reference self beyond this point */
628 Py_DECREF(type);
629
630 /* Done */
631 return;
632 }
633
634 /* We get here only if the type has GC */
635
636 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000637 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000638 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000639 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000640 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000641 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000642 /* DO NOT restore GC tracking at this point. weakref callbacks
643 * (if any, and whether directly here or indirectly in something we
644 * call) may trigger GC, and if self is tracked at that point, it
645 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000646 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000647
Guido van Rossum59195fd2003-06-13 20:54:40 +0000648 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000649 base = type;
650 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000651 base = base->tp_base;
652 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000653 }
654
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000655 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000656 the finalizer (__del__), clearing slots, or clearing the instance
657 dict. */
658
Guido van Rossum1987c662003-05-29 14:29:23 +0000659 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
660 PyObject_ClearWeakRefs(self);
661
662 /* Maybe call finalizer; exit early if resurrected */
663 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000664 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000665 type->tp_del(self);
666 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000667 goto endlabel; /* resurrected */
668 else
669 _PyObject_GC_UNTRACK(self);
Brett Cannonf5bee302007-01-23 23:21:22 +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 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
675 /* Modeled after GET_WEAKREFS_LISTPTR() */
676 PyWeakReference **list = (PyWeakReference **) \
677 PyObject_GET_WEAKREFS_LISTPTR(self);
678 while (*list)
679 _PyWeakref_ClearRef(*list);
680 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000681 }
682
Guido van Rossum59195fd2003-06-13 20:54:40 +0000683 /* Clear slots up to the nearest base with a different tp_dealloc */
684 base = type;
685 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
686 if (base->ob_size)
687 clear_slots(base, self);
688 base = base->tp_base;
689 assert(base);
690 }
691
Tim Peters6d6c1a32001-08-02 04:15:00 +0000692 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000693 if (type->tp_dictoffset && !base->tp_dictoffset) {
694 PyObject **dictptr = _PyObject_GetDictPtr(self);
695 if (dictptr != NULL) {
696 PyObject *dict = *dictptr;
697 if (dict != NULL) {
698 Py_DECREF(dict);
699 *dictptr = NULL;
700 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000701 }
702 }
703
Tim Peters0bd743c2003-11-13 22:50:00 +0000704 /* Call the base tp_dealloc(); first retrack self if
705 * basedealloc knows about gc.
706 */
707 if (PyType_IS_GC(base))
708 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000709 assert(basedealloc);
710 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000711
712 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000713 Py_DECREF(type);
714
Guido van Rossum0906e072002-08-07 20:42:09 +0000715 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000716 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000717 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000718 --_PyTrash_delete_nesting;
719
720 /* Explanation of the weirdness around the trashcan macros:
721
722 Q. What do the trashcan macros do?
723
724 A. Read the comment titled "Trashcan mechanism" in object.h.
725 For one, this explains why there must be a call to GC-untrack
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000726 before the trashcan begin macro. Without understanding the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000727 trashcan code, the answers to the following questions don't make
728 sense.
729
730 Q. Why do we GC-untrack before the trashcan and then immediately
731 GC-track again afterward?
732
733 A. In the case that the base class is GC-aware, the base class
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000734 probably GC-untracks the object. If it does that using the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000735 UNTRACK macro, this will crash when the object is already
736 untracked. Because we don't know what the base class does, the
737 only safe thing is to make sure the object is tracked when we
738 call the base class dealloc. But... The trashcan begin macro
739 requires that the object is *untracked* before it is called. So
740 the dance becomes:
741
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000742 GC untrack
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000743 trashcan begin
744 GC track
745
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000746 Q. Why did the last question say "immediately GC-track again"?
747 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +0000748
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000749 A. Because the code *used* to re-track immediately. Bad Idea.
750 self has a refcount of 0, and if gc ever gets its hands on it
751 (which can happen if any weakref callback gets invoked), it
752 looks like trash to gc too, and gc also tries to delete self
753 then. But we're already deleting self. Double dealloction is
754 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +0000755
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000756 Q. Why the bizarre (net-zero) manipulation of
757 _PyTrash_delete_nesting around the trashcan macros?
758
759 A. Some base classes (e.g. list) also use the trashcan mechanism.
760 The following scenario used to be possible:
761
762 - suppose the trashcan level is one below the trashcan limit
763
764 - subtype_dealloc() is called
765
766 - the trashcan limit is not yet reached, so the trashcan level
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000767 is incremented and the code between trashcan begin and end is
768 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000769
770 - this destroys much of the object's contents, including its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000771 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000772
773 - basedealloc() is called; this is really list_dealloc(), or
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000774 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000775
776 - the trashcan limit is now reached, so the object is put on the
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000777 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000778
779 - basedealloc() returns
780
781 - subtype_dealloc() decrefs the object's type
782
783 - subtype_dealloc() returns
784
785 - later, the trashcan code starts deleting the objects from its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000786 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000787
788 - subtype_dealloc() is called *AGAIN* for the same object
789
790 - at the very least (if the destroyed slots and __dict__ don't
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000791 cause problems) the object's type gets decref'ed a second
792 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000793
794 The remedy is to make sure that if the code between trashcan
795 begin and end in subtype_dealloc() is called, the code between
796 trashcan begin and end in basedealloc() will also be called.
797 This is done by decrementing the level after passing into the
798 trashcan block, and incrementing it just before leaving the
799 block.
800
801 But now it's possible that a chain of objects consisting solely
802 of objects whose deallocator is subtype_dealloc() will defeat
803 the trashcan mechanism completely: the decremented level means
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000804 that the effective level never reaches the limit. Therefore, we
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000805 *increment* the level *before* entering the trashcan block, and
806 matchingly decrement it after leaving. This means the trashcan
807 code will trigger a little early, but that's no big deal.
808
809 Q. Are there any live examples of code in need of all this
810 complexity?
811
812 A. Yes. See SF bug 668433 for code that crashed (when Python was
813 compiled in debug mode) before the trashcan level manipulations
814 were added. For more discussion, see SF patches 581742, 575073
815 and bug 574207.
816 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000817}
818
Jeremy Hylton938ace62002-07-17 16:30:39 +0000819static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000820
Tim Peters6d6c1a32001-08-02 04:15:00 +0000821/* type test with subclassing support */
822
823int
824PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
825{
826 PyObject *mro;
827
Guido van Rossum9478d072001-09-07 18:52:13 +0000828 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
829 return b == a || b == &PyBaseObject_Type;
830
Tim Peters6d6c1a32001-08-02 04:15:00 +0000831 mro = a->tp_mro;
832 if (mro != NULL) {
833 /* Deal with multiple inheritance without recursion
834 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000835 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000836 assert(PyTuple_Check(mro));
837 n = PyTuple_GET_SIZE(mro);
838 for (i = 0; i < n; i++) {
839 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
840 return 1;
841 }
842 return 0;
843 }
844 else {
845 /* a is not completely initilized yet; follow tp_base */
846 do {
847 if (a == b)
848 return 1;
849 a = a->tp_base;
850 } while (a != NULL);
851 return b == &PyBaseObject_Type;
852 }
853}
854
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000855/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000856 without looking in the instance dictionary
857 (so we can't use PyObject_GetAttr) but still binding
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000858 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +0000859 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000860 static variable used to cache the interned Python string.
861
862 Two variants:
863
864 - lookup_maybe() returns NULL without raising an exception
865 when the _PyType_Lookup() call fails;
866
867 - lookup_method() always raises an exception upon errors.
868*/
Guido van Rossum60718732001-08-28 17:47:51 +0000869
870static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000871lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000872{
873 PyObject *res;
874
875 if (*attrobj == NULL) {
876 *attrobj = PyString_InternFromString(attrstr);
877 if (*attrobj == NULL)
878 return NULL;
879 }
880 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000881 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000882 descrgetfunc f;
883 if ((f = res->ob_type->tp_descr_get) == NULL)
884 Py_INCREF(res);
885 else
886 res = f(res, self, (PyObject *)(self->ob_type));
887 }
888 return res;
889}
890
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000891static PyObject *
892lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
893{
894 PyObject *res = lookup_maybe(self, attrstr, attrobj);
895 if (res == NULL && !PyErr_Occurred())
896 PyErr_SetObject(PyExc_AttributeError, *attrobj);
897 return res;
898}
899
Guido van Rossum2730b132001-08-28 18:22:14 +0000900/* A variation of PyObject_CallMethod that uses lookup_method()
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000901 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +0000902 as lookup_method to cache the interned name string object. */
903
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000904static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000905call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
906{
907 va_list va;
908 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000909 va_start(va, format);
910
Guido van Rossumda21c012001-10-03 00:50:18 +0000911 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000912 if (func == NULL) {
913 va_end(va);
914 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000915 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000916 return NULL;
917 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000918
919 if (format && *format)
920 args = Py_VaBuildValue(format, va);
921 else
922 args = PyTuple_New(0);
923
924 va_end(va);
925
926 if (args == NULL)
927 return NULL;
928
929 assert(PyTuple_Check(args));
930 retval = PyObject_Call(func, args, NULL);
931
932 Py_DECREF(args);
933 Py_DECREF(func);
934
935 return retval;
936}
937
938/* Clone of call_method() that returns NotImplemented when the lookup fails. */
939
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000940static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000941call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
942{
943 va_list va;
944 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000945 va_start(va, format);
946
Guido van Rossumda21c012001-10-03 00:50:18 +0000947 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000948 if (func == NULL) {
949 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000950 if (!PyErr_Occurred()) {
951 Py_INCREF(Py_NotImplemented);
952 return Py_NotImplemented;
953 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000954 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000955 }
956
957 if (format && *format)
958 args = Py_VaBuildValue(format, va);
959 else
960 args = PyTuple_New(0);
961
962 va_end(va);
963
Guido van Rossum717ce002001-09-14 16:58:08 +0000964 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000965 return NULL;
966
Guido van Rossum717ce002001-09-14 16:58:08 +0000967 assert(PyTuple_Check(args));
968 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000969
970 Py_DECREF(args);
971 Py_DECREF(func);
972
973 return retval;
974}
975
Tim Petersa91e9642001-11-14 23:32:33 +0000976static int
977fill_classic_mro(PyObject *mro, PyObject *cls)
978{
979 PyObject *bases, *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000980 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +0000981
982 assert(PyList_Check(mro));
983 assert(PyClass_Check(cls));
984 i = PySequence_Contains(mro, cls);
985 if (i < 0)
986 return -1;
987 if (!i) {
988 if (PyList_Append(mro, cls) < 0)
989 return -1;
990 }
991 bases = ((PyClassObject *)cls)->cl_bases;
992 assert(bases && PyTuple_Check(bases));
993 n = PyTuple_GET_SIZE(bases);
994 for (i = 0; i < n; i++) {
995 base = PyTuple_GET_ITEM(bases, i);
996 if (fill_classic_mro(mro, base) < 0)
997 return -1;
998 }
999 return 0;
1000}
1001
1002static PyObject *
1003classic_mro(PyObject *cls)
1004{
1005 PyObject *mro;
1006
1007 assert(PyClass_Check(cls));
1008 mro = PyList_New(0);
1009 if (mro != NULL) {
1010 if (fill_classic_mro(mro, cls) == 0)
1011 return mro;
1012 Py_DECREF(mro);
1013 }
1014 return NULL;
1015}
1016
Tim Petersea7f75d2002-12-07 21:39:16 +00001017/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001018 Method resolution order algorithm C3 described in
1019 "A Monotonic Superclass Linearization for Dylan",
1020 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001021 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001022 (OOPSLA 1996)
1023
Guido van Rossum98f33732002-11-25 21:36:54 +00001024 Some notes about the rules implied by C3:
1025
Tim Petersea7f75d2002-12-07 21:39:16 +00001026 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001027 It isn't legal to repeat a class in a list of base classes.
1028
1029 The next three properties are the 3 constraints in "C3".
1030
Tim Petersea7f75d2002-12-07 21:39:16 +00001031 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001032 If A precedes B in C's MRO, then A will precede B in the MRO of all
1033 subclasses of C.
1034
1035 Monotonicity.
1036 The MRO of a class must be an extension without reordering of the
1037 MRO of each of its superclasses.
1038
1039 Extended Precedence Graph (EPG).
1040 Linearization is consistent if there is a path in the EPG from
1041 each class to all its successors in the linearization. See
1042 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001043 */
1044
Tim Petersea7f75d2002-12-07 21:39:16 +00001045static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001046tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001047 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +00001048 size = PyList_GET_SIZE(list);
1049
1050 for (j = whence+1; j < size; j++) {
1051 if (PyList_GET_ITEM(list, j) == o)
1052 return 1;
1053 }
1054 return 0;
1055}
1056
Guido van Rossum98f33732002-11-25 21:36:54 +00001057static PyObject *
1058class_name(PyObject *cls)
1059{
1060 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1061 if (name == NULL) {
1062 PyErr_Clear();
1063 Py_XDECREF(name);
1064 name = PyObject_Repr(cls);
1065 }
1066 if (name == NULL)
1067 return NULL;
1068 if (!PyString_Check(name)) {
1069 Py_DECREF(name);
1070 return NULL;
1071 }
1072 return name;
1073}
1074
1075static int
1076check_duplicates(PyObject *list)
1077{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001078 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001079 /* Let's use a quadratic time algorithm,
1080 assuming that the bases lists is short.
1081 */
1082 n = PyList_GET_SIZE(list);
1083 for (i = 0; i < n; i++) {
1084 PyObject *o = PyList_GET_ITEM(list, i);
1085 for (j = i + 1; j < n; j++) {
1086 if (PyList_GET_ITEM(list, j) == o) {
1087 o = class_name(o);
1088 PyErr_Format(PyExc_TypeError,
1089 "duplicate base class %s",
1090 o ? PyString_AS_STRING(o) : "?");
1091 Py_XDECREF(o);
1092 return -1;
1093 }
1094 }
1095 }
1096 return 0;
1097}
1098
1099/* Raise a TypeError for an MRO order disagreement.
1100
1101 It's hard to produce a good error message. In the absence of better
1102 insight into error reporting, report the classes that were candidates
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001103 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001104 order in which they should be put in the MRO, but it's hard to
1105 diagnose what constraint can't be satisfied.
1106*/
1107
1108static void
1109set_mro_error(PyObject *to_merge, int *remain)
1110{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001111 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001112 char buf[1000];
1113 PyObject *k, *v;
1114 PyObject *set = PyDict_New();
Georg Brandl5c170fd2006-03-17 19:03:25 +00001115 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001116
1117 to_merge_size = PyList_GET_SIZE(to_merge);
1118 for (i = 0; i < to_merge_size; i++) {
1119 PyObject *L = PyList_GET_ITEM(to_merge, i);
1120 if (remain[i] < PyList_GET_SIZE(L)) {
1121 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Georg Brandl5c170fd2006-03-17 19:03:25 +00001122 if (PyDict_SetItem(set, c, Py_None) < 0) {
1123 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001124 return;
Georg Brandl5c170fd2006-03-17 19:03:25 +00001125 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001126 }
1127 }
1128 n = PyDict_Size(set);
1129
Raymond Hettingerf394df42003-04-06 19:13:41 +00001130 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1131consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001132 i = 0;
Skip Montanaro429433b2006-04-18 00:35:43 +00001133 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001134 PyObject *name = class_name(k);
1135 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1136 name ? PyString_AS_STRING(name) : "?");
1137 Py_XDECREF(name);
Skip Montanaro429433b2006-04-18 00:35:43 +00001138 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001139 buf[off++] = ',';
1140 buf[off] = '\0';
1141 }
1142 }
1143 PyErr_SetString(PyExc_TypeError, buf);
1144 Py_DECREF(set);
1145}
1146
Tim Petersea7f75d2002-12-07 21:39:16 +00001147static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001148pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001149 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001150 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001151 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001152
Guido van Rossum1f121312002-11-14 19:49:16 +00001153 to_merge_size = PyList_GET_SIZE(to_merge);
1154
Guido van Rossum98f33732002-11-25 21:36:54 +00001155 /* remain stores an index into each sublist of to_merge.
1156 remain[i] is the index of the next base in to_merge[i]
1157 that is not included in acc.
1158 */
Anthony Baxtera6286212006-04-11 07:42:36 +00001159 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001160 if (remain == NULL)
1161 return -1;
1162 for (i = 0; i < to_merge_size; i++)
1163 remain[i] = 0;
1164
1165 again:
1166 empty_cnt = 0;
1167 for (i = 0; i < to_merge_size; i++) {
1168 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001169
Guido van Rossum1f121312002-11-14 19:49:16 +00001170 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1171
1172 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1173 empty_cnt++;
1174 continue;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001175 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001176
Guido van Rossum98f33732002-11-25 21:36:54 +00001177 /* Choose next candidate for MRO.
1178
1179 The input sequences alone can determine the choice.
1180 If not, choose the class which appears in the MRO
1181 of the earliest direct superclass of the new class.
1182 */
1183
Guido van Rossum1f121312002-11-14 19:49:16 +00001184 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1185 for (j = 0; j < to_merge_size; j++) {
1186 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001187 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001188 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001189 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001190 }
1191 ok = PyList_Append(acc, candidate);
1192 if (ok < 0) {
1193 PyMem_Free(remain);
1194 return -1;
1195 }
1196 for (j = 0; j < to_merge_size; j++) {
1197 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001198 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1199 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001200 remain[j]++;
1201 }
1202 }
1203 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001204 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001205 }
1206
Guido van Rossum98f33732002-11-25 21:36:54 +00001207 if (empty_cnt == to_merge_size) {
1208 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001209 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001210 }
1211 set_mro_error(to_merge, remain);
1212 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001213 return -1;
1214}
1215
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216static PyObject *
1217mro_implementation(PyTypeObject *type)
1218{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001219 Py_ssize_t i, n;
1220 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001221 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001222 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001223
Guido van Rossum63517572002-06-18 16:44:57 +00001224 if(type->tp_dict == NULL) {
1225 if(PyType_Ready(type) < 0)
1226 return NULL;
1227 }
1228
Guido van Rossum98f33732002-11-25 21:36:54 +00001229 /* Find a superclass linearization that honors the constraints
1230 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001231 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001232
1233 to_merge is a list of lists, where each list is a superclass
1234 linearization implied by a base class. The last element of
1235 to_merge is the declared list of bases.
1236 */
1237
Tim Peters6d6c1a32001-08-02 04:15:00 +00001238 bases = type->tp_bases;
1239 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001240
1241 to_merge = PyList_New(n+1);
1242 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001243 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001244
Tim Peters6d6c1a32001-08-02 04:15:00 +00001245 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001246 PyObject *base = PyTuple_GET_ITEM(bases, i);
1247 PyObject *parentMRO;
1248 if (PyType_Check(base))
1249 parentMRO = PySequence_List(
1250 ((PyTypeObject*)base)->tp_mro);
1251 else
1252 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001253 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001254 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001255 return NULL;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001256 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001257
1258 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001259 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001260
1261 bases_aslist = PySequence_List(bases);
1262 if (bases_aslist == NULL) {
1263 Py_DECREF(to_merge);
1264 return NULL;
1265 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001266 /* This is just a basic sanity check. */
1267 if (check_duplicates(bases_aslist) < 0) {
1268 Py_DECREF(to_merge);
1269 Py_DECREF(bases_aslist);
1270 return NULL;
1271 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001272 PyList_SET_ITEM(to_merge, n, bases_aslist);
1273
1274 result = Py_BuildValue("[O]", (PyObject *)type);
1275 if (result == NULL) {
1276 Py_DECREF(to_merge);
1277 return NULL;
1278 }
1279
1280 ok = pmerge(result, to_merge);
1281 Py_DECREF(to_merge);
1282 if (ok < 0) {
1283 Py_DECREF(result);
1284 return NULL;
1285 }
1286
Tim Peters6d6c1a32001-08-02 04:15:00 +00001287 return result;
1288}
1289
1290static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001291mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001292{
1293 PyTypeObject *type = (PyTypeObject *)self;
1294
Tim Peters6d6c1a32001-08-02 04:15:00 +00001295 return mro_implementation(type);
1296}
1297
1298static int
1299mro_internal(PyTypeObject *type)
1300{
1301 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001302 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303
1304 if (type->ob_type == &PyType_Type) {
1305 result = mro_implementation(type);
1306 }
1307 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001308 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001309 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001310 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001311 if (mro == NULL)
1312 return -1;
1313 result = PyObject_CallObject(mro, NULL);
1314 Py_DECREF(mro);
1315 }
1316 if (result == NULL)
1317 return -1;
1318 tuple = PySequence_Tuple(result);
1319 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001320 if (tuple == NULL)
1321 return -1;
1322 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001323 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001324 PyObject *cls;
1325 PyTypeObject *solid;
1326
1327 solid = solid_base(type);
1328
1329 len = PyTuple_GET_SIZE(tuple);
1330
1331 for (i = 0; i < len; i++) {
1332 PyTypeObject *t;
1333 cls = PyTuple_GET_ITEM(tuple, i);
1334 if (PyClass_Check(cls))
1335 continue;
1336 else if (!PyType_Check(cls)) {
1337 PyErr_Format(PyExc_TypeError,
1338 "mro() returned a non-class ('%.500s')",
1339 cls->ob_type->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001340 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001341 return -1;
1342 }
1343 t = (PyTypeObject*)cls;
1344 if (!PyType_IsSubtype(solid, solid_base(t))) {
1345 PyErr_Format(PyExc_TypeError,
1346 "mro() returned base with unsuitable layout ('%.500s')",
1347 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001348 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001349 return -1;
1350 }
1351 }
1352 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001353 type->tp_mro = tuple;
1354 return 0;
1355}
1356
1357
1358/* Calculate the best base amongst multiple base classes.
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001359 This is the first one that's on the path to the "solid base". */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001360
1361static PyTypeObject *
1362best_base(PyObject *bases)
1363{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001364 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001365 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001366 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001367
1368 assert(PyTuple_Check(bases));
1369 n = PyTuple_GET_SIZE(bases);
1370 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001371 base = NULL;
1372 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001373 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001374 base_proto = PyTuple_GET_ITEM(bases, i);
1375 if (PyClass_Check(base_proto))
1376 continue;
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001377 if (!PyType_Check(base_proto)) {
1378 PyErr_SetString(
1379 PyExc_TypeError,
1380 "bases must be types");
1381 return NULL;
1382 }
Tim Petersa91e9642001-11-14 23:32:33 +00001383 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001384 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001385 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001386 return NULL;
1387 }
1388 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001389 if (winner == NULL) {
1390 winner = candidate;
1391 base = base_i;
1392 }
1393 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001394 ;
1395 else if (PyType_IsSubtype(candidate, winner)) {
1396 winner = candidate;
1397 base = base_i;
1398 }
1399 else {
1400 PyErr_SetString(
1401 PyExc_TypeError,
1402 "multiple bases have "
1403 "instance lay-out conflict");
1404 return NULL;
1405 }
1406 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001407 if (base == NULL)
1408 PyErr_SetString(PyExc_TypeError,
1409 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001410 return base;
1411}
1412
1413static int
1414extra_ivars(PyTypeObject *type, PyTypeObject *base)
1415{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001416 size_t t_size = type->tp_basicsize;
1417 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001418
Guido van Rossum9676b222001-08-17 20:32:36 +00001419 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001420 if (type->tp_itemsize || base->tp_itemsize) {
1421 /* If itemsize is involved, stricter rules */
1422 return t_size != b_size ||
1423 type->tp_itemsize != base->tp_itemsize;
1424 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001425 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1426 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1427 t_size -= sizeof(PyObject *);
1428 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1429 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1430 t_size -= sizeof(PyObject *);
1431
1432 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001433}
1434
1435static PyTypeObject *
1436solid_base(PyTypeObject *type)
1437{
1438 PyTypeObject *base;
1439
1440 if (type->tp_base)
1441 base = solid_base(type->tp_base);
1442 else
1443 base = &PyBaseObject_Type;
1444 if (extra_ivars(type, base))
1445 return type;
1446 else
1447 return base;
1448}
1449
Jeremy Hylton938ace62002-07-17 16:30:39 +00001450static void object_dealloc(PyObject *);
1451static int object_init(PyObject *, PyObject *, PyObject *);
1452static int update_slot(PyTypeObject *, PyObject *);
1453static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001454
1455static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001456subtype_dict(PyObject *obj, void *context)
1457{
1458 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1459 PyObject *dict;
1460
1461 if (dictptr == NULL) {
1462 PyErr_SetString(PyExc_AttributeError,
1463 "This object has no __dict__");
1464 return NULL;
1465 }
1466 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001467 if (dict == NULL)
1468 *dictptr = dict = PyDict_New();
1469 Py_XINCREF(dict);
1470 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001471}
1472
Guido van Rossum6661be32001-10-26 04:26:12 +00001473static int
1474subtype_setdict(PyObject *obj, PyObject *value, void *context)
1475{
1476 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1477 PyObject *dict;
1478
1479 if (dictptr == NULL) {
1480 PyErr_SetString(PyExc_AttributeError,
1481 "This object has no __dict__");
1482 return -1;
1483 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001484 if (value != NULL && !PyDict_Check(value)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001485 PyErr_Format(PyExc_TypeError,
1486 "__dict__ must be set to a dictionary, "
1487 "not a '%.200s'", value->ob_type->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001488 return -1;
1489 }
1490 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001491 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001492 *dictptr = value;
1493 Py_XDECREF(dict);
1494 return 0;
1495}
1496
Guido van Rossumad47da02002-08-12 19:05:44 +00001497static PyObject *
1498subtype_getweakref(PyObject *obj, void *context)
1499{
1500 PyObject **weaklistptr;
1501 PyObject *result;
1502
1503 if (obj->ob_type->tp_weaklistoffset == 0) {
1504 PyErr_SetString(PyExc_AttributeError,
Fred Drake7a36f5f2006-08-04 05:17:21 +00001505 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001506 return NULL;
1507 }
1508 assert(obj->ob_type->tp_weaklistoffset > 0);
1509 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001510 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001511 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001512 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001513 if (*weaklistptr == NULL)
1514 result = Py_None;
1515 else
1516 result = *weaklistptr;
1517 Py_INCREF(result);
1518 return result;
1519}
1520
Guido van Rossum373c7412003-01-07 13:41:37 +00001521/* Three variants on the subtype_getsets list. */
1522
1523static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001524 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001525 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001526 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001527 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001528 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001529};
1530
Guido van Rossum373c7412003-01-07 13:41:37 +00001531static PyGetSetDef subtype_getsets_dict_only[] = {
1532 {"__dict__", subtype_dict, subtype_setdict,
1533 PyDoc_STR("dictionary for instance variables (if defined)")},
1534 {0}
1535};
1536
1537static PyGetSetDef subtype_getsets_weakref_only[] = {
1538 {"__weakref__", subtype_getweakref, NULL,
1539 PyDoc_STR("list of weak references to the object (if defined)")},
1540 {0}
1541};
1542
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001543static int
1544valid_identifier(PyObject *s)
1545{
Guido van Rossum03013a02002-07-16 14:30:28 +00001546 unsigned char *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001547 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001548
1549 if (!PyString_Check(s)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001550 PyErr_Format(PyExc_TypeError,
1551 "__slots__ items must be strings, not '%.200s'",
1552 s->ob_type->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001553 return 0;
1554 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001555 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001556 n = PyString_GET_SIZE(s);
1557 /* We must reject an empty name. As a hack, we bump the
1558 length to 1 so that the loop will balk on the trailing \0. */
1559 if (n == 0)
1560 n = 1;
1561 for (i = 0; i < n; i++, p++) {
1562 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1563 PyErr_SetString(PyExc_TypeError,
1564 "__slots__ must be identifiers");
1565 return 0;
1566 }
1567 }
1568 return 1;
1569}
1570
Martin v. Löwisd919a592002-10-14 21:07:28 +00001571#ifdef Py_USING_UNICODE
1572/* Replace Unicode objects in slots. */
1573
1574static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001575_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001576{
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001577 PyObject *tmp = NULL;
1578 PyObject *slot_name, *new_name;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001579 Py_ssize_t i;
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001580
Martin v. Löwisd919a592002-10-14 21:07:28 +00001581 for (i = 0; i < nslots; i++) {
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001582 if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
1583 if (tmp == NULL) {
1584 tmp = PySequence_List(slots);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001585 if (tmp == NULL)
1586 return NULL;
1587 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001588 new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
1589 NULL);
1590 if (new_name == NULL) {
Martin v. Löwisd919a592002-10-14 21:07:28 +00001591 Py_DECREF(tmp);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001592 return NULL;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001593 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001594 Py_INCREF(new_name);
1595 PyList_SET_ITEM(tmp, i, new_name);
1596 Py_DECREF(slot_name);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001597 }
1598 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001599 if (tmp != NULL) {
1600 slots = PyList_AsTuple(tmp);
1601 Py_DECREF(tmp);
1602 }
1603 return slots;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001604}
1605#endif
1606
Guido van Rossumf102e242007-03-23 18:53:03 +00001607/* Forward */
1608static int
1609object_init(PyObject *self, PyObject *args, PyObject *kwds);
1610
1611static int
1612type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1613{
1614 int res;
1615
1616 assert(args != NULL && PyTuple_Check(args));
1617 assert(kwds == NULL || PyDict_Check(kwds));
1618
1619 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1620 PyErr_SetString(PyExc_TypeError,
1621 "type.__init__() takes no keyword arguments");
1622 return -1;
1623 }
1624
1625 if (args != NULL && PyTuple_Check(args) &&
1626 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1627 PyErr_SetString(PyExc_TypeError,
1628 "type.__init__() takes 1 or 3 arguments");
1629 return -1;
1630 }
1631
1632 /* Call object.__init__(self) now. */
1633 /* XXX Could call super(type, cls).__init__() but what's the point? */
1634 args = PyTuple_GetSlice(args, 0, 0);
1635 res = object_init(cls, args, NULL);
1636 Py_DECREF(args);
1637 return res;
1638}
1639
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001640static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001641type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1642{
1643 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001644 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001645 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001646 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001647 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001648 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001649 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001650 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001651
Tim Peters3abca122001-10-27 19:37:48 +00001652 assert(args != NULL && PyTuple_Check(args));
1653 assert(kwds == NULL || PyDict_Check(kwds));
1654
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001655 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001656 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001657 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1658 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001659
1660 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1661 PyObject *x = PyTuple_GET_ITEM(args, 0);
1662 Py_INCREF(x->ob_type);
1663 return (PyObject *) x->ob_type;
1664 }
1665
1666 /* SF bug 475327 -- if that didn't trigger, we need 3
1667 arguments. but PyArg_ParseTupleAndKeywords below may give
1668 a msg saying type() needs exactly 3. */
1669 if (nargs + nkwds != 3) {
1670 PyErr_SetString(PyExc_TypeError,
1671 "type() takes 1 or 3 arguments");
1672 return NULL;
1673 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001674 }
1675
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001676 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001677 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1678 &name,
1679 &PyTuple_Type, &bases,
1680 &PyDict_Type, &dict))
1681 return NULL;
1682
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001683 /* Determine the proper metatype to deal with this,
1684 and check for metatype conflicts while we're at it.
1685 Note that if some other metatype wins to contract,
1686 it's possible that its instances are not types. */
1687 nbases = PyTuple_GET_SIZE(bases);
1688 winner = metatype;
1689 for (i = 0; i < nbases; i++) {
1690 tmp = PyTuple_GET_ITEM(bases, i);
1691 tmptype = tmp->ob_type;
1692 if (tmptype == &PyClass_Type)
1693 continue; /* Special case classic classes */
1694 if (PyType_IsSubtype(winner, tmptype))
1695 continue;
1696 if (PyType_IsSubtype(tmptype, winner)) {
1697 winner = tmptype;
1698 continue;
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001699 }
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001700 PyErr_SetString(PyExc_TypeError,
1701 "metaclass conflict: "
1702 "the metaclass of a derived class "
1703 "must be a (non-strict) subclass "
1704 "of the metaclasses of all its bases");
1705 return NULL;
1706 }
1707 if (winner != metatype) {
1708 if (winner->tp_new != type_new) /* Pass it to the winner */
1709 return winner->tp_new(winner, args, kwds);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001710 metatype = winner;
1711 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001712
1713 /* Adjust for empty tuple bases */
1714 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001715 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001716 if (bases == NULL)
1717 return NULL;
1718 nbases = 1;
1719 }
1720 else
1721 Py_INCREF(bases);
1722
1723 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1724
1725 /* Calculate best base, and check that all bases are type objects */
1726 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001727 if (base == NULL) {
1728 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001729 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001730 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001731 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1732 PyErr_Format(PyExc_TypeError,
1733 "type '%.100s' is not an acceptable base type",
1734 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001735 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001736 return NULL;
1737 }
1738
Tim Peters6d6c1a32001-08-02 04:15:00 +00001739 /* Check for a __slots__ sequence variable in dict, and count it */
1740 slots = PyDict_GetItemString(dict, "__slots__");
1741 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001742 add_dict = 0;
1743 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001744 may_add_dict = base->tp_dictoffset == 0;
1745 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1746 if (slots == NULL) {
1747 if (may_add_dict) {
1748 add_dict++;
1749 }
1750 if (may_add_weak) {
1751 add_weak++;
1752 }
1753 }
1754 else {
1755 /* Have slots */
1756
Tim Peters6d6c1a32001-08-02 04:15:00 +00001757 /* Make it into a tuple */
Neal Norwitzcbd9ee62007-04-14 05:25:50 +00001758 if (PyString_Check(slots) || PyUnicode_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001759 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001760 else
1761 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001762 if (slots == NULL) {
1763 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001764 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001765 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001766 assert(PyTuple_Check(slots));
1767
1768 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001769 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001770 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001771 PyErr_Format(PyExc_TypeError,
1772 "nonempty __slots__ "
1773 "not supported for subtype of '%s'",
1774 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001775 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001776 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001777 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001778 return NULL;
1779 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001780
Martin v. Löwisd919a592002-10-14 21:07:28 +00001781#ifdef Py_USING_UNICODE
1782 tmp = _unicode_to_string(slots, nslots);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001783 if (tmp == NULL)
1784 goto bad_slots;
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001785 if (tmp != slots) {
1786 Py_DECREF(slots);
1787 slots = tmp;
1788 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001789#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001790 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001791 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001792 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1793 char *s;
1794 if (!valid_identifier(tmp))
1795 goto bad_slots;
1796 assert(PyString_Check(tmp));
1797 s = PyString_AS_STRING(tmp);
1798 if (strcmp(s, "__dict__") == 0) {
1799 if (!may_add_dict || add_dict) {
1800 PyErr_SetString(PyExc_TypeError,
1801 "__dict__ slot disallowed: "
1802 "we already got one");
1803 goto bad_slots;
1804 }
1805 add_dict++;
1806 }
1807 if (strcmp(s, "__weakref__") == 0) {
1808 if (!may_add_weak || add_weak) {
1809 PyErr_SetString(PyExc_TypeError,
1810 "__weakref__ slot disallowed: "
1811 "either we already got one, "
1812 "or __itemsize__ != 0");
1813 goto bad_slots;
1814 }
1815 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001816 }
1817 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001818
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00001819 /* Copy slots into a list, mangle names and sort them.
1820 Sorted names are needed for __class__ assignment.
1821 Convert them back to tuple at the end.
1822 */
1823 newslots = PyList_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001824 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001825 goto bad_slots;
1826 for (i = j = 0; i < nslots; i++) {
1827 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001828 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001829 s = PyString_AS_STRING(tmp);
1830 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1831 (add_weak && strcmp(s, "__weakref__") == 0))
1832 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001833 tmp =_Py_Mangle(name, tmp);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001834 if (!tmp)
1835 goto bad_slots;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00001836 PyList_SET_ITEM(newslots, j, tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00001837 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001838 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001839 assert(j == nslots - add_dict - add_weak);
1840 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001841 Py_DECREF(slots);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00001842 if (PyList_Sort(newslots) == -1) {
1843 Py_DECREF(bases);
1844 Py_DECREF(newslots);
1845 return NULL;
1846 }
1847 slots = PyList_AsTuple(newslots);
1848 Py_DECREF(newslots);
1849 if (slots == NULL) {
1850 Py_DECREF(bases);
1851 return NULL;
1852 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001853
Guido van Rossumad47da02002-08-12 19:05:44 +00001854 /* Secondary bases may provide weakrefs or dict */
1855 if (nbases > 1 &&
1856 ((may_add_dict && !add_dict) ||
1857 (may_add_weak && !add_weak))) {
1858 for (i = 0; i < nbases; i++) {
1859 tmp = PyTuple_GET_ITEM(bases, i);
1860 if (tmp == (PyObject *)base)
1861 continue; /* Skip primary base */
1862 if (PyClass_Check(tmp)) {
1863 /* Classic base class provides both */
1864 if (may_add_dict && !add_dict)
1865 add_dict++;
1866 if (may_add_weak && !add_weak)
1867 add_weak++;
1868 break;
1869 }
1870 assert(PyType_Check(tmp));
1871 tmptype = (PyTypeObject *)tmp;
1872 if (may_add_dict && !add_dict &&
1873 tmptype->tp_dictoffset != 0)
1874 add_dict++;
1875 if (may_add_weak && !add_weak &&
1876 tmptype->tp_weaklistoffset != 0)
1877 add_weak++;
1878 if (may_add_dict && !add_dict)
1879 continue;
1880 if (may_add_weak && !add_weak)
1881 continue;
1882 /* Nothing more to check */
1883 break;
1884 }
1885 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001886 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001887
1888 /* XXX From here until type is safely allocated,
1889 "return NULL" may leak slots! */
1890
1891 /* Allocate the type object */
1892 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001893 if (type == NULL) {
1894 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001895 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001896 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001897 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001898
1899 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001900 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001901 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00001902 et->ht_name = name;
1903 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001904
Guido van Rossumdc91b992001-08-08 22:26:22 +00001905 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001906 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1907 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001908 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1909 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001910
1911 /* It's a new-style number unless it specifically inherits any
1912 old-style numeric behavior */
1913 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1914 (base->tp_as_number == NULL))
1915 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1916
1917 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001918 type->tp_as_number = &et->as_number;
1919 type->tp_as_sequence = &et->as_sequence;
1920 type->tp_as_mapping = &et->as_mapping;
1921 type->tp_as_buffer = &et->as_buffer;
1922 type->tp_name = PyString_AS_STRING(name);
1923
1924 /* Set tp_base and tp_bases */
1925 type->tp_bases = bases;
1926 Py_INCREF(base);
1927 type->tp_base = base;
1928
Guido van Rossum687ae002001-10-15 22:03:32 +00001929 /* Initialize tp_dict from passed-in dict */
1930 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001931 if (dict == NULL) {
1932 Py_DECREF(type);
1933 return NULL;
1934 }
1935
Guido van Rossumc3542212001-08-16 09:18:56 +00001936 /* Set __module__ in the dict */
1937 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1938 tmp = PyEval_GetGlobals();
1939 if (tmp != NULL) {
1940 tmp = PyDict_GetItemString(tmp, "__name__");
1941 if (tmp != NULL) {
1942 if (PyDict_SetItemString(dict, "__module__",
1943 tmp) < 0)
1944 return NULL;
1945 }
1946 }
1947 }
1948
Tim Peters2f93e282001-10-04 05:27:00 +00001949 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001950 and is a string. The __doc__ accessor will first look for tp_doc;
1951 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001952 */
1953 {
1954 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1955 if (doc != NULL && PyString_Check(doc)) {
1956 const size_t n = (size_t)PyString_GET_SIZE(doc);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001957 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001958 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00001959 Py_DECREF(type);
1960 return NULL;
1961 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001962 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001963 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00001964 }
1965 }
1966
Tim Peters6d6c1a32001-08-02 04:15:00 +00001967 /* Special-case __new__: if it's a plain function,
1968 make it a static function */
1969 tmp = PyDict_GetItemString(dict, "__new__");
1970 if (tmp != NULL && PyFunction_Check(tmp)) {
1971 tmp = PyStaticMethod_New(tmp);
1972 if (tmp == NULL) {
1973 Py_DECREF(type);
1974 return NULL;
1975 }
1976 PyDict_SetItemString(dict, "__new__", tmp);
1977 Py_DECREF(tmp);
1978 }
1979
1980 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001981 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001982 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001983 if (slots != NULL) {
1984 for (i = 0; i < nslots; i++, mp++) {
1985 mp->name = PyString_AS_STRING(
1986 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001987 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001988 mp->offset = slotoffset;
Žiga Seilnacht89032082007-03-11 15:54:54 +00001989
1990 /* __dict__ and __weakref__ are already filtered out */
1991 assert(strcmp(mp->name, "__dict__") != 0);
1992 assert(strcmp(mp->name, "__weakref__") != 0);
1993
Tim Peters6d6c1a32001-08-02 04:15:00 +00001994 slotoffset += sizeof(PyObject *);
1995 }
1996 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001997 if (add_dict) {
1998 if (base->tp_itemsize)
1999 type->tp_dictoffset = -(long)sizeof(PyObject *);
2000 else
2001 type->tp_dictoffset = slotoffset;
2002 slotoffset += sizeof(PyObject *);
2003 }
2004 if (add_weak) {
2005 assert(!base->tp_itemsize);
2006 type->tp_weaklistoffset = slotoffset;
2007 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002008 }
2009 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002010 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00002011 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002012
2013 if (type->tp_weaklistoffset && type->tp_dictoffset)
2014 type->tp_getset = subtype_getsets_full;
2015 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2016 type->tp_getset = subtype_getsets_weakref_only;
2017 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2018 type->tp_getset = subtype_getsets_dict_only;
2019 else
2020 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002021
2022 /* Special case some slots */
2023 if (type->tp_dictoffset != 0 || nslots > 0) {
2024 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2025 type->tp_getattro = PyObject_GenericGetAttr;
2026 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2027 type->tp_setattro = PyObject_GenericSetAttr;
2028 }
2029 type->tp_dealloc = subtype_dealloc;
2030
Guido van Rossum9475a232001-10-05 20:51:39 +00002031 /* Enable GC unless there are really no instance variables possible */
2032 if (!(type->tp_basicsize == sizeof(PyObject) &&
2033 type->tp_itemsize == 0))
2034 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2035
Tim Peters6d6c1a32001-08-02 04:15:00 +00002036 /* Always override allocation strategy to use regular heap */
2037 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00002038 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002039 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00002040 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002041 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00002042 }
2043 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002044 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002045
2046 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002047 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002048 Py_DECREF(type);
2049 return NULL;
2050 }
2051
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002052 /* Put the proper slots in place */
2053 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002054
Tim Peters6d6c1a32001-08-02 04:15:00 +00002055 return (PyObject *)type;
2056}
2057
2058/* Internal API to look for a name through the MRO.
2059 This returns a borrowed reference, and doesn't set an exception! */
2060PyObject *
2061_PyType_Lookup(PyTypeObject *type, PyObject *name)
2062{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002063 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002064 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002065
Guido van Rossum687ae002001-10-15 22:03:32 +00002066 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002067 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002068
2069 /* If mro is NULL, the type is either not yet initialized
2070 by PyType_Ready(), or already cleared by type_clear().
2071 Either way the safest thing to do is to return NULL. */
2072 if (mro == NULL)
2073 return NULL;
2074
Tim Peters6d6c1a32001-08-02 04:15:00 +00002075 assert(PyTuple_Check(mro));
2076 n = PyTuple_GET_SIZE(mro);
2077 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002078 base = PyTuple_GET_ITEM(mro, i);
2079 if (PyClass_Check(base))
2080 dict = ((PyClassObject *)base)->cl_dict;
2081 else {
2082 assert(PyType_Check(base));
2083 dict = ((PyTypeObject *)base)->tp_dict;
2084 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002085 assert(dict && PyDict_Check(dict));
2086 res = PyDict_GetItem(dict, name);
2087 if (res != NULL)
2088 return res;
2089 }
2090 return NULL;
2091}
2092
2093/* This is similar to PyObject_GenericGetAttr(),
2094 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2095static PyObject *
2096type_getattro(PyTypeObject *type, PyObject *name)
2097{
2098 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002099 PyObject *meta_attribute, *attribute;
2100 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002101
2102 /* Initialize this type (we'll assume the metatype is initialized) */
2103 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002104 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002105 return NULL;
2106 }
2107
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002108 /* No readable descriptor found yet */
2109 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002110
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002111 /* Look for the attribute in the metatype */
2112 meta_attribute = _PyType_Lookup(metatype, name);
2113
2114 if (meta_attribute != NULL) {
2115 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002116
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002117 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2118 /* Data descriptors implement tp_descr_set to intercept
2119 * writes. Assume the attribute is not overridden in
2120 * type's tp_dict (and bases): call the descriptor now.
2121 */
2122 return meta_get(meta_attribute, (PyObject *)type,
2123 (PyObject *)metatype);
2124 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002125 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002126 }
2127
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002128 /* No data descriptor found on metatype. Look in tp_dict of this
2129 * type and its bases */
2130 attribute = _PyType_Lookup(type, name);
2131 if (attribute != NULL) {
2132 /* Implement descriptor functionality, if any */
2133 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002134
2135 Py_XDECREF(meta_attribute);
2136
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002137 if (local_get != NULL) {
2138 /* NULL 2nd argument indicates the descriptor was
2139 * found on the target object itself (or a base) */
2140 return local_get(attribute, (PyObject *)NULL,
2141 (PyObject *)type);
2142 }
Tim Peters34592512002-07-11 06:23:50 +00002143
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002144 Py_INCREF(attribute);
2145 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002146 }
2147
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002148 /* No attribute found in local __dict__ (or bases): use the
2149 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002150 if (meta_get != NULL) {
2151 PyObject *res;
2152 res = meta_get(meta_attribute, (PyObject *)type,
2153 (PyObject *)metatype);
2154 Py_DECREF(meta_attribute);
2155 return res;
2156 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002157
2158 /* If an ordinary attribute was found on the metatype, return it now */
2159 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002160 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002161 }
2162
2163 /* Give up */
2164 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002165 "type object '%.50s' has no attribute '%.400s'",
2166 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002167 return NULL;
2168}
2169
2170static int
2171type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2172{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002173 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2174 PyErr_Format(
2175 PyExc_TypeError,
2176 "can't set attributes of built-in/extension type '%s'",
2177 type->tp_name);
2178 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002179 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002180 /* XXX Example of how I expect this to be used...
2181 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2182 return -1;
2183 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002184 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2185 return -1;
2186 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002187}
2188
2189static void
2190type_dealloc(PyTypeObject *type)
2191{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002192 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002193
2194 /* Assert this is a heap-allocated type object */
2195 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002196 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002197 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002198 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002199 Py_XDECREF(type->tp_base);
2200 Py_XDECREF(type->tp_dict);
2201 Py_XDECREF(type->tp_bases);
2202 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002203 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002204 Py_XDECREF(type->tp_subclasses);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002205 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2206 * of most other objects. It's okay to cast it to char *.
2207 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002208 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002209 Py_XDECREF(et->ht_name);
2210 Py_XDECREF(et->ht_slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002211 type->ob_type->tp_free((PyObject *)type);
2212}
2213
Guido van Rossum1c450732001-10-08 15:18:27 +00002214static PyObject *
2215type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2216{
2217 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002218 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002219
2220 list = PyList_New(0);
2221 if (list == NULL)
2222 return NULL;
2223 raw = type->tp_subclasses;
2224 if (raw == NULL)
2225 return list;
2226 assert(PyList_Check(raw));
2227 n = PyList_GET_SIZE(raw);
2228 for (i = 0; i < n; i++) {
2229 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002230 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002231 ref = PyWeakref_GET_OBJECT(ref);
2232 if (ref != Py_None) {
2233 if (PyList_Append(list, ref) < 0) {
2234 Py_DECREF(list);
2235 return NULL;
2236 }
2237 }
2238 }
2239 return list;
2240}
2241
Tim Peters6d6c1a32001-08-02 04:15:00 +00002242static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002243 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002244 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002245 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002246 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002247 {0}
2248};
2249
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002250PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002251"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002252"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002253
Guido van Rossum048eb752001-10-02 21:24:57 +00002254static int
2255type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2256{
Guido van Rossuma3862092002-06-10 15:24:42 +00002257 /* Because of type_is_gc(), the collector only calls this
2258 for heaptypes. */
2259 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002260
Thomas Woutersc6e55062006-04-15 21:47:09 +00002261 Py_VISIT(type->tp_dict);
2262 Py_VISIT(type->tp_cache);
2263 Py_VISIT(type->tp_mro);
2264 Py_VISIT(type->tp_bases);
2265 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002266
2267 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002268 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002269 in cycles; tp_subclasses is a list of weak references,
2270 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002271
Guido van Rossum048eb752001-10-02 21:24:57 +00002272 return 0;
2273}
2274
2275static int
2276type_clear(PyTypeObject *type)
2277{
Guido van Rossuma3862092002-06-10 15:24:42 +00002278 /* Because of type_is_gc(), the collector only calls this
2279 for heaptypes. */
2280 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002281
Guido van Rossuma3862092002-06-10 15:24:42 +00002282 /* The only field we need to clear is tp_mro, which is part of a
2283 hard cycle (its first element is the class itself) that won't
2284 be broken otherwise (it's a tuple and tuples don't have a
2285 tp_clear handler). None of the other fields need to be
2286 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002287
Guido van Rossuma3862092002-06-10 15:24:42 +00002288 tp_dict:
2289 It is a dict, so the collector will call its tp_clear.
2290
2291 tp_cache:
2292 Not used; if it were, it would be a dict.
2293
2294 tp_bases, tp_base:
2295 If these are involved in a cycle, there must be at least
2296 one other, mutable object in the cycle, e.g. a base
2297 class's dict; the cycle will be broken that way.
2298
2299 tp_subclasses:
2300 A list of weak references can't be part of a cycle; and
2301 lists have their own tp_clear.
2302
Guido van Rossume5c691a2003-03-07 15:13:17 +00002303 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002304 A tuple of strings can't be part of a cycle.
2305 */
2306
Thomas Woutersedf17d82006-04-15 17:28:34 +00002307 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002308
2309 return 0;
2310}
2311
2312static int
2313type_is_gc(PyTypeObject *type)
2314{
2315 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2316}
2317
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002318PyTypeObject PyType_Type = {
2319 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002320 0, /* ob_size */
2321 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002322 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002323 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002324 (destructor)type_dealloc, /* tp_dealloc */
2325 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002326 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002327 0, /* tp_setattr */
2328 type_compare, /* tp_compare */
2329 (reprfunc)type_repr, /* tp_repr */
2330 0, /* tp_as_number */
2331 0, /* tp_as_sequence */
2332 0, /* tp_as_mapping */
2333 (hashfunc)_Py_HashPointer, /* tp_hash */
2334 (ternaryfunc)type_call, /* tp_call */
2335 0, /* tp_str */
2336 (getattrofunc)type_getattro, /* tp_getattro */
2337 (setattrofunc)type_setattro, /* tp_setattro */
2338 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002339 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002340 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002341 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002342 (traverseproc)type_traverse, /* tp_traverse */
2343 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002344 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002345 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002346 0, /* tp_iter */
2347 0, /* tp_iternext */
2348 type_methods, /* tp_methods */
2349 type_members, /* tp_members */
2350 type_getsets, /* tp_getset */
2351 0, /* tp_base */
2352 0, /* tp_dict */
2353 0, /* tp_descr_get */
2354 0, /* tp_descr_set */
2355 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
Guido van Rossumf102e242007-03-23 18:53:03 +00002356 type_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002357 0, /* tp_alloc */
2358 type_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002359 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002360 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002361};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002362
2363
2364/* The base type of all types (eventually)... except itself. */
2365
Guido van Rossum143b5642007-03-23 04:58:42 +00002366/* You may wonder why object.__new__() only complains about arguments
2367 when object.__init__() is not overridden, and vice versa.
2368
2369 Consider the use cases:
2370
2371 1. When neither is overridden, we want to hear complaints about
2372 excess (i.e., any) arguments, since their presence could
2373 indicate there's a bug.
2374
2375 2. When defining an Immutable type, we are likely to override only
2376 __new__(), since __init__() is called too late to initialize an
2377 Immutable object. Since __new__() defines the signature for the
2378 type, it would be a pain to have to override __init__() just to
2379 stop it from complaining about excess arguments.
2380
2381 3. When defining a Mutable type, we are likely to override only
2382 __init__(). So here the converse reasoning applies: we don't
2383 want to have to override __new__() just to stop it from
2384 complaining.
2385
2386 4. When __init__() is overridden, and the subclass __init__() calls
2387 object.__init__(), the latter should complain about excess
2388 arguments; ditto for __new__().
2389
2390 Use cases 2 and 3 make it unattractive to unconditionally check for
2391 excess arguments. The best solution that addresses all four use
2392 cases is as follows: __init__() complains about excess arguments
2393 unless __new__() is overridden and __init__() is not overridden
2394 (IOW, if __init__() is overridden or __new__() is not overridden);
2395 symmetrically, __new__() complains about excess arguments unless
2396 __init__() is overridden and __new__() is not overridden
2397 (IOW, if __new__() is overridden or __init__() is not overridden).
2398
2399 However, for backwards compatibility, this breaks too much code.
2400 Therefore, in 2.6, we'll *warn* about excess arguments when both
2401 methods are overridden; for all other cases we'll use the above
2402 rules.
2403
2404*/
2405
2406/* Forward */
2407static PyObject *
2408object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2409
2410static int
2411excess_args(PyObject *args, PyObject *kwds)
2412{
2413 return PyTuple_GET_SIZE(args) ||
2414 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2415}
2416
Tim Peters6d6c1a32001-08-02 04:15:00 +00002417static int
2418object_init(PyObject *self, PyObject *args, PyObject *kwds)
2419{
Guido van Rossum143b5642007-03-23 04:58:42 +00002420 int err = 0;
2421 if (excess_args(args, kwds)) {
2422 PyTypeObject *type = self->ob_type;
2423 if (type->tp_init != object_init &&
2424 type->tp_new != object_new)
2425 {
2426 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2427 "object.__init__() takes no parameters",
2428 1);
2429 }
2430 else if (type->tp_init != object_init ||
2431 type->tp_new == object_new)
2432 {
2433 PyErr_SetString(PyExc_TypeError,
2434 "object.__init__() takes no parameters");
2435 err = -1;
2436 }
2437 }
2438 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002439}
2440
Guido van Rossum298e4212003-02-13 16:30:16 +00002441static PyObject *
2442object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2443{
Guido van Rossum143b5642007-03-23 04:58:42 +00002444 int err = 0;
2445 if (excess_args(args, kwds)) {
2446 if (type->tp_new != object_new &&
2447 type->tp_init != object_init)
2448 {
2449 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2450 "object.__new__() takes no parameters",
2451 1);
2452 }
2453 else if (type->tp_new != object_new ||
2454 type->tp_init == object_init)
2455 {
2456 PyErr_SetString(PyExc_TypeError,
2457 "object.__new__() takes no parameters");
2458 err = -1;
2459 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002460 }
Guido van Rossum143b5642007-03-23 04:58:42 +00002461 if (err < 0)
2462 return NULL;
Guido van Rossum298e4212003-02-13 16:30:16 +00002463 return type->tp_alloc(type, 0);
2464}
2465
Tim Peters6d6c1a32001-08-02 04:15:00 +00002466static void
2467object_dealloc(PyObject *self)
2468{
2469 self->ob_type->tp_free(self);
2470}
2471
Guido van Rossum8e248182001-08-12 05:17:56 +00002472static PyObject *
2473object_repr(PyObject *self)
2474{
Guido van Rossum76e69632001-08-16 18:52:43 +00002475 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002476 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002477
Guido van Rossum76e69632001-08-16 18:52:43 +00002478 type = self->ob_type;
2479 mod = type_module(type, NULL);
2480 if (mod == NULL)
2481 PyErr_Clear();
2482 else if (!PyString_Check(mod)) {
2483 Py_DECREF(mod);
2484 mod = NULL;
2485 }
2486 name = type_name(type, NULL);
2487 if (name == NULL)
2488 return NULL;
2489 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002490 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002491 PyString_AS_STRING(mod),
2492 PyString_AS_STRING(name),
2493 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002494 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002495 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002496 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002497 Py_XDECREF(mod);
2498 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002499 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002500}
2501
Guido van Rossumb8f63662001-08-15 23:57:02 +00002502static PyObject *
2503object_str(PyObject *self)
2504{
2505 unaryfunc f;
2506
2507 f = self->ob_type->tp_repr;
2508 if (f == NULL)
2509 f = object_repr;
2510 return f(self);
2511}
2512
Guido van Rossum8e248182001-08-12 05:17:56 +00002513static long
2514object_hash(PyObject *self)
2515{
2516 return _Py_HashPointer(self);
2517}
Guido van Rossum8e248182001-08-12 05:17:56 +00002518
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002519static PyObject *
2520object_get_class(PyObject *self, void *closure)
2521{
2522 Py_INCREF(self->ob_type);
2523 return (PyObject *)(self->ob_type);
2524}
2525
2526static int
2527equiv_structs(PyTypeObject *a, PyTypeObject *b)
2528{
2529 return a == b ||
2530 (a != NULL &&
2531 b != NULL &&
2532 a->tp_basicsize == b->tp_basicsize &&
2533 a->tp_itemsize == b->tp_itemsize &&
2534 a->tp_dictoffset == b->tp_dictoffset &&
2535 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2536 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2537 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2538}
2539
2540static int
2541same_slots_added(PyTypeObject *a, PyTypeObject *b)
2542{
2543 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002544 Py_ssize_t size;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002545 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002546
2547 if (base != b->tp_base)
2548 return 0;
2549 if (equiv_structs(a, base) && equiv_structs(b, base))
2550 return 1;
2551 size = base->tp_basicsize;
2552 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2553 size += sizeof(PyObject *);
2554 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2555 size += sizeof(PyObject *);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002556
2557 /* Check slots compliance */
2558 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2559 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2560 if (slots_a && slots_b) {
2561 if (PyObject_Compare(slots_a, slots_b) != 0)
2562 return 0;
2563 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2564 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002565 return size == a->tp_basicsize && size == b->tp_basicsize;
2566}
2567
2568static int
Anthony Baxtera6286212006-04-11 07:42:36 +00002569compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002570{
2571 PyTypeObject *newbase, *oldbase;
2572
Anthony Baxtera6286212006-04-11 07:42:36 +00002573 if (newto->tp_dealloc != oldto->tp_dealloc ||
2574 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002575 {
2576 PyErr_Format(PyExc_TypeError,
2577 "%s assignment: "
2578 "'%s' deallocator differs from '%s'",
2579 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002580 newto->tp_name,
2581 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002582 return 0;
2583 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002584 newbase = newto;
2585 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002586 while (equiv_structs(newbase, newbase->tp_base))
2587 newbase = newbase->tp_base;
2588 while (equiv_structs(oldbase, oldbase->tp_base))
2589 oldbase = oldbase->tp_base;
2590 if (newbase != oldbase &&
2591 (newbase->tp_base != oldbase->tp_base ||
2592 !same_slots_added(newbase, oldbase))) {
2593 PyErr_Format(PyExc_TypeError,
2594 "%s assignment: "
2595 "'%s' object layout differs from '%s'",
2596 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002597 newto->tp_name,
2598 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002599 return 0;
2600 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002601
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002602 return 1;
2603}
2604
2605static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002606object_set_class(PyObject *self, PyObject *value, void *closure)
2607{
Anthony Baxtera6286212006-04-11 07:42:36 +00002608 PyTypeObject *oldto = self->ob_type;
2609 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002610
Guido van Rossumb6b89422002-04-15 01:03:30 +00002611 if (value == NULL) {
2612 PyErr_SetString(PyExc_TypeError,
2613 "can't delete __class__ attribute");
2614 return -1;
2615 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002616 if (!PyType_Check(value)) {
2617 PyErr_Format(PyExc_TypeError,
2618 "__class__ must be set to new-style class, not '%s' object",
2619 value->ob_type->tp_name);
2620 return -1;
2621 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002622 newto = (PyTypeObject *)value;
2623 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2624 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002625 {
2626 PyErr_Format(PyExc_TypeError,
2627 "__class__ assignment: only for heap types");
2628 return -1;
2629 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002630 if (compatible_for_assignment(newto, oldto, "__class__")) {
2631 Py_INCREF(newto);
2632 self->ob_type = newto;
2633 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002634 return 0;
2635 }
2636 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002637 return -1;
2638 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002639}
2640
2641static PyGetSetDef object_getsets[] = {
2642 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002643 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002644 {0}
2645};
2646
Guido van Rossumc53f0092003-02-18 22:05:12 +00002647
Guido van Rossum036f9992003-02-21 22:02:54 +00002648/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2649 We fall back to helpers in copy_reg for:
2650 - pickle protocols < 2
2651 - calculating the list of slot names (done only once per class)
2652 - the __newobj__ function (which is used as a token but never called)
2653*/
2654
2655static PyObject *
2656import_copy_reg(void)
2657{
2658 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002659
2660 if (!copy_reg_str) {
2661 copy_reg_str = PyString_InternFromString("copy_reg");
2662 if (copy_reg_str == NULL)
2663 return NULL;
2664 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002665
2666 return PyImport_Import(copy_reg_str);
2667}
2668
2669static PyObject *
2670slotnames(PyObject *cls)
2671{
2672 PyObject *clsdict;
2673 PyObject *copy_reg;
2674 PyObject *slotnames;
2675
2676 if (!PyType_Check(cls)) {
2677 Py_INCREF(Py_None);
2678 return Py_None;
2679 }
2680
2681 clsdict = ((PyTypeObject *)cls)->tp_dict;
2682 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002683 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002684 Py_INCREF(slotnames);
2685 return slotnames;
2686 }
2687
2688 copy_reg = import_copy_reg();
2689 if (copy_reg == NULL)
2690 return NULL;
2691
2692 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2693 Py_DECREF(copy_reg);
2694 if (slotnames != NULL &&
2695 slotnames != Py_None &&
2696 !PyList_Check(slotnames))
2697 {
2698 PyErr_SetString(PyExc_TypeError,
2699 "copy_reg._slotnames didn't return a list or None");
2700 Py_DECREF(slotnames);
2701 slotnames = NULL;
2702 }
2703
2704 return slotnames;
2705}
2706
2707static PyObject *
2708reduce_2(PyObject *obj)
2709{
2710 PyObject *cls, *getnewargs;
2711 PyObject *args = NULL, *args2 = NULL;
2712 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2713 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2714 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002715 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00002716
2717 cls = PyObject_GetAttrString(obj, "__class__");
2718 if (cls == NULL)
2719 return NULL;
2720
2721 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2722 if (getnewargs != NULL) {
2723 args = PyObject_CallObject(getnewargs, NULL);
2724 Py_DECREF(getnewargs);
2725 if (args != NULL && !PyTuple_Check(args)) {
Georg Brandlccff7852006-06-18 22:17:29 +00002726 PyErr_Format(PyExc_TypeError,
2727 "__getnewargs__ should return a tuple, "
2728 "not '%.200s'", args->ob_type->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00002729 goto end;
2730 }
2731 }
2732 else {
2733 PyErr_Clear();
2734 args = PyTuple_New(0);
2735 }
2736 if (args == NULL)
2737 goto end;
2738
2739 getstate = PyObject_GetAttrString(obj, "__getstate__");
2740 if (getstate != NULL) {
2741 state = PyObject_CallObject(getstate, NULL);
2742 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002743 if (state == NULL)
2744 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002745 }
2746 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002747 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002748 state = PyObject_GetAttrString(obj, "__dict__");
2749 if (state == NULL) {
2750 PyErr_Clear();
2751 state = Py_None;
2752 Py_INCREF(state);
2753 }
2754 names = slotnames(cls);
2755 if (names == NULL)
2756 goto end;
2757 if (names != Py_None) {
2758 assert(PyList_Check(names));
2759 slots = PyDict_New();
2760 if (slots == NULL)
2761 goto end;
2762 n = 0;
2763 /* Can't pre-compute the list size; the list
2764 is stored on the class so accessible to other
2765 threads, which may be run by DECREF */
2766 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2767 PyObject *name, *value;
2768 name = PyList_GET_ITEM(names, i);
2769 value = PyObject_GetAttr(obj, name);
2770 if (value == NULL)
2771 PyErr_Clear();
2772 else {
2773 int err = PyDict_SetItem(slots, name,
2774 value);
2775 Py_DECREF(value);
2776 if (err)
2777 goto end;
2778 n++;
2779 }
2780 }
2781 if (n) {
2782 state = Py_BuildValue("(NO)", state, slots);
2783 if (state == NULL)
2784 goto end;
2785 }
2786 }
2787 }
2788
2789 if (!PyList_Check(obj)) {
2790 listitems = Py_None;
2791 Py_INCREF(listitems);
2792 }
2793 else {
2794 listitems = PyObject_GetIter(obj);
2795 if (listitems == NULL)
2796 goto end;
2797 }
2798
2799 if (!PyDict_Check(obj)) {
2800 dictitems = Py_None;
2801 Py_INCREF(dictitems);
2802 }
2803 else {
2804 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2805 if (dictitems == NULL)
2806 goto end;
2807 }
2808
2809 copy_reg = import_copy_reg();
2810 if (copy_reg == NULL)
2811 goto end;
2812 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2813 if (newobj == NULL)
2814 goto end;
2815
2816 n = PyTuple_GET_SIZE(args);
2817 args2 = PyTuple_New(n+1);
2818 if (args2 == NULL)
2819 goto end;
2820 PyTuple_SET_ITEM(args2, 0, cls);
2821 cls = NULL;
2822 for (i = 0; i < n; i++) {
2823 PyObject *v = PyTuple_GET_ITEM(args, i);
2824 Py_INCREF(v);
2825 PyTuple_SET_ITEM(args2, i+1, v);
2826 }
2827
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002828 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002829
2830 end:
2831 Py_XDECREF(cls);
2832 Py_XDECREF(args);
2833 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002834 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002835 Py_XDECREF(state);
2836 Py_XDECREF(names);
2837 Py_XDECREF(listitems);
2838 Py_XDECREF(dictitems);
2839 Py_XDECREF(copy_reg);
2840 Py_XDECREF(newobj);
2841 return res;
2842}
2843
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00002844/*
2845 * There were two problems when object.__reduce__ and object.__reduce_ex__
2846 * were implemented in the same function:
2847 * - trying to pickle an object with a custom __reduce__ method that
2848 * fell back to object.__reduce__ in certain circumstances led to
2849 * infinite recursion at Python level and eventual RuntimeError.
2850 * - Pickling objects that lied about their type by overwriting the
2851 * __class__ descriptor could lead to infinite recursion at C level
2852 * and eventual segfault.
2853 *
2854 * Because of backwards compatibility, the two methods still have to
2855 * behave in the same way, even if this is not required by the pickle
2856 * protocol. This common functionality was moved to the _common_reduce
2857 * function.
2858 */
2859static PyObject *
2860_common_reduce(PyObject *self, int proto)
2861{
2862 PyObject *copy_reg, *res;
2863
2864 if (proto >= 2)
2865 return reduce_2(self);
2866
2867 copy_reg = import_copy_reg();
2868 if (!copy_reg)
2869 return NULL;
2870
2871 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
2872 Py_DECREF(copy_reg);
2873
2874 return res;
2875}
2876
2877static PyObject *
2878object_reduce(PyObject *self, PyObject *args)
2879{
2880 int proto = 0;
2881
2882 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
2883 return NULL;
2884
2885 return _common_reduce(self, proto);
2886}
2887
Guido van Rossum036f9992003-02-21 22:02:54 +00002888static PyObject *
2889object_reduce_ex(PyObject *self, PyObject *args)
2890{
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00002891 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00002892 int proto = 0;
2893
2894 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2895 return NULL;
2896
2897 reduce = PyObject_GetAttrString(self, "__reduce__");
2898 if (reduce == NULL)
2899 PyErr_Clear();
2900 else {
2901 PyObject *cls, *clsreduce, *objreduce;
2902 int override;
2903 cls = PyObject_GetAttrString(self, "__class__");
2904 if (cls == NULL) {
2905 Py_DECREF(reduce);
2906 return NULL;
2907 }
2908 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2909 Py_DECREF(cls);
2910 if (clsreduce == NULL) {
2911 Py_DECREF(reduce);
2912 return NULL;
2913 }
2914 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2915 "__reduce__");
2916 override = (clsreduce != objreduce);
2917 Py_DECREF(clsreduce);
2918 if (override) {
2919 res = PyObject_CallObject(reduce, NULL);
2920 Py_DECREF(reduce);
2921 return res;
2922 }
2923 else
2924 Py_DECREF(reduce);
2925 }
2926
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00002927 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002928}
2929
2930static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002931 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2932 PyDoc_STR("helper for pickle")},
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00002933 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002934 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002935 {0}
2936};
2937
Guido van Rossum036f9992003-02-21 22:02:54 +00002938
Tim Peters6d6c1a32001-08-02 04:15:00 +00002939PyTypeObject PyBaseObject_Type = {
2940 PyObject_HEAD_INIT(&PyType_Type)
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002941 0, /* ob_size */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002942 "object", /* tp_name */
2943 sizeof(PyObject), /* tp_basicsize */
2944 0, /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00002945 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002946 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002947 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002948 0, /* tp_setattr */
2949 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002950 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002951 0, /* tp_as_number */
2952 0, /* tp_as_sequence */
2953 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002954 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002955 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002956 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002957 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002958 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002959 0, /* tp_as_buffer */
2960 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002961 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002962 0, /* tp_traverse */
2963 0, /* tp_clear */
2964 0, /* tp_richcompare */
2965 0, /* tp_weaklistoffset */
2966 0, /* tp_iter */
2967 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002968 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002969 0, /* tp_members */
2970 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002971 0, /* tp_base */
2972 0, /* tp_dict */
2973 0, /* tp_descr_get */
2974 0, /* tp_descr_set */
2975 0, /* tp_dictoffset */
2976 object_init, /* tp_init */
2977 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002978 object_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002979 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002980};
2981
2982
2983/* Initialize the __dict__ in a type object */
2984
2985static int
2986add_methods(PyTypeObject *type, PyMethodDef *meth)
2987{
Guido van Rossum687ae002001-10-15 22:03:32 +00002988 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002989
2990 for (; meth->ml_name != NULL; meth++) {
2991 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002992 if (PyDict_GetItemString(dict, meth->ml_name) &&
2993 !(meth->ml_flags & METH_COEXIST))
2994 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002995 if (meth->ml_flags & METH_CLASS) {
2996 if (meth->ml_flags & METH_STATIC) {
2997 PyErr_SetString(PyExc_ValueError,
2998 "method cannot be both class and static");
2999 return -1;
3000 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00003001 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00003002 }
3003 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00003004 PyObject *cfunc = PyCFunction_New(meth, NULL);
3005 if (cfunc == NULL)
3006 return -1;
3007 descr = PyStaticMethod_New(cfunc);
3008 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003009 }
3010 else {
3011 descr = PyDescr_NewMethod(type, meth);
3012 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003013 if (descr == NULL)
3014 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003015 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003016 return -1;
3017 Py_DECREF(descr);
3018 }
3019 return 0;
3020}
3021
3022static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003023add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003024{
Guido van Rossum687ae002001-10-15 22:03:32 +00003025 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003026
3027 for (; memb->name != NULL; memb++) {
3028 PyObject *descr;
3029 if (PyDict_GetItemString(dict, memb->name))
3030 continue;
3031 descr = PyDescr_NewMember(type, memb);
3032 if (descr == NULL)
3033 return -1;
3034 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3035 return -1;
3036 Py_DECREF(descr);
3037 }
3038 return 0;
3039}
3040
3041static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003042add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003043{
Guido van Rossum687ae002001-10-15 22:03:32 +00003044 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003045
3046 for (; gsp->name != NULL; gsp++) {
3047 PyObject *descr;
3048 if (PyDict_GetItemString(dict, gsp->name))
3049 continue;
3050 descr = PyDescr_NewGetSet(type, gsp);
3051
3052 if (descr == NULL)
3053 return -1;
3054 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3055 return -1;
3056 Py_DECREF(descr);
3057 }
3058 return 0;
3059}
3060
Guido van Rossum13d52f02001-08-10 21:24:08 +00003061static void
3062inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003063{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003064 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003065
Guido van Rossum13d52f02001-08-10 21:24:08 +00003066 /* Special flag magic */
3067 if (!type->tp_as_buffer && base->tp_as_buffer) {
3068 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
3069 type->tp_flags |=
3070 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
3071 }
3072 if (!type->tp_as_sequence && base->tp_as_sequence) {
3073 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
3074 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
3075 }
3076 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
3077 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
3078 if ((!type->tp_as_number && base->tp_as_number) ||
3079 (!type->tp_as_sequence && base->tp_as_sequence)) {
3080 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
3081 if (!type->tp_as_number && !type->tp_as_sequence) {
3082 type->tp_flags |= base->tp_flags &
3083 Py_TPFLAGS_HAVE_INPLACEOPS;
3084 }
3085 }
3086 /* Wow */
3087 }
3088 if (!type->tp_as_number && base->tp_as_number) {
3089 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
3090 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
3091 }
3092
3093 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003094 oldsize = base->tp_basicsize;
3095 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3096 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3097 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003098 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
3099 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003100 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003101 if (type->tp_traverse == NULL)
3102 type->tp_traverse = base->tp_traverse;
3103 if (type->tp_clear == NULL)
3104 type->tp_clear = base->tp_clear;
3105 }
3106 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00003107 /* The condition below could use some explanation.
3108 It appears that tp_new is not inherited for static types
3109 whose base class is 'object'; this seems to be a precaution
3110 so that old extension types don't suddenly become
3111 callable (object.__new__ wouldn't insure the invariants
3112 that the extension type's own factory function ensures).
3113 Heap types, of course, are under our control, so they do
3114 inherit tp_new; static extension types that specify some
3115 other built-in type as the default are considered
3116 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003117 if (base != &PyBaseObject_Type ||
3118 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3119 if (type->tp_new == NULL)
3120 type->tp_new = base->tp_new;
3121 }
3122 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003123 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003124
3125 /* Copy other non-function slots */
3126
3127#undef COPYVAL
3128#define COPYVAL(SLOT) \
3129 if (type->SLOT == 0) type->SLOT = base->SLOT
3130
3131 COPYVAL(tp_itemsize);
3132 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
3133 COPYVAL(tp_weaklistoffset);
3134 }
3135 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3136 COPYVAL(tp_dictoffset);
3137 }
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003138
3139 /* Setup fast subclass flags */
3140 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3141 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3142 else if (PyType_IsSubtype(base, &PyType_Type))
3143 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3144 else if (PyType_IsSubtype(base, &PyInt_Type))
3145 type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS;
3146 else if (PyType_IsSubtype(base, &PyLong_Type))
3147 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3148 else if (PyType_IsSubtype(base, &PyString_Type))
3149 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
3150 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3151 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3152 else if (PyType_IsSubtype(base, &PyTuple_Type))
3153 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3154 else if (PyType_IsSubtype(base, &PyList_Type))
3155 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3156 else if (PyType_IsSubtype(base, &PyDict_Type))
3157 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003158}
3159
3160static void
3161inherit_slots(PyTypeObject *type, PyTypeObject *base)
3162{
3163 PyTypeObject *basebase;
3164
3165#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003166#undef COPYSLOT
3167#undef COPYNUM
3168#undef COPYSEQ
3169#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003170#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003171
3172#define SLOTDEFINED(SLOT) \
3173 (base->SLOT != 0 && \
3174 (basebase == NULL || base->SLOT != basebase->SLOT))
3175
Tim Peters6d6c1a32001-08-02 04:15:00 +00003176#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003177 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003178
3179#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3180#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3181#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003182#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003183
Guido van Rossum13d52f02001-08-10 21:24:08 +00003184 /* This won't inherit indirect slots (from tp_as_number etc.)
3185 if type doesn't provide the space. */
3186
3187 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3188 basebase = base->tp_base;
3189 if (basebase->tp_as_number == NULL)
3190 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003191 COPYNUM(nb_add);
3192 COPYNUM(nb_subtract);
3193 COPYNUM(nb_multiply);
3194 COPYNUM(nb_divide);
3195 COPYNUM(nb_remainder);
3196 COPYNUM(nb_divmod);
3197 COPYNUM(nb_power);
3198 COPYNUM(nb_negative);
3199 COPYNUM(nb_positive);
3200 COPYNUM(nb_absolute);
3201 COPYNUM(nb_nonzero);
3202 COPYNUM(nb_invert);
3203 COPYNUM(nb_lshift);
3204 COPYNUM(nb_rshift);
3205 COPYNUM(nb_and);
3206 COPYNUM(nb_xor);
3207 COPYNUM(nb_or);
3208 COPYNUM(nb_coerce);
3209 COPYNUM(nb_int);
3210 COPYNUM(nb_long);
3211 COPYNUM(nb_float);
3212 COPYNUM(nb_oct);
3213 COPYNUM(nb_hex);
3214 COPYNUM(nb_inplace_add);
3215 COPYNUM(nb_inplace_subtract);
3216 COPYNUM(nb_inplace_multiply);
3217 COPYNUM(nb_inplace_divide);
3218 COPYNUM(nb_inplace_remainder);
3219 COPYNUM(nb_inplace_power);
3220 COPYNUM(nb_inplace_lshift);
3221 COPYNUM(nb_inplace_rshift);
3222 COPYNUM(nb_inplace_and);
3223 COPYNUM(nb_inplace_xor);
3224 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003225 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3226 COPYNUM(nb_true_divide);
3227 COPYNUM(nb_floor_divide);
3228 COPYNUM(nb_inplace_true_divide);
3229 COPYNUM(nb_inplace_floor_divide);
3230 }
Guido van Rossum38fff8c2006-03-07 18:50:55 +00003231 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3232 COPYNUM(nb_index);
3233 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003234 }
3235
Guido van Rossum13d52f02001-08-10 21:24:08 +00003236 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3237 basebase = base->tp_base;
3238 if (basebase->tp_as_sequence == NULL)
3239 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003240 COPYSEQ(sq_length);
3241 COPYSEQ(sq_concat);
3242 COPYSEQ(sq_repeat);
3243 COPYSEQ(sq_item);
3244 COPYSEQ(sq_slice);
3245 COPYSEQ(sq_ass_item);
3246 COPYSEQ(sq_ass_slice);
3247 COPYSEQ(sq_contains);
3248 COPYSEQ(sq_inplace_concat);
3249 COPYSEQ(sq_inplace_repeat);
3250 }
3251
Guido van Rossum13d52f02001-08-10 21:24:08 +00003252 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3253 basebase = base->tp_base;
3254 if (basebase->tp_as_mapping == NULL)
3255 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003256 COPYMAP(mp_length);
3257 COPYMAP(mp_subscript);
3258 COPYMAP(mp_ass_subscript);
3259 }
3260
Tim Petersfc57ccb2001-10-12 02:38:24 +00003261 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3262 basebase = base->tp_base;
3263 if (basebase->tp_as_buffer == NULL)
3264 basebase = NULL;
3265 COPYBUF(bf_getreadbuffer);
3266 COPYBUF(bf_getwritebuffer);
3267 COPYBUF(bf_getsegcount);
3268 COPYBUF(bf_getcharbuffer);
3269 }
3270
Guido van Rossum13d52f02001-08-10 21:24:08 +00003271 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003272
Tim Peters6d6c1a32001-08-02 04:15:00 +00003273 COPYSLOT(tp_dealloc);
3274 COPYSLOT(tp_print);
3275 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3276 type->tp_getattr = base->tp_getattr;
3277 type->tp_getattro = base->tp_getattro;
3278 }
3279 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3280 type->tp_setattr = base->tp_setattr;
3281 type->tp_setattro = base->tp_setattro;
3282 }
3283 /* tp_compare see tp_richcompare */
3284 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003285 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003286 COPYSLOT(tp_call);
3287 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003288 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003289 if (type->tp_compare == NULL &&
3290 type->tp_richcompare == NULL &&
3291 type->tp_hash == NULL)
3292 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003293 type->tp_compare = base->tp_compare;
3294 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003295 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003296 }
3297 }
3298 else {
3299 COPYSLOT(tp_compare);
3300 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003301 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3302 COPYSLOT(tp_iter);
3303 COPYSLOT(tp_iternext);
3304 }
3305 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3306 COPYSLOT(tp_descr_get);
3307 COPYSLOT(tp_descr_set);
3308 COPYSLOT(tp_dictoffset);
3309 COPYSLOT(tp_init);
3310 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003311 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003312 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3313 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3314 /* They agree about gc. */
3315 COPYSLOT(tp_free);
3316 }
3317 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3318 type->tp_free == NULL &&
3319 base->tp_free == _PyObject_Del) {
3320 /* A bit of magic to plug in the correct default
3321 * tp_free function when a derived class adds gc,
3322 * didn't define tp_free, and the base uses the
3323 * default non-gc tp_free.
3324 */
3325 type->tp_free = PyObject_GC_Del;
3326 }
3327 /* else they didn't agree about gc, and there isn't something
3328 * obvious to be done -- the type is on its own.
3329 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003330 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003331}
3332
Jeremy Hylton938ace62002-07-17 16:30:39 +00003333static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003334
Tim Peters6d6c1a32001-08-02 04:15:00 +00003335int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003336PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003337{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003338 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003339 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003340 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003341
Guido van Rossumcab05802002-06-10 15:29:03 +00003342 if (type->tp_flags & Py_TPFLAGS_READY) {
3343 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003344 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003345 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003346 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003347
3348 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003349
Tim Peters36eb4df2003-03-23 03:33:13 +00003350#ifdef Py_TRACE_REFS
3351 /* PyType_Ready is the closest thing we have to a choke point
3352 * for type objects, so is the best place I can think of to try
3353 * to get type objects into the doubly-linked list of all objects.
3354 * Still, not all type objects go thru PyType_Ready.
3355 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003356 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003357#endif
3358
Tim Peters6d6c1a32001-08-02 04:15:00 +00003359 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3360 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003361 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003362 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003363 Py_INCREF(base);
3364 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003365
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003366 /* Now the only way base can still be NULL is if type is
3367 * &PyBaseObject_Type.
3368 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003369
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003370 /* Initialize the base class */
3371 if (base && base->tp_dict == NULL) {
3372 if (PyType_Ready(base) < 0)
3373 goto error;
3374 }
3375
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003376 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003377 compilable separately on Windows can call PyType_Ready() instead of
3378 initializing the ob_type field of their type objects. */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003379 /* The test for base != NULL is really unnecessary, since base is only
3380 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3381 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3382 know that. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003383 if (type->ob_type == NULL && base != NULL)
Guido van Rossum0986d822002-04-08 01:38:42 +00003384 type->ob_type = base->ob_type;
3385
Tim Peters6d6c1a32001-08-02 04:15:00 +00003386 /* Initialize tp_bases */
3387 bases = type->tp_bases;
3388 if (bases == NULL) {
3389 if (base == NULL)
3390 bases = PyTuple_New(0);
3391 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003392 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003393 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003394 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003395 type->tp_bases = bases;
3396 }
3397
Guido van Rossum687ae002001-10-15 22:03:32 +00003398 /* Initialize tp_dict */
3399 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003400 if (dict == NULL) {
3401 dict = PyDict_New();
3402 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003403 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003404 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003405 }
3406
Guido van Rossum687ae002001-10-15 22:03:32 +00003407 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003408 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003409 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003410 if (type->tp_methods != NULL) {
3411 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003412 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003413 }
3414 if (type->tp_members != NULL) {
3415 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003416 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003417 }
3418 if (type->tp_getset != NULL) {
3419 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003420 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003421 }
3422
Tim Peters6d6c1a32001-08-02 04:15:00 +00003423 /* Calculate method resolution order */
3424 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003425 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003426 }
3427
Guido van Rossum13d52f02001-08-10 21:24:08 +00003428 /* Inherit special flags from dominant base */
3429 if (type->tp_base != NULL)
3430 inherit_special(type, type->tp_base);
3431
Tim Peters6d6c1a32001-08-02 04:15:00 +00003432 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003433 bases = type->tp_mro;
3434 assert(bases != NULL);
3435 assert(PyTuple_Check(bases));
3436 n = PyTuple_GET_SIZE(bases);
3437 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003438 PyObject *b = PyTuple_GET_ITEM(bases, i);
3439 if (PyType_Check(b))
3440 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003441 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003442
Tim Peters3cfe7542003-05-21 21:29:48 +00003443 /* Sanity check for tp_free. */
3444 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3445 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003446 /* This base class needs to call tp_free, but doesn't have
3447 * one, or its tp_free is for non-gc'ed objects.
3448 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003449 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3450 "gc and is a base type but has inappropriate "
3451 "tp_free slot",
3452 type->tp_name);
3453 goto error;
3454 }
3455
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003456 /* if the type dictionary doesn't contain a __doc__, set it from
3457 the tp_doc slot.
3458 */
3459 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3460 if (type->tp_doc != NULL) {
3461 PyObject *doc = PyString_FromString(type->tp_doc);
Neal Norwitze1fdb322006-07-21 05:32:28 +00003462 if (doc == NULL)
3463 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003464 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3465 Py_DECREF(doc);
3466 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003467 PyDict_SetItemString(type->tp_dict,
3468 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003469 }
3470 }
3471
Guido van Rossum13d52f02001-08-10 21:24:08 +00003472 /* Some more special stuff */
3473 base = type->tp_base;
3474 if (base != NULL) {
3475 if (type->tp_as_number == NULL)
3476 type->tp_as_number = base->tp_as_number;
3477 if (type->tp_as_sequence == NULL)
3478 type->tp_as_sequence = base->tp_as_sequence;
3479 if (type->tp_as_mapping == NULL)
3480 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003481 if (type->tp_as_buffer == NULL)
3482 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003483 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003484
Guido van Rossum1c450732001-10-08 15:18:27 +00003485 /* Link into each base class's list of subclasses */
3486 bases = type->tp_bases;
3487 n = PyTuple_GET_SIZE(bases);
3488 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003489 PyObject *b = PyTuple_GET_ITEM(bases, i);
3490 if (PyType_Check(b) &&
3491 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003492 goto error;
3493 }
3494
Guido van Rossum13d52f02001-08-10 21:24:08 +00003495 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003496 assert(type->tp_dict != NULL);
3497 type->tp_flags =
3498 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003499 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003500
3501 error:
3502 type->tp_flags &= ~Py_TPFLAGS_READYING;
3503 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003504}
3505
Guido van Rossum1c450732001-10-08 15:18:27 +00003506static int
3507add_subclass(PyTypeObject *base, PyTypeObject *type)
3508{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003509 Py_ssize_t i;
3510 int result;
Anthony Baxtera6286212006-04-11 07:42:36 +00003511 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003512
3513 list = base->tp_subclasses;
3514 if (list == NULL) {
3515 base->tp_subclasses = list = PyList_New(0);
3516 if (list == NULL)
3517 return -1;
3518 }
3519 assert(PyList_Check(list));
Anthony Baxtera6286212006-04-11 07:42:36 +00003520 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003521 i = PyList_GET_SIZE(list);
3522 while (--i >= 0) {
3523 ref = PyList_GET_ITEM(list, i);
3524 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003525 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Anthony Baxtera6286212006-04-11 07:42:36 +00003526 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003527 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003528 result = PyList_Append(list, newobj);
3529 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003530 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003531}
3532
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003533static void
3534remove_subclass(PyTypeObject *base, PyTypeObject *type)
3535{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003536 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003537 PyObject *list, *ref;
3538
3539 list = base->tp_subclasses;
3540 if (list == NULL) {
3541 return;
3542 }
3543 assert(PyList_Check(list));
3544 i = PyList_GET_SIZE(list);
3545 while (--i >= 0) {
3546 ref = PyList_GET_ITEM(list, i);
3547 assert(PyWeakref_CheckRef(ref));
3548 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3549 /* this can't fail, right? */
3550 PySequence_DelItem(list, i);
3551 return;
3552 }
3553 }
3554}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003555
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003556static int
3557check_num_args(PyObject *ob, int n)
3558{
3559 if (!PyTuple_CheckExact(ob)) {
3560 PyErr_SetString(PyExc_SystemError,
3561 "PyArg_UnpackTuple() argument list is not a tuple");
3562 return 0;
3563 }
3564 if (n == PyTuple_GET_SIZE(ob))
3565 return 1;
3566 PyErr_Format(
3567 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003568 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003569 return 0;
3570}
3571
Tim Peters6d6c1a32001-08-02 04:15:00 +00003572/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3573
3574/* There's a wrapper *function* for each distinct function typedef used
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003575 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00003576 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3577 Most tables have only one entry; the tables for binary operators have two
3578 entries, one regular and one with reversed arguments. */
3579
3580static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003581wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003582{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003583 lenfunc func = (lenfunc)wrapped;
3584 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003585
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003586 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003587 return NULL;
3588 res = (*func)(self);
3589 if (res == -1 && PyErr_Occurred())
3590 return NULL;
3591 return PyInt_FromLong((long)res);
3592}
3593
Tim Peters6d6c1a32001-08-02 04:15:00 +00003594static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003595wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3596{
3597 inquiry func = (inquiry)wrapped;
3598 int res;
3599
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003600 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003601 return NULL;
3602 res = (*func)(self);
3603 if (res == -1 && PyErr_Occurred())
3604 return NULL;
3605 return PyBool_FromLong((long)res);
3606}
3607
3608static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003609wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3610{
3611 binaryfunc func = (binaryfunc)wrapped;
3612 PyObject *other;
3613
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003614 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003615 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003616 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003617 return (*func)(self, other);
3618}
3619
3620static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003621wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3622{
3623 binaryfunc func = (binaryfunc)wrapped;
3624 PyObject *other;
3625
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003626 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003627 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003628 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003629 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003630 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003631 Py_INCREF(Py_NotImplemented);
3632 return Py_NotImplemented;
3633 }
3634 return (*func)(self, other);
3635}
3636
3637static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003638wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3639{
3640 binaryfunc func = (binaryfunc)wrapped;
3641 PyObject *other;
3642
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003643 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003644 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003645 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003646 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003647 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003648 Py_INCREF(Py_NotImplemented);
3649 return Py_NotImplemented;
3650 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003651 return (*func)(other, self);
3652}
3653
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003654static PyObject *
3655wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3656{
3657 coercion func = (coercion)wrapped;
3658 PyObject *other, *res;
3659 int ok;
3660
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003661 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003662 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003663 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003664 ok = func(&self, &other);
3665 if (ok < 0)
3666 return NULL;
3667 if (ok > 0) {
3668 Py_INCREF(Py_NotImplemented);
3669 return Py_NotImplemented;
3670 }
3671 res = PyTuple_New(2);
3672 if (res == NULL) {
3673 Py_DECREF(self);
3674 Py_DECREF(other);
3675 return NULL;
3676 }
3677 PyTuple_SET_ITEM(res, 0, self);
3678 PyTuple_SET_ITEM(res, 1, other);
3679 return res;
3680}
3681
Tim Peters6d6c1a32001-08-02 04:15:00 +00003682static PyObject *
3683wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3684{
3685 ternaryfunc func = (ternaryfunc)wrapped;
3686 PyObject *other;
3687 PyObject *third = Py_None;
3688
3689 /* Note: This wrapper only works for __pow__() */
3690
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003691 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003692 return NULL;
3693 return (*func)(self, other, third);
3694}
3695
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003696static PyObject *
3697wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3698{
3699 ternaryfunc func = (ternaryfunc)wrapped;
3700 PyObject *other;
3701 PyObject *third = Py_None;
3702
3703 /* Note: This wrapper only works for __pow__() */
3704
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003705 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003706 return NULL;
3707 return (*func)(other, self, third);
3708}
3709
Tim Peters6d6c1a32001-08-02 04:15:00 +00003710static PyObject *
3711wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3712{
3713 unaryfunc func = (unaryfunc)wrapped;
3714
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003715 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003716 return NULL;
3717 return (*func)(self);
3718}
3719
Tim Peters6d6c1a32001-08-02 04:15:00 +00003720static PyObject *
Armin Rigo314861c2006-03-30 14:04:02 +00003721wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003722{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003723 ssizeargfunc func = (ssizeargfunc)wrapped;
Armin Rigo314861c2006-03-30 14:04:02 +00003724 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003725 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003726
Armin Rigo314861c2006-03-30 14:04:02 +00003727 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
3728 return NULL;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00003729 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Armin Rigo314861c2006-03-30 14:04:02 +00003730 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003731 return NULL;
3732 return (*func)(self, i);
3733}
3734
Martin v. Löwis18e16552006-02-15 17:27:45 +00003735static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00003736getindex(PyObject *self, PyObject *arg)
3737{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003738 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003739
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00003740 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003741 if (i == -1 && PyErr_Occurred())
3742 return -1;
3743 if (i < 0) {
3744 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3745 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003746 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003747 if (n < 0)
3748 return -1;
3749 i += n;
3750 }
3751 }
3752 return i;
3753}
3754
3755static PyObject *
3756wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3757{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003758 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003759 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003760 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003761
Guido van Rossumf4593e02001-10-03 12:09:30 +00003762 if (PyTuple_GET_SIZE(args) == 1) {
3763 arg = PyTuple_GET_ITEM(args, 0);
3764 i = getindex(self, arg);
3765 if (i == -1 && PyErr_Occurred())
3766 return NULL;
3767 return (*func)(self, i);
3768 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003769 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003770 assert(PyErr_Occurred());
3771 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003772}
3773
Tim Peters6d6c1a32001-08-02 04:15:00 +00003774static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003775wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003776{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003777 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
3778 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003779
Martin v. Löwis18e16552006-02-15 17:27:45 +00003780 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003781 return NULL;
3782 return (*func)(self, i, j);
3783}
3784
Tim Peters6d6c1a32001-08-02 04:15:00 +00003785static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003786wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003787{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003788 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3789 Py_ssize_t i;
3790 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003791 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003792
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003793 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003794 return NULL;
3795 i = getindex(self, arg);
3796 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003797 return NULL;
3798 res = (*func)(self, i, value);
3799 if (res == -1 && PyErr_Occurred())
3800 return NULL;
3801 Py_INCREF(Py_None);
3802 return Py_None;
3803}
3804
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003805static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003806wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003807{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003808 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3809 Py_ssize_t i;
3810 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003811 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003812
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003813 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003814 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003815 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003816 i = getindex(self, arg);
3817 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003818 return NULL;
3819 res = (*func)(self, i, NULL);
3820 if (res == -1 && PyErr_Occurred())
3821 return NULL;
3822 Py_INCREF(Py_None);
3823 return Py_None;
3824}
3825
Tim Peters6d6c1a32001-08-02 04:15:00 +00003826static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003827wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003828{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003829 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3830 Py_ssize_t i, j;
3831 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003832 PyObject *value;
3833
Martin v. Löwis18e16552006-02-15 17:27:45 +00003834 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003835 return NULL;
3836 res = (*func)(self, i, j, value);
3837 if (res == -1 && PyErr_Occurred())
3838 return NULL;
3839 Py_INCREF(Py_None);
3840 return Py_None;
3841}
3842
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003843static PyObject *
3844wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3845{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003846 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3847 Py_ssize_t i, j;
3848 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003849
Martin v. Löwis18e16552006-02-15 17:27:45 +00003850 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003851 return NULL;
3852 res = (*func)(self, i, j, NULL);
3853 if (res == -1 && PyErr_Occurred())
3854 return NULL;
3855 Py_INCREF(Py_None);
3856 return Py_None;
3857}
3858
Tim Peters6d6c1a32001-08-02 04:15:00 +00003859/* XXX objobjproc is a misnomer; should be objargpred */
3860static PyObject *
3861wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3862{
3863 objobjproc func = (objobjproc)wrapped;
3864 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003865 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003866
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003867 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003868 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003869 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003870 res = (*func)(self, value);
3871 if (res == -1 && PyErr_Occurred())
3872 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003873 else
3874 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003875}
3876
Tim Peters6d6c1a32001-08-02 04:15:00 +00003877static PyObject *
3878wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3879{
3880 objobjargproc func = (objobjargproc)wrapped;
3881 int res;
3882 PyObject *key, *value;
3883
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003884 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003885 return NULL;
3886 res = (*func)(self, key, value);
3887 if (res == -1 && PyErr_Occurred())
3888 return NULL;
3889 Py_INCREF(Py_None);
3890 return Py_None;
3891}
3892
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003893static PyObject *
3894wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3895{
3896 objobjargproc func = (objobjargproc)wrapped;
3897 int res;
3898 PyObject *key;
3899
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003900 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003901 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003902 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003903 res = (*func)(self, key, NULL);
3904 if (res == -1 && PyErr_Occurred())
3905 return NULL;
3906 Py_INCREF(Py_None);
3907 return Py_None;
3908}
3909
Tim Peters6d6c1a32001-08-02 04:15:00 +00003910static PyObject *
3911wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3912{
3913 cmpfunc func = (cmpfunc)wrapped;
3914 int res;
3915 PyObject *other;
3916
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003917 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003918 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003919 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003920 if (other->ob_type->tp_compare != func &&
3921 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003922 PyErr_Format(
3923 PyExc_TypeError,
3924 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3925 self->ob_type->tp_name,
3926 self->ob_type->tp_name,
3927 other->ob_type->tp_name);
3928 return NULL;
3929 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003930 res = (*func)(self, other);
3931 if (PyErr_Occurred())
3932 return NULL;
3933 return PyInt_FromLong((long)res);
3934}
3935
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003936/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003937 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003938static int
3939hackcheck(PyObject *self, setattrofunc func, char *what)
3940{
3941 PyTypeObject *type = self->ob_type;
3942 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3943 type = type->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003944 /* If type is NULL now, this is a really weird type.
3945 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003946 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003947 PyErr_Format(PyExc_TypeError,
3948 "can't apply this %s to %s object",
3949 what,
3950 type->tp_name);
3951 return 0;
3952 }
3953 return 1;
3954}
3955
Tim Peters6d6c1a32001-08-02 04:15:00 +00003956static PyObject *
3957wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3958{
3959 setattrofunc func = (setattrofunc)wrapped;
3960 int res;
3961 PyObject *name, *value;
3962
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003963 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003964 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003965 if (!hackcheck(self, func, "__setattr__"))
3966 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003967 res = (*func)(self, name, value);
3968 if (res < 0)
3969 return NULL;
3970 Py_INCREF(Py_None);
3971 return Py_None;
3972}
3973
3974static PyObject *
3975wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3976{
3977 setattrofunc func = (setattrofunc)wrapped;
3978 int res;
3979 PyObject *name;
3980
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003981 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003982 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003983 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003984 if (!hackcheck(self, func, "__delattr__"))
3985 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003986 res = (*func)(self, name, NULL);
3987 if (res < 0)
3988 return NULL;
3989 Py_INCREF(Py_None);
3990 return Py_None;
3991}
3992
Tim Peters6d6c1a32001-08-02 04:15:00 +00003993static PyObject *
3994wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3995{
3996 hashfunc func = (hashfunc)wrapped;
3997 long res;
3998
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003999 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004000 return NULL;
4001 res = (*func)(self);
4002 if (res == -1 && PyErr_Occurred())
4003 return NULL;
4004 return PyInt_FromLong(res);
4005}
4006
Tim Peters6d6c1a32001-08-02 04:15:00 +00004007static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004008wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004009{
4010 ternaryfunc func = (ternaryfunc)wrapped;
4011
Guido van Rossumc8e56452001-10-22 00:43:43 +00004012 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004013}
4014
Tim Peters6d6c1a32001-08-02 04:15:00 +00004015static PyObject *
4016wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4017{
4018 richcmpfunc func = (richcmpfunc)wrapped;
4019 PyObject *other;
4020
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004021 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004022 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004023 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004024 return (*func)(self, other, op);
4025}
4026
4027#undef RICHCMP_WRAPPER
4028#define RICHCMP_WRAPPER(NAME, OP) \
4029static PyObject * \
4030richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4031{ \
4032 return wrap_richcmpfunc(self, args, wrapped, OP); \
4033}
4034
Jack Jansen8e938b42001-08-08 15:29:49 +00004035RICHCMP_WRAPPER(lt, Py_LT)
4036RICHCMP_WRAPPER(le, Py_LE)
4037RICHCMP_WRAPPER(eq, Py_EQ)
4038RICHCMP_WRAPPER(ne, Py_NE)
4039RICHCMP_WRAPPER(gt, Py_GT)
4040RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004041
Tim Peters6d6c1a32001-08-02 04:15:00 +00004042static PyObject *
4043wrap_next(PyObject *self, PyObject *args, void *wrapped)
4044{
4045 unaryfunc func = (unaryfunc)wrapped;
4046 PyObject *res;
4047
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004048 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004049 return NULL;
4050 res = (*func)(self);
4051 if (res == NULL && !PyErr_Occurred())
4052 PyErr_SetNone(PyExc_StopIteration);
4053 return res;
4054}
4055
Tim Peters6d6c1a32001-08-02 04:15:00 +00004056static PyObject *
4057wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4058{
4059 descrgetfunc func = (descrgetfunc)wrapped;
4060 PyObject *obj;
4061 PyObject *type = NULL;
4062
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004063 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004064 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004065 if (obj == Py_None)
4066 obj = NULL;
4067 if (type == Py_None)
4068 type = NULL;
4069 if (type == NULL &&obj == NULL) {
4070 PyErr_SetString(PyExc_TypeError,
4071 "__get__(None, None) is invalid");
4072 return NULL;
4073 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004074 return (*func)(self, obj, type);
4075}
4076
Tim Peters6d6c1a32001-08-02 04:15:00 +00004077static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004078wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004079{
4080 descrsetfunc func = (descrsetfunc)wrapped;
4081 PyObject *obj, *value;
4082 int ret;
4083
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004084 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004085 return NULL;
4086 ret = (*func)(self, obj, value);
4087 if (ret < 0)
4088 return NULL;
4089 Py_INCREF(Py_None);
4090 return Py_None;
4091}
Guido van Rossum22b13872002-08-06 21:41:44 +00004092
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004093static PyObject *
4094wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4095{
4096 descrsetfunc func = (descrsetfunc)wrapped;
4097 PyObject *obj;
4098 int ret;
4099
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004100 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004101 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004102 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004103 ret = (*func)(self, obj, NULL);
4104 if (ret < 0)
4105 return NULL;
4106 Py_INCREF(Py_None);
4107 return Py_None;
4108}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004109
Tim Peters6d6c1a32001-08-02 04:15:00 +00004110static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004111wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004112{
4113 initproc func = (initproc)wrapped;
4114
Guido van Rossumc8e56452001-10-22 00:43:43 +00004115 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004116 return NULL;
4117 Py_INCREF(Py_None);
4118 return Py_None;
4119}
4120
Tim Peters6d6c1a32001-08-02 04:15:00 +00004121static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004122tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004123{
Barry Warsaw60f01882001-08-22 19:24:42 +00004124 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004125 PyObject *arg0, *res;
4126
4127 if (self == NULL || !PyType_Check(self))
4128 Py_FatalError("__new__() called with non-type 'self'");
4129 type = (PyTypeObject *)self;
4130 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004131 PyErr_Format(PyExc_TypeError,
4132 "%s.__new__(): not enough arguments",
4133 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004134 return NULL;
4135 }
4136 arg0 = PyTuple_GET_ITEM(args, 0);
4137 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004138 PyErr_Format(PyExc_TypeError,
4139 "%s.__new__(X): X is not a type object (%s)",
4140 type->tp_name,
4141 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004142 return NULL;
4143 }
4144 subtype = (PyTypeObject *)arg0;
4145 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004146 PyErr_Format(PyExc_TypeError,
4147 "%s.__new__(%s): %s is not a subtype of %s",
4148 type->tp_name,
4149 subtype->tp_name,
4150 subtype->tp_name,
4151 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004152 return NULL;
4153 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004154
4155 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004156 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004157 most derived base that's not a heap type is this type. */
4158 staticbase = subtype;
4159 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4160 staticbase = staticbase->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004161 /* If staticbase is NULL now, it is a really weird type.
4162 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004163 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004164 PyErr_Format(PyExc_TypeError,
4165 "%s.__new__(%s) is not safe, use %s.__new__()",
4166 type->tp_name,
4167 subtype->tp_name,
4168 staticbase == NULL ? "?" : staticbase->tp_name);
4169 return NULL;
4170 }
4171
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004172 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4173 if (args == NULL)
4174 return NULL;
4175 res = type->tp_new(subtype, args, kwds);
4176 Py_DECREF(args);
4177 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004178}
4179
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004180static struct PyMethodDef tp_new_methoddef[] = {
4181 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004182 PyDoc_STR("T.__new__(S, ...) -> "
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004183 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004184 {0}
4185};
4186
4187static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004188add_tp_new_wrapper(PyTypeObject *type)
4189{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004190 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004191
Guido van Rossum687ae002001-10-15 22:03:32 +00004192 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004193 return 0;
4194 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004195 if (func == NULL)
4196 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004197 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004198 Py_DECREF(func);
4199 return -1;
4200 }
4201 Py_DECREF(func);
4202 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004203}
4204
Guido van Rossumf040ede2001-08-07 16:40:56 +00004205/* Slot wrappers that call the corresponding __foo__ slot. See comments
4206 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004207
Guido van Rossumdc91b992001-08-08 22:26:22 +00004208#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004209static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004210FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004211{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004212 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004213 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004214}
4215
Guido van Rossumdc91b992001-08-08 22:26:22 +00004216#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004217static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004218FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004219{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004220 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004221 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004222}
4223
Guido van Rossumcd118802003-01-06 22:57:47 +00004224/* Boolean helper for SLOT1BINFULL().
4225 right.__class__ is a nontrivial subclass of left.__class__. */
4226static int
4227method_is_overloaded(PyObject *left, PyObject *right, char *name)
4228{
4229 PyObject *a, *b;
4230 int ok;
4231
4232 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
4233 if (b == NULL) {
4234 PyErr_Clear();
4235 /* If right doesn't have it, it's not overloaded */
4236 return 0;
4237 }
4238
4239 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
4240 if (a == NULL) {
4241 PyErr_Clear();
4242 Py_DECREF(b);
4243 /* If right has it but left doesn't, it's overloaded */
4244 return 1;
4245 }
4246
4247 ok = PyObject_RichCompareBool(a, b, Py_NE);
4248 Py_DECREF(a);
4249 Py_DECREF(b);
4250 if (ok < 0) {
4251 PyErr_Clear();
4252 return 0;
4253 }
4254
4255 return ok;
4256}
4257
Guido van Rossumdc91b992001-08-08 22:26:22 +00004258
4259#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004260static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004261FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004262{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004263 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004264 int do_other = self->ob_type != other->ob_type && \
4265 other->ob_type->tp_as_number != NULL && \
4266 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004267 if (self->ob_type->tp_as_number != NULL && \
4268 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
4269 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004270 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004271 PyType_IsSubtype(other->ob_type, self->ob_type) && \
4272 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004273 r = call_maybe( \
4274 other, ROPSTR, &rcache_str, "(O)", self); \
4275 if (r != Py_NotImplemented) \
4276 return r; \
4277 Py_DECREF(r); \
4278 do_other = 0; \
4279 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004280 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004281 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004282 if (r != Py_NotImplemented || \
4283 other->ob_type == self->ob_type) \
4284 return r; \
4285 Py_DECREF(r); \
4286 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004287 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004288 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004289 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004290 } \
4291 Py_INCREF(Py_NotImplemented); \
4292 return Py_NotImplemented; \
4293}
4294
4295#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4296 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4297
4298#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4299static PyObject * \
4300FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4301{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004302 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004303 return call_method(self, OPSTR, &cache_str, \
4304 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004305}
4306
Martin v. Löwis18e16552006-02-15 17:27:45 +00004307static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004308slot_sq_length(PyObject *self)
4309{
Guido van Rossum2730b132001-08-28 18:22:14 +00004310 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004311 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004312 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004313
4314 if (res == NULL)
4315 return -1;
Neal Norwitz1872b1c2006-08-12 18:44:06 +00004316 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004317 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004318 if (len < 0) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00004319 if (!PyErr_Occurred())
4320 PyErr_SetString(PyExc_ValueError,
4321 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004322 return -1;
4323 }
Guido van Rossum26111622001-10-01 16:42:49 +00004324 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004325}
4326
Guido van Rossumf4593e02001-10-03 12:09:30 +00004327/* Super-optimized version of slot_sq_item.
4328 Other slots could do the same... */
4329static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004330slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004331{
4332 static PyObject *getitem_str;
4333 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4334 descrgetfunc f;
4335
4336 if (getitem_str == NULL) {
4337 getitem_str = PyString_InternFromString("__getitem__");
4338 if (getitem_str == NULL)
4339 return NULL;
4340 }
4341 func = _PyType_Lookup(self->ob_type, getitem_str);
4342 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004343 if ((f = func->ob_type->tp_descr_get) == NULL)
4344 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004345 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004346 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004347 if (func == NULL) {
4348 return NULL;
4349 }
4350 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004351 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004352 if (ival != NULL) {
4353 args = PyTuple_New(1);
4354 if (args != NULL) {
4355 PyTuple_SET_ITEM(args, 0, ival);
4356 retval = PyObject_Call(func, args, NULL);
4357 Py_XDECREF(args);
4358 Py_XDECREF(func);
4359 return retval;
4360 }
4361 }
4362 }
4363 else {
4364 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4365 }
4366 Py_XDECREF(args);
4367 Py_XDECREF(ival);
4368 Py_XDECREF(func);
4369 return NULL;
4370}
4371
Martin v. Löwis18e16552006-02-15 17:27:45 +00004372SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004373
4374static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004375slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004376{
4377 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004378 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004379
4380 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004381 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004382 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004383 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004384 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004385 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004386 if (res == NULL)
4387 return -1;
4388 Py_DECREF(res);
4389 return 0;
4390}
4391
4392static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004393slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004394{
4395 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004396 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004397
4398 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004399 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004400 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004401 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004402 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004403 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004404 if (res == NULL)
4405 return -1;
4406 Py_DECREF(res);
4407 return 0;
4408}
4409
4410static int
4411slot_sq_contains(PyObject *self, PyObject *value)
4412{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004413 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004414 int result = -1;
4415
Guido van Rossum60718732001-08-28 17:47:51 +00004416 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004417
Guido van Rossum55f20992001-10-01 17:18:22 +00004418 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004419 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004420 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004421 if (args == NULL)
4422 res = NULL;
4423 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004424 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004425 Py_DECREF(args);
4426 }
4427 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004428 if (res != NULL) {
4429 result = PyObject_IsTrue(res);
4430 Py_DECREF(res);
4431 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004432 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004433 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004434 /* Possible results: -1 and 1 */
4435 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004436 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004437 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004438 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004439}
4440
Tim Peters6d6c1a32001-08-02 04:15:00 +00004441#define slot_mp_length slot_sq_length
4442
Guido van Rossumdc91b992001-08-08 22:26:22 +00004443SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004444
4445static int
4446slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4447{
4448 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004449 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004450
4451 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004452 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004453 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004454 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004455 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004456 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004457 if (res == NULL)
4458 return -1;
4459 Py_DECREF(res);
4460 return 0;
4461}
4462
Guido van Rossumdc91b992001-08-08 22:26:22 +00004463SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4464SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4465SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4466SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4467SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4468SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4469
Jeremy Hylton938ace62002-07-17 16:30:39 +00004470static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004471
4472SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4473 nb_power, "__pow__", "__rpow__")
4474
4475static PyObject *
4476slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4477{
Guido van Rossum2730b132001-08-28 18:22:14 +00004478 static PyObject *pow_str;
4479
Guido van Rossumdc91b992001-08-08 22:26:22 +00004480 if (modulus == Py_None)
4481 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004482 /* Three-arg power doesn't use __rpow__. But ternary_op
4483 can call this when the second argument's type uses
4484 slot_nb_power, so check before calling self.__pow__. */
4485 if (self->ob_type->tp_as_number != NULL &&
4486 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4487 return call_method(self, "__pow__", &pow_str,
4488 "(OO)", other, modulus);
4489 }
4490 Py_INCREF(Py_NotImplemented);
4491 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004492}
4493
4494SLOT0(slot_nb_negative, "__neg__")
4495SLOT0(slot_nb_positive, "__pos__")
4496SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004497
4498static int
4499slot_nb_nonzero(PyObject *self)
4500{
Tim Petersea7f75d2002-12-07 21:39:16 +00004501 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004502 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004503 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004504
Guido van Rossum55f20992001-10-01 17:18:22 +00004505 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004506 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004507 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004508 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004509 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004510 if (func == NULL)
4511 return PyErr_Occurred() ? -1 : 1;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004512 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004513 args = PyTuple_New(0);
4514 if (args != NULL) {
4515 PyObject *temp = PyObject_Call(func, args, NULL);
4516 Py_DECREF(args);
4517 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004518 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004519 result = PyObject_IsTrue(temp);
4520 else {
4521 PyErr_Format(PyExc_TypeError,
4522 "__nonzero__ should return "
4523 "bool or int, returned %s",
4524 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004525 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004526 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004527 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004528 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004529 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004530 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004531 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004532}
4533
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004534
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004535static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004536slot_nb_index(PyObject *self)
4537{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004538 static PyObject *index_str;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004539 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004540}
4541
4542
Guido van Rossumdc91b992001-08-08 22:26:22 +00004543SLOT0(slot_nb_invert, "__invert__")
4544SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4545SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4546SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4547SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4548SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004549
4550static int
4551slot_nb_coerce(PyObject **a, PyObject **b)
4552{
4553 static PyObject *coerce_str;
4554 PyObject *self = *a, *other = *b;
4555
4556 if (self->ob_type->tp_as_number != NULL &&
4557 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4558 PyObject *r;
4559 r = call_maybe(
4560 self, "__coerce__", &coerce_str, "(O)", other);
4561 if (r == NULL)
4562 return -1;
4563 if (r == Py_NotImplemented) {
4564 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004565 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004566 else {
4567 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4568 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004569 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004570 Py_DECREF(r);
4571 return -1;
4572 }
4573 *a = PyTuple_GET_ITEM(r, 0);
4574 Py_INCREF(*a);
4575 *b = PyTuple_GET_ITEM(r, 1);
4576 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004577 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004578 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004579 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004580 }
4581 if (other->ob_type->tp_as_number != NULL &&
4582 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4583 PyObject *r;
4584 r = call_maybe(
4585 other, "__coerce__", &coerce_str, "(O)", self);
4586 if (r == NULL)
4587 return -1;
4588 if (r == Py_NotImplemented) {
4589 Py_DECREF(r);
4590 return 1;
4591 }
4592 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4593 PyErr_SetString(PyExc_TypeError,
4594 "__coerce__ didn't return a 2-tuple");
4595 Py_DECREF(r);
4596 return -1;
4597 }
4598 *a = PyTuple_GET_ITEM(r, 1);
4599 Py_INCREF(*a);
4600 *b = PyTuple_GET_ITEM(r, 0);
4601 Py_INCREF(*b);
4602 Py_DECREF(r);
4603 return 0;
4604 }
4605 return 1;
4606}
4607
Guido van Rossumdc91b992001-08-08 22:26:22 +00004608SLOT0(slot_nb_int, "__int__")
4609SLOT0(slot_nb_long, "__long__")
4610SLOT0(slot_nb_float, "__float__")
4611SLOT0(slot_nb_oct, "__oct__")
4612SLOT0(slot_nb_hex, "__hex__")
4613SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4614SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4615SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4616SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4617SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Martin v. Löwisfd963262007-02-09 12:19:32 +00004618/* Can't use SLOT1 here, because nb_inplace_power is ternary */
4619static PyObject *
4620slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4621{
4622 static PyObject *cache_str;
4623 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
4624}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004625SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4626SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4627SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4628SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4629SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4630SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4631 "__floordiv__", "__rfloordiv__")
4632SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4633SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4634SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004635
4636static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004637half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004638{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004639 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004640 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004641 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004642
Guido van Rossum60718732001-08-28 17:47:51 +00004643 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004644 if (func == NULL) {
4645 PyErr_Clear();
4646 }
4647 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004648 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004649 if (args == NULL)
4650 res = NULL;
4651 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004652 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004653 Py_DECREF(args);
4654 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004655 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004656 if (res != Py_NotImplemented) {
4657 if (res == NULL)
4658 return -2;
4659 c = PyInt_AsLong(res);
4660 Py_DECREF(res);
4661 if (c == -1 && PyErr_Occurred())
4662 return -2;
4663 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4664 }
4665 Py_DECREF(res);
4666 }
4667 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004668}
4669
Guido van Rossumab3b0342001-09-18 20:38:53 +00004670/* This slot is published for the benefit of try_3way_compare in object.c */
4671int
4672_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004673{
4674 int c;
4675
Guido van Rossumab3b0342001-09-18 20:38:53 +00004676 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004677 c = half_compare(self, other);
4678 if (c <= 1)
4679 return c;
4680 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004681 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004682 c = half_compare(other, self);
4683 if (c < -1)
4684 return -2;
4685 if (c <= 1)
4686 return -c;
4687 }
4688 return (void *)self < (void *)other ? -1 :
4689 (void *)self > (void *)other ? 1 : 0;
4690}
4691
4692static PyObject *
4693slot_tp_repr(PyObject *self)
4694{
4695 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004696 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004697
Guido van Rossum60718732001-08-28 17:47:51 +00004698 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004699 if (func != NULL) {
4700 res = PyEval_CallObject(func, NULL);
4701 Py_DECREF(func);
4702 return res;
4703 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004704 PyErr_Clear();
4705 return PyString_FromFormat("<%s object at %p>",
4706 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004707}
4708
4709static PyObject *
4710slot_tp_str(PyObject *self)
4711{
4712 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004713 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004714
Guido van Rossum60718732001-08-28 17:47:51 +00004715 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004716 if (func != NULL) {
4717 res = PyEval_CallObject(func, NULL);
4718 Py_DECREF(func);
4719 return res;
4720 }
4721 else {
4722 PyErr_Clear();
4723 return slot_tp_repr(self);
4724 }
4725}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004726
4727static long
4728slot_tp_hash(PyObject *self)
4729{
Tim Peters61ce0a92002-12-06 23:38:02 +00004730 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004731 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004732 long h;
4733
Guido van Rossum60718732001-08-28 17:47:51 +00004734 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004735
4736 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004737 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004738 Py_DECREF(func);
4739 if (res == NULL)
4740 return -1;
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00004741 if (PyLong_Check(res))
Armin Rigo51fc8c42006-08-09 14:55:26 +00004742 h = PyLong_Type.tp_hash(res);
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00004743 else
4744 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004745 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004746 }
4747 else {
4748 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004749 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004750 if (func == NULL) {
4751 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004752 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004753 }
4754 if (func != NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00004755 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
4756 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004757 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004758 return -1;
4759 }
4760 PyErr_Clear();
4761 h = _Py_HashPointer((void *)self);
4762 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004763 if (h == -1 && !PyErr_Occurred())
4764 h = -2;
4765 return h;
4766}
4767
4768static PyObject *
4769slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4770{
Guido van Rossum60718732001-08-28 17:47:51 +00004771 static PyObject *call_str;
4772 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004773 PyObject *res;
4774
4775 if (meth == NULL)
4776 return NULL;
Armin Rigo53c1692f2006-06-21 21:58:50 +00004777
4778 /* PyObject_Call() will end up calling slot_tp_call() again if
4779 the object returned for __call__ has __call__ itself defined
4780 upon it. This can be an infinite recursion if you set
4781 __call__ in a class to an instance of it. */
Neal Norwitzb1149842006-06-23 03:32:44 +00004782 if (Py_EnterRecursiveCall(" in __call__")) {
4783 Py_DECREF(meth);
Armin Rigo53c1692f2006-06-21 21:58:50 +00004784 return NULL;
Neal Norwitzb1149842006-06-23 03:32:44 +00004785 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004786 res = PyObject_Call(meth, args, kwds);
Armin Rigo53c1692f2006-06-21 21:58:50 +00004787 Py_LeaveRecursiveCall();
4788
Tim Peters6d6c1a32001-08-02 04:15:00 +00004789 Py_DECREF(meth);
4790 return res;
4791}
4792
Guido van Rossum14a6f832001-10-17 13:59:09 +00004793/* There are two slot dispatch functions for tp_getattro.
4794
4795 - slot_tp_getattro() is used when __getattribute__ is overridden
4796 but no __getattr__ hook is present;
4797
4798 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4799
Guido van Rossumc334df52002-04-04 23:44:47 +00004800 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4801 detects the absence of __getattr__ and then installs the simpler slot if
4802 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004803
Tim Peters6d6c1a32001-08-02 04:15:00 +00004804static PyObject *
4805slot_tp_getattro(PyObject *self, PyObject *name)
4806{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004807 static PyObject *getattribute_str = NULL;
4808 return call_method(self, "__getattribute__", &getattribute_str,
4809 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004810}
4811
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004812static PyObject *
4813slot_tp_getattr_hook(PyObject *self, PyObject *name)
4814{
4815 PyTypeObject *tp = self->ob_type;
4816 PyObject *getattr, *getattribute, *res;
4817 static PyObject *getattribute_str = NULL;
4818 static PyObject *getattr_str = NULL;
4819
4820 if (getattr_str == NULL) {
4821 getattr_str = PyString_InternFromString("__getattr__");
4822 if (getattr_str == NULL)
4823 return NULL;
4824 }
4825 if (getattribute_str == NULL) {
4826 getattribute_str =
4827 PyString_InternFromString("__getattribute__");
4828 if (getattribute_str == NULL)
4829 return NULL;
4830 }
4831 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004832 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004833 /* No __getattr__ hook: use a simpler dispatcher */
4834 tp->tp_getattro = slot_tp_getattro;
4835 return slot_tp_getattro(self, name);
4836 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004837 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004838 if (getattribute == NULL ||
4839 (getattribute->ob_type == &PyWrapperDescr_Type &&
4840 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4841 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004842 res = PyObject_GenericGetAttr(self, name);
4843 else
Georg Brandl684fd0c2006-05-25 19:15:31 +00004844 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004845 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004846 PyErr_Clear();
Georg Brandl684fd0c2006-05-25 19:15:31 +00004847 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004848 }
4849 return res;
4850}
4851
Tim Peters6d6c1a32001-08-02 04:15:00 +00004852static int
4853slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4854{
4855 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004856 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004857
4858 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004859 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004860 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004861 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004862 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004863 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004864 if (res == NULL)
4865 return -1;
4866 Py_DECREF(res);
4867 return 0;
4868}
4869
4870/* Map rich comparison operators to their __xx__ namesakes */
4871static char *name_op[] = {
4872 "__lt__",
4873 "__le__",
4874 "__eq__",
4875 "__ne__",
4876 "__gt__",
4877 "__ge__",
4878};
4879
4880static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004881half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004882{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004883 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004884 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004885
Guido van Rossum60718732001-08-28 17:47:51 +00004886 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004887 if (func == NULL) {
4888 PyErr_Clear();
4889 Py_INCREF(Py_NotImplemented);
4890 return Py_NotImplemented;
4891 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004892 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004893 if (args == NULL)
4894 res = NULL;
4895 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004896 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004897 Py_DECREF(args);
4898 }
4899 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004900 return res;
4901}
4902
Guido van Rossumb8f63662001-08-15 23:57:02 +00004903static PyObject *
4904slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4905{
4906 PyObject *res;
4907
4908 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4909 res = half_richcompare(self, other, op);
4910 if (res != Py_NotImplemented)
4911 return res;
4912 Py_DECREF(res);
4913 }
4914 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004915 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004916 if (res != Py_NotImplemented) {
4917 return res;
4918 }
4919 Py_DECREF(res);
4920 }
4921 Py_INCREF(Py_NotImplemented);
4922 return Py_NotImplemented;
4923}
4924
4925static PyObject *
4926slot_tp_iter(PyObject *self)
4927{
4928 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004929 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004930
Guido van Rossum60718732001-08-28 17:47:51 +00004931 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004932 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004933 PyObject *args;
4934 args = res = PyTuple_New(0);
4935 if (args != NULL) {
4936 res = PyObject_Call(func, args, NULL);
4937 Py_DECREF(args);
4938 }
4939 Py_DECREF(func);
4940 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004941 }
4942 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004943 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004944 if (func == NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00004945 PyErr_Format(PyExc_TypeError,
4946 "'%.200s' object is not iterable",
4947 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004948 return NULL;
4949 }
4950 Py_DECREF(func);
4951 return PySeqIter_New(self);
4952}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004953
4954static PyObject *
4955slot_tp_iternext(PyObject *self)
4956{
Guido van Rossum2730b132001-08-28 18:22:14 +00004957 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004958 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004959}
4960
Guido van Rossum1a493502001-08-17 16:47:50 +00004961static PyObject *
4962slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4963{
4964 PyTypeObject *tp = self->ob_type;
4965 PyObject *get;
4966 static PyObject *get_str = NULL;
4967
4968 if (get_str == NULL) {
4969 get_str = PyString_InternFromString("__get__");
4970 if (get_str == NULL)
4971 return NULL;
4972 }
4973 get = _PyType_Lookup(tp, get_str);
4974 if (get == NULL) {
4975 /* Avoid further slowdowns */
4976 if (tp->tp_descr_get == slot_tp_descr_get)
4977 tp->tp_descr_get = NULL;
4978 Py_INCREF(self);
4979 return self;
4980 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004981 if (obj == NULL)
4982 obj = Py_None;
4983 if (type == NULL)
4984 type = Py_None;
Georg Brandl684fd0c2006-05-25 19:15:31 +00004985 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00004986}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004987
4988static int
4989slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4990{
Guido van Rossum2c252392001-08-24 10:13:31 +00004991 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004992 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004993
4994 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004995 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004996 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004997 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004998 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004999 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005000 if (res == NULL)
5001 return -1;
5002 Py_DECREF(res);
5003 return 0;
5004}
5005
5006static int
5007slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5008{
Guido van Rossum60718732001-08-28 17:47:51 +00005009 static PyObject *init_str;
5010 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005011 PyObject *res;
5012
5013 if (meth == NULL)
5014 return -1;
5015 res = PyObject_Call(meth, args, kwds);
5016 Py_DECREF(meth);
5017 if (res == NULL)
5018 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005019 if (res != Py_None) {
Georg Brandlccff7852006-06-18 22:17:29 +00005020 PyErr_Format(PyExc_TypeError,
5021 "__init__() should return None, not '%.200s'",
5022 res->ob_type->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005023 Py_DECREF(res);
5024 return -1;
5025 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005026 Py_DECREF(res);
5027 return 0;
5028}
5029
5030static PyObject *
5031slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5032{
Guido van Rossum7bed2132002-08-08 21:57:53 +00005033 static PyObject *new_str;
5034 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005035 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005036 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005037
Guido van Rossum7bed2132002-08-08 21:57:53 +00005038 if (new_str == NULL) {
5039 new_str = PyString_InternFromString("__new__");
5040 if (new_str == NULL)
5041 return NULL;
5042 }
5043 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005044 if (func == NULL)
5045 return NULL;
5046 assert(PyTuple_Check(args));
5047 n = PyTuple_GET_SIZE(args);
5048 newargs = PyTuple_New(n+1);
5049 if (newargs == NULL)
5050 return NULL;
5051 Py_INCREF(type);
5052 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5053 for (i = 0; i < n; i++) {
5054 x = PyTuple_GET_ITEM(args, i);
5055 Py_INCREF(x);
5056 PyTuple_SET_ITEM(newargs, i+1, x);
5057 }
5058 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00005059 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005060 Py_DECREF(func);
5061 return x;
5062}
5063
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005064static void
5065slot_tp_del(PyObject *self)
5066{
5067 static PyObject *del_str = NULL;
5068 PyObject *del, *res;
5069 PyObject *error_type, *error_value, *error_traceback;
5070
5071 /* Temporarily resurrect the object. */
5072 assert(self->ob_refcnt == 0);
5073 self->ob_refcnt = 1;
5074
5075 /* Save the current exception, if any. */
5076 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5077
5078 /* Execute __del__ method, if any. */
5079 del = lookup_maybe(self, "__del__", &del_str);
5080 if (del != NULL) {
5081 res = PyEval_CallObject(del, NULL);
5082 if (res == NULL)
5083 PyErr_WriteUnraisable(del);
5084 else
5085 Py_DECREF(res);
5086 Py_DECREF(del);
5087 }
5088
5089 /* Restore the saved exception. */
5090 PyErr_Restore(error_type, error_value, error_traceback);
5091
5092 /* Undo the temporary resurrection; can't use DECREF here, it would
5093 * cause a recursive call.
5094 */
5095 assert(self->ob_refcnt > 0);
5096 if (--self->ob_refcnt == 0)
5097 return; /* this is the normal path out */
5098
5099 /* __del__ resurrected it! Make it look like the original Py_DECREF
5100 * never happened.
5101 */
5102 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005103 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005104 _Py_NewReference(self);
5105 self->ob_refcnt = refcnt;
5106 }
5107 assert(!PyType_IS_GC(self->ob_type) ||
5108 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00005109 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5110 * we need to undo that. */
5111 _Py_DEC_REFTOTAL;
5112 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5113 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005114 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5115 * _Py_NewReference bumped tp_allocs: both of those need to be
5116 * undone.
5117 */
5118#ifdef COUNT_ALLOCS
5119 --self->ob_type->tp_frees;
5120 --self->ob_type->tp_allocs;
5121#endif
5122}
5123
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005124
5125/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005126 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005127 structure, which incorporates the additional structures used for numbers,
5128 sequences and mappings.
5129 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005130 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005131 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5132 terminated with an all-zero entry. (This table is further initialized and
5133 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005134
Guido van Rossum6d204072001-10-21 00:44:31 +00005135typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005136
5137#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005138#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005139#undef ETSLOT
5140#undef SQSLOT
5141#undef MPSLOT
5142#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005143#undef UNSLOT
5144#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005145#undef BINSLOT
5146#undef RBINSLOT
5147
Guido van Rossum6d204072001-10-21 00:44:31 +00005148#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005149 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5150 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005151#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5152 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005153 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005154#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005155 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005156 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005157#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5158 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5159#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5160 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5161#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5162 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5163#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5164 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5165 "x." NAME "() <==> " DOC)
5166#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5167 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5168 "x." NAME "(y) <==> x" DOC "y")
5169#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5170 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5171 "x." NAME "(y) <==> x" DOC "y")
5172#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5173 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5174 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005175#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5176 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5177 "x." NAME "(y) <==> " DOC)
5178#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5179 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5180 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005181
5182static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005183 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005184 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005185 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5186 The logic in abstract.c always falls back to nb_add/nb_multiply in
5187 this case. Defining both the nb_* and the sq_* slots to call the
5188 user-defined methods has unexpected side-effects, as shown by
5189 test_descr.notimplemented() */
5190 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005191 "x.__add__(y) <==> x+y"),
Armin Rigo314861c2006-03-30 14:04:02 +00005192 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005193 "x.__mul__(n) <==> x*n"),
Armin Rigo314861c2006-03-30 14:04:02 +00005194 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005195 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005196 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5197 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005198 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005199 "x.__getslice__(i, j) <==> x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005200 \n\
5201 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005202 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005203 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005204 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005205 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005206 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005207 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005208 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005209 \n\
5210 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005211 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005212 "x.__delslice__(i, j) <==> del x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005213 \n\
5214 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005215 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5216 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005217 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005218 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005219 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005220 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005221
Martin v. Löwis18e16552006-02-15 17:27:45 +00005222 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005223 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005224 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005225 wrap_binaryfunc,
5226 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005227 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005228 wrap_objobjargproc,
5229 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005230 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005231 wrap_delitem,
5232 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005233
Guido van Rossum6d204072001-10-21 00:44:31 +00005234 BINSLOT("__add__", nb_add, slot_nb_add,
5235 "+"),
5236 RBINSLOT("__radd__", nb_add, slot_nb_add,
5237 "+"),
5238 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5239 "-"),
5240 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5241 "-"),
5242 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5243 "*"),
5244 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5245 "*"),
5246 BINSLOT("__div__", nb_divide, slot_nb_divide,
5247 "/"),
5248 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5249 "/"),
5250 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5251 "%"),
5252 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5253 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005254 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005255 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005256 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005257 "divmod(y, x)"),
5258 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5259 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5260 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5261 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5262 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5263 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5264 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5265 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005266 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005267 "x != 0"),
5268 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5269 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5270 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5271 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5272 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5273 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5274 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5275 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5276 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5277 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5278 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5279 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5280 "x.__coerce__(y) <==> coerce(x, y)"),
5281 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5282 "int(x)"),
5283 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5284 "long(x)"),
5285 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5286 "float(x)"),
5287 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5288 "oct(x)"),
5289 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5290 "hex(x)"),
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005291 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005292 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005293 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5294 wrap_binaryfunc, "+"),
5295 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5296 wrap_binaryfunc, "-"),
5297 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5298 wrap_binaryfunc, "*"),
5299 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5300 wrap_binaryfunc, "/"),
5301 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5302 wrap_binaryfunc, "%"),
5303 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005304 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005305 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5306 wrap_binaryfunc, "<<"),
5307 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5308 wrap_binaryfunc, ">>"),
5309 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5310 wrap_binaryfunc, "&"),
5311 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5312 wrap_binaryfunc, "^"),
5313 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5314 wrap_binaryfunc, "|"),
5315 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5316 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5317 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5318 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5319 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5320 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5321 IBSLOT("__itruediv__", nb_inplace_true_divide,
5322 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005323
Guido van Rossum6d204072001-10-21 00:44:31 +00005324 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5325 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005326 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005327 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5328 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005329 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005330 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5331 "x.__cmp__(y) <==> cmp(x,y)"),
5332 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5333 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005334 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5335 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005336 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005337 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5338 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5339 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5340 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5341 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5342 "x.__setattr__('name', value) <==> x.name = value"),
5343 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5344 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5345 "x.__delattr__('name') <==> del x.name"),
5346 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5347 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5348 "x.__lt__(y) <==> x<y"),
5349 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5350 "x.__le__(y) <==> x<=y"),
5351 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5352 "x.__eq__(y) <==> x==y"),
5353 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5354 "x.__ne__(y) <==> x!=y"),
5355 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5356 "x.__gt__(y) <==> x>y"),
5357 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5358 "x.__ge__(y) <==> x>=y"),
5359 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5360 "x.__iter__() <==> iter(x)"),
5361 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5362 "x.next() -> the next value, or raise StopIteration"),
5363 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5364 "descr.__get__(obj[, type]) -> value"),
5365 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5366 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005367 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5368 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005369 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005370 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005371 "see x.__class__.__doc__ for signature",
5372 PyWrapperFlag_KEYWORDS),
5373 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005374 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005375 {NULL}
5376};
5377
Guido van Rossumc334df52002-04-04 23:44:47 +00005378/* Given a type pointer and an offset gotten from a slotdef entry, return a
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005379 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005380 the offset to the type pointer, since it takes care to indirect through the
5381 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5382 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005383static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005384slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005385{
5386 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005387 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005388
Guido van Rossume5c691a2003-03-07 15:13:17 +00005389 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005390 assert(offset >= 0);
Skip Montanaro429433b2006-04-18 00:35:43 +00005391 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5392 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005393 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005394 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005395 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005396 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005397 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005398 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005399 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005400 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005401 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005402 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005403 }
5404 else {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005405 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005406 }
5407 if (ptr != NULL)
5408 ptr += offset;
5409 return (void **)ptr;
5410}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005411
Guido van Rossumc334df52002-04-04 23:44:47 +00005412/* Length of array of slotdef pointers used to store slots with the
5413 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5414 the same __name__, for any __name__. Since that's a static property, it is
5415 appropriate to declare fixed-size arrays for this. */
5416#define MAX_EQUIV 10
5417
5418/* Return a slot pointer for a given name, but ONLY if the attribute has
5419 exactly one slot function. The name must be an interned string. */
5420static void **
5421resolve_slotdups(PyTypeObject *type, PyObject *name)
5422{
5423 /* XXX Maybe this could be optimized more -- but is it worth it? */
5424
5425 /* pname and ptrs act as a little cache */
5426 static PyObject *pname;
5427 static slotdef *ptrs[MAX_EQUIV];
5428 slotdef *p, **pp;
5429 void **res, **ptr;
5430
5431 if (pname != name) {
5432 /* Collect all slotdefs that match name into ptrs. */
5433 pname = name;
5434 pp = ptrs;
5435 for (p = slotdefs; p->name_strobj; p++) {
5436 if (p->name_strobj == name)
5437 *pp++ = p;
5438 }
5439 *pp = NULL;
5440 }
5441
5442 /* Look in all matching slots of the type; if exactly one of these has
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005443 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005444 res = NULL;
5445 for (pp = ptrs; *pp; pp++) {
5446 ptr = slotptr(type, (*pp)->offset);
5447 if (ptr == NULL || *ptr == NULL)
5448 continue;
5449 if (res != NULL)
5450 return NULL;
5451 res = ptr;
5452 }
5453 return res;
5454}
5455
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005456/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005457 does some incredibly complex thinking and then sticks something into the
5458 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5459 interests, and then stores a generic wrapper or a specific function into
5460 the slot.) Return a pointer to the next slotdef with a different offset,
5461 because that's convenient for fixup_slot_dispatchers(). */
5462static slotdef *
5463update_one_slot(PyTypeObject *type, slotdef *p)
5464{
5465 PyObject *descr;
5466 PyWrapperDescrObject *d;
5467 void *generic = NULL, *specific = NULL;
5468 int use_generic = 0;
5469 int offset = p->offset;
5470 void **ptr = slotptr(type, offset);
5471
5472 if (ptr == NULL) {
5473 do {
5474 ++p;
5475 } while (p->offset == offset);
5476 return p;
5477 }
5478 do {
5479 descr = _PyType_Lookup(type, p->name_strobj);
5480 if (descr == NULL)
5481 continue;
5482 if (descr->ob_type == &PyWrapperDescr_Type) {
5483 void **tptr = resolve_slotdups(type, p->name_strobj);
5484 if (tptr == NULL || tptr == ptr)
5485 generic = p->function;
5486 d = (PyWrapperDescrObject *)descr;
5487 if (d->d_base->wrapper == p->wrapper &&
5488 PyType_IsSubtype(type, d->d_type))
5489 {
5490 if (specific == NULL ||
5491 specific == d->d_wrapped)
5492 specific = d->d_wrapped;
5493 else
5494 use_generic = 1;
5495 }
5496 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005497 else if (descr->ob_type == &PyCFunction_Type &&
5498 PyCFunction_GET_FUNCTION(descr) ==
5499 (PyCFunction)tp_new_wrapper &&
5500 strcmp(p->name, "__new__") == 0)
5501 {
5502 /* The __new__ wrapper is not a wrapper descriptor,
5503 so must be special-cased differently.
5504 If we don't do this, creating an instance will
5505 always use slot_tp_new which will look up
5506 __new__ in the MRO which will call tp_new_wrapper
5507 which will look through the base classes looking
5508 for a static base and call its tp_new (usually
5509 PyType_GenericNew), after performing various
5510 sanity checks and constructing a new argument
5511 list. Cut all that nonsense short -- this speeds
5512 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005513 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005514 /* XXX I'm not 100% sure that there isn't a hole
5515 in this reasoning that requires additional
5516 sanity checks. I'll buy the first person to
5517 point out a bug in this reasoning a beer. */
5518 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005519 else {
5520 use_generic = 1;
5521 generic = p->function;
5522 }
5523 } while ((++p)->offset == offset);
5524 if (specific && !use_generic)
5525 *ptr = specific;
5526 else
5527 *ptr = generic;
5528 return p;
5529}
5530
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005531/* In the type, update the slots whose slotdefs are gathered in the pp array.
5532 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005533static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005534update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005535{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005536 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005537
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005538 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005539 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005540 return 0;
5541}
5542
Guido van Rossumc334df52002-04-04 23:44:47 +00005543/* Comparison function for qsort() to compare slotdefs by their offset, and
5544 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005545static int
5546slotdef_cmp(const void *aa, const void *bb)
5547{
5548 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5549 int c = a->offset - b->offset;
5550 if (c != 0)
5551 return c;
5552 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005553 /* Cannot use a-b, as this gives off_t,
5554 which may lose precision when converted to int. */
5555 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005556}
5557
Guido van Rossumc334df52002-04-04 23:44:47 +00005558/* Initialize the slotdefs table by adding interned string objects for the
5559 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005560static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005561init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005562{
5563 slotdef *p;
5564 static int initialized = 0;
5565
5566 if (initialized)
5567 return;
5568 for (p = slotdefs; p->name; p++) {
5569 p->name_strobj = PyString_InternFromString(p->name);
5570 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005571 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005572 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005573 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5574 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005575 initialized = 1;
5576}
5577
Guido van Rossumc334df52002-04-04 23:44:47 +00005578/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005579static int
5580update_slot(PyTypeObject *type, PyObject *name)
5581{
Guido van Rossumc334df52002-04-04 23:44:47 +00005582 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005583 slotdef *p;
5584 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005585 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005586
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005587 init_slotdefs();
5588 pp = ptrs;
5589 for (p = slotdefs; p->name; p++) {
5590 /* XXX assume name is interned! */
5591 if (p->name_strobj == name)
5592 *pp++ = p;
5593 }
5594 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005595 for (pp = ptrs; *pp; pp++) {
5596 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005597 offset = p->offset;
5598 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005599 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005600 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005601 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005602 if (ptrs[0] == NULL)
5603 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005604 return update_subclasses(type, name,
5605 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005606}
5607
Guido van Rossumc334df52002-04-04 23:44:47 +00005608/* Store the proper functions in the slot dispatches at class (type)
5609 definition time, based upon which operations the class overrides in its
5610 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005611static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005612fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005613{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005614 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005615
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005616 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005617 for (p = slotdefs; p->name; )
5618 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005619}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005620
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005621static void
5622update_all_slots(PyTypeObject* type)
5623{
5624 slotdef *p;
5625
5626 init_slotdefs();
5627 for (p = slotdefs; p->name; p++) {
5628 /* update_slot returns int but can't actually fail */
5629 update_slot(type, p->name_strobj);
5630 }
5631}
5632
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005633/* recurse_down_subclasses() and update_subclasses() are mutually
5634 recursive functions to call a callback for all subclasses,
5635 but refraining from recursing into subclasses that define 'name'. */
5636
5637static int
5638update_subclasses(PyTypeObject *type, PyObject *name,
5639 update_callback callback, void *data)
5640{
5641 if (callback(type, data) < 0)
5642 return -1;
5643 return recurse_down_subclasses(type, name, callback, data);
5644}
5645
5646static int
5647recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5648 update_callback callback, void *data)
5649{
5650 PyTypeObject *subclass;
5651 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005652 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005653
5654 subclasses = type->tp_subclasses;
5655 if (subclasses == NULL)
5656 return 0;
5657 assert(PyList_Check(subclasses));
5658 n = PyList_GET_SIZE(subclasses);
5659 for (i = 0; i < n; i++) {
5660 ref = PyList_GET_ITEM(subclasses, i);
5661 assert(PyWeakref_CheckRef(ref));
5662 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5663 assert(subclass != NULL);
5664 if ((PyObject *)subclass == Py_None)
5665 continue;
5666 assert(PyType_Check(subclass));
5667 /* Avoid recursing down into unaffected classes */
5668 dict = subclass->tp_dict;
5669 if (dict != NULL && PyDict_Check(dict) &&
5670 PyDict_GetItem(dict, name) != NULL)
5671 continue;
5672 if (update_subclasses(subclass, name, callback, data) < 0)
5673 return -1;
5674 }
5675 return 0;
5676}
5677
Guido van Rossum6d204072001-10-21 00:44:31 +00005678/* This function is called by PyType_Ready() to populate the type's
5679 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005680 function slot (like tp_repr) that's defined in the type, one or more
5681 corresponding descriptors are added in the type's tp_dict dictionary
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005682 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005683 cause more than one descriptor to be added (for example, the nb_add
5684 slot adds both __add__ and __radd__ descriptors) and some function
5685 slots compete for the same descriptor (for example both sq_item and
5686 mp_subscript generate a __getitem__ descriptor).
5687
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005688 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005689 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005690 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005691 between competing slots: the members of PyHeapTypeObject are listed
5692 from most general to least general, so the most general slot is
5693 preferred. In particular, because as_mapping comes before as_sequence,
5694 for a type that defines both mp_subscript and sq_item, mp_subscript
5695 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005696
5697 This only adds new descriptors and doesn't overwrite entries in
5698 tp_dict that were previously defined. The descriptors contain a
5699 reference to the C function they must call, so that it's safe if they
5700 are copied into a subtype's __dict__ and the subtype has a different
5701 C function in its slot -- calling the method defined by the
5702 descriptor will call the C function that was used to create it,
5703 rather than the C function present in the slot when it is called.
5704 (This is important because a subtype may have a C function in the
5705 slot that calls the method from the dictionary, and we want to avoid
5706 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005707
5708static int
5709add_operators(PyTypeObject *type)
5710{
5711 PyObject *dict = type->tp_dict;
5712 slotdef *p;
5713 PyObject *descr;
5714 void **ptr;
5715
5716 init_slotdefs();
5717 for (p = slotdefs; p->name; p++) {
5718 if (p->wrapper == NULL)
5719 continue;
5720 ptr = slotptr(type, p->offset);
5721 if (!ptr || !*ptr)
5722 continue;
5723 if (PyDict_GetItem(dict, p->name_strobj))
5724 continue;
5725 descr = PyDescr_NewWrapper(type, p, *ptr);
5726 if (descr == NULL)
5727 return -1;
5728 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5729 return -1;
5730 Py_DECREF(descr);
5731 }
5732 if (type->tp_new != NULL) {
5733 if (add_tp_new_wrapper(type) < 0)
5734 return -1;
5735 }
5736 return 0;
5737}
5738
Guido van Rossum705f0f52001-08-24 16:47:00 +00005739
5740/* Cooperative 'super' */
5741
5742typedef struct {
5743 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005744 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005745 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005746 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005747} superobject;
5748
Guido van Rossum6f799372001-09-20 20:46:19 +00005749static PyMemberDef super_members[] = {
5750 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5751 "the class invoking super()"},
5752 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5753 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005754 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005755 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005756 {0}
5757};
5758
Guido van Rossum705f0f52001-08-24 16:47:00 +00005759static void
5760super_dealloc(PyObject *self)
5761{
5762 superobject *su = (superobject *)self;
5763
Guido van Rossum048eb752001-10-02 21:24:57 +00005764 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005765 Py_XDECREF(su->obj);
5766 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005767 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005768 self->ob_type->tp_free(self);
5769}
5770
5771static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005772super_repr(PyObject *self)
5773{
5774 superobject *su = (superobject *)self;
5775
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005776 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005777 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005778 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005779 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005780 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005781 else
5782 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005783 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005784 su->type ? su->type->tp_name : "NULL");
5785}
5786
5787static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005788super_getattro(PyObject *self, PyObject *name)
5789{
5790 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005791 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005792
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005793 if (!skip) {
5794 /* We want __class__ to return the class of the super object
5795 (i.e. super, or a subclass), not the class of su->obj. */
5796 skip = (PyString_Check(name) &&
5797 PyString_GET_SIZE(name) == 9 &&
5798 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5799 }
5800
5801 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005802 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005803 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005804 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005805 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005806
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005807 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005808 mro = starttype->tp_mro;
5809
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005810 if (mro == NULL)
5811 n = 0;
5812 else {
5813 assert(PyTuple_Check(mro));
5814 n = PyTuple_GET_SIZE(mro);
5815 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005816 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005817 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005818 break;
5819 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005820 i++;
5821 res = NULL;
5822 for (; i < n; i++) {
5823 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005824 if (PyType_Check(tmp))
5825 dict = ((PyTypeObject *)tmp)->tp_dict;
5826 else if (PyClass_Check(tmp))
5827 dict = ((PyClassObject *)tmp)->cl_dict;
5828 else
5829 continue;
5830 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005831 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005832 Py_INCREF(res);
5833 f = res->ob_type->tp_descr_get;
5834 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005835 tmp = f(res,
5836 /* Only pass 'obj' param if
5837 this is instance-mode super
5838 (See SF ID #743627)
5839 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005840 (su->obj == (PyObject *)
5841 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005842 ? (PyObject *)NULL
5843 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005844 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005845 Py_DECREF(res);
5846 res = tmp;
5847 }
5848 return res;
5849 }
5850 }
5851 }
5852 return PyObject_GenericGetAttr(self, name);
5853}
5854
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005855static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005856supercheck(PyTypeObject *type, PyObject *obj)
5857{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005858 /* Check that a super() call makes sense. Return a type object.
5859
5860 obj can be a new-style class, or an instance of one:
5861
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005862 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005863 used for class methods; the return value is obj.
5864
5865 - If it is an instance, it must be an instance of 'type'. This is
5866 the normal case; the return value is obj.__class__.
5867
5868 But... when obj is an instance, we want to allow for the case where
5869 obj->ob_type is not a subclass of type, but obj.__class__ is!
5870 This will allow using super() with a proxy for obj.
5871 */
5872
Guido van Rossum8e80a722003-02-18 19:22:22 +00005873 /* Check for first bullet above (special case) */
5874 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5875 Py_INCREF(obj);
5876 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005877 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005878
5879 /* Normal case */
5880 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005881 Py_INCREF(obj->ob_type);
5882 return obj->ob_type;
5883 }
5884 else {
5885 /* Try the slow way */
5886 static PyObject *class_str = NULL;
5887 PyObject *class_attr;
5888
5889 if (class_str == NULL) {
5890 class_str = PyString_FromString("__class__");
5891 if (class_str == NULL)
5892 return NULL;
5893 }
5894
5895 class_attr = PyObject_GetAttr(obj, class_str);
5896
5897 if (class_attr != NULL &&
5898 PyType_Check(class_attr) &&
5899 (PyTypeObject *)class_attr != obj->ob_type)
5900 {
5901 int ok = PyType_IsSubtype(
5902 (PyTypeObject *)class_attr, type);
5903 if (ok)
5904 return (PyTypeObject *)class_attr;
5905 }
5906
5907 if (class_attr == NULL)
5908 PyErr_Clear();
5909 else
5910 Py_DECREF(class_attr);
5911 }
5912
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005913 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005914 "super(type, obj): "
5915 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005916 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005917}
5918
Guido van Rossum705f0f52001-08-24 16:47:00 +00005919static PyObject *
5920super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5921{
5922 superobject *su = (superobject *)self;
Anthony Baxtera6286212006-04-11 07:42:36 +00005923 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005924
5925 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5926 /* Not binding to an object, or already bound */
5927 Py_INCREF(self);
5928 return self;
5929 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005930 if (su->ob_type != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005931 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005932 call its type */
Georg Brandl684fd0c2006-05-25 19:15:31 +00005933 return PyObject_CallFunctionObjArgs((PyObject *)su->ob_type,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005934 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005935 else {
5936 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005937 PyTypeObject *obj_type = supercheck(su->type, obj);
5938 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005939 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00005940 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005941 NULL, NULL);
Anthony Baxtera6286212006-04-11 07:42:36 +00005942 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005943 return NULL;
5944 Py_INCREF(su->type);
5945 Py_INCREF(obj);
Anthony Baxtera6286212006-04-11 07:42:36 +00005946 newobj->type = su->type;
5947 newobj->obj = obj;
5948 newobj->obj_type = obj_type;
5949 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005950 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005951}
5952
5953static int
5954super_init(PyObject *self, PyObject *args, PyObject *kwds)
5955{
5956 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005957 PyTypeObject *type;
5958 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005959 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005960
Georg Brandl5d59c092006-09-30 08:43:30 +00005961 if (!_PyArg_NoKeywords("super", kwds))
5962 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005963 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5964 return -1;
5965 if (obj == Py_None)
5966 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005967 if (obj != NULL) {
5968 obj_type = supercheck(type, obj);
5969 if (obj_type == NULL)
5970 return -1;
5971 Py_INCREF(obj);
5972 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005973 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005974 su->type = type;
5975 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005976 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005977 return 0;
5978}
5979
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005980PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005981"super(type) -> unbound super object\n"
5982"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005983"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005984"Typical use to call a cooperative superclass method:\n"
5985"class C(B):\n"
5986" def meth(self, arg):\n"
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005987" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005988
Guido van Rossum048eb752001-10-02 21:24:57 +00005989static int
5990super_traverse(PyObject *self, visitproc visit, void *arg)
5991{
5992 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00005993
Thomas Woutersc6e55062006-04-15 21:47:09 +00005994 Py_VISIT(su->obj);
5995 Py_VISIT(su->type);
5996 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005997
5998 return 0;
5999}
6000
Guido van Rossum705f0f52001-08-24 16:47:00 +00006001PyTypeObject PySuper_Type = {
6002 PyObject_HEAD_INIT(&PyType_Type)
6003 0, /* ob_size */
6004 "super", /* tp_name */
6005 sizeof(superobject), /* tp_basicsize */
6006 0, /* tp_itemsize */
6007 /* methods */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006008 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006009 0, /* tp_print */
6010 0, /* tp_getattr */
6011 0, /* tp_setattr */
6012 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006013 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006014 0, /* tp_as_number */
6015 0, /* tp_as_sequence */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006016 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006017 0, /* tp_hash */
6018 0, /* tp_call */
6019 0, /* tp_str */
6020 super_getattro, /* tp_getattro */
6021 0, /* tp_setattro */
6022 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00006023 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6024 Py_TPFLAGS_BASETYPE, /* tp_flags */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006025 super_doc, /* tp_doc */
6026 super_traverse, /* tp_traverse */
6027 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006028 0, /* tp_richcompare */
6029 0, /* tp_weaklistoffset */
6030 0, /* tp_iter */
6031 0, /* tp_iternext */
6032 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006033 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006034 0, /* tp_getset */
6035 0, /* tp_base */
6036 0, /* tp_dict */
6037 super_descr_get, /* tp_descr_get */
6038 0, /* tp_descr_set */
6039 0, /* tp_dictoffset */
6040 super_init, /* tp_init */
6041 PyType_GenericAlloc, /* tp_alloc */
6042 PyType_GenericNew, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006043 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006044};