blob: 65bf404a3d2aa072bca5cd200748599d9850309f [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(
101 type->tp_name, (int)(s - type->tp_name));
102 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;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000190 PyTypeObject *new_base, *old_base;
191 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);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000268 Py_DECREF(cls->tp_mro);
269 cls->tp_mro = mro;
270 Py_INCREF(cls->tp_mro);
271 }
272 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000273 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000274 }
275
276 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000277
278 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000279 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000280 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000281 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000282
283 /* for now, sod that: just remove from all old_bases,
284 add to all new_bases */
285
286 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
287 ob = PyTuple_GET_ITEM(old_bases, i);
288 if (PyType_Check(ob)) {
289 remove_subclass(
290 (PyTypeObject*)ob, type);
291 }
292 }
293
294 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
295 ob = PyTuple_GET_ITEM(value, i);
296 if (PyType_Check(ob)) {
297 if (add_subclass((PyTypeObject*)ob, type) < 0)
298 r = -1;
299 }
300 }
301
302 update_all_slots(type);
303
304 Py_DECREF(old_bases);
305 Py_DECREF(old_base);
306 Py_DECREF(old_mro);
307
308 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000309
310 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000311 Py_DECREF(type->tp_bases);
312 Py_DECREF(type->tp_base);
313 if (type->tp_mro != old_mro) {
314 Py_DECREF(type->tp_mro);
315 }
316
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000317 type->tp_bases = old_bases;
318 type->tp_base = old_base;
319 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000320
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000321 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000322}
323
324static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000325type_dict(PyTypeObject *type, void *context)
326{
327 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000328 Py_INCREF(Py_None);
329 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000330 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000331 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000332}
333
Tim Peters24008312002-03-17 18:56:20 +0000334static PyObject *
335type_get_doc(PyTypeObject *type, void *context)
336{
337 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000338 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000339 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000340 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000341 if (result == NULL) {
342 result = Py_None;
343 Py_INCREF(result);
344 }
345 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000346 result = result->ob_type->tp_descr_get(result, NULL,
347 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000348 }
349 else {
350 Py_INCREF(result);
351 }
Tim Peters24008312002-03-17 18:56:20 +0000352 return result;
353}
354
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000355static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000356 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
357 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000358 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000359 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000360 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000361 {0}
362};
363
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000364static int
365type_compare(PyObject *v, PyObject *w)
366{
367 /* This is called with type objects only. So we
368 can just compare the addresses. */
369 Py_uintptr_t vv = (Py_uintptr_t)v;
370 Py_uintptr_t ww = (Py_uintptr_t)w;
371 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
372}
373
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000374static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000375type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000376{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000377 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000378 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000379
380 mod = type_module(type, NULL);
381 if (mod == NULL)
382 PyErr_Clear();
383 else if (!PyString_Check(mod)) {
384 Py_DECREF(mod);
385 mod = NULL;
386 }
387 name = type_name(type, NULL);
388 if (name == NULL)
389 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000390
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000391 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
392 kind = "class";
393 else
394 kind = "type";
395
Barry Warsaw7ce36942001-08-24 18:34:26 +0000396 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000397 rtn = PyString_FromFormat("<%s '%s.%s'>",
398 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000399 PyString_AS_STRING(mod),
400 PyString_AS_STRING(name));
401 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000402 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000403 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000404
Guido van Rossumc3542212001-08-16 09:18:56 +0000405 Py_XDECREF(mod);
406 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000407 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000408}
409
Tim Peters6d6c1a32001-08-02 04:15:00 +0000410static PyObject *
411type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
412{
413 PyObject *obj;
414
415 if (type->tp_new == NULL) {
416 PyErr_Format(PyExc_TypeError,
417 "cannot create '%.100s' instances",
418 type->tp_name);
419 return NULL;
420 }
421
Tim Peters3f996e72001-09-13 19:18:27 +0000422 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000423 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000424 /* Ugly exception: when the call was type(something),
425 don't call tp_init on the result. */
426 if (type == &PyType_Type &&
427 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
428 (kwds == NULL ||
429 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
430 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000431 /* If the returned object is not an instance of type,
432 it won't be initialized. */
433 if (!PyType_IsSubtype(obj->ob_type, type))
434 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000435 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000436 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
437 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000438 type->tp_init(obj, args, kwds) < 0) {
439 Py_DECREF(obj);
440 obj = NULL;
441 }
442 }
443 return obj;
444}
445
446PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000447PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000448{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000449 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000450 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
451 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000452
453 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000454 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000455 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000456 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000457
Neil Schemenauerc806c882001-08-29 23:54:54 +0000458 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000459 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000460
Neil Schemenauerc806c882001-08-29 23:54:54 +0000461 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000462
Tim Peters6d6c1a32001-08-02 04:15:00 +0000463 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
464 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000465
Tim Peters6d6c1a32001-08-02 04:15:00 +0000466 if (type->tp_itemsize == 0)
467 PyObject_INIT(obj, type);
468 else
469 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000470
Tim Peters6d6c1a32001-08-02 04:15:00 +0000471 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000472 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000473 return obj;
474}
475
476PyObject *
477PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
478{
479 return type->tp_alloc(type, 0);
480}
481
Guido van Rossum9475a232001-10-05 20:51:39 +0000482/* Helpers for subtyping */
483
484static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000485traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
486{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000487 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000488 PyMemberDef *mp;
489
490 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000491 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000492 for (i = 0; i < n; i++, mp++) {
493 if (mp->type == T_OBJECT_EX) {
494 char *addr = (char *)self + mp->offset;
495 PyObject *obj = *(PyObject **)addr;
496 if (obj != NULL) {
497 int err = visit(obj, arg);
498 if (err)
499 return err;
500 }
501 }
502 }
503 return 0;
504}
505
506static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000507subtype_traverse(PyObject *self, visitproc visit, void *arg)
508{
509 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000510 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000511
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000512 /* Find the nearest base with a different tp_traverse,
513 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000514 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000515 base = type;
516 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
517 if (base->ob_size) {
518 int err = traverse_slots(base, self, visit, arg);
519 if (err)
520 return err;
521 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000522 base = base->tp_base;
523 assert(base);
524 }
525
526 if (type->tp_dictoffset != base->tp_dictoffset) {
527 PyObject **dictptr = _PyObject_GetDictPtr(self);
528 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000529 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000530 if (err)
531 return err;
532 }
533 }
534
Guido van Rossuma3862092002-06-10 15:24:42 +0000535 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
536 /* For a heaptype, the instances count as references
537 to the type. Traverse the type so the collector
538 can find cycles involving this link. */
539 int err = visit((PyObject *)type, arg);
540 if (err)
541 return err;
542 }
543
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000544 if (basetraverse)
545 return basetraverse(self, visit, arg);
546 return 0;
547}
548
549static void
550clear_slots(PyTypeObject *type, PyObject *self)
551{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000552 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000553 PyMemberDef *mp;
554
555 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000556 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000557 for (i = 0; i < n; i++, mp++) {
558 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
559 char *addr = (char *)self + mp->offset;
560 PyObject *obj = *(PyObject **)addr;
561 if (obj != NULL) {
562 Py_DECREF(obj);
563 *(PyObject **)addr = NULL;
564 }
565 }
566 }
567}
568
569static int
570subtype_clear(PyObject *self)
571{
572 PyTypeObject *type, *base;
573 inquiry baseclear;
574
575 /* Find the nearest base with a different tp_clear
576 and clear slots while we're at it */
577 type = self->ob_type;
578 base = type;
579 while ((baseclear = base->tp_clear) == subtype_clear) {
580 if (base->ob_size)
581 clear_slots(base, self);
582 base = base->tp_base;
583 assert(base);
584 }
585
Guido van Rossuma3862092002-06-10 15:24:42 +0000586 /* There's no need to clear the instance dict (if any);
587 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000588
589 if (baseclear)
590 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000591 return 0;
592}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000593
594static void
595subtype_dealloc(PyObject *self)
596{
Guido van Rossum14227b42001-12-06 02:35:58 +0000597 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000598 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000599
Guido van Rossum22b13872002-08-06 21:41:44 +0000600 /* Extract the type; we expect it to be a heap type */
601 type = self->ob_type;
602 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000603
Guido van Rossum22b13872002-08-06 21:41:44 +0000604 /* Test whether the type has GC exactly once */
605
606 if (!PyType_IS_GC(type)) {
607 /* It's really rare to find a dynamic type that doesn't have
608 GC; it can only happen when deriving from 'object' and not
609 adding any slots or instance variables. This allows
610 certain simplifications: there's no need to call
611 clear_slots(), or DECREF the dict, or clear weakrefs. */
612
613 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000614 if (type->tp_del) {
615 type->tp_del(self);
616 if (self->ob_refcnt > 0)
617 return;
618 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000619
620 /* Find the nearest base with a different tp_dealloc */
621 base = type;
622 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
623 assert(base->ob_size == 0);
624 base = base->tp_base;
625 assert(base);
626 }
627
628 /* Call the base tp_dealloc() */
629 assert(basedealloc);
630 basedealloc(self);
631
632 /* Can't reference self beyond this point */
633 Py_DECREF(type);
634
635 /* Done */
636 return;
637 }
638
639 /* We get here only if the type has GC */
640
641 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000642 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000643 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000644 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000645 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000646 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000647 /* DO NOT restore GC tracking at this point. weakref callbacks
648 * (if any, and whether directly here or indirectly in something we
649 * call) may trigger GC, and if self is tracked at that point, it
650 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000651 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000652
Guido van Rossum59195fd2003-06-13 20:54:40 +0000653 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000654 base = type;
655 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000656 base = base->tp_base;
657 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000658 }
659
Guido van Rossum1987c662003-05-29 14:29:23 +0000660 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000661 the finalizer (__del__), clearing slots, or clearing the instance
662 dict. */
663
Guido van Rossum1987c662003-05-29 14:29:23 +0000664 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
665 PyObject_ClearWeakRefs(self);
666
667 /* Maybe call finalizer; exit early if resurrected */
668 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000669 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000670 type->tp_del(self);
671 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000672 goto endlabel; /* resurrected */
673 else
674 _PyObject_GC_UNTRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000675 }
676
Guido van Rossum59195fd2003-06-13 20:54:40 +0000677 /* Clear slots up to the nearest base with a different tp_dealloc */
678 base = type;
679 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
680 if (base->ob_size)
681 clear_slots(base, self);
682 base = base->tp_base;
683 assert(base);
684 }
685
Tim Peters6d6c1a32001-08-02 04:15:00 +0000686 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000687 if (type->tp_dictoffset && !base->tp_dictoffset) {
688 PyObject **dictptr = _PyObject_GetDictPtr(self);
689 if (dictptr != NULL) {
690 PyObject *dict = *dictptr;
691 if (dict != NULL) {
692 Py_DECREF(dict);
693 *dictptr = NULL;
694 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000695 }
696 }
697
Tim Peters0bd743c2003-11-13 22:50:00 +0000698 /* Call the base tp_dealloc(); first retrack self if
699 * basedealloc knows about gc.
700 */
701 if (PyType_IS_GC(base))
702 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000703 assert(basedealloc);
704 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000705
706 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000707 Py_DECREF(type);
708
Guido van Rossum0906e072002-08-07 20:42:09 +0000709 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000710 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000711 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000712 --_PyTrash_delete_nesting;
713
714 /* Explanation of the weirdness around the trashcan macros:
715
716 Q. What do the trashcan macros do?
717
718 A. Read the comment titled "Trashcan mechanism" in object.h.
719 For one, this explains why there must be a call to GC-untrack
720 before the trashcan begin macro. Without understanding the
721 trashcan code, the answers to the following questions don't make
722 sense.
723
724 Q. Why do we GC-untrack before the trashcan and then immediately
725 GC-track again afterward?
726
727 A. In the case that the base class is GC-aware, the base class
728 probably GC-untracks the object. If it does that using the
729 UNTRACK macro, this will crash when the object is already
730 untracked. Because we don't know what the base class does, the
731 only safe thing is to make sure the object is tracked when we
732 call the base class dealloc. But... The trashcan begin macro
733 requires that the object is *untracked* before it is called. So
734 the dance becomes:
735
736 GC untrack
737 trashcan begin
738 GC track
739
Tim Petersf7f9e992003-11-13 21:59:32 +0000740 Q. Why did the last question say "immediately GC-track again"?
741 It's nowhere near immediately.
742
743 A. Because the code *used* to re-track immediately. Bad Idea.
744 self has a refcount of 0, and if gc ever gets its hands on it
745 (which can happen if any weakref callback gets invoked), it
746 looks like trash to gc too, and gc also tries to delete self
747 then. But we're already deleting self. Double dealloction is
748 a subtle disaster.
749
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000750 Q. Why the bizarre (net-zero) manipulation of
751 _PyTrash_delete_nesting around the trashcan macros?
752
753 A. Some base classes (e.g. list) also use the trashcan mechanism.
754 The following scenario used to be possible:
755
756 - suppose the trashcan level is one below the trashcan limit
757
758 - subtype_dealloc() is called
759
760 - the trashcan limit is not yet reached, so the trashcan level
761 is incremented and the code between trashcan begin and end is
762 executed
763
764 - this destroys much of the object's contents, including its
765 slots and __dict__
766
767 - basedealloc() is called; this is really list_dealloc(), or
768 some other type which also uses the trashcan macros
769
770 - the trashcan limit is now reached, so the object is put on the
771 trashcan's to-be-deleted-later list
772
773 - basedealloc() returns
774
775 - subtype_dealloc() decrefs the object's type
776
777 - subtype_dealloc() returns
778
779 - later, the trashcan code starts deleting the objects from its
780 to-be-deleted-later list
781
782 - subtype_dealloc() is called *AGAIN* for the same object
783
784 - at the very least (if the destroyed slots and __dict__ don't
785 cause problems) the object's type gets decref'ed a second
786 time, which is *BAD*!!!
787
788 The remedy is to make sure that if the code between trashcan
789 begin and end in subtype_dealloc() is called, the code between
790 trashcan begin and end in basedealloc() will also be called.
791 This is done by decrementing the level after passing into the
792 trashcan block, and incrementing it just before leaving the
793 block.
794
795 But now it's possible that a chain of objects consisting solely
796 of objects whose deallocator is subtype_dealloc() will defeat
797 the trashcan mechanism completely: the decremented level means
798 that the effective level never reaches the limit. Therefore, we
799 *increment* the level *before* entering the trashcan block, and
800 matchingly decrement it after leaving. This means the trashcan
801 code will trigger a little early, but that's no big deal.
802
803 Q. Are there any live examples of code in need of all this
804 complexity?
805
806 A. Yes. See SF bug 668433 for code that crashed (when Python was
807 compiled in debug mode) before the trashcan level manipulations
808 were added. For more discussion, see SF patches 581742, 575073
809 and bug 574207.
810 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000811}
812
Jeremy Hylton938ace62002-07-17 16:30:39 +0000813static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000814
Tim Peters6d6c1a32001-08-02 04:15:00 +0000815/* type test with subclassing support */
816
817int
818PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
819{
820 PyObject *mro;
821
Guido van Rossum9478d072001-09-07 18:52:13 +0000822 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
823 return b == a || b == &PyBaseObject_Type;
824
Tim Peters6d6c1a32001-08-02 04:15:00 +0000825 mro = a->tp_mro;
826 if (mro != NULL) {
827 /* Deal with multiple inheritance without recursion
828 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000829 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000830 assert(PyTuple_Check(mro));
831 n = PyTuple_GET_SIZE(mro);
832 for (i = 0; i < n; i++) {
833 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
834 return 1;
835 }
836 return 0;
837 }
838 else {
839 /* a is not completely initilized yet; follow tp_base */
840 do {
841 if (a == b)
842 return 1;
843 a = a->tp_base;
844 } while (a != NULL);
845 return b == &PyBaseObject_Type;
846 }
847}
848
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000849/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000850 without looking in the instance dictionary
851 (so we can't use PyObject_GetAttr) but still binding
852 it to the instance. The arguments are the object,
853 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000854 static variable used to cache the interned Python string.
855
856 Two variants:
857
858 - lookup_maybe() returns NULL without raising an exception
859 when the _PyType_Lookup() call fails;
860
861 - lookup_method() always raises an exception upon errors.
862*/
Guido van Rossum60718732001-08-28 17:47:51 +0000863
864static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000865lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000866{
867 PyObject *res;
868
869 if (*attrobj == NULL) {
870 *attrobj = PyString_InternFromString(attrstr);
871 if (*attrobj == NULL)
872 return NULL;
873 }
874 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000875 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000876 descrgetfunc f;
877 if ((f = res->ob_type->tp_descr_get) == NULL)
878 Py_INCREF(res);
879 else
880 res = f(res, self, (PyObject *)(self->ob_type));
881 }
882 return res;
883}
884
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000885static PyObject *
886lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
887{
888 PyObject *res = lookup_maybe(self, attrstr, attrobj);
889 if (res == NULL && !PyErr_Occurred())
890 PyErr_SetObject(PyExc_AttributeError, *attrobj);
891 return res;
892}
893
Guido van Rossum2730b132001-08-28 18:22:14 +0000894/* A variation of PyObject_CallMethod that uses lookup_method()
895 instead of PyObject_GetAttrString(). This uses the same convention
896 as lookup_method to cache the interned name string object. */
897
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000898static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000899call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
900{
901 va_list va;
902 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000903 va_start(va, format);
904
Guido van Rossumda21c012001-10-03 00:50:18 +0000905 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000906 if (func == NULL) {
907 va_end(va);
908 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000909 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000910 return NULL;
911 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000912
913 if (format && *format)
914 args = Py_VaBuildValue(format, va);
915 else
916 args = PyTuple_New(0);
917
918 va_end(va);
919
920 if (args == NULL)
921 return NULL;
922
923 assert(PyTuple_Check(args));
924 retval = PyObject_Call(func, args, NULL);
925
926 Py_DECREF(args);
927 Py_DECREF(func);
928
929 return retval;
930}
931
932/* Clone of call_method() that returns NotImplemented when the lookup fails. */
933
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000934static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000935call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
936{
937 va_list va;
938 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000939 va_start(va, format);
940
Guido van Rossumda21c012001-10-03 00:50:18 +0000941 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000942 if (func == NULL) {
943 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000944 if (!PyErr_Occurred()) {
945 Py_INCREF(Py_NotImplemented);
946 return Py_NotImplemented;
947 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000948 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000949 }
950
951 if (format && *format)
952 args = Py_VaBuildValue(format, va);
953 else
954 args = PyTuple_New(0);
955
956 va_end(va);
957
Guido van Rossum717ce002001-09-14 16:58:08 +0000958 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000959 return NULL;
960
Guido van Rossum717ce002001-09-14 16:58:08 +0000961 assert(PyTuple_Check(args));
962 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000963
964 Py_DECREF(args);
965 Py_DECREF(func);
966
967 return retval;
968}
969
Tim Petersa91e9642001-11-14 23:32:33 +0000970static int
971fill_classic_mro(PyObject *mro, PyObject *cls)
972{
973 PyObject *bases, *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000974 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +0000975
976 assert(PyList_Check(mro));
977 assert(PyClass_Check(cls));
978 i = PySequence_Contains(mro, cls);
979 if (i < 0)
980 return -1;
981 if (!i) {
982 if (PyList_Append(mro, cls) < 0)
983 return -1;
984 }
985 bases = ((PyClassObject *)cls)->cl_bases;
986 assert(bases && PyTuple_Check(bases));
987 n = PyTuple_GET_SIZE(bases);
988 for (i = 0; i < n; i++) {
989 base = PyTuple_GET_ITEM(bases, i);
990 if (fill_classic_mro(mro, base) < 0)
991 return -1;
992 }
993 return 0;
994}
995
996static PyObject *
997classic_mro(PyObject *cls)
998{
999 PyObject *mro;
1000
1001 assert(PyClass_Check(cls));
1002 mro = PyList_New(0);
1003 if (mro != NULL) {
1004 if (fill_classic_mro(mro, cls) == 0)
1005 return mro;
1006 Py_DECREF(mro);
1007 }
1008 return NULL;
1009}
1010
Tim Petersea7f75d2002-12-07 21:39:16 +00001011/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001012 Method resolution order algorithm C3 described in
1013 "A Monotonic Superclass Linearization for Dylan",
1014 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001015 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001016 (OOPSLA 1996)
1017
Guido van Rossum98f33732002-11-25 21:36:54 +00001018 Some notes about the rules implied by C3:
1019
Tim Petersea7f75d2002-12-07 21:39:16 +00001020 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001021 It isn't legal to repeat a class in a list of base classes.
1022
1023 The next three properties are the 3 constraints in "C3".
1024
Tim Petersea7f75d2002-12-07 21:39:16 +00001025 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001026 If A precedes B in C's MRO, then A will precede B in the MRO of all
1027 subclasses of C.
1028
1029 Monotonicity.
1030 The MRO of a class must be an extension without reordering of the
1031 MRO of each of its superclasses.
1032
1033 Extended Precedence Graph (EPG).
1034 Linearization is consistent if there is a path in the EPG from
1035 each class to all its successors in the linearization. See
1036 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001037 */
1038
Tim Petersea7f75d2002-12-07 21:39:16 +00001039static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001040tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001041 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +00001042 size = PyList_GET_SIZE(list);
1043
1044 for (j = whence+1; j < size; j++) {
1045 if (PyList_GET_ITEM(list, j) == o)
1046 return 1;
1047 }
1048 return 0;
1049}
1050
Guido van Rossum98f33732002-11-25 21:36:54 +00001051static PyObject *
1052class_name(PyObject *cls)
1053{
1054 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1055 if (name == NULL) {
1056 PyErr_Clear();
1057 Py_XDECREF(name);
1058 name = PyObject_Repr(cls);
1059 }
1060 if (name == NULL)
1061 return NULL;
1062 if (!PyString_Check(name)) {
1063 Py_DECREF(name);
1064 return NULL;
1065 }
1066 return name;
1067}
1068
1069static int
1070check_duplicates(PyObject *list)
1071{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001072 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001073 /* Let's use a quadratic time algorithm,
1074 assuming that the bases lists is short.
1075 */
1076 n = PyList_GET_SIZE(list);
1077 for (i = 0; i < n; i++) {
1078 PyObject *o = PyList_GET_ITEM(list, i);
1079 for (j = i + 1; j < n; j++) {
1080 if (PyList_GET_ITEM(list, j) == o) {
1081 o = class_name(o);
1082 PyErr_Format(PyExc_TypeError,
1083 "duplicate base class %s",
1084 o ? PyString_AS_STRING(o) : "?");
1085 Py_XDECREF(o);
1086 return -1;
1087 }
1088 }
1089 }
1090 return 0;
1091}
1092
1093/* Raise a TypeError for an MRO order disagreement.
1094
1095 It's hard to produce a good error message. In the absence of better
1096 insight into error reporting, report the classes that were candidates
1097 to be put next into the MRO. There is some conflict between the
1098 order in which they should be put in the MRO, but it's hard to
1099 diagnose what constraint can't be satisfied.
1100*/
1101
1102static void
1103set_mro_error(PyObject *to_merge, int *remain)
1104{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001105 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001106 char buf[1000];
1107 PyObject *k, *v;
1108 PyObject *set = PyDict_New();
1109
1110 to_merge_size = PyList_GET_SIZE(to_merge);
1111 for (i = 0; i < to_merge_size; i++) {
1112 PyObject *L = PyList_GET_ITEM(to_merge, i);
1113 if (remain[i] < PyList_GET_SIZE(L)) {
1114 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1115 if (PyDict_SetItem(set, c, Py_None) < 0)
1116 return;
1117 }
1118 }
1119 n = PyDict_Size(set);
1120
Raymond Hettingerf394df42003-04-06 19:13:41 +00001121 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1122consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001123 i = 0;
1124 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1125 PyObject *name = class_name(k);
1126 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1127 name ? PyString_AS_STRING(name) : "?");
1128 Py_XDECREF(name);
1129 if (--n && off+1 < sizeof(buf)) {
1130 buf[off++] = ',';
1131 buf[off] = '\0';
1132 }
1133 }
1134 PyErr_SetString(PyExc_TypeError, buf);
1135 Py_DECREF(set);
1136}
1137
Tim Petersea7f75d2002-12-07 21:39:16 +00001138static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001139pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001140 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001141 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001142 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001143
Guido van Rossum1f121312002-11-14 19:49:16 +00001144 to_merge_size = PyList_GET_SIZE(to_merge);
1145
Guido van Rossum98f33732002-11-25 21:36:54 +00001146 /* remain stores an index into each sublist of to_merge.
1147 remain[i] is the index of the next base in to_merge[i]
1148 that is not included in acc.
1149 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001150 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1151 if (remain == NULL)
1152 return -1;
1153 for (i = 0; i < to_merge_size; i++)
1154 remain[i] = 0;
1155
1156 again:
1157 empty_cnt = 0;
1158 for (i = 0; i < to_merge_size; i++) {
1159 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001160
Guido van Rossum1f121312002-11-14 19:49:16 +00001161 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1162
1163 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1164 empty_cnt++;
1165 continue;
1166 }
1167
Guido van Rossum98f33732002-11-25 21:36:54 +00001168 /* Choose next candidate for MRO.
1169
1170 The input sequences alone can determine the choice.
1171 If not, choose the class which appears in the MRO
1172 of the earliest direct superclass of the new class.
1173 */
1174
Guido van Rossum1f121312002-11-14 19:49:16 +00001175 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1176 for (j = 0; j < to_merge_size; j++) {
1177 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001178 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001179 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001180 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001181 }
1182 ok = PyList_Append(acc, candidate);
1183 if (ok < 0) {
1184 PyMem_Free(remain);
1185 return -1;
1186 }
1187 for (j = 0; j < to_merge_size; j++) {
1188 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001189 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1190 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001191 remain[j]++;
1192 }
1193 }
1194 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001195 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001196 }
1197
Guido van Rossum98f33732002-11-25 21:36:54 +00001198 if (empty_cnt == to_merge_size) {
1199 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001200 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001201 }
1202 set_mro_error(to_merge, remain);
1203 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001204 return -1;
1205}
1206
Tim Peters6d6c1a32001-08-02 04:15:00 +00001207static PyObject *
1208mro_implementation(PyTypeObject *type)
1209{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001210 Py_ssize_t i, n;
1211 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001212 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001213 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001214
Guido van Rossum63517572002-06-18 16:44:57 +00001215 if(type->tp_dict == NULL) {
1216 if(PyType_Ready(type) < 0)
1217 return NULL;
1218 }
1219
Guido van Rossum98f33732002-11-25 21:36:54 +00001220 /* Find a superclass linearization that honors the constraints
1221 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001222 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001223
1224 to_merge is a list of lists, where each list is a superclass
1225 linearization implied by a base class. The last element of
1226 to_merge is the declared list of bases.
1227 */
1228
Tim Peters6d6c1a32001-08-02 04:15:00 +00001229 bases = type->tp_bases;
1230 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001231
1232 to_merge = PyList_New(n+1);
1233 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001234 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001235
Tim Peters6d6c1a32001-08-02 04:15:00 +00001236 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001237 PyObject *base = PyTuple_GET_ITEM(bases, i);
1238 PyObject *parentMRO;
1239 if (PyType_Check(base))
1240 parentMRO = PySequence_List(
1241 ((PyTypeObject*)base)->tp_mro);
1242 else
1243 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001244 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001245 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001246 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001247 }
1248
1249 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001250 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001251
1252 bases_aslist = PySequence_List(bases);
1253 if (bases_aslist == NULL) {
1254 Py_DECREF(to_merge);
1255 return NULL;
1256 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001257 /* This is just a basic sanity check. */
1258 if (check_duplicates(bases_aslist) < 0) {
1259 Py_DECREF(to_merge);
1260 Py_DECREF(bases_aslist);
1261 return NULL;
1262 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001263 PyList_SET_ITEM(to_merge, n, bases_aslist);
1264
1265 result = Py_BuildValue("[O]", (PyObject *)type);
1266 if (result == NULL) {
1267 Py_DECREF(to_merge);
1268 return NULL;
1269 }
1270
1271 ok = pmerge(result, to_merge);
1272 Py_DECREF(to_merge);
1273 if (ok < 0) {
1274 Py_DECREF(result);
1275 return NULL;
1276 }
1277
Tim Peters6d6c1a32001-08-02 04:15:00 +00001278 return result;
1279}
1280
1281static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001282mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001283{
1284 PyTypeObject *type = (PyTypeObject *)self;
1285
Tim Peters6d6c1a32001-08-02 04:15:00 +00001286 return mro_implementation(type);
1287}
1288
1289static int
1290mro_internal(PyTypeObject *type)
1291{
1292 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001293 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001294
1295 if (type->ob_type == &PyType_Type) {
1296 result = mro_implementation(type);
1297 }
1298 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001299 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001300 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001301 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001302 if (mro == NULL)
1303 return -1;
1304 result = PyObject_CallObject(mro, NULL);
1305 Py_DECREF(mro);
1306 }
1307 if (result == NULL)
1308 return -1;
1309 tuple = PySequence_Tuple(result);
1310 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001311 if (tuple == NULL)
1312 return -1;
1313 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001314 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001315 PyObject *cls;
1316 PyTypeObject *solid;
1317
1318 solid = solid_base(type);
1319
1320 len = PyTuple_GET_SIZE(tuple);
1321
1322 for (i = 0; i < len; i++) {
1323 PyTypeObject *t;
1324 cls = PyTuple_GET_ITEM(tuple, i);
1325 if (PyClass_Check(cls))
1326 continue;
1327 else if (!PyType_Check(cls)) {
1328 PyErr_Format(PyExc_TypeError,
1329 "mro() returned a non-class ('%.500s')",
1330 cls->ob_type->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001331 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001332 return -1;
1333 }
1334 t = (PyTypeObject*)cls;
1335 if (!PyType_IsSubtype(solid, solid_base(t))) {
1336 PyErr_Format(PyExc_TypeError,
1337 "mro() returned base with unsuitable layout ('%.500s')",
1338 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001339 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001340 return -1;
1341 }
1342 }
1343 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001344 type->tp_mro = tuple;
1345 return 0;
1346}
1347
1348
1349/* Calculate the best base amongst multiple base classes.
1350 This is the first one that's on the path to the "solid base". */
1351
1352static PyTypeObject *
1353best_base(PyObject *bases)
1354{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001355 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001356 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001357 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001358
1359 assert(PyTuple_Check(bases));
1360 n = PyTuple_GET_SIZE(bases);
1361 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001362 base = NULL;
1363 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001364 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001365 base_proto = PyTuple_GET_ITEM(bases, i);
1366 if (PyClass_Check(base_proto))
1367 continue;
1368 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001369 PyErr_SetString(
1370 PyExc_TypeError,
1371 "bases must be types");
1372 return NULL;
1373 }
Tim Petersa91e9642001-11-14 23:32:33 +00001374 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001375 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001376 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001377 return NULL;
1378 }
1379 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001380 if (winner == NULL) {
1381 winner = candidate;
1382 base = base_i;
1383 }
1384 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001385 ;
1386 else if (PyType_IsSubtype(candidate, winner)) {
1387 winner = candidate;
1388 base = base_i;
1389 }
1390 else {
1391 PyErr_SetString(
1392 PyExc_TypeError,
1393 "multiple bases have "
1394 "instance lay-out conflict");
1395 return NULL;
1396 }
1397 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001398 if (base == NULL)
1399 PyErr_SetString(PyExc_TypeError,
1400 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001401 return base;
1402}
1403
1404static int
1405extra_ivars(PyTypeObject *type, PyTypeObject *base)
1406{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001407 size_t t_size = type->tp_basicsize;
1408 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001409
Guido van Rossum9676b222001-08-17 20:32:36 +00001410 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001411 if (type->tp_itemsize || base->tp_itemsize) {
1412 /* If itemsize is involved, stricter rules */
1413 return t_size != b_size ||
1414 type->tp_itemsize != base->tp_itemsize;
1415 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001416 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1417 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1418 t_size -= sizeof(PyObject *);
1419 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1420 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1421 t_size -= sizeof(PyObject *);
1422
1423 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001424}
1425
1426static PyTypeObject *
1427solid_base(PyTypeObject *type)
1428{
1429 PyTypeObject *base;
1430
1431 if (type->tp_base)
1432 base = solid_base(type->tp_base);
1433 else
1434 base = &PyBaseObject_Type;
1435 if (extra_ivars(type, base))
1436 return type;
1437 else
1438 return base;
1439}
1440
Jeremy Hylton938ace62002-07-17 16:30:39 +00001441static void object_dealloc(PyObject *);
1442static int object_init(PyObject *, PyObject *, PyObject *);
1443static int update_slot(PyTypeObject *, PyObject *);
1444static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001445
1446static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001447subtype_dict(PyObject *obj, void *context)
1448{
1449 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1450 PyObject *dict;
1451
1452 if (dictptr == NULL) {
1453 PyErr_SetString(PyExc_AttributeError,
1454 "This object has no __dict__");
1455 return NULL;
1456 }
1457 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001458 if (dict == NULL)
1459 *dictptr = dict = PyDict_New();
1460 Py_XINCREF(dict);
1461 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001462}
1463
Guido van Rossum6661be32001-10-26 04:26:12 +00001464static int
1465subtype_setdict(PyObject *obj, PyObject *value, void *context)
1466{
1467 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1468 PyObject *dict;
1469
1470 if (dictptr == NULL) {
1471 PyErr_SetString(PyExc_AttributeError,
1472 "This object has no __dict__");
1473 return -1;
1474 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001475 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001476 PyErr_SetString(PyExc_TypeError,
1477 "__dict__ must be set to a dictionary");
1478 return -1;
1479 }
1480 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001481 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001482 *dictptr = value;
1483 Py_XDECREF(dict);
1484 return 0;
1485}
1486
Guido van Rossumad47da02002-08-12 19:05:44 +00001487static PyObject *
1488subtype_getweakref(PyObject *obj, void *context)
1489{
1490 PyObject **weaklistptr;
1491 PyObject *result;
1492
1493 if (obj->ob_type->tp_weaklistoffset == 0) {
1494 PyErr_SetString(PyExc_AttributeError,
1495 "This object has no __weaklist__");
1496 return NULL;
1497 }
1498 assert(obj->ob_type->tp_weaklistoffset > 0);
1499 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001500 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001501 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001502 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001503 if (*weaklistptr == NULL)
1504 result = Py_None;
1505 else
1506 result = *weaklistptr;
1507 Py_INCREF(result);
1508 return result;
1509}
1510
Guido van Rossum373c7412003-01-07 13:41:37 +00001511/* Three variants on the subtype_getsets list. */
1512
1513static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001514 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001515 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001516 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001517 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001518 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001519};
1520
Guido van Rossum373c7412003-01-07 13:41:37 +00001521static PyGetSetDef subtype_getsets_dict_only[] = {
1522 {"__dict__", subtype_dict, subtype_setdict,
1523 PyDoc_STR("dictionary for instance variables (if defined)")},
1524 {0}
1525};
1526
1527static PyGetSetDef subtype_getsets_weakref_only[] = {
1528 {"__weakref__", subtype_getweakref, NULL,
1529 PyDoc_STR("list of weak references to the object (if defined)")},
1530 {0}
1531};
1532
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001533static int
1534valid_identifier(PyObject *s)
1535{
Guido van Rossum03013a02002-07-16 14:30:28 +00001536 unsigned char *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001537 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001538
1539 if (!PyString_Check(s)) {
1540 PyErr_SetString(PyExc_TypeError,
1541 "__slots__ must be strings");
1542 return 0;
1543 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001544 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001545 n = PyString_GET_SIZE(s);
1546 /* We must reject an empty name. As a hack, we bump the
1547 length to 1 so that the loop will balk on the trailing \0. */
1548 if (n == 0)
1549 n = 1;
1550 for (i = 0; i < n; i++, p++) {
1551 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1552 PyErr_SetString(PyExc_TypeError,
1553 "__slots__ must be identifiers");
1554 return 0;
1555 }
1556 }
1557 return 1;
1558}
1559
Martin v. Löwisd919a592002-10-14 21:07:28 +00001560#ifdef Py_USING_UNICODE
1561/* Replace Unicode objects in slots. */
1562
1563static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001564_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001565{
1566 PyObject *tmp = slots;
1567 PyObject *o, *o1;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001568 Py_ssize_t i;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001569 ssizessizeargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001570 for (i = 0; i < nslots; i++) {
1571 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1572 if (tmp == slots) {
1573 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1574 if (tmp == NULL)
1575 return NULL;
1576 }
1577 o1 = _PyUnicode_AsDefaultEncodedString
1578 (o, NULL);
1579 if (o1 == NULL) {
1580 Py_DECREF(tmp);
1581 return 0;
1582 }
1583 Py_INCREF(o1);
1584 Py_DECREF(o);
1585 PyTuple_SET_ITEM(tmp, i, o1);
1586 }
1587 }
1588 return tmp;
1589}
1590#endif
1591
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001592static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001593type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1594{
1595 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001596 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001597 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001598 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001599 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001600 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001601 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001602 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001603
Tim Peters3abca122001-10-27 19:37:48 +00001604 assert(args != NULL && PyTuple_Check(args));
1605 assert(kwds == NULL || PyDict_Check(kwds));
1606
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001607 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001608 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001609 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1610 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001611
1612 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1613 PyObject *x = PyTuple_GET_ITEM(args, 0);
1614 Py_INCREF(x->ob_type);
1615 return (PyObject *) x->ob_type;
1616 }
1617
1618 /* SF bug 475327 -- if that didn't trigger, we need 3
1619 arguments. but PyArg_ParseTupleAndKeywords below may give
1620 a msg saying type() needs exactly 3. */
1621 if (nargs + nkwds != 3) {
1622 PyErr_SetString(PyExc_TypeError,
1623 "type() takes 1 or 3 arguments");
1624 return NULL;
1625 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001626 }
1627
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001628 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001629 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1630 &name,
1631 &PyTuple_Type, &bases,
1632 &PyDict_Type, &dict))
1633 return NULL;
1634
1635 /* Determine the proper metatype to deal with this,
1636 and check for metatype conflicts while we're at it.
1637 Note that if some other metatype wins to contract,
1638 it's possible that its instances are not types. */
1639 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001640 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001641 for (i = 0; i < nbases; i++) {
1642 tmp = PyTuple_GET_ITEM(bases, i);
1643 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001644 if (tmptype == &PyClass_Type)
1645 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001646 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001647 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001648 if (PyType_IsSubtype(tmptype, winner)) {
1649 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001650 continue;
1651 }
1652 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001653 "metaclass conflict: "
1654 "the metaclass of a derived class "
1655 "must be a (non-strict) subclass "
1656 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001657 return NULL;
1658 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001659 if (winner != metatype) {
1660 if (winner->tp_new != type_new) /* Pass it to the winner */
1661 return winner->tp_new(winner, args, kwds);
1662 metatype = winner;
1663 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001664
1665 /* Adjust for empty tuple bases */
1666 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001667 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001668 if (bases == NULL)
1669 return NULL;
1670 nbases = 1;
1671 }
1672 else
1673 Py_INCREF(bases);
1674
1675 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1676
1677 /* Calculate best base, and check that all bases are type objects */
1678 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001679 if (base == NULL) {
1680 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001681 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001682 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001683 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1684 PyErr_Format(PyExc_TypeError,
1685 "type '%.100s' is not an acceptable base type",
1686 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001687 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001688 return NULL;
1689 }
1690
Tim Peters6d6c1a32001-08-02 04:15:00 +00001691 /* Check for a __slots__ sequence variable in dict, and count it */
1692 slots = PyDict_GetItemString(dict, "__slots__");
1693 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001694 add_dict = 0;
1695 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001696 may_add_dict = base->tp_dictoffset == 0;
1697 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1698 if (slots == NULL) {
1699 if (may_add_dict) {
1700 add_dict++;
1701 }
1702 if (may_add_weak) {
1703 add_weak++;
1704 }
1705 }
1706 else {
1707 /* Have slots */
1708
Tim Peters6d6c1a32001-08-02 04:15:00 +00001709 /* Make it into a tuple */
1710 if (PyString_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001711 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001712 else
1713 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001714 if (slots == NULL) {
1715 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001716 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001717 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001718 assert(PyTuple_Check(slots));
1719
1720 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001721 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001722 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001723 PyErr_Format(PyExc_TypeError,
1724 "nonempty __slots__ "
1725 "not supported for subtype of '%s'",
1726 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001727 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001728 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001729 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001730 return NULL;
1731 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001732
Martin v. Löwisd919a592002-10-14 21:07:28 +00001733#ifdef Py_USING_UNICODE
1734 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001735 if (tmp != slots) {
1736 Py_DECREF(slots);
1737 slots = tmp;
1738 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001739 if (!tmp)
1740 return NULL;
1741#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001742 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001743 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001744 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1745 char *s;
1746 if (!valid_identifier(tmp))
1747 goto bad_slots;
1748 assert(PyString_Check(tmp));
1749 s = PyString_AS_STRING(tmp);
1750 if (strcmp(s, "__dict__") == 0) {
1751 if (!may_add_dict || add_dict) {
1752 PyErr_SetString(PyExc_TypeError,
1753 "__dict__ slot disallowed: "
1754 "we already got one");
1755 goto bad_slots;
1756 }
1757 add_dict++;
1758 }
1759 if (strcmp(s, "__weakref__") == 0) {
1760 if (!may_add_weak || add_weak) {
1761 PyErr_SetString(PyExc_TypeError,
1762 "__weakref__ slot disallowed: "
1763 "either we already got one, "
1764 "or __itemsize__ != 0");
1765 goto bad_slots;
1766 }
1767 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001768 }
1769 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001770
Guido van Rossumad47da02002-08-12 19:05:44 +00001771 /* Copy slots into yet another tuple, demangling names */
1772 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001773 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001774 goto bad_slots;
1775 for (i = j = 0; i < nslots; i++) {
1776 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001777 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001778 s = PyString_AS_STRING(tmp);
1779 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1780 (add_weak && strcmp(s, "__weakref__") == 0))
1781 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001782 tmp =_Py_Mangle(name, tmp);
1783 if (!tmp)
1784 goto bad_slots;
Guido van Rossumad47da02002-08-12 19:05:44 +00001785 PyTuple_SET_ITEM(newslots, j, tmp);
1786 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001787 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001788 assert(j == nslots - add_dict - add_weak);
1789 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001790 Py_DECREF(slots);
1791 slots = newslots;
1792
Guido van Rossumad47da02002-08-12 19:05:44 +00001793 /* Secondary bases may provide weakrefs or dict */
1794 if (nbases > 1 &&
1795 ((may_add_dict && !add_dict) ||
1796 (may_add_weak && !add_weak))) {
1797 for (i = 0; i < nbases; i++) {
1798 tmp = PyTuple_GET_ITEM(bases, i);
1799 if (tmp == (PyObject *)base)
1800 continue; /* Skip primary base */
1801 if (PyClass_Check(tmp)) {
1802 /* Classic base class provides both */
1803 if (may_add_dict && !add_dict)
1804 add_dict++;
1805 if (may_add_weak && !add_weak)
1806 add_weak++;
1807 break;
1808 }
1809 assert(PyType_Check(tmp));
1810 tmptype = (PyTypeObject *)tmp;
1811 if (may_add_dict && !add_dict &&
1812 tmptype->tp_dictoffset != 0)
1813 add_dict++;
1814 if (may_add_weak && !add_weak &&
1815 tmptype->tp_weaklistoffset != 0)
1816 add_weak++;
1817 if (may_add_dict && !add_dict)
1818 continue;
1819 if (may_add_weak && !add_weak)
1820 continue;
1821 /* Nothing more to check */
1822 break;
1823 }
1824 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001825 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001826
1827 /* XXX From here until type is safely allocated,
1828 "return NULL" may leak slots! */
1829
1830 /* Allocate the type object */
1831 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001832 if (type == NULL) {
1833 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001834 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001835 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001836 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001837
1838 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001839 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001840 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00001841 et->ht_name = name;
1842 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001843
Guido van Rossumdc91b992001-08-08 22:26:22 +00001844 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001845 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1846 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001847 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1848 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001849
1850 /* It's a new-style number unless it specifically inherits any
1851 old-style numeric behavior */
1852 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1853 (base->tp_as_number == NULL))
1854 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1855
1856 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001857 type->tp_as_number = &et->as_number;
1858 type->tp_as_sequence = &et->as_sequence;
1859 type->tp_as_mapping = &et->as_mapping;
1860 type->tp_as_buffer = &et->as_buffer;
1861 type->tp_name = PyString_AS_STRING(name);
1862
1863 /* Set tp_base and tp_bases */
1864 type->tp_bases = bases;
1865 Py_INCREF(base);
1866 type->tp_base = base;
1867
Guido van Rossum687ae002001-10-15 22:03:32 +00001868 /* Initialize tp_dict from passed-in dict */
1869 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001870 if (dict == NULL) {
1871 Py_DECREF(type);
1872 return NULL;
1873 }
1874
Guido van Rossumc3542212001-08-16 09:18:56 +00001875 /* Set __module__ in the dict */
1876 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1877 tmp = PyEval_GetGlobals();
1878 if (tmp != NULL) {
1879 tmp = PyDict_GetItemString(tmp, "__name__");
1880 if (tmp != NULL) {
1881 if (PyDict_SetItemString(dict, "__module__",
1882 tmp) < 0)
1883 return NULL;
1884 }
1885 }
1886 }
1887
Tim Peters2f93e282001-10-04 05:27:00 +00001888 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001889 and is a string. The __doc__ accessor will first look for tp_doc;
1890 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001891 */
1892 {
1893 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1894 if (doc != NULL && PyString_Check(doc)) {
1895 const size_t n = (size_t)PyString_GET_SIZE(doc);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001896 char *tp_doc = PyObject_MALLOC(n+1);
1897 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00001898 Py_DECREF(type);
1899 return NULL;
1900 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001901 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
1902 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00001903 }
1904 }
1905
Tim Peters6d6c1a32001-08-02 04:15:00 +00001906 /* Special-case __new__: if it's a plain function,
1907 make it a static function */
1908 tmp = PyDict_GetItemString(dict, "__new__");
1909 if (tmp != NULL && PyFunction_Check(tmp)) {
1910 tmp = PyStaticMethod_New(tmp);
1911 if (tmp == NULL) {
1912 Py_DECREF(type);
1913 return NULL;
1914 }
1915 PyDict_SetItemString(dict, "__new__", tmp);
1916 Py_DECREF(tmp);
1917 }
1918
1919 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001920 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001921 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001922 if (slots != NULL) {
1923 for (i = 0; i < nslots; i++, mp++) {
1924 mp->name = PyString_AS_STRING(
1925 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001926 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001927 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001928 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001929 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001930 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001931 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001932 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001933 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001934 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001935 slotoffset += sizeof(PyObject *);
1936 }
1937 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001938 if (add_dict) {
1939 if (base->tp_itemsize)
1940 type->tp_dictoffset = -(long)sizeof(PyObject *);
1941 else
1942 type->tp_dictoffset = slotoffset;
1943 slotoffset += sizeof(PyObject *);
1944 }
1945 if (add_weak) {
1946 assert(!base->tp_itemsize);
1947 type->tp_weaklistoffset = slotoffset;
1948 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001949 }
1950 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001951 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001952 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001953
1954 if (type->tp_weaklistoffset && type->tp_dictoffset)
1955 type->tp_getset = subtype_getsets_full;
1956 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1957 type->tp_getset = subtype_getsets_weakref_only;
1958 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1959 type->tp_getset = subtype_getsets_dict_only;
1960 else
1961 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001962
1963 /* Special case some slots */
1964 if (type->tp_dictoffset != 0 || nslots > 0) {
1965 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1966 type->tp_getattro = PyObject_GenericGetAttr;
1967 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1968 type->tp_setattro = PyObject_GenericSetAttr;
1969 }
1970 type->tp_dealloc = subtype_dealloc;
1971
Guido van Rossum9475a232001-10-05 20:51:39 +00001972 /* Enable GC unless there are really no instance variables possible */
1973 if (!(type->tp_basicsize == sizeof(PyObject) &&
1974 type->tp_itemsize == 0))
1975 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1976
Tim Peters6d6c1a32001-08-02 04:15:00 +00001977 /* Always override allocation strategy to use regular heap */
1978 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001979 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001980 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001981 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001982 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001983 }
1984 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001985 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001986
1987 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001988 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001989 Py_DECREF(type);
1990 return NULL;
1991 }
1992
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001993 /* Put the proper slots in place */
1994 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001995
Tim Peters6d6c1a32001-08-02 04:15:00 +00001996 return (PyObject *)type;
1997}
1998
1999/* Internal API to look for a name through the MRO.
2000 This returns a borrowed reference, and doesn't set an exception! */
2001PyObject *
2002_PyType_Lookup(PyTypeObject *type, PyObject *name)
2003{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002004 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002005 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002006
Guido van Rossum687ae002001-10-15 22:03:32 +00002007 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002008 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002009
2010 /* If mro is NULL, the type is either not yet initialized
2011 by PyType_Ready(), or already cleared by type_clear().
2012 Either way the safest thing to do is to return NULL. */
2013 if (mro == NULL)
2014 return NULL;
2015
Tim Peters6d6c1a32001-08-02 04:15:00 +00002016 assert(PyTuple_Check(mro));
2017 n = PyTuple_GET_SIZE(mro);
2018 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002019 base = PyTuple_GET_ITEM(mro, i);
2020 if (PyClass_Check(base))
2021 dict = ((PyClassObject *)base)->cl_dict;
2022 else {
2023 assert(PyType_Check(base));
2024 dict = ((PyTypeObject *)base)->tp_dict;
2025 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002026 assert(dict && PyDict_Check(dict));
2027 res = PyDict_GetItem(dict, name);
2028 if (res != NULL)
2029 return res;
2030 }
2031 return NULL;
2032}
2033
2034/* This is similar to PyObject_GenericGetAttr(),
2035 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2036static PyObject *
2037type_getattro(PyTypeObject *type, PyObject *name)
2038{
2039 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002040 PyObject *meta_attribute, *attribute;
2041 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002042
2043 /* Initialize this type (we'll assume the metatype is initialized) */
2044 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002045 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002046 return NULL;
2047 }
2048
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002049 /* No readable descriptor found yet */
2050 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002051
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002052 /* Look for the attribute in the metatype */
2053 meta_attribute = _PyType_Lookup(metatype, name);
2054
2055 if (meta_attribute != NULL) {
2056 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002057
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002058 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2059 /* Data descriptors implement tp_descr_set to intercept
2060 * writes. Assume the attribute is not overridden in
2061 * type's tp_dict (and bases): call the descriptor now.
2062 */
2063 return meta_get(meta_attribute, (PyObject *)type,
2064 (PyObject *)metatype);
2065 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002066 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002067 }
2068
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002069 /* No data descriptor found on metatype. Look in tp_dict of this
2070 * type and its bases */
2071 attribute = _PyType_Lookup(type, name);
2072 if (attribute != NULL) {
2073 /* Implement descriptor functionality, if any */
2074 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002075
2076 Py_XDECREF(meta_attribute);
2077
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002078 if (local_get != NULL) {
2079 /* NULL 2nd argument indicates the descriptor was
2080 * found on the target object itself (or a base) */
2081 return local_get(attribute, (PyObject *)NULL,
2082 (PyObject *)type);
2083 }
Tim Peters34592512002-07-11 06:23:50 +00002084
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002085 Py_INCREF(attribute);
2086 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002087 }
2088
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002089 /* No attribute found in local __dict__ (or bases): use the
2090 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002091 if (meta_get != NULL) {
2092 PyObject *res;
2093 res = meta_get(meta_attribute, (PyObject *)type,
2094 (PyObject *)metatype);
2095 Py_DECREF(meta_attribute);
2096 return res;
2097 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002098
2099 /* If an ordinary attribute was found on the metatype, return it now */
2100 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002101 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002102 }
2103
2104 /* Give up */
2105 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002106 "type object '%.50s' has no attribute '%.400s'",
2107 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002108 return NULL;
2109}
2110
2111static int
2112type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2113{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002114 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2115 PyErr_Format(
2116 PyExc_TypeError,
2117 "can't set attributes of built-in/extension type '%s'",
2118 type->tp_name);
2119 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002120 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002121 /* XXX Example of how I expect this to be used...
2122 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2123 return -1;
2124 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002125 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2126 return -1;
2127 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002128}
2129
2130static void
2131type_dealloc(PyTypeObject *type)
2132{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002133 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002134
2135 /* Assert this is a heap-allocated type object */
2136 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002137 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002138 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002139 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002140 Py_XDECREF(type->tp_base);
2141 Py_XDECREF(type->tp_dict);
2142 Py_XDECREF(type->tp_bases);
2143 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002144 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002145 Py_XDECREF(type->tp_subclasses);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002146 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2147 * of most other objects. It's okay to cast it to char *.
2148 */
2149 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002150 Py_XDECREF(et->ht_name);
2151 Py_XDECREF(et->ht_slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002152 type->ob_type->tp_free((PyObject *)type);
2153}
2154
Guido van Rossum1c450732001-10-08 15:18:27 +00002155static PyObject *
2156type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2157{
2158 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002159 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002160
2161 list = PyList_New(0);
2162 if (list == NULL)
2163 return NULL;
2164 raw = type->tp_subclasses;
2165 if (raw == NULL)
2166 return list;
2167 assert(PyList_Check(raw));
2168 n = PyList_GET_SIZE(raw);
2169 for (i = 0; i < n; i++) {
2170 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002171 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002172 ref = PyWeakref_GET_OBJECT(ref);
2173 if (ref != Py_None) {
2174 if (PyList_Append(list, ref) < 0) {
2175 Py_DECREF(list);
2176 return NULL;
2177 }
2178 }
2179 }
2180 return list;
2181}
2182
Tim Peters6d6c1a32001-08-02 04:15:00 +00002183static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002184 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002185 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002186 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002187 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002188 {0}
2189};
2190
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002191PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002192"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002193"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002194
Guido van Rossum048eb752001-10-02 21:24:57 +00002195static int
2196type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2197{
Guido van Rossum048eb752001-10-02 21:24:57 +00002198 int err;
2199
Guido van Rossuma3862092002-06-10 15:24:42 +00002200 /* Because of type_is_gc(), the collector only calls this
2201 for heaptypes. */
2202 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002203
2204#define VISIT(SLOT) \
2205 if (SLOT) { \
2206 err = visit((PyObject *)(SLOT), arg); \
2207 if (err) \
2208 return err; \
2209 }
2210
2211 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002212 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002213 VISIT(type->tp_mro);
2214 VISIT(type->tp_bases);
2215 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002216
2217 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002218 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002219 in cycles; tp_subclasses is a list of weak references,
2220 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002221
2222#undef VISIT
2223
2224 return 0;
2225}
2226
2227static int
2228type_clear(PyTypeObject *type)
2229{
Guido van Rossum048eb752001-10-02 21:24:57 +00002230 PyObject *tmp;
2231
Guido van Rossuma3862092002-06-10 15:24:42 +00002232 /* Because of type_is_gc(), the collector only calls this
2233 for heaptypes. */
2234 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002235
2236#define CLEAR(SLOT) \
2237 if (SLOT) { \
2238 tmp = (PyObject *)(SLOT); \
2239 SLOT = NULL; \
2240 Py_DECREF(tmp); \
2241 }
2242
Guido van Rossuma3862092002-06-10 15:24:42 +00002243 /* The only field we need to clear is tp_mro, which is part of a
2244 hard cycle (its first element is the class itself) that won't
2245 be broken otherwise (it's a tuple and tuples don't have a
2246 tp_clear handler). None of the other fields need to be
2247 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002248
Guido van Rossuma3862092002-06-10 15:24:42 +00002249 tp_dict:
2250 It is a dict, so the collector will call its tp_clear.
2251
2252 tp_cache:
2253 Not used; if it were, it would be a dict.
2254
2255 tp_bases, tp_base:
2256 If these are involved in a cycle, there must be at least
2257 one other, mutable object in the cycle, e.g. a base
2258 class's dict; the cycle will be broken that way.
2259
2260 tp_subclasses:
2261 A list of weak references can't be part of a cycle; and
2262 lists have their own tp_clear.
2263
Guido van Rossume5c691a2003-03-07 15:13:17 +00002264 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002265 A tuple of strings can't be part of a cycle.
2266 */
2267
2268 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002269
Guido van Rossum048eb752001-10-02 21:24:57 +00002270#undef CLEAR
2271
2272 return 0;
2273}
2274
2275static int
2276type_is_gc(PyTypeObject *type)
2277{
2278 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2279}
2280
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002281PyTypeObject PyType_Type = {
2282 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002283 0, /* ob_size */
2284 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002285 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002286 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002287 (destructor)type_dealloc, /* tp_dealloc */
2288 0, /* tp_print */
2289 0, /* tp_getattr */
2290 0, /* tp_setattr */
2291 type_compare, /* tp_compare */
2292 (reprfunc)type_repr, /* tp_repr */
2293 0, /* tp_as_number */
2294 0, /* tp_as_sequence */
2295 0, /* tp_as_mapping */
2296 (hashfunc)_Py_HashPointer, /* tp_hash */
2297 (ternaryfunc)type_call, /* tp_call */
2298 0, /* tp_str */
2299 (getattrofunc)type_getattro, /* tp_getattro */
2300 (setattrofunc)type_setattro, /* tp_setattro */
2301 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002302 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2303 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002304 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002305 (traverseproc)type_traverse, /* tp_traverse */
2306 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002307 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002308 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002309 0, /* tp_iter */
2310 0, /* tp_iternext */
2311 type_methods, /* tp_methods */
2312 type_members, /* tp_members */
2313 type_getsets, /* tp_getset */
2314 0, /* tp_base */
2315 0, /* tp_dict */
2316 0, /* tp_descr_get */
2317 0, /* tp_descr_set */
2318 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2319 0, /* tp_init */
2320 0, /* tp_alloc */
2321 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002322 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002323 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002324};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002325
2326
2327/* The base type of all types (eventually)... except itself. */
2328
2329static int
2330object_init(PyObject *self, PyObject *args, PyObject *kwds)
2331{
2332 return 0;
2333}
2334
Guido van Rossum298e4212003-02-13 16:30:16 +00002335/* If we don't have a tp_new for a new-style class, new will use this one.
2336 Therefore this should take no arguments/keywords. However, this new may
2337 also be inherited by objects that define a tp_init but no tp_new. These
2338 objects WILL pass argumets to tp_new, because it gets the same args as
2339 tp_init. So only allow arguments if we aren't using the default init, in
2340 which case we expect init to handle argument parsing. */
2341static PyObject *
2342object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2343{
2344 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2345 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2346 PyErr_SetString(PyExc_TypeError,
2347 "default __new__ takes no parameters");
2348 return NULL;
2349 }
2350 return type->tp_alloc(type, 0);
2351}
2352
Tim Peters6d6c1a32001-08-02 04:15:00 +00002353static void
2354object_dealloc(PyObject *self)
2355{
2356 self->ob_type->tp_free(self);
2357}
2358
Guido van Rossum8e248182001-08-12 05:17:56 +00002359static PyObject *
2360object_repr(PyObject *self)
2361{
Guido van Rossum76e69632001-08-16 18:52:43 +00002362 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002363 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002364
Guido van Rossum76e69632001-08-16 18:52:43 +00002365 type = self->ob_type;
2366 mod = type_module(type, NULL);
2367 if (mod == NULL)
2368 PyErr_Clear();
2369 else if (!PyString_Check(mod)) {
2370 Py_DECREF(mod);
2371 mod = NULL;
2372 }
2373 name = type_name(type, NULL);
2374 if (name == NULL)
2375 return NULL;
2376 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002377 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002378 PyString_AS_STRING(mod),
2379 PyString_AS_STRING(name),
2380 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002381 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002382 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002383 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002384 Py_XDECREF(mod);
2385 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002386 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002387}
2388
Guido van Rossumb8f63662001-08-15 23:57:02 +00002389static PyObject *
2390object_str(PyObject *self)
2391{
2392 unaryfunc f;
2393
2394 f = self->ob_type->tp_repr;
2395 if (f == NULL)
2396 f = object_repr;
2397 return f(self);
2398}
2399
Guido van Rossum8e248182001-08-12 05:17:56 +00002400static long
2401object_hash(PyObject *self)
2402{
2403 return _Py_HashPointer(self);
2404}
Guido van Rossum8e248182001-08-12 05:17:56 +00002405
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002406static PyObject *
2407object_get_class(PyObject *self, void *closure)
2408{
2409 Py_INCREF(self->ob_type);
2410 return (PyObject *)(self->ob_type);
2411}
2412
2413static int
2414equiv_structs(PyTypeObject *a, PyTypeObject *b)
2415{
2416 return a == b ||
2417 (a != NULL &&
2418 b != NULL &&
2419 a->tp_basicsize == b->tp_basicsize &&
2420 a->tp_itemsize == b->tp_itemsize &&
2421 a->tp_dictoffset == b->tp_dictoffset &&
2422 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2423 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2424 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2425}
2426
2427static int
2428same_slots_added(PyTypeObject *a, PyTypeObject *b)
2429{
2430 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002431 Py_ssize_t size;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002432
2433 if (base != b->tp_base)
2434 return 0;
2435 if (equiv_structs(a, base) && equiv_structs(b, base))
2436 return 1;
2437 size = base->tp_basicsize;
2438 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2439 size += sizeof(PyObject *);
2440 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2441 size += sizeof(PyObject *);
2442 return size == a->tp_basicsize && size == b->tp_basicsize;
2443}
2444
2445static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002446compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2447{
2448 PyTypeObject *newbase, *oldbase;
2449
2450 if (new->tp_dealloc != old->tp_dealloc ||
2451 new->tp_free != old->tp_free)
2452 {
2453 PyErr_Format(PyExc_TypeError,
2454 "%s assignment: "
2455 "'%s' deallocator differs from '%s'",
2456 attr,
2457 new->tp_name,
2458 old->tp_name);
2459 return 0;
2460 }
2461 newbase = new;
2462 oldbase = old;
2463 while (equiv_structs(newbase, newbase->tp_base))
2464 newbase = newbase->tp_base;
2465 while (equiv_structs(oldbase, oldbase->tp_base))
2466 oldbase = oldbase->tp_base;
2467 if (newbase != oldbase &&
2468 (newbase->tp_base != oldbase->tp_base ||
2469 !same_slots_added(newbase, oldbase))) {
2470 PyErr_Format(PyExc_TypeError,
2471 "%s assignment: "
2472 "'%s' object layout differs from '%s'",
2473 attr,
2474 new->tp_name,
2475 old->tp_name);
2476 return 0;
2477 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002478
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002479 return 1;
2480}
2481
2482static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002483object_set_class(PyObject *self, PyObject *value, void *closure)
2484{
2485 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002486 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002487
Guido van Rossumb6b89422002-04-15 01:03:30 +00002488 if (value == NULL) {
2489 PyErr_SetString(PyExc_TypeError,
2490 "can't delete __class__ attribute");
2491 return -1;
2492 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002493 if (!PyType_Check(value)) {
2494 PyErr_Format(PyExc_TypeError,
2495 "__class__ must be set to new-style class, not '%s' object",
2496 value->ob_type->tp_name);
2497 return -1;
2498 }
2499 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002500 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2501 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2502 {
2503 PyErr_Format(PyExc_TypeError,
2504 "__class__ assignment: only for heap types");
2505 return -1;
2506 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002507 if (compatible_for_assignment(new, old, "__class__")) {
2508 Py_INCREF(new);
2509 self->ob_type = new;
2510 Py_DECREF(old);
2511 return 0;
2512 }
2513 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002514 return -1;
2515 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002516}
2517
2518static PyGetSetDef object_getsets[] = {
2519 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002520 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002521 {0}
2522};
2523
Guido van Rossumc53f0092003-02-18 22:05:12 +00002524
Guido van Rossum036f9992003-02-21 22:02:54 +00002525/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2526 We fall back to helpers in copy_reg for:
2527 - pickle protocols < 2
2528 - calculating the list of slot names (done only once per class)
2529 - the __newobj__ function (which is used as a token but never called)
2530*/
2531
2532static PyObject *
2533import_copy_reg(void)
2534{
2535 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002536
2537 if (!copy_reg_str) {
2538 copy_reg_str = PyString_InternFromString("copy_reg");
2539 if (copy_reg_str == NULL)
2540 return NULL;
2541 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002542
2543 return PyImport_Import(copy_reg_str);
2544}
2545
2546static PyObject *
2547slotnames(PyObject *cls)
2548{
2549 PyObject *clsdict;
2550 PyObject *copy_reg;
2551 PyObject *slotnames;
2552
2553 if (!PyType_Check(cls)) {
2554 Py_INCREF(Py_None);
2555 return Py_None;
2556 }
2557
2558 clsdict = ((PyTypeObject *)cls)->tp_dict;
2559 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002560 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002561 Py_INCREF(slotnames);
2562 return slotnames;
2563 }
2564
2565 copy_reg = import_copy_reg();
2566 if (copy_reg == NULL)
2567 return NULL;
2568
2569 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2570 Py_DECREF(copy_reg);
2571 if (slotnames != NULL &&
2572 slotnames != Py_None &&
2573 !PyList_Check(slotnames))
2574 {
2575 PyErr_SetString(PyExc_TypeError,
2576 "copy_reg._slotnames didn't return a list or None");
2577 Py_DECREF(slotnames);
2578 slotnames = NULL;
2579 }
2580
2581 return slotnames;
2582}
2583
2584static PyObject *
2585reduce_2(PyObject *obj)
2586{
2587 PyObject *cls, *getnewargs;
2588 PyObject *args = NULL, *args2 = NULL;
2589 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2590 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2591 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002592 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00002593
2594 cls = PyObject_GetAttrString(obj, "__class__");
2595 if (cls == NULL)
2596 return NULL;
2597
2598 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2599 if (getnewargs != NULL) {
2600 args = PyObject_CallObject(getnewargs, NULL);
2601 Py_DECREF(getnewargs);
2602 if (args != NULL && !PyTuple_Check(args)) {
2603 PyErr_SetString(PyExc_TypeError,
2604 "__getnewargs__ should return a tuple");
2605 goto end;
2606 }
2607 }
2608 else {
2609 PyErr_Clear();
2610 args = PyTuple_New(0);
2611 }
2612 if (args == NULL)
2613 goto end;
2614
2615 getstate = PyObject_GetAttrString(obj, "__getstate__");
2616 if (getstate != NULL) {
2617 state = PyObject_CallObject(getstate, NULL);
2618 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002619 if (state == NULL)
2620 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002621 }
2622 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002623 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002624 state = PyObject_GetAttrString(obj, "__dict__");
2625 if (state == NULL) {
2626 PyErr_Clear();
2627 state = Py_None;
2628 Py_INCREF(state);
2629 }
2630 names = slotnames(cls);
2631 if (names == NULL)
2632 goto end;
2633 if (names != Py_None) {
2634 assert(PyList_Check(names));
2635 slots = PyDict_New();
2636 if (slots == NULL)
2637 goto end;
2638 n = 0;
2639 /* Can't pre-compute the list size; the list
2640 is stored on the class so accessible to other
2641 threads, which may be run by DECREF */
2642 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2643 PyObject *name, *value;
2644 name = PyList_GET_ITEM(names, i);
2645 value = PyObject_GetAttr(obj, name);
2646 if (value == NULL)
2647 PyErr_Clear();
2648 else {
2649 int err = PyDict_SetItem(slots, name,
2650 value);
2651 Py_DECREF(value);
2652 if (err)
2653 goto end;
2654 n++;
2655 }
2656 }
2657 if (n) {
2658 state = Py_BuildValue("(NO)", state, slots);
2659 if (state == NULL)
2660 goto end;
2661 }
2662 }
2663 }
2664
2665 if (!PyList_Check(obj)) {
2666 listitems = Py_None;
2667 Py_INCREF(listitems);
2668 }
2669 else {
2670 listitems = PyObject_GetIter(obj);
2671 if (listitems == NULL)
2672 goto end;
2673 }
2674
2675 if (!PyDict_Check(obj)) {
2676 dictitems = Py_None;
2677 Py_INCREF(dictitems);
2678 }
2679 else {
2680 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2681 if (dictitems == NULL)
2682 goto end;
2683 }
2684
2685 copy_reg = import_copy_reg();
2686 if (copy_reg == NULL)
2687 goto end;
2688 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2689 if (newobj == NULL)
2690 goto end;
2691
2692 n = PyTuple_GET_SIZE(args);
2693 args2 = PyTuple_New(n+1);
2694 if (args2 == NULL)
2695 goto end;
2696 PyTuple_SET_ITEM(args2, 0, cls);
2697 cls = NULL;
2698 for (i = 0; i < n; i++) {
2699 PyObject *v = PyTuple_GET_ITEM(args, i);
2700 Py_INCREF(v);
2701 PyTuple_SET_ITEM(args2, i+1, v);
2702 }
2703
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002704 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002705
2706 end:
2707 Py_XDECREF(cls);
2708 Py_XDECREF(args);
2709 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002710 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002711 Py_XDECREF(state);
2712 Py_XDECREF(names);
2713 Py_XDECREF(listitems);
2714 Py_XDECREF(dictitems);
2715 Py_XDECREF(copy_reg);
2716 Py_XDECREF(newobj);
2717 return res;
2718}
2719
2720static PyObject *
2721object_reduce_ex(PyObject *self, PyObject *args)
2722{
2723 /* Call copy_reg._reduce_ex(self, proto) */
2724 PyObject *reduce, *copy_reg, *res;
2725 int proto = 0;
2726
2727 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2728 return NULL;
2729
2730 reduce = PyObject_GetAttrString(self, "__reduce__");
2731 if (reduce == NULL)
2732 PyErr_Clear();
2733 else {
2734 PyObject *cls, *clsreduce, *objreduce;
2735 int override;
2736 cls = PyObject_GetAttrString(self, "__class__");
2737 if (cls == NULL) {
2738 Py_DECREF(reduce);
2739 return NULL;
2740 }
2741 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2742 Py_DECREF(cls);
2743 if (clsreduce == NULL) {
2744 Py_DECREF(reduce);
2745 return NULL;
2746 }
2747 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2748 "__reduce__");
2749 override = (clsreduce != objreduce);
2750 Py_DECREF(clsreduce);
2751 if (override) {
2752 res = PyObject_CallObject(reduce, NULL);
2753 Py_DECREF(reduce);
2754 return res;
2755 }
2756 else
2757 Py_DECREF(reduce);
2758 }
2759
2760 if (proto >= 2)
2761 return reduce_2(self);
2762
2763 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002764 if (!copy_reg)
2765 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002766
Guido van Rossumc53f0092003-02-18 22:05:12 +00002767 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002768 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002769
Guido van Rossum3926a632001-09-25 16:25:58 +00002770 return res;
2771}
2772
2773static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002774 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2775 PyDoc_STR("helper for pickle")},
2776 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002777 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002778 {0}
2779};
2780
Guido van Rossum036f9992003-02-21 22:02:54 +00002781
Tim Peters6d6c1a32001-08-02 04:15:00 +00002782PyTypeObject PyBaseObject_Type = {
2783 PyObject_HEAD_INIT(&PyType_Type)
2784 0, /* ob_size */
2785 "object", /* tp_name */
2786 sizeof(PyObject), /* tp_basicsize */
2787 0, /* tp_itemsize */
2788 (destructor)object_dealloc, /* tp_dealloc */
2789 0, /* tp_print */
2790 0, /* tp_getattr */
2791 0, /* tp_setattr */
2792 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002793 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002794 0, /* tp_as_number */
2795 0, /* tp_as_sequence */
2796 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002797 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002798 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002799 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002800 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002801 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002802 0, /* tp_as_buffer */
2803 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002804 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002805 0, /* tp_traverse */
2806 0, /* tp_clear */
2807 0, /* tp_richcompare */
2808 0, /* tp_weaklistoffset */
2809 0, /* tp_iter */
2810 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002811 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002812 0, /* tp_members */
2813 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002814 0, /* tp_base */
2815 0, /* tp_dict */
2816 0, /* tp_descr_get */
2817 0, /* tp_descr_set */
2818 0, /* tp_dictoffset */
2819 object_init, /* tp_init */
2820 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002821 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002822 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002823};
2824
2825
2826/* Initialize the __dict__ in a type object */
2827
2828static int
2829add_methods(PyTypeObject *type, PyMethodDef *meth)
2830{
Guido van Rossum687ae002001-10-15 22:03:32 +00002831 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002832
2833 for (; meth->ml_name != NULL; meth++) {
2834 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002835 if (PyDict_GetItemString(dict, meth->ml_name) &&
2836 !(meth->ml_flags & METH_COEXIST))
2837 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002838 if (meth->ml_flags & METH_CLASS) {
2839 if (meth->ml_flags & METH_STATIC) {
2840 PyErr_SetString(PyExc_ValueError,
2841 "method cannot be both class and static");
2842 return -1;
2843 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002844 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002845 }
2846 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002847 PyObject *cfunc = PyCFunction_New(meth, NULL);
2848 if (cfunc == NULL)
2849 return -1;
2850 descr = PyStaticMethod_New(cfunc);
2851 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002852 }
2853 else {
2854 descr = PyDescr_NewMethod(type, meth);
2855 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002856 if (descr == NULL)
2857 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002858 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002859 return -1;
2860 Py_DECREF(descr);
2861 }
2862 return 0;
2863}
2864
2865static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002866add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002867{
Guido van Rossum687ae002001-10-15 22:03:32 +00002868 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002869
2870 for (; memb->name != NULL; memb++) {
2871 PyObject *descr;
2872 if (PyDict_GetItemString(dict, memb->name))
2873 continue;
2874 descr = PyDescr_NewMember(type, memb);
2875 if (descr == NULL)
2876 return -1;
2877 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2878 return -1;
2879 Py_DECREF(descr);
2880 }
2881 return 0;
2882}
2883
2884static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002885add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002886{
Guido van Rossum687ae002001-10-15 22:03:32 +00002887 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002888
2889 for (; gsp->name != NULL; gsp++) {
2890 PyObject *descr;
2891 if (PyDict_GetItemString(dict, gsp->name))
2892 continue;
2893 descr = PyDescr_NewGetSet(type, gsp);
2894
2895 if (descr == NULL)
2896 return -1;
2897 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2898 return -1;
2899 Py_DECREF(descr);
2900 }
2901 return 0;
2902}
2903
Guido van Rossum13d52f02001-08-10 21:24:08 +00002904static void
2905inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002906{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002907 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002908
Guido van Rossum13d52f02001-08-10 21:24:08 +00002909 /* Special flag magic */
2910 if (!type->tp_as_buffer && base->tp_as_buffer) {
2911 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2912 type->tp_flags |=
2913 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2914 }
2915 if (!type->tp_as_sequence && base->tp_as_sequence) {
2916 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2917 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2918 }
2919 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2920 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2921 if ((!type->tp_as_number && base->tp_as_number) ||
2922 (!type->tp_as_sequence && base->tp_as_sequence)) {
2923 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2924 if (!type->tp_as_number && !type->tp_as_sequence) {
2925 type->tp_flags |= base->tp_flags &
2926 Py_TPFLAGS_HAVE_INPLACEOPS;
2927 }
2928 }
2929 /* Wow */
2930 }
2931 if (!type->tp_as_number && base->tp_as_number) {
2932 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2933 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2934 }
2935
2936 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002937 oldsize = base->tp_basicsize;
2938 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2939 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2940 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002941 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2942 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002943 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002944 if (type->tp_traverse == NULL)
2945 type->tp_traverse = base->tp_traverse;
2946 if (type->tp_clear == NULL)
2947 type->tp_clear = base->tp_clear;
2948 }
2949 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002950 /* The condition below could use some explanation.
2951 It appears that tp_new is not inherited for static types
2952 whose base class is 'object'; this seems to be a precaution
2953 so that old extension types don't suddenly become
2954 callable (object.__new__ wouldn't insure the invariants
2955 that the extension type's own factory function ensures).
2956 Heap types, of course, are under our control, so they do
2957 inherit tp_new; static extension types that specify some
2958 other built-in type as the default are considered
2959 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002960 if (base != &PyBaseObject_Type ||
2961 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2962 if (type->tp_new == NULL)
2963 type->tp_new = base->tp_new;
2964 }
2965 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002966 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002967
2968 /* Copy other non-function slots */
2969
2970#undef COPYVAL
2971#define COPYVAL(SLOT) \
2972 if (type->SLOT == 0) type->SLOT = base->SLOT
2973
2974 COPYVAL(tp_itemsize);
2975 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2976 COPYVAL(tp_weaklistoffset);
2977 }
2978 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2979 COPYVAL(tp_dictoffset);
2980 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002981}
2982
2983static void
2984inherit_slots(PyTypeObject *type, PyTypeObject *base)
2985{
2986 PyTypeObject *basebase;
2987
2988#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002989#undef COPYSLOT
2990#undef COPYNUM
2991#undef COPYSEQ
2992#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002993#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002994
2995#define SLOTDEFINED(SLOT) \
2996 (base->SLOT != 0 && \
2997 (basebase == NULL || base->SLOT != basebase->SLOT))
2998
Tim Peters6d6c1a32001-08-02 04:15:00 +00002999#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003000 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003001
3002#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3003#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3004#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003005#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003006
Guido van Rossum13d52f02001-08-10 21:24:08 +00003007 /* This won't inherit indirect slots (from tp_as_number etc.)
3008 if type doesn't provide the space. */
3009
3010 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3011 basebase = base->tp_base;
3012 if (basebase->tp_as_number == NULL)
3013 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003014 COPYNUM(nb_add);
3015 COPYNUM(nb_subtract);
3016 COPYNUM(nb_multiply);
3017 COPYNUM(nb_divide);
3018 COPYNUM(nb_remainder);
3019 COPYNUM(nb_divmod);
3020 COPYNUM(nb_power);
3021 COPYNUM(nb_negative);
3022 COPYNUM(nb_positive);
3023 COPYNUM(nb_absolute);
3024 COPYNUM(nb_nonzero);
3025 COPYNUM(nb_invert);
3026 COPYNUM(nb_lshift);
3027 COPYNUM(nb_rshift);
3028 COPYNUM(nb_and);
3029 COPYNUM(nb_xor);
3030 COPYNUM(nb_or);
3031 COPYNUM(nb_coerce);
3032 COPYNUM(nb_int);
3033 COPYNUM(nb_long);
3034 COPYNUM(nb_float);
3035 COPYNUM(nb_oct);
3036 COPYNUM(nb_hex);
3037 COPYNUM(nb_inplace_add);
3038 COPYNUM(nb_inplace_subtract);
3039 COPYNUM(nb_inplace_multiply);
3040 COPYNUM(nb_inplace_divide);
3041 COPYNUM(nb_inplace_remainder);
3042 COPYNUM(nb_inplace_power);
3043 COPYNUM(nb_inplace_lshift);
3044 COPYNUM(nb_inplace_rshift);
3045 COPYNUM(nb_inplace_and);
3046 COPYNUM(nb_inplace_xor);
3047 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003048 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3049 COPYNUM(nb_true_divide);
3050 COPYNUM(nb_floor_divide);
3051 COPYNUM(nb_inplace_true_divide);
3052 COPYNUM(nb_inplace_floor_divide);
3053 }
Guido van Rossum38fff8c2006-03-07 18:50:55 +00003054 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3055 COPYNUM(nb_index);
3056 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003057 }
3058
Guido van Rossum13d52f02001-08-10 21:24:08 +00003059 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3060 basebase = base->tp_base;
3061 if (basebase->tp_as_sequence == NULL)
3062 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003063 COPYSEQ(sq_length);
3064 COPYSEQ(sq_concat);
3065 COPYSEQ(sq_repeat);
3066 COPYSEQ(sq_item);
3067 COPYSEQ(sq_slice);
3068 COPYSEQ(sq_ass_item);
3069 COPYSEQ(sq_ass_slice);
3070 COPYSEQ(sq_contains);
3071 COPYSEQ(sq_inplace_concat);
3072 COPYSEQ(sq_inplace_repeat);
3073 }
3074
Guido van Rossum13d52f02001-08-10 21:24:08 +00003075 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3076 basebase = base->tp_base;
3077 if (basebase->tp_as_mapping == NULL)
3078 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003079 COPYMAP(mp_length);
3080 COPYMAP(mp_subscript);
3081 COPYMAP(mp_ass_subscript);
3082 }
3083
Tim Petersfc57ccb2001-10-12 02:38:24 +00003084 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3085 basebase = base->tp_base;
3086 if (basebase->tp_as_buffer == NULL)
3087 basebase = NULL;
3088 COPYBUF(bf_getreadbuffer);
3089 COPYBUF(bf_getwritebuffer);
3090 COPYBUF(bf_getsegcount);
3091 COPYBUF(bf_getcharbuffer);
3092 }
3093
Guido van Rossum13d52f02001-08-10 21:24:08 +00003094 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003095
Tim Peters6d6c1a32001-08-02 04:15:00 +00003096 COPYSLOT(tp_dealloc);
3097 COPYSLOT(tp_print);
3098 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3099 type->tp_getattr = base->tp_getattr;
3100 type->tp_getattro = base->tp_getattro;
3101 }
3102 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3103 type->tp_setattr = base->tp_setattr;
3104 type->tp_setattro = base->tp_setattro;
3105 }
3106 /* tp_compare see tp_richcompare */
3107 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003108 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003109 COPYSLOT(tp_call);
3110 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003111 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003112 if (type->tp_compare == NULL &&
3113 type->tp_richcompare == NULL &&
3114 type->tp_hash == NULL)
3115 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003116 type->tp_compare = base->tp_compare;
3117 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003118 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003119 }
3120 }
3121 else {
3122 COPYSLOT(tp_compare);
3123 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003124 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3125 COPYSLOT(tp_iter);
3126 COPYSLOT(tp_iternext);
3127 }
3128 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3129 COPYSLOT(tp_descr_get);
3130 COPYSLOT(tp_descr_set);
3131 COPYSLOT(tp_dictoffset);
3132 COPYSLOT(tp_init);
3133 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003134 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003135 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3136 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3137 /* They agree about gc. */
3138 COPYSLOT(tp_free);
3139 }
3140 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3141 type->tp_free == NULL &&
3142 base->tp_free == _PyObject_Del) {
3143 /* A bit of magic to plug in the correct default
3144 * tp_free function when a derived class adds gc,
3145 * didn't define tp_free, and the base uses the
3146 * default non-gc tp_free.
3147 */
3148 type->tp_free = PyObject_GC_Del;
3149 }
3150 /* else they didn't agree about gc, and there isn't something
3151 * obvious to be done -- the type is on its own.
3152 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003153 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003154}
3155
Jeremy Hylton938ace62002-07-17 16:30:39 +00003156static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003157
Tim Peters6d6c1a32001-08-02 04:15:00 +00003158int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003159PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003160{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003161 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003162 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003163 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003164
Guido van Rossumcab05802002-06-10 15:29:03 +00003165 if (type->tp_flags & Py_TPFLAGS_READY) {
3166 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003167 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003168 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003169 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003170
3171 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003172
Tim Peters36eb4df2003-03-23 03:33:13 +00003173#ifdef Py_TRACE_REFS
3174 /* PyType_Ready is the closest thing we have to a choke point
3175 * for type objects, so is the best place I can think of to try
3176 * to get type objects into the doubly-linked list of all objects.
3177 * Still, not all type objects go thru PyType_Ready.
3178 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003179 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003180#endif
3181
Tim Peters6d6c1a32001-08-02 04:15:00 +00003182 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3183 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003184 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003185 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003186 Py_INCREF(base);
3187 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003188
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003189 /* Now the only way base can still be NULL is if type is
3190 * &PyBaseObject_Type.
3191 */
3192
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003193 /* Initialize the base class */
3194 if (base && base->tp_dict == NULL) {
3195 if (PyType_Ready(base) < 0)
3196 goto error;
3197 }
3198
Guido van Rossum0986d822002-04-08 01:38:42 +00003199 /* Initialize ob_type if NULL. This means extensions that want to be
3200 compilable separately on Windows can call PyType_Ready() instead of
3201 initializing the ob_type field of their type objects. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003202 /* The test for base != NULL is really unnecessary, since base is only
3203 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3204 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3205 know that. */
3206 if (type->ob_type == NULL && base != NULL)
Guido van Rossum0986d822002-04-08 01:38:42 +00003207 type->ob_type = base->ob_type;
3208
Tim Peters6d6c1a32001-08-02 04:15:00 +00003209 /* Initialize tp_bases */
3210 bases = type->tp_bases;
3211 if (bases == NULL) {
3212 if (base == NULL)
3213 bases = PyTuple_New(0);
3214 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003215 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003216 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003217 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003218 type->tp_bases = bases;
3219 }
3220
Guido van Rossum687ae002001-10-15 22:03:32 +00003221 /* Initialize tp_dict */
3222 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003223 if (dict == NULL) {
3224 dict = PyDict_New();
3225 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003226 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003227 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003228 }
3229
Guido van Rossum687ae002001-10-15 22:03:32 +00003230 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003231 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003232 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003233 if (type->tp_methods != NULL) {
3234 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003235 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003236 }
3237 if (type->tp_members != NULL) {
3238 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003239 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003240 }
3241 if (type->tp_getset != NULL) {
3242 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003243 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003244 }
3245
Tim Peters6d6c1a32001-08-02 04:15:00 +00003246 /* Calculate method resolution order */
3247 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003248 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003249 }
3250
Guido van Rossum13d52f02001-08-10 21:24:08 +00003251 /* Inherit special flags from dominant base */
3252 if (type->tp_base != NULL)
3253 inherit_special(type, type->tp_base);
3254
Tim Peters6d6c1a32001-08-02 04:15:00 +00003255 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003256 bases = type->tp_mro;
3257 assert(bases != NULL);
3258 assert(PyTuple_Check(bases));
3259 n = PyTuple_GET_SIZE(bases);
3260 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003261 PyObject *b = PyTuple_GET_ITEM(bases, i);
3262 if (PyType_Check(b))
3263 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003264 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003265
Tim Peters3cfe7542003-05-21 21:29:48 +00003266 /* Sanity check for tp_free. */
3267 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3268 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3269 /* This base class needs to call tp_free, but doesn't have
3270 * one, or its tp_free is for non-gc'ed objects.
3271 */
3272 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3273 "gc and is a base type but has inappropriate "
3274 "tp_free slot",
3275 type->tp_name);
3276 goto error;
3277 }
3278
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003279 /* if the type dictionary doesn't contain a __doc__, set it from
3280 the tp_doc slot.
3281 */
3282 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3283 if (type->tp_doc != NULL) {
3284 PyObject *doc = PyString_FromString(type->tp_doc);
3285 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3286 Py_DECREF(doc);
3287 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003288 PyDict_SetItemString(type->tp_dict,
3289 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003290 }
3291 }
3292
Guido van Rossum13d52f02001-08-10 21:24:08 +00003293 /* Some more special stuff */
3294 base = type->tp_base;
3295 if (base != NULL) {
3296 if (type->tp_as_number == NULL)
3297 type->tp_as_number = base->tp_as_number;
3298 if (type->tp_as_sequence == NULL)
3299 type->tp_as_sequence = base->tp_as_sequence;
3300 if (type->tp_as_mapping == NULL)
3301 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003302 if (type->tp_as_buffer == NULL)
3303 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003304 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003305
Guido van Rossum1c450732001-10-08 15:18:27 +00003306 /* Link into each base class's list of subclasses */
3307 bases = type->tp_bases;
3308 n = PyTuple_GET_SIZE(bases);
3309 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003310 PyObject *b = PyTuple_GET_ITEM(bases, i);
3311 if (PyType_Check(b) &&
3312 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003313 goto error;
3314 }
3315
Guido van Rossum13d52f02001-08-10 21:24:08 +00003316 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003317 assert(type->tp_dict != NULL);
3318 type->tp_flags =
3319 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003320 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003321
3322 error:
3323 type->tp_flags &= ~Py_TPFLAGS_READYING;
3324 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003325}
3326
Guido van Rossum1c450732001-10-08 15:18:27 +00003327static int
3328add_subclass(PyTypeObject *base, PyTypeObject *type)
3329{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003330 Py_ssize_t i;
3331 int result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003332 PyObject *list, *ref, *new;
3333
3334 list = base->tp_subclasses;
3335 if (list == NULL) {
3336 base->tp_subclasses = list = PyList_New(0);
3337 if (list == NULL)
3338 return -1;
3339 }
3340 assert(PyList_Check(list));
3341 new = PyWeakref_NewRef((PyObject *)type, NULL);
3342 i = PyList_GET_SIZE(list);
3343 while (--i >= 0) {
3344 ref = PyList_GET_ITEM(list, i);
3345 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003346 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3347 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003348 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003349 result = PyList_Append(list, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003350 Py_DECREF(new);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003351 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003352}
3353
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003354static void
3355remove_subclass(PyTypeObject *base, PyTypeObject *type)
3356{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003357 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003358 PyObject *list, *ref;
3359
3360 list = base->tp_subclasses;
3361 if (list == NULL) {
3362 return;
3363 }
3364 assert(PyList_Check(list));
3365 i = PyList_GET_SIZE(list);
3366 while (--i >= 0) {
3367 ref = PyList_GET_ITEM(list, i);
3368 assert(PyWeakref_CheckRef(ref));
3369 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3370 /* this can't fail, right? */
3371 PySequence_DelItem(list, i);
3372 return;
3373 }
3374 }
3375}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003376
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003377static int
3378check_num_args(PyObject *ob, int n)
3379{
3380 if (!PyTuple_CheckExact(ob)) {
3381 PyErr_SetString(PyExc_SystemError,
3382 "PyArg_UnpackTuple() argument list is not a tuple");
3383 return 0;
3384 }
3385 if (n == PyTuple_GET_SIZE(ob))
3386 return 1;
3387 PyErr_Format(
3388 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003389 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003390 return 0;
3391}
3392
Tim Peters6d6c1a32001-08-02 04:15:00 +00003393/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3394
3395/* There's a wrapper *function* for each distinct function typedef used
3396 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3397 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3398 Most tables have only one entry; the tables for binary operators have two
3399 entries, one regular and one with reversed arguments. */
3400
3401static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003402wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003403{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003404 lenfunc func = (lenfunc)wrapped;
3405 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003406
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003407 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003408 return NULL;
3409 res = (*func)(self);
3410 if (res == -1 && PyErr_Occurred())
3411 return NULL;
3412 return PyInt_FromLong((long)res);
3413}
3414
Tim Peters6d6c1a32001-08-02 04:15:00 +00003415static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003416wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3417{
3418 inquiry func = (inquiry)wrapped;
3419 int res;
3420
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003421 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003422 return NULL;
3423 res = (*func)(self);
3424 if (res == -1 && PyErr_Occurred())
3425 return NULL;
3426 return PyBool_FromLong((long)res);
3427}
3428
3429static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003430wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3431{
3432 binaryfunc func = (binaryfunc)wrapped;
3433 PyObject *other;
3434
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003435 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003436 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003437 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003438 return (*func)(self, other);
3439}
3440
3441static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003442wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3443{
3444 binaryfunc func = (binaryfunc)wrapped;
3445 PyObject *other;
3446
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003447 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003448 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003449 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003450 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003451 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003452 Py_INCREF(Py_NotImplemented);
3453 return Py_NotImplemented;
3454 }
3455 return (*func)(self, other);
3456}
3457
3458static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003459wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3460{
3461 binaryfunc func = (binaryfunc)wrapped;
3462 PyObject *other;
3463
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003464 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003465 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003466 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003467 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003468 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003469 Py_INCREF(Py_NotImplemented);
3470 return Py_NotImplemented;
3471 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003472 return (*func)(other, self);
3473}
3474
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003475static PyObject *
3476wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3477{
3478 coercion func = (coercion)wrapped;
3479 PyObject *other, *res;
3480 int ok;
3481
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003482 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003483 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003484 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003485 ok = func(&self, &other);
3486 if (ok < 0)
3487 return NULL;
3488 if (ok > 0) {
3489 Py_INCREF(Py_NotImplemented);
3490 return Py_NotImplemented;
3491 }
3492 res = PyTuple_New(2);
3493 if (res == NULL) {
3494 Py_DECREF(self);
3495 Py_DECREF(other);
3496 return NULL;
3497 }
3498 PyTuple_SET_ITEM(res, 0, self);
3499 PyTuple_SET_ITEM(res, 1, other);
3500 return res;
3501}
3502
Tim Peters6d6c1a32001-08-02 04:15:00 +00003503static PyObject *
3504wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3505{
3506 ternaryfunc func = (ternaryfunc)wrapped;
3507 PyObject *other;
3508 PyObject *third = Py_None;
3509
3510 /* Note: This wrapper only works for __pow__() */
3511
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003512 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003513 return NULL;
3514 return (*func)(self, other, third);
3515}
3516
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003517static PyObject *
3518wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3519{
3520 ternaryfunc func = (ternaryfunc)wrapped;
3521 PyObject *other;
3522 PyObject *third = Py_None;
3523
3524 /* Note: This wrapper only works for __pow__() */
3525
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003526 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003527 return NULL;
3528 return (*func)(other, self, third);
3529}
3530
Tim Peters6d6c1a32001-08-02 04:15:00 +00003531static PyObject *
3532wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3533{
3534 unaryfunc func = (unaryfunc)wrapped;
3535
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003536 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003537 return NULL;
3538 return (*func)(self);
3539}
3540
Tim Peters6d6c1a32001-08-02 04:15:00 +00003541static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003542wrap_ssizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003543{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003544 ssizeargfunc func = (ssizeargfunc)wrapped;
3545 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003546
Martin v. Löwis18e16552006-02-15 17:27:45 +00003547 if (!PyArg_ParseTuple(args, "n", &i))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003548 return NULL;
3549 return (*func)(self, i);
3550}
3551
Martin v. Löwis18e16552006-02-15 17:27:45 +00003552static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00003553getindex(PyObject *self, PyObject *arg)
3554{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003555 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003556
Martin v. Löwis18e16552006-02-15 17:27:45 +00003557 i = PyInt_AsSsize_t(arg);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003558 if (i == -1 && PyErr_Occurred())
3559 return -1;
3560 if (i < 0) {
3561 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3562 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003563 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003564 if (n < 0)
3565 return -1;
3566 i += n;
3567 }
3568 }
3569 return i;
3570}
3571
3572static PyObject *
3573wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3574{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003575 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003576 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003577 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003578
Guido van Rossumf4593e02001-10-03 12:09:30 +00003579 if (PyTuple_GET_SIZE(args) == 1) {
3580 arg = PyTuple_GET_ITEM(args, 0);
3581 i = getindex(self, arg);
3582 if (i == -1 && PyErr_Occurred())
3583 return NULL;
3584 return (*func)(self, i);
3585 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003586 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003587 assert(PyErr_Occurred());
3588 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003589}
3590
Tim Peters6d6c1a32001-08-02 04:15:00 +00003591static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003592wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003593{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003594 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
3595 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003596
Martin v. Löwis18e16552006-02-15 17:27:45 +00003597 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003598 return NULL;
3599 return (*func)(self, i, j);
3600}
3601
Tim Peters6d6c1a32001-08-02 04:15:00 +00003602static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003603wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003604{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003605 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3606 Py_ssize_t i;
3607 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003608 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003609
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003610 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003611 return NULL;
3612 i = getindex(self, arg);
3613 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003614 return NULL;
3615 res = (*func)(self, i, value);
3616 if (res == -1 && PyErr_Occurred())
3617 return NULL;
3618 Py_INCREF(Py_None);
3619 return Py_None;
3620}
3621
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003622static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003623wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003624{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003625 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3626 Py_ssize_t i;
3627 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003628 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003629
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003630 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003631 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003632 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003633 i = getindex(self, arg);
3634 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003635 return NULL;
3636 res = (*func)(self, i, NULL);
3637 if (res == -1 && PyErr_Occurred())
3638 return NULL;
3639 Py_INCREF(Py_None);
3640 return Py_None;
3641}
3642
Tim Peters6d6c1a32001-08-02 04:15:00 +00003643static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003644wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003645{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003646 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3647 Py_ssize_t i, j;
3648 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003649 PyObject *value;
3650
Martin v. Löwis18e16552006-02-15 17:27:45 +00003651 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003652 return NULL;
3653 res = (*func)(self, i, j, value);
3654 if (res == -1 && PyErr_Occurred())
3655 return NULL;
3656 Py_INCREF(Py_None);
3657 return Py_None;
3658}
3659
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003660static PyObject *
3661wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3662{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003663 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3664 Py_ssize_t i, j;
3665 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003666
Martin v. Löwis18e16552006-02-15 17:27:45 +00003667 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003668 return NULL;
3669 res = (*func)(self, i, j, NULL);
3670 if (res == -1 && PyErr_Occurred())
3671 return NULL;
3672 Py_INCREF(Py_None);
3673 return Py_None;
3674}
3675
Tim Peters6d6c1a32001-08-02 04:15:00 +00003676/* XXX objobjproc is a misnomer; should be objargpred */
3677static PyObject *
3678wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3679{
3680 objobjproc func = (objobjproc)wrapped;
3681 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003682 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003683
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003684 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003685 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003686 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003687 res = (*func)(self, value);
3688 if (res == -1 && PyErr_Occurred())
3689 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003690 else
3691 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003692}
3693
Tim Peters6d6c1a32001-08-02 04:15:00 +00003694static PyObject *
3695wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3696{
3697 objobjargproc func = (objobjargproc)wrapped;
3698 int res;
3699 PyObject *key, *value;
3700
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003701 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003702 return NULL;
3703 res = (*func)(self, key, value);
3704 if (res == -1 && PyErr_Occurred())
3705 return NULL;
3706 Py_INCREF(Py_None);
3707 return Py_None;
3708}
3709
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003710static PyObject *
3711wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3712{
3713 objobjargproc func = (objobjargproc)wrapped;
3714 int res;
3715 PyObject *key;
3716
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003717 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003718 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003719 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003720 res = (*func)(self, key, NULL);
3721 if (res == -1 && PyErr_Occurred())
3722 return NULL;
3723 Py_INCREF(Py_None);
3724 return Py_None;
3725}
3726
Tim Peters6d6c1a32001-08-02 04:15:00 +00003727static PyObject *
3728wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3729{
3730 cmpfunc func = (cmpfunc)wrapped;
3731 int res;
3732 PyObject *other;
3733
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003734 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003735 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003736 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003737 if (other->ob_type->tp_compare != func &&
3738 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003739 PyErr_Format(
3740 PyExc_TypeError,
3741 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3742 self->ob_type->tp_name,
3743 self->ob_type->tp_name,
3744 other->ob_type->tp_name);
3745 return NULL;
3746 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003747 res = (*func)(self, other);
3748 if (PyErr_Occurred())
3749 return NULL;
3750 return PyInt_FromLong((long)res);
3751}
3752
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003753/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003754 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003755static int
3756hackcheck(PyObject *self, setattrofunc func, char *what)
3757{
3758 PyTypeObject *type = self->ob_type;
3759 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3760 type = type->tp_base;
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003761 /* If type is NULL now, this is a really weird type.
3762 In the same of backwards compatibility (?), just shut up. */
3763 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003764 PyErr_Format(PyExc_TypeError,
3765 "can't apply this %s to %s object",
3766 what,
3767 type->tp_name);
3768 return 0;
3769 }
3770 return 1;
3771}
3772
Tim Peters6d6c1a32001-08-02 04:15:00 +00003773static PyObject *
3774wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3775{
3776 setattrofunc func = (setattrofunc)wrapped;
3777 int res;
3778 PyObject *name, *value;
3779
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003780 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003781 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003782 if (!hackcheck(self, func, "__setattr__"))
3783 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003784 res = (*func)(self, name, value);
3785 if (res < 0)
3786 return NULL;
3787 Py_INCREF(Py_None);
3788 return Py_None;
3789}
3790
3791static PyObject *
3792wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3793{
3794 setattrofunc func = (setattrofunc)wrapped;
3795 int res;
3796 PyObject *name;
3797
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003798 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003799 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003800 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003801 if (!hackcheck(self, func, "__delattr__"))
3802 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003803 res = (*func)(self, name, NULL);
3804 if (res < 0)
3805 return NULL;
3806 Py_INCREF(Py_None);
3807 return Py_None;
3808}
3809
Tim Peters6d6c1a32001-08-02 04:15:00 +00003810static PyObject *
3811wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3812{
3813 hashfunc func = (hashfunc)wrapped;
3814 long res;
3815
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003816 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003817 return NULL;
3818 res = (*func)(self);
3819 if (res == -1 && PyErr_Occurred())
3820 return NULL;
3821 return PyInt_FromLong(res);
3822}
3823
Tim Peters6d6c1a32001-08-02 04:15:00 +00003824static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003825wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003826{
3827 ternaryfunc func = (ternaryfunc)wrapped;
3828
Guido van Rossumc8e56452001-10-22 00:43:43 +00003829 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003830}
3831
Tim Peters6d6c1a32001-08-02 04:15:00 +00003832static PyObject *
3833wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3834{
3835 richcmpfunc func = (richcmpfunc)wrapped;
3836 PyObject *other;
3837
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003838 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003839 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003840 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003841 return (*func)(self, other, op);
3842}
3843
3844#undef RICHCMP_WRAPPER
3845#define RICHCMP_WRAPPER(NAME, OP) \
3846static PyObject * \
3847richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3848{ \
3849 return wrap_richcmpfunc(self, args, wrapped, OP); \
3850}
3851
Jack Jansen8e938b42001-08-08 15:29:49 +00003852RICHCMP_WRAPPER(lt, Py_LT)
3853RICHCMP_WRAPPER(le, Py_LE)
3854RICHCMP_WRAPPER(eq, Py_EQ)
3855RICHCMP_WRAPPER(ne, Py_NE)
3856RICHCMP_WRAPPER(gt, Py_GT)
3857RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003858
Tim Peters6d6c1a32001-08-02 04:15:00 +00003859static PyObject *
3860wrap_next(PyObject *self, PyObject *args, void *wrapped)
3861{
3862 unaryfunc func = (unaryfunc)wrapped;
3863 PyObject *res;
3864
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003865 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003866 return NULL;
3867 res = (*func)(self);
3868 if (res == NULL && !PyErr_Occurred())
3869 PyErr_SetNone(PyExc_StopIteration);
3870 return res;
3871}
3872
Tim Peters6d6c1a32001-08-02 04:15:00 +00003873static PyObject *
3874wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3875{
3876 descrgetfunc func = (descrgetfunc)wrapped;
3877 PyObject *obj;
3878 PyObject *type = NULL;
3879
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003880 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003881 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003882 if (obj == Py_None)
3883 obj = NULL;
3884 if (type == Py_None)
3885 type = NULL;
3886 if (type == NULL &&obj == NULL) {
3887 PyErr_SetString(PyExc_TypeError,
3888 "__get__(None, None) is invalid");
3889 return NULL;
3890 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003891 return (*func)(self, obj, type);
3892}
3893
Tim Peters6d6c1a32001-08-02 04:15:00 +00003894static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003895wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003896{
3897 descrsetfunc func = (descrsetfunc)wrapped;
3898 PyObject *obj, *value;
3899 int ret;
3900
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003901 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003902 return NULL;
3903 ret = (*func)(self, obj, value);
3904 if (ret < 0)
3905 return NULL;
3906 Py_INCREF(Py_None);
3907 return Py_None;
3908}
Guido van Rossum22b13872002-08-06 21:41:44 +00003909
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003910static PyObject *
3911wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3912{
3913 descrsetfunc func = (descrsetfunc)wrapped;
3914 PyObject *obj;
3915 int ret;
3916
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003917 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003918 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003919 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003920 ret = (*func)(self, obj, NULL);
3921 if (ret < 0)
3922 return NULL;
3923 Py_INCREF(Py_None);
3924 return Py_None;
3925}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003926
Tim Peters6d6c1a32001-08-02 04:15:00 +00003927static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003928wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003929{
3930 initproc func = (initproc)wrapped;
3931
Guido van Rossumc8e56452001-10-22 00:43:43 +00003932 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003933 return NULL;
3934 Py_INCREF(Py_None);
3935 return Py_None;
3936}
3937
Tim Peters6d6c1a32001-08-02 04:15:00 +00003938static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003939tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003940{
Barry Warsaw60f01882001-08-22 19:24:42 +00003941 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003942 PyObject *arg0, *res;
3943
3944 if (self == NULL || !PyType_Check(self))
3945 Py_FatalError("__new__() called with non-type 'self'");
3946 type = (PyTypeObject *)self;
3947 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003948 PyErr_Format(PyExc_TypeError,
3949 "%s.__new__(): not enough arguments",
3950 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003951 return NULL;
3952 }
3953 arg0 = PyTuple_GET_ITEM(args, 0);
3954 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003955 PyErr_Format(PyExc_TypeError,
3956 "%s.__new__(X): X is not a type object (%s)",
3957 type->tp_name,
3958 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003959 return NULL;
3960 }
3961 subtype = (PyTypeObject *)arg0;
3962 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003963 PyErr_Format(PyExc_TypeError,
3964 "%s.__new__(%s): %s is not a subtype of %s",
3965 type->tp_name,
3966 subtype->tp_name,
3967 subtype->tp_name,
3968 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003969 return NULL;
3970 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003971
3972 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003973 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003974 most derived base that's not a heap type is this type. */
3975 staticbase = subtype;
3976 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3977 staticbase = staticbase->tp_base;
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003978 /* If staticbase is NULL now, it is a really weird type.
3979 In the same of backwards compatibility (?), just shut up. */
3980 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003981 PyErr_Format(PyExc_TypeError,
3982 "%s.__new__(%s) is not safe, use %s.__new__()",
3983 type->tp_name,
3984 subtype->tp_name,
3985 staticbase == NULL ? "?" : staticbase->tp_name);
3986 return NULL;
3987 }
3988
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003989 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3990 if (args == NULL)
3991 return NULL;
3992 res = type->tp_new(subtype, args, kwds);
3993 Py_DECREF(args);
3994 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003995}
3996
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003997static struct PyMethodDef tp_new_methoddef[] = {
3998 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003999 PyDoc_STR("T.__new__(S, ...) -> "
4000 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004001 {0}
4002};
4003
4004static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004005add_tp_new_wrapper(PyTypeObject *type)
4006{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004007 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004008
Guido van Rossum687ae002001-10-15 22:03:32 +00004009 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004010 return 0;
4011 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004012 if (func == NULL)
4013 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004014 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004015 Py_DECREF(func);
4016 return -1;
4017 }
4018 Py_DECREF(func);
4019 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004020}
4021
Guido van Rossumf040ede2001-08-07 16:40:56 +00004022/* Slot wrappers that call the corresponding __foo__ slot. See comments
4023 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004024
Guido van Rossumdc91b992001-08-08 22:26:22 +00004025#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004026static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004027FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004028{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004029 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004030 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004031}
4032
Guido van Rossumdc91b992001-08-08 22:26:22 +00004033#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004034static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004035FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004036{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004037 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004038 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004039}
4040
Guido van Rossumcd118802003-01-06 22:57:47 +00004041/* Boolean helper for SLOT1BINFULL().
4042 right.__class__ is a nontrivial subclass of left.__class__. */
4043static int
4044method_is_overloaded(PyObject *left, PyObject *right, char *name)
4045{
4046 PyObject *a, *b;
4047 int ok;
4048
4049 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
4050 if (b == NULL) {
4051 PyErr_Clear();
4052 /* If right doesn't have it, it's not overloaded */
4053 return 0;
4054 }
4055
4056 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
4057 if (a == NULL) {
4058 PyErr_Clear();
4059 Py_DECREF(b);
4060 /* If right has it but left doesn't, it's overloaded */
4061 return 1;
4062 }
4063
4064 ok = PyObject_RichCompareBool(a, b, Py_NE);
4065 Py_DECREF(a);
4066 Py_DECREF(b);
4067 if (ok < 0) {
4068 PyErr_Clear();
4069 return 0;
4070 }
4071
4072 return ok;
4073}
4074
Guido van Rossumdc91b992001-08-08 22:26:22 +00004075
4076#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004077static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004078FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004079{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004080 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004081 int do_other = self->ob_type != other->ob_type && \
4082 other->ob_type->tp_as_number != NULL && \
4083 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004084 if (self->ob_type->tp_as_number != NULL && \
4085 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
4086 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004087 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004088 PyType_IsSubtype(other->ob_type, self->ob_type) && \
4089 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004090 r = call_maybe( \
4091 other, ROPSTR, &rcache_str, "(O)", self); \
4092 if (r != Py_NotImplemented) \
4093 return r; \
4094 Py_DECREF(r); \
4095 do_other = 0; \
4096 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004097 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004098 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004099 if (r != Py_NotImplemented || \
4100 other->ob_type == self->ob_type) \
4101 return r; \
4102 Py_DECREF(r); \
4103 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004104 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004105 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004106 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004107 } \
4108 Py_INCREF(Py_NotImplemented); \
4109 return Py_NotImplemented; \
4110}
4111
4112#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4113 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4114
4115#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4116static PyObject * \
4117FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4118{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004119 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004120 return call_method(self, OPSTR, &cache_str, \
4121 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004122}
4123
Martin v. Löwis18e16552006-02-15 17:27:45 +00004124static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004125slot_sq_length(PyObject *self)
4126{
Guido van Rossum2730b132001-08-28 18:22:14 +00004127 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004128 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004129 Py_ssize_t temp;
4130 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004131
4132 if (res == NULL)
4133 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004134 temp = PyInt_AsSsize_t(res);
Guido van Rossum630db602005-09-20 18:49:54 +00004135 len = (int)temp;
Guido van Rossum26111622001-10-01 16:42:49 +00004136 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00004137 if (len == -1 && PyErr_Occurred())
4138 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004139#if SIZEOF_SIZE_T < SIZEOF_LONG
4140 /* Overflow check -- range of PyInt is more than C ssize_t */
Guido van Rossum630db602005-09-20 18:49:54 +00004141 if (len != temp) {
4142 PyErr_SetString(PyExc_OverflowError,
4143 "__len__() should return 0 <= outcome < 2**31");
4144 return -1;
4145 }
4146#endif
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004147 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00004148 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004149 "__len__() should return >= 0");
4150 return -1;
4151 }
Guido van Rossum26111622001-10-01 16:42:49 +00004152 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004153}
4154
Guido van Rossumf4593e02001-10-03 12:09:30 +00004155/* Super-optimized version of slot_sq_item.
4156 Other slots could do the same... */
4157static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004158slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004159{
4160 static PyObject *getitem_str;
4161 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4162 descrgetfunc f;
4163
4164 if (getitem_str == NULL) {
4165 getitem_str = PyString_InternFromString("__getitem__");
4166 if (getitem_str == NULL)
4167 return NULL;
4168 }
4169 func = _PyType_Lookup(self->ob_type, getitem_str);
4170 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004171 if ((f = func->ob_type->tp_descr_get) == NULL)
4172 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004173 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004174 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004175 if (func == NULL) {
4176 return NULL;
4177 }
4178 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004179 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004180 if (ival != NULL) {
4181 args = PyTuple_New(1);
4182 if (args != NULL) {
4183 PyTuple_SET_ITEM(args, 0, ival);
4184 retval = PyObject_Call(func, args, NULL);
4185 Py_XDECREF(args);
4186 Py_XDECREF(func);
4187 return retval;
4188 }
4189 }
4190 }
4191 else {
4192 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4193 }
4194 Py_XDECREF(args);
4195 Py_XDECREF(ival);
4196 Py_XDECREF(func);
4197 return NULL;
4198}
4199
Martin v. Löwis18e16552006-02-15 17:27:45 +00004200SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004201
4202static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004203slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004204{
4205 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004206 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004207
4208 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004209 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004210 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004211 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004212 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004213 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004214 if (res == NULL)
4215 return -1;
4216 Py_DECREF(res);
4217 return 0;
4218}
4219
4220static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004221slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004222{
4223 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004224 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004225
4226 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004227 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004228 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004229 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004230 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004231 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004232 if (res == NULL)
4233 return -1;
4234 Py_DECREF(res);
4235 return 0;
4236}
4237
4238static int
4239slot_sq_contains(PyObject *self, PyObject *value)
4240{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004241 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004242 int result = -1;
4243
Guido van Rossum60718732001-08-28 17:47:51 +00004244 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004245
Guido van Rossum55f20992001-10-01 17:18:22 +00004246 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004247 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004248 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004249 if (args == NULL)
4250 res = NULL;
4251 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004252 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004253 Py_DECREF(args);
4254 }
4255 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004256 if (res != NULL) {
4257 result = PyObject_IsTrue(res);
4258 Py_DECREF(res);
4259 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004260 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004261 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004262 /* Possible results: -1 and 1 */
4263 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004264 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004265 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004266 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004267}
4268
Tim Peters6d6c1a32001-08-02 04:15:00 +00004269#define slot_mp_length slot_sq_length
4270
Guido van Rossumdc91b992001-08-08 22:26:22 +00004271SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004272
4273static int
4274slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4275{
4276 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004277 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004278
4279 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004280 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004281 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004282 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004283 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004284 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004285 if (res == NULL)
4286 return -1;
4287 Py_DECREF(res);
4288 return 0;
4289}
4290
Guido van Rossumdc91b992001-08-08 22:26:22 +00004291SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4292SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4293SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4294SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4295SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4296SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4297
Jeremy Hylton938ace62002-07-17 16:30:39 +00004298static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004299
4300SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4301 nb_power, "__pow__", "__rpow__")
4302
4303static PyObject *
4304slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4305{
Guido van Rossum2730b132001-08-28 18:22:14 +00004306 static PyObject *pow_str;
4307
Guido van Rossumdc91b992001-08-08 22:26:22 +00004308 if (modulus == Py_None)
4309 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004310 /* Three-arg power doesn't use __rpow__. But ternary_op
4311 can call this when the second argument's type uses
4312 slot_nb_power, so check before calling self.__pow__. */
4313 if (self->ob_type->tp_as_number != NULL &&
4314 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4315 return call_method(self, "__pow__", &pow_str,
4316 "(OO)", other, modulus);
4317 }
4318 Py_INCREF(Py_NotImplemented);
4319 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004320}
4321
4322SLOT0(slot_nb_negative, "__neg__")
4323SLOT0(slot_nb_positive, "__pos__")
4324SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004325
4326static int
4327slot_nb_nonzero(PyObject *self)
4328{
Tim Petersea7f75d2002-12-07 21:39:16 +00004329 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004330 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004331 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004332
Guido van Rossum55f20992001-10-01 17:18:22 +00004333 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004334 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004335 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004336 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004337 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004338 if (func == NULL)
4339 return PyErr_Occurred() ? -1 : 1;
4340 }
4341 args = PyTuple_New(0);
4342 if (args != NULL) {
4343 PyObject *temp = PyObject_Call(func, args, NULL);
4344 Py_DECREF(args);
4345 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004346 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004347 result = PyObject_IsTrue(temp);
4348 else {
4349 PyErr_Format(PyExc_TypeError,
4350 "__nonzero__ should return "
4351 "bool or int, returned %s",
4352 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004353 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004354 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004355 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004356 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004357 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004358 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004359 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004360}
4361
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004362
4363static Py_ssize_t
4364slot_nb_index(PyObject *self)
4365{
4366 PyObject *func, *args;
4367 static PyObject *index_str;
4368 Py_ssize_t result = -1;
4369
4370 func = lookup_maybe(self, "__index__", &index_str);
4371 if (func == NULL) {
4372 if (!PyErr_Occurred()) {
4373 PyErr_SetString(PyExc_TypeError,
4374 "object cannot be interpreted as an index");
4375 }
4376 return -1;
4377 }
4378 args = PyTuple_New(0);
4379 if (args != NULL) {
4380 PyObject *temp = PyObject_Call(func, args, NULL);
4381 Py_DECREF(args);
4382 if (temp != NULL) {
4383 if (PyInt_Check(temp) || PyLong_Check(temp)) {
4384 result =
4385 temp->ob_type->tp_as_number->nb_index(temp);
4386 }
4387 else {
4388 PyErr_SetString(PyExc_TypeError,
4389 "__index__ must return an int or a long");
4390 result = -1;
4391 }
4392 Py_DECREF(temp);
4393 }
4394 }
4395 Py_DECREF(func);
4396 return result;
4397}
4398
4399
Guido van Rossumdc91b992001-08-08 22:26:22 +00004400SLOT0(slot_nb_invert, "__invert__")
4401SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4402SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4403SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4404SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4405SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004406
4407static int
4408slot_nb_coerce(PyObject **a, PyObject **b)
4409{
4410 static PyObject *coerce_str;
4411 PyObject *self = *a, *other = *b;
4412
4413 if (self->ob_type->tp_as_number != NULL &&
4414 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4415 PyObject *r;
4416 r = call_maybe(
4417 self, "__coerce__", &coerce_str, "(O)", other);
4418 if (r == NULL)
4419 return -1;
4420 if (r == Py_NotImplemented) {
4421 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004422 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004423 else {
4424 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4425 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004426 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004427 Py_DECREF(r);
4428 return -1;
4429 }
4430 *a = PyTuple_GET_ITEM(r, 0);
4431 Py_INCREF(*a);
4432 *b = PyTuple_GET_ITEM(r, 1);
4433 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004434 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004435 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004436 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004437 }
4438 if (other->ob_type->tp_as_number != NULL &&
4439 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4440 PyObject *r;
4441 r = call_maybe(
4442 other, "__coerce__", &coerce_str, "(O)", self);
4443 if (r == NULL)
4444 return -1;
4445 if (r == Py_NotImplemented) {
4446 Py_DECREF(r);
4447 return 1;
4448 }
4449 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4450 PyErr_SetString(PyExc_TypeError,
4451 "__coerce__ didn't return a 2-tuple");
4452 Py_DECREF(r);
4453 return -1;
4454 }
4455 *a = PyTuple_GET_ITEM(r, 1);
4456 Py_INCREF(*a);
4457 *b = PyTuple_GET_ITEM(r, 0);
4458 Py_INCREF(*b);
4459 Py_DECREF(r);
4460 return 0;
4461 }
4462 return 1;
4463}
4464
Guido van Rossumdc91b992001-08-08 22:26:22 +00004465SLOT0(slot_nb_int, "__int__")
4466SLOT0(slot_nb_long, "__long__")
4467SLOT0(slot_nb_float, "__float__")
4468SLOT0(slot_nb_oct, "__oct__")
4469SLOT0(slot_nb_hex, "__hex__")
4470SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4471SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4472SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4473SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4474SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004475SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004476SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4477SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4478SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4479SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4480SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4481SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4482 "__floordiv__", "__rfloordiv__")
4483SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4484SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4485SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004486
4487static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004488half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004489{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004490 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004491 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004492 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004493
Guido van Rossum60718732001-08-28 17:47:51 +00004494 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004495 if (func == NULL) {
4496 PyErr_Clear();
4497 }
4498 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004499 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004500 if (args == NULL)
4501 res = NULL;
4502 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004503 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004504 Py_DECREF(args);
4505 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004506 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004507 if (res != Py_NotImplemented) {
4508 if (res == NULL)
4509 return -2;
4510 c = PyInt_AsLong(res);
4511 Py_DECREF(res);
4512 if (c == -1 && PyErr_Occurred())
4513 return -2;
4514 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4515 }
4516 Py_DECREF(res);
4517 }
4518 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004519}
4520
Guido van Rossumab3b0342001-09-18 20:38:53 +00004521/* This slot is published for the benefit of try_3way_compare in object.c */
4522int
4523_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004524{
4525 int c;
4526
Guido van Rossumab3b0342001-09-18 20:38:53 +00004527 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004528 c = half_compare(self, other);
4529 if (c <= 1)
4530 return c;
4531 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004532 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004533 c = half_compare(other, self);
4534 if (c < -1)
4535 return -2;
4536 if (c <= 1)
4537 return -c;
4538 }
4539 return (void *)self < (void *)other ? -1 :
4540 (void *)self > (void *)other ? 1 : 0;
4541}
4542
4543static PyObject *
4544slot_tp_repr(PyObject *self)
4545{
4546 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004547 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004548
Guido van Rossum60718732001-08-28 17:47:51 +00004549 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004550 if (func != NULL) {
4551 res = PyEval_CallObject(func, NULL);
4552 Py_DECREF(func);
4553 return res;
4554 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004555 PyErr_Clear();
4556 return PyString_FromFormat("<%s object at %p>",
4557 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004558}
4559
4560static PyObject *
4561slot_tp_str(PyObject *self)
4562{
4563 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004564 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004565
Guido van Rossum60718732001-08-28 17:47:51 +00004566 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004567 if (func != NULL) {
4568 res = PyEval_CallObject(func, NULL);
4569 Py_DECREF(func);
4570 return res;
4571 }
4572 else {
4573 PyErr_Clear();
4574 return slot_tp_repr(self);
4575 }
4576}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004577
4578static long
4579slot_tp_hash(PyObject *self)
4580{
Tim Peters61ce0a92002-12-06 23:38:02 +00004581 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004582 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004583 long h;
4584
Guido van Rossum60718732001-08-28 17:47:51 +00004585 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004586
4587 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004588 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004589 Py_DECREF(func);
4590 if (res == NULL)
4591 return -1;
4592 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004593 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004594 }
4595 else {
4596 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004597 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004598 if (func == NULL) {
4599 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004600 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004601 }
4602 if (func != NULL) {
4603 Py_DECREF(func);
4604 PyErr_SetString(PyExc_TypeError, "unhashable type");
4605 return -1;
4606 }
4607 PyErr_Clear();
4608 h = _Py_HashPointer((void *)self);
4609 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004610 if (h == -1 && !PyErr_Occurred())
4611 h = -2;
4612 return h;
4613}
4614
4615static PyObject *
4616slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4617{
Guido van Rossum60718732001-08-28 17:47:51 +00004618 static PyObject *call_str;
4619 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004620 PyObject *res;
4621
4622 if (meth == NULL)
4623 return NULL;
4624 res = PyObject_Call(meth, args, kwds);
4625 Py_DECREF(meth);
4626 return res;
4627}
4628
Guido van Rossum14a6f832001-10-17 13:59:09 +00004629/* There are two slot dispatch functions for tp_getattro.
4630
4631 - slot_tp_getattro() is used when __getattribute__ is overridden
4632 but no __getattr__ hook is present;
4633
4634 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4635
Guido van Rossumc334df52002-04-04 23:44:47 +00004636 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4637 detects the absence of __getattr__ and then installs the simpler slot if
4638 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004639
Tim Peters6d6c1a32001-08-02 04:15:00 +00004640static PyObject *
4641slot_tp_getattro(PyObject *self, PyObject *name)
4642{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004643 static PyObject *getattribute_str = NULL;
4644 return call_method(self, "__getattribute__", &getattribute_str,
4645 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004646}
4647
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004648static PyObject *
4649slot_tp_getattr_hook(PyObject *self, PyObject *name)
4650{
4651 PyTypeObject *tp = self->ob_type;
4652 PyObject *getattr, *getattribute, *res;
4653 static PyObject *getattribute_str = NULL;
4654 static PyObject *getattr_str = NULL;
4655
4656 if (getattr_str == NULL) {
4657 getattr_str = PyString_InternFromString("__getattr__");
4658 if (getattr_str == NULL)
4659 return NULL;
4660 }
4661 if (getattribute_str == NULL) {
4662 getattribute_str =
4663 PyString_InternFromString("__getattribute__");
4664 if (getattribute_str == NULL)
4665 return NULL;
4666 }
4667 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004668 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004669 /* No __getattr__ hook: use a simpler dispatcher */
4670 tp->tp_getattro = slot_tp_getattro;
4671 return slot_tp_getattro(self, name);
4672 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004673 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004674 if (getattribute == NULL ||
4675 (getattribute->ob_type == &PyWrapperDescr_Type &&
4676 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4677 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004678 res = PyObject_GenericGetAttr(self, name);
4679 else
4680 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004681 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004682 PyErr_Clear();
4683 res = PyObject_CallFunction(getattr, "OO", self, name);
4684 }
4685 return res;
4686}
4687
Tim Peters6d6c1a32001-08-02 04:15:00 +00004688static int
4689slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4690{
4691 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004692 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004693
4694 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004695 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004696 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004697 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004698 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004699 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004700 if (res == NULL)
4701 return -1;
4702 Py_DECREF(res);
4703 return 0;
4704}
4705
4706/* Map rich comparison operators to their __xx__ namesakes */
4707static char *name_op[] = {
4708 "__lt__",
4709 "__le__",
4710 "__eq__",
4711 "__ne__",
4712 "__gt__",
4713 "__ge__",
4714};
4715
4716static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004717half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004718{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004719 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004720 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004721
Guido van Rossum60718732001-08-28 17:47:51 +00004722 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004723 if (func == NULL) {
4724 PyErr_Clear();
4725 Py_INCREF(Py_NotImplemented);
4726 return Py_NotImplemented;
4727 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004728 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004729 if (args == NULL)
4730 res = NULL;
4731 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004732 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004733 Py_DECREF(args);
4734 }
4735 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004736 return res;
4737}
4738
Guido van Rossumb8f63662001-08-15 23:57:02 +00004739static PyObject *
4740slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4741{
4742 PyObject *res;
4743
4744 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4745 res = half_richcompare(self, other, op);
4746 if (res != Py_NotImplemented)
4747 return res;
4748 Py_DECREF(res);
4749 }
4750 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004751 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004752 if (res != Py_NotImplemented) {
4753 return res;
4754 }
4755 Py_DECREF(res);
4756 }
4757 Py_INCREF(Py_NotImplemented);
4758 return Py_NotImplemented;
4759}
4760
4761static PyObject *
4762slot_tp_iter(PyObject *self)
4763{
4764 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004765 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004766
Guido van Rossum60718732001-08-28 17:47:51 +00004767 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004768 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004769 PyObject *args;
4770 args = res = PyTuple_New(0);
4771 if (args != NULL) {
4772 res = PyObject_Call(func, args, NULL);
4773 Py_DECREF(args);
4774 }
4775 Py_DECREF(func);
4776 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004777 }
4778 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004779 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004780 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004781 PyErr_SetString(PyExc_TypeError,
4782 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004783 return NULL;
4784 }
4785 Py_DECREF(func);
4786 return PySeqIter_New(self);
4787}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004788
4789static PyObject *
4790slot_tp_iternext(PyObject *self)
4791{
Guido van Rossum2730b132001-08-28 18:22:14 +00004792 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004793 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004794}
4795
Guido van Rossum1a493502001-08-17 16:47:50 +00004796static PyObject *
4797slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4798{
4799 PyTypeObject *tp = self->ob_type;
4800 PyObject *get;
4801 static PyObject *get_str = NULL;
4802
4803 if (get_str == NULL) {
4804 get_str = PyString_InternFromString("__get__");
4805 if (get_str == NULL)
4806 return NULL;
4807 }
4808 get = _PyType_Lookup(tp, get_str);
4809 if (get == NULL) {
4810 /* Avoid further slowdowns */
4811 if (tp->tp_descr_get == slot_tp_descr_get)
4812 tp->tp_descr_get = NULL;
4813 Py_INCREF(self);
4814 return self;
4815 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004816 if (obj == NULL)
4817 obj = Py_None;
4818 if (type == NULL)
4819 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004820 return PyObject_CallFunction(get, "OOO", self, obj, type);
4821}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004822
4823static int
4824slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4825{
Guido van Rossum2c252392001-08-24 10:13:31 +00004826 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004827 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004828
4829 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004830 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004831 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004832 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004833 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004834 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004835 if (res == NULL)
4836 return -1;
4837 Py_DECREF(res);
4838 return 0;
4839}
4840
4841static int
4842slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4843{
Guido van Rossum60718732001-08-28 17:47:51 +00004844 static PyObject *init_str;
4845 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004846 PyObject *res;
4847
4848 if (meth == NULL)
4849 return -1;
4850 res = PyObject_Call(meth, args, kwds);
4851 Py_DECREF(meth);
4852 if (res == NULL)
4853 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004854 if (res != Py_None) {
4855 PyErr_SetString(PyExc_TypeError,
4856 "__init__() should return None");
4857 Py_DECREF(res);
4858 return -1;
4859 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004860 Py_DECREF(res);
4861 return 0;
4862}
4863
4864static PyObject *
4865slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4866{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004867 static PyObject *new_str;
4868 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004869 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004870 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004871
Guido van Rossum7bed2132002-08-08 21:57:53 +00004872 if (new_str == NULL) {
4873 new_str = PyString_InternFromString("__new__");
4874 if (new_str == NULL)
4875 return NULL;
4876 }
4877 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004878 if (func == NULL)
4879 return NULL;
4880 assert(PyTuple_Check(args));
4881 n = PyTuple_GET_SIZE(args);
4882 newargs = PyTuple_New(n+1);
4883 if (newargs == NULL)
4884 return NULL;
4885 Py_INCREF(type);
4886 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4887 for (i = 0; i < n; i++) {
4888 x = PyTuple_GET_ITEM(args, i);
4889 Py_INCREF(x);
4890 PyTuple_SET_ITEM(newargs, i+1, x);
4891 }
4892 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004893 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004894 Py_DECREF(func);
4895 return x;
4896}
4897
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004898static void
4899slot_tp_del(PyObject *self)
4900{
4901 static PyObject *del_str = NULL;
4902 PyObject *del, *res;
4903 PyObject *error_type, *error_value, *error_traceback;
4904
4905 /* Temporarily resurrect the object. */
4906 assert(self->ob_refcnt == 0);
4907 self->ob_refcnt = 1;
4908
4909 /* Save the current exception, if any. */
4910 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4911
4912 /* Execute __del__ method, if any. */
4913 del = lookup_maybe(self, "__del__", &del_str);
4914 if (del != NULL) {
4915 res = PyEval_CallObject(del, NULL);
4916 if (res == NULL)
4917 PyErr_WriteUnraisable(del);
4918 else
4919 Py_DECREF(res);
4920 Py_DECREF(del);
4921 }
4922
4923 /* Restore the saved exception. */
4924 PyErr_Restore(error_type, error_value, error_traceback);
4925
4926 /* Undo the temporary resurrection; can't use DECREF here, it would
4927 * cause a recursive call.
4928 */
4929 assert(self->ob_refcnt > 0);
4930 if (--self->ob_refcnt == 0)
4931 return; /* this is the normal path out */
4932
4933 /* __del__ resurrected it! Make it look like the original Py_DECREF
4934 * never happened.
4935 */
4936 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004937 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004938 _Py_NewReference(self);
4939 self->ob_refcnt = refcnt;
4940 }
4941 assert(!PyType_IS_GC(self->ob_type) ||
4942 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00004943 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
4944 * we need to undo that. */
4945 _Py_DEC_REFTOTAL;
4946 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4947 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004948 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4949 * _Py_NewReference bumped tp_allocs: both of those need to be
4950 * undone.
4951 */
4952#ifdef COUNT_ALLOCS
4953 --self->ob_type->tp_frees;
4954 --self->ob_type->tp_allocs;
4955#endif
4956}
4957
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004958
4959/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004960 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004961 structure, which incorporates the additional structures used for numbers,
4962 sequences and mappings.
4963 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004964 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004965 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4966 terminated with an all-zero entry. (This table is further initialized and
4967 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004968
Guido van Rossum6d204072001-10-21 00:44:31 +00004969typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004970
4971#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004972#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004973#undef ETSLOT
4974#undef SQSLOT
4975#undef MPSLOT
4976#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004977#undef UNSLOT
4978#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004979#undef BINSLOT
4980#undef RBINSLOT
4981
Guido van Rossum6d204072001-10-21 00:44:31 +00004982#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004983 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4984 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004985#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4986 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004987 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004988#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004989 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004990 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004991#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4992 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4993#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4994 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4995#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4996 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4997#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4998 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4999 "x." NAME "() <==> " DOC)
5000#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5001 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5002 "x." NAME "(y) <==> x" DOC "y")
5003#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5004 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5005 "x." NAME "(y) <==> x" DOC "y")
5006#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5007 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5008 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005009#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5010 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5011 "x." NAME "(y) <==> " DOC)
5012#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5013 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5014 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005015
5016static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005017 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005018 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005019 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5020 The logic in abstract.c always falls back to nb_add/nb_multiply in
5021 this case. Defining both the nb_* and the sq_* slots to call the
5022 user-defined methods has unexpected side-effects, as shown by
5023 test_descr.notimplemented() */
5024 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5025 "x.__add__(y) <==> x+y"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005026 SQSLOT("__mul__", sq_repeat, NULL, wrap_ssizeargfunc,
Armin Rigofd163f92005-12-29 15:59:19 +00005027 "x.__mul__(n) <==> x*n"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005028 SQSLOT("__rmul__", sq_repeat, NULL, wrap_ssizeargfunc,
Armin Rigofd163f92005-12-29 15:59:19 +00005029 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005030 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5031 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005032 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005033 "x.__getslice__(i, j) <==> x[i:j]\n\
5034 \n\
5035 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005036 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005037 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005038 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005039 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005040 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005041 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005042 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
5043 \n\
5044 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005045 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005046 "x.__delslice__(i, j) <==> del x[i:j]\n\
5047 \n\
5048 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005049 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5050 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005051 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5052 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5053 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005054 wrap_ssizeargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005055
Martin v. Löwis18e16552006-02-15 17:27:45 +00005056 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005057 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005058 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005059 wrap_binaryfunc,
5060 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005061 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005062 wrap_objobjargproc,
5063 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005064 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005065 wrap_delitem,
5066 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005067
Guido van Rossum6d204072001-10-21 00:44:31 +00005068 BINSLOT("__add__", nb_add, slot_nb_add,
5069 "+"),
5070 RBINSLOT("__radd__", nb_add, slot_nb_add,
5071 "+"),
5072 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5073 "-"),
5074 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5075 "-"),
5076 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5077 "*"),
5078 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5079 "*"),
5080 BINSLOT("__div__", nb_divide, slot_nb_divide,
5081 "/"),
5082 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5083 "/"),
5084 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5085 "%"),
5086 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5087 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005088 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005089 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005090 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005091 "divmod(y, x)"),
5092 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5093 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5094 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5095 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5096 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5097 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5098 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5099 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005100 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005101 "x != 0"),
5102 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5103 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5104 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5105 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5106 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5107 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5108 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5109 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5110 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5111 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5112 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5113 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5114 "x.__coerce__(y) <==> coerce(x, y)"),
5115 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5116 "int(x)"),
5117 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5118 "long(x)"),
5119 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5120 "float(x)"),
5121 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5122 "oct(x)"),
5123 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5124 "hex(x)"),
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005125 NBSLOT("__index__", nb_index, slot_nb_index, wrap_lenfunc,
5126 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005127 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5128 wrap_binaryfunc, "+"),
5129 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5130 wrap_binaryfunc, "-"),
5131 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5132 wrap_binaryfunc, "*"),
5133 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5134 wrap_binaryfunc, "/"),
5135 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5136 wrap_binaryfunc, "%"),
5137 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005138 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005139 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5140 wrap_binaryfunc, "<<"),
5141 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5142 wrap_binaryfunc, ">>"),
5143 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5144 wrap_binaryfunc, "&"),
5145 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5146 wrap_binaryfunc, "^"),
5147 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5148 wrap_binaryfunc, "|"),
5149 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5150 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5151 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5152 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5153 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5154 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5155 IBSLOT("__itruediv__", nb_inplace_true_divide,
5156 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005157
Guido van Rossum6d204072001-10-21 00:44:31 +00005158 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5159 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005160 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005161 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5162 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005163 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005164 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5165 "x.__cmp__(y) <==> cmp(x,y)"),
5166 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5167 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005168 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5169 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005170 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005171 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5172 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5173 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5174 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5175 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5176 "x.__setattr__('name', value) <==> x.name = value"),
5177 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5178 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5179 "x.__delattr__('name') <==> del x.name"),
5180 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5181 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5182 "x.__lt__(y) <==> x<y"),
5183 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5184 "x.__le__(y) <==> x<=y"),
5185 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5186 "x.__eq__(y) <==> x==y"),
5187 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5188 "x.__ne__(y) <==> x!=y"),
5189 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5190 "x.__gt__(y) <==> x>y"),
5191 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5192 "x.__ge__(y) <==> x>=y"),
5193 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5194 "x.__iter__() <==> iter(x)"),
5195 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5196 "x.next() -> the next value, or raise StopIteration"),
5197 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5198 "descr.__get__(obj[, type]) -> value"),
5199 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5200 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005201 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5202 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005203 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005204 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005205 "see x.__class__.__doc__ for signature",
5206 PyWrapperFlag_KEYWORDS),
5207 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005208 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005209 {NULL}
5210};
5211
Guido van Rossumc334df52002-04-04 23:44:47 +00005212/* Given a type pointer and an offset gotten from a slotdef entry, return a
5213 pointer to the actual slot. This is not quite the same as simply adding
5214 the offset to the type pointer, since it takes care to indirect through the
5215 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5216 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005217static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005218slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005219{
5220 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005221 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005222
Guido van Rossume5c691a2003-03-07 15:13:17 +00005223 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005224 assert(offset >= 0);
Guido van Rossume5c691a2003-03-07 15:13:17 +00005225 assert(offset < offsetof(PyHeapTypeObject, as_buffer));
5226 if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005227 ptr = (void *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005228 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005229 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005230 else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Guido van Rossum09638c12002-06-13 19:17:46 +00005231 ptr = (void *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005232 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005233 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005234 else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005235 ptr = (void *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005236 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005237 }
5238 else {
5239 ptr = (void *)type;
5240 }
5241 if (ptr != NULL)
5242 ptr += offset;
5243 return (void **)ptr;
5244}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005245
Guido van Rossumc334df52002-04-04 23:44:47 +00005246/* Length of array of slotdef pointers used to store slots with the
5247 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5248 the same __name__, for any __name__. Since that's a static property, it is
5249 appropriate to declare fixed-size arrays for this. */
5250#define MAX_EQUIV 10
5251
5252/* Return a slot pointer for a given name, but ONLY if the attribute has
5253 exactly one slot function. The name must be an interned string. */
5254static void **
5255resolve_slotdups(PyTypeObject *type, PyObject *name)
5256{
5257 /* XXX Maybe this could be optimized more -- but is it worth it? */
5258
5259 /* pname and ptrs act as a little cache */
5260 static PyObject *pname;
5261 static slotdef *ptrs[MAX_EQUIV];
5262 slotdef *p, **pp;
5263 void **res, **ptr;
5264
5265 if (pname != name) {
5266 /* Collect all slotdefs that match name into ptrs. */
5267 pname = name;
5268 pp = ptrs;
5269 for (p = slotdefs; p->name_strobj; p++) {
5270 if (p->name_strobj == name)
5271 *pp++ = p;
5272 }
5273 *pp = NULL;
5274 }
5275
5276 /* Look in all matching slots of the type; if exactly one of these has
5277 a filled-in slot, return its value. Otherwise return NULL. */
5278 res = NULL;
5279 for (pp = ptrs; *pp; pp++) {
5280 ptr = slotptr(type, (*pp)->offset);
5281 if (ptr == NULL || *ptr == NULL)
5282 continue;
5283 if (res != NULL)
5284 return NULL;
5285 res = ptr;
5286 }
5287 return res;
5288}
5289
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005290/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005291 does some incredibly complex thinking and then sticks something into the
5292 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5293 interests, and then stores a generic wrapper or a specific function into
5294 the slot.) Return a pointer to the next slotdef with a different offset,
5295 because that's convenient for fixup_slot_dispatchers(). */
5296static slotdef *
5297update_one_slot(PyTypeObject *type, slotdef *p)
5298{
5299 PyObject *descr;
5300 PyWrapperDescrObject *d;
5301 void *generic = NULL, *specific = NULL;
5302 int use_generic = 0;
5303 int offset = p->offset;
5304 void **ptr = slotptr(type, offset);
5305
5306 if (ptr == NULL) {
5307 do {
5308 ++p;
5309 } while (p->offset == offset);
5310 return p;
5311 }
5312 do {
5313 descr = _PyType_Lookup(type, p->name_strobj);
5314 if (descr == NULL)
5315 continue;
5316 if (descr->ob_type == &PyWrapperDescr_Type) {
5317 void **tptr = resolve_slotdups(type, p->name_strobj);
5318 if (tptr == NULL || tptr == ptr)
5319 generic = p->function;
5320 d = (PyWrapperDescrObject *)descr;
5321 if (d->d_base->wrapper == p->wrapper &&
5322 PyType_IsSubtype(type, d->d_type))
5323 {
5324 if (specific == NULL ||
5325 specific == d->d_wrapped)
5326 specific = d->d_wrapped;
5327 else
5328 use_generic = 1;
5329 }
5330 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005331 else if (descr->ob_type == &PyCFunction_Type &&
5332 PyCFunction_GET_FUNCTION(descr) ==
5333 (PyCFunction)tp_new_wrapper &&
5334 strcmp(p->name, "__new__") == 0)
5335 {
5336 /* The __new__ wrapper is not a wrapper descriptor,
5337 so must be special-cased differently.
5338 If we don't do this, creating an instance will
5339 always use slot_tp_new which will look up
5340 __new__ in the MRO which will call tp_new_wrapper
5341 which will look through the base classes looking
5342 for a static base and call its tp_new (usually
5343 PyType_GenericNew), after performing various
5344 sanity checks and constructing a new argument
5345 list. Cut all that nonsense short -- this speeds
5346 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005347 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005348 /* XXX I'm not 100% sure that there isn't a hole
5349 in this reasoning that requires additional
5350 sanity checks. I'll buy the first person to
5351 point out a bug in this reasoning a beer. */
5352 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005353 else {
5354 use_generic = 1;
5355 generic = p->function;
5356 }
5357 } while ((++p)->offset == offset);
5358 if (specific && !use_generic)
5359 *ptr = specific;
5360 else
5361 *ptr = generic;
5362 return p;
5363}
5364
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005365/* In the type, update the slots whose slotdefs are gathered in the pp array.
5366 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005367static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005368update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005369{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005370 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005371
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005372 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005373 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005374 return 0;
5375}
5376
Guido van Rossumc334df52002-04-04 23:44:47 +00005377/* Comparison function for qsort() to compare slotdefs by their offset, and
5378 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005379static int
5380slotdef_cmp(const void *aa, const void *bb)
5381{
5382 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5383 int c = a->offset - b->offset;
5384 if (c != 0)
5385 return c;
5386 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005387 /* Cannot use a-b, as this gives off_t,
5388 which may lose precision when converted to int. */
5389 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005390}
5391
Guido van Rossumc334df52002-04-04 23:44:47 +00005392/* Initialize the slotdefs table by adding interned string objects for the
5393 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005394static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005395init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005396{
5397 slotdef *p;
5398 static int initialized = 0;
5399
5400 if (initialized)
5401 return;
5402 for (p = slotdefs; p->name; p++) {
5403 p->name_strobj = PyString_InternFromString(p->name);
5404 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005405 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005406 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005407 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5408 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005409 initialized = 1;
5410}
5411
Guido van Rossumc334df52002-04-04 23:44:47 +00005412/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005413static int
5414update_slot(PyTypeObject *type, PyObject *name)
5415{
Guido van Rossumc334df52002-04-04 23:44:47 +00005416 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005417 slotdef *p;
5418 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005419 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005420
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005421 init_slotdefs();
5422 pp = ptrs;
5423 for (p = slotdefs; p->name; p++) {
5424 /* XXX assume name is interned! */
5425 if (p->name_strobj == name)
5426 *pp++ = p;
5427 }
5428 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005429 for (pp = ptrs; *pp; pp++) {
5430 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005431 offset = p->offset;
5432 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005433 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005434 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005435 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005436 if (ptrs[0] == NULL)
5437 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005438 return update_subclasses(type, name,
5439 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005440}
5441
Guido van Rossumc334df52002-04-04 23:44:47 +00005442/* Store the proper functions in the slot dispatches at class (type)
5443 definition time, based upon which operations the class overrides in its
5444 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005445static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005446fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005447{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005448 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005449
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005450 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005451 for (p = slotdefs; p->name; )
5452 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005453}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005454
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005455static void
5456update_all_slots(PyTypeObject* type)
5457{
5458 slotdef *p;
5459
5460 init_slotdefs();
5461 for (p = slotdefs; p->name; p++) {
5462 /* update_slot returns int but can't actually fail */
5463 update_slot(type, p->name_strobj);
5464 }
5465}
5466
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005467/* recurse_down_subclasses() and update_subclasses() are mutually
5468 recursive functions to call a callback for all subclasses,
5469 but refraining from recursing into subclasses that define 'name'. */
5470
5471static int
5472update_subclasses(PyTypeObject *type, PyObject *name,
5473 update_callback callback, void *data)
5474{
5475 if (callback(type, data) < 0)
5476 return -1;
5477 return recurse_down_subclasses(type, name, callback, data);
5478}
5479
5480static int
5481recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5482 update_callback callback, void *data)
5483{
5484 PyTypeObject *subclass;
5485 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005486 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005487
5488 subclasses = type->tp_subclasses;
5489 if (subclasses == NULL)
5490 return 0;
5491 assert(PyList_Check(subclasses));
5492 n = PyList_GET_SIZE(subclasses);
5493 for (i = 0; i < n; i++) {
5494 ref = PyList_GET_ITEM(subclasses, i);
5495 assert(PyWeakref_CheckRef(ref));
5496 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5497 assert(subclass != NULL);
5498 if ((PyObject *)subclass == Py_None)
5499 continue;
5500 assert(PyType_Check(subclass));
5501 /* Avoid recursing down into unaffected classes */
5502 dict = subclass->tp_dict;
5503 if (dict != NULL && PyDict_Check(dict) &&
5504 PyDict_GetItem(dict, name) != NULL)
5505 continue;
5506 if (update_subclasses(subclass, name, callback, data) < 0)
5507 return -1;
5508 }
5509 return 0;
5510}
5511
Guido van Rossum6d204072001-10-21 00:44:31 +00005512/* This function is called by PyType_Ready() to populate the type's
5513 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005514 function slot (like tp_repr) that's defined in the type, one or more
5515 corresponding descriptors are added in the type's tp_dict dictionary
5516 under the appropriate name (like __repr__). Some function slots
5517 cause more than one descriptor to be added (for example, the nb_add
5518 slot adds both __add__ and __radd__ descriptors) and some function
5519 slots compete for the same descriptor (for example both sq_item and
5520 mp_subscript generate a __getitem__ descriptor).
5521
5522 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005523 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005524 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005525 between competing slots: the members of PyHeapTypeObject are listed
5526 from most general to least general, so the most general slot is
5527 preferred. In particular, because as_mapping comes before as_sequence,
5528 for a type that defines both mp_subscript and sq_item, mp_subscript
5529 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005530
5531 This only adds new descriptors and doesn't overwrite entries in
5532 tp_dict that were previously defined. The descriptors contain a
5533 reference to the C function they must call, so that it's safe if they
5534 are copied into a subtype's __dict__ and the subtype has a different
5535 C function in its slot -- calling the method defined by the
5536 descriptor will call the C function that was used to create it,
5537 rather than the C function present in the slot when it is called.
5538 (This is important because a subtype may have a C function in the
5539 slot that calls the method from the dictionary, and we want to avoid
5540 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005541
5542static int
5543add_operators(PyTypeObject *type)
5544{
5545 PyObject *dict = type->tp_dict;
5546 slotdef *p;
5547 PyObject *descr;
5548 void **ptr;
5549
5550 init_slotdefs();
5551 for (p = slotdefs; p->name; p++) {
5552 if (p->wrapper == NULL)
5553 continue;
5554 ptr = slotptr(type, p->offset);
5555 if (!ptr || !*ptr)
5556 continue;
5557 if (PyDict_GetItem(dict, p->name_strobj))
5558 continue;
5559 descr = PyDescr_NewWrapper(type, p, *ptr);
5560 if (descr == NULL)
5561 return -1;
5562 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5563 return -1;
5564 Py_DECREF(descr);
5565 }
5566 if (type->tp_new != NULL) {
5567 if (add_tp_new_wrapper(type) < 0)
5568 return -1;
5569 }
5570 return 0;
5571}
5572
Guido van Rossum705f0f52001-08-24 16:47:00 +00005573
5574/* Cooperative 'super' */
5575
5576typedef struct {
5577 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005578 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005579 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005580 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005581} superobject;
5582
Guido van Rossum6f799372001-09-20 20:46:19 +00005583static PyMemberDef super_members[] = {
5584 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5585 "the class invoking super()"},
5586 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5587 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005588 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005589 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005590 {0}
5591};
5592
Guido van Rossum705f0f52001-08-24 16:47:00 +00005593static void
5594super_dealloc(PyObject *self)
5595{
5596 superobject *su = (superobject *)self;
5597
Guido van Rossum048eb752001-10-02 21:24:57 +00005598 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005599 Py_XDECREF(su->obj);
5600 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005601 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005602 self->ob_type->tp_free(self);
5603}
5604
5605static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005606super_repr(PyObject *self)
5607{
5608 superobject *su = (superobject *)self;
5609
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005610 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005611 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005612 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005613 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005614 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005615 else
5616 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005617 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005618 su->type ? su->type->tp_name : "NULL");
5619}
5620
5621static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005622super_getattro(PyObject *self, PyObject *name)
5623{
5624 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005625 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005626
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005627 if (!skip) {
5628 /* We want __class__ to return the class of the super object
5629 (i.e. super, or a subclass), not the class of su->obj. */
5630 skip = (PyString_Check(name) &&
5631 PyString_GET_SIZE(name) == 9 &&
5632 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5633 }
5634
5635 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005636 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005637 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005638 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005639 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005640
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005641 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005642 mro = starttype->tp_mro;
5643
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005644 if (mro == NULL)
5645 n = 0;
5646 else {
5647 assert(PyTuple_Check(mro));
5648 n = PyTuple_GET_SIZE(mro);
5649 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005650 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005651 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005652 break;
5653 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005654 i++;
5655 res = NULL;
5656 for (; i < n; i++) {
5657 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005658 if (PyType_Check(tmp))
5659 dict = ((PyTypeObject *)tmp)->tp_dict;
5660 else if (PyClass_Check(tmp))
5661 dict = ((PyClassObject *)tmp)->cl_dict;
5662 else
5663 continue;
5664 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005665 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005666 Py_INCREF(res);
5667 f = res->ob_type->tp_descr_get;
5668 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005669 tmp = f(res,
5670 /* Only pass 'obj' param if
5671 this is instance-mode super
5672 (See SF ID #743627)
5673 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005674 (su->obj == (PyObject *)
5675 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005676 ? (PyObject *)NULL
5677 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005678 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005679 Py_DECREF(res);
5680 res = tmp;
5681 }
5682 return res;
5683 }
5684 }
5685 }
5686 return PyObject_GenericGetAttr(self, name);
5687}
5688
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005689static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005690supercheck(PyTypeObject *type, PyObject *obj)
5691{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005692 /* Check that a super() call makes sense. Return a type object.
5693
5694 obj can be a new-style class, or an instance of one:
5695
5696 - If it is a class, it must be a subclass of 'type'. This case is
5697 used for class methods; the return value is obj.
5698
5699 - If it is an instance, it must be an instance of 'type'. This is
5700 the normal case; the return value is obj.__class__.
5701
5702 But... when obj is an instance, we want to allow for the case where
5703 obj->ob_type is not a subclass of type, but obj.__class__ is!
5704 This will allow using super() with a proxy for obj.
5705 */
5706
Guido van Rossum8e80a722003-02-18 19:22:22 +00005707 /* Check for first bullet above (special case) */
5708 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5709 Py_INCREF(obj);
5710 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005711 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005712
5713 /* Normal case */
5714 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005715 Py_INCREF(obj->ob_type);
5716 return obj->ob_type;
5717 }
5718 else {
5719 /* Try the slow way */
5720 static PyObject *class_str = NULL;
5721 PyObject *class_attr;
5722
5723 if (class_str == NULL) {
5724 class_str = PyString_FromString("__class__");
5725 if (class_str == NULL)
5726 return NULL;
5727 }
5728
5729 class_attr = PyObject_GetAttr(obj, class_str);
5730
5731 if (class_attr != NULL &&
5732 PyType_Check(class_attr) &&
5733 (PyTypeObject *)class_attr != obj->ob_type)
5734 {
5735 int ok = PyType_IsSubtype(
5736 (PyTypeObject *)class_attr, type);
5737 if (ok)
5738 return (PyTypeObject *)class_attr;
5739 }
5740
5741 if (class_attr == NULL)
5742 PyErr_Clear();
5743 else
5744 Py_DECREF(class_attr);
5745 }
5746
Tim Peters97e5ff52003-02-18 19:32:50 +00005747 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005748 "super(type, obj): "
5749 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005750 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005751}
5752
Guido van Rossum705f0f52001-08-24 16:47:00 +00005753static PyObject *
5754super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5755{
5756 superobject *su = (superobject *)self;
5757 superobject *new;
5758
5759 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5760 /* Not binding to an object, or already bound */
5761 Py_INCREF(self);
5762 return self;
5763 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005764 if (su->ob_type != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005765 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005766 call its type */
5767 return PyObject_CallFunction((PyObject *)su->ob_type,
5768 "OO", su->type, obj);
5769 else {
5770 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005771 PyTypeObject *obj_type = supercheck(su->type, obj);
5772 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005773 return NULL;
5774 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5775 NULL, NULL);
5776 if (new == NULL)
5777 return NULL;
5778 Py_INCREF(su->type);
5779 Py_INCREF(obj);
5780 new->type = su->type;
5781 new->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005782 new->obj_type = obj_type;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005783 return (PyObject *)new;
5784 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005785}
5786
5787static int
5788super_init(PyObject *self, PyObject *args, PyObject *kwds)
5789{
5790 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005791 PyTypeObject *type;
5792 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005793 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005794
5795 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5796 return -1;
5797 if (obj == Py_None)
5798 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005799 if (obj != NULL) {
5800 obj_type = supercheck(type, obj);
5801 if (obj_type == NULL)
5802 return -1;
5803 Py_INCREF(obj);
5804 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005805 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005806 su->type = type;
5807 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005808 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005809 return 0;
5810}
5811
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005812PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005813"super(type) -> unbound super object\n"
5814"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005815"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005816"Typical use to call a cooperative superclass method:\n"
5817"class C(B):\n"
5818" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005819" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005820
Guido van Rossum048eb752001-10-02 21:24:57 +00005821static int
5822super_traverse(PyObject *self, visitproc visit, void *arg)
5823{
5824 superobject *su = (superobject *)self;
5825 int err;
5826
5827#define VISIT(SLOT) \
5828 if (SLOT) { \
5829 err = visit((PyObject *)(SLOT), arg); \
5830 if (err) \
5831 return err; \
5832 }
5833
5834 VISIT(su->obj);
5835 VISIT(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005836 VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005837
5838#undef VISIT
5839
5840 return 0;
5841}
5842
Guido van Rossum705f0f52001-08-24 16:47:00 +00005843PyTypeObject PySuper_Type = {
5844 PyObject_HEAD_INIT(&PyType_Type)
5845 0, /* ob_size */
5846 "super", /* tp_name */
5847 sizeof(superobject), /* tp_basicsize */
5848 0, /* tp_itemsize */
5849 /* methods */
5850 super_dealloc, /* tp_dealloc */
5851 0, /* tp_print */
5852 0, /* tp_getattr */
5853 0, /* tp_setattr */
5854 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005855 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005856 0, /* tp_as_number */
5857 0, /* tp_as_sequence */
5858 0, /* tp_as_mapping */
5859 0, /* tp_hash */
5860 0, /* tp_call */
5861 0, /* tp_str */
5862 super_getattro, /* tp_getattro */
5863 0, /* tp_setattro */
5864 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005865 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5866 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005867 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005868 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005869 0, /* tp_clear */
5870 0, /* tp_richcompare */
5871 0, /* tp_weaklistoffset */
5872 0, /* tp_iter */
5873 0, /* tp_iternext */
5874 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005875 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005876 0, /* tp_getset */
5877 0, /* tp_base */
5878 0, /* tp_dict */
5879 super_descr_get, /* tp_descr_get */
5880 0, /* tp_descr_set */
5881 0, /* tp_dictoffset */
5882 super_init, /* tp_init */
5883 PyType_GenericAlloc, /* tp_alloc */
5884 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005885 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005886};