blob: cc60d6c6af732b5a9e9db5632bf6a971c9fd7a99 [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
8/* The *real* layout of a type object when allocated on the heap */
9/* XXX Should we publish this in a header file? */
10typedef struct {
Guido van Rossum09638c12002-06-13 19:17:46 +000011 /* Note: there's a dependency on the order of these members
12 in slotptr() below. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +000013 PyTypeObject type;
14 PyNumberMethods as_number;
Guido van Rossum9923ffe2002-06-04 19:52:53 +000015 PyMappingMethods as_mapping;
Guido van Rossum09638c12002-06-13 19:17:46 +000016 PySequenceMethods as_sequence; /* as_sequence comes after as_mapping,
17 so that the mapping wins when both
18 the mapping and the sequence define
19 a given operator (e.g. __getitem__).
20 see add_operators() below. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +000021 PyBufferProcs as_buffer;
22 PyObject *name, *slots;
23 PyMemberDef members[1];
24} etype;
25
Guido van Rossum6f799372001-09-20 20:46:19 +000026static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +000027 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
28 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
29 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000030 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000031 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
32 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
33 {"__dictoffset__", T_LONG,
34 offsetof(PyTypeObject, tp_dictoffset), READONLY},
35 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
36 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
37 {0}
38};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000039
Guido van Rossumc0b618a1997-05-02 03:12:38 +000040static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000041type_name(PyTypeObject *type, void *context)
42{
43 char *s;
44
45 s = strrchr(type->tp_name, '.');
46 if (s == NULL)
47 s = type->tp_name;
48 else
49 s++;
50 return PyString_FromString(s);
51}
52
53static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000054type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000055{
Guido van Rossumc3542212001-08-16 09:18:56 +000056 PyObject *mod;
57 char *s;
58
59 s = strrchr(type->tp_name, '.');
60 if (s != NULL)
61 return PyString_FromStringAndSize(type->tp_name,
62 (int)(s - type->tp_name));
63 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
64 return PyString_FromString("__builtin__");
Guido van Rossum687ae002001-10-15 22:03:32 +000065 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Guido van Rossumc3542212001-08-16 09:18:56 +000066 if (mod != NULL && PyString_Check(mod)) {
67 Py_INCREF(mod);
68 return mod;
69 }
70 PyErr_SetString(PyExc_AttributeError, "__module__");
71 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000072}
73
Guido van Rossum3926a632001-09-25 16:25:58 +000074static int
75type_set_module(PyTypeObject *type, PyObject *value, void *context)
76{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000077 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
Guido van Rossum3926a632001-09-25 16:25:58 +000078 strrchr(type->tp_name, '.')) {
79 PyErr_Format(PyExc_TypeError,
80 "can't set %s.__module__", type->tp_name);
81 return -1;
82 }
83 if (!value) {
84 PyErr_Format(PyExc_TypeError,
85 "can't delete %s.__module__", type->tp_name);
86 return -1;
87 }
88 return PyDict_SetItemString(type->tp_dict, "__module__", value);
89}
90
Tim Peters6d6c1a32001-08-02 04:15:00 +000091static PyObject *
92type_dict(PyTypeObject *type, void *context)
93{
94 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000095 Py_INCREF(Py_None);
96 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000097 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000098 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000099}
100
Tim Peters24008312002-03-17 18:56:20 +0000101static PyObject *
102type_get_doc(PyTypeObject *type, void *context)
103{
104 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000105 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000106 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000107 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000108 if (result == NULL) {
109 result = Py_None;
110 Py_INCREF(result);
111 }
112 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000113 result = result->ob_type->tp_descr_get(result, NULL,
114 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000115 }
116 else {
117 Py_INCREF(result);
118 }
Tim Peters24008312002-03-17 18:56:20 +0000119 return result;
120}
121
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000122static PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +0000123 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000124 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000125 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000126 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000127 {0}
128};
129
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000130static int
131type_compare(PyObject *v, PyObject *w)
132{
133 /* This is called with type objects only. So we
134 can just compare the addresses. */
135 Py_uintptr_t vv = (Py_uintptr_t)v;
136 Py_uintptr_t ww = (Py_uintptr_t)w;
137 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
138}
139
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000140static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000141type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000142{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000143 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000144 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000145
146 mod = type_module(type, NULL);
147 if (mod == NULL)
148 PyErr_Clear();
149 else if (!PyString_Check(mod)) {
150 Py_DECREF(mod);
151 mod = NULL;
152 }
153 name = type_name(type, NULL);
154 if (name == NULL)
155 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000156
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000157 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
158 kind = "class";
159 else
160 kind = "type";
161
Barry Warsaw7ce36942001-08-24 18:34:26 +0000162 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000163 rtn = PyString_FromFormat("<%s '%s.%s'>",
164 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000165 PyString_AS_STRING(mod),
166 PyString_AS_STRING(name));
167 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000168 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000169 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000170
Guido van Rossumc3542212001-08-16 09:18:56 +0000171 Py_XDECREF(mod);
172 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000173 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000174}
175
Tim Peters6d6c1a32001-08-02 04:15:00 +0000176static PyObject *
177type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
178{
179 PyObject *obj;
180
181 if (type->tp_new == NULL) {
182 PyErr_Format(PyExc_TypeError,
183 "cannot create '%.100s' instances",
184 type->tp_name);
185 return NULL;
186 }
187
Tim Peters3f996e72001-09-13 19:18:27 +0000188 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000189 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000190 /* Ugly exception: when the call was type(something),
191 don't call tp_init on the result. */
192 if (type == &PyType_Type &&
193 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
194 (kwds == NULL ||
195 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
196 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000197 /* If the returned object is not an instance of type,
198 it won't be initialized. */
199 if (!PyType_IsSubtype(obj->ob_type, type))
200 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000201 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000202 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
203 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000204 type->tp_init(obj, args, kwds) < 0) {
205 Py_DECREF(obj);
206 obj = NULL;
207 }
208 }
209 return obj;
210}
211
212PyObject *
213PyType_GenericAlloc(PyTypeObject *type, int nitems)
214{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000215 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000216 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000217
218 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000219 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000220 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000221 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000222
Neil Schemenauerc806c882001-08-29 23:54:54 +0000223 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000224 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000225
Neil Schemenauerc806c882001-08-29 23:54:54 +0000226 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000227
Tim Peters6d6c1a32001-08-02 04:15:00 +0000228 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
229 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000230
Tim Peters6d6c1a32001-08-02 04:15:00 +0000231 if (type->tp_itemsize == 0)
232 PyObject_INIT(obj, type);
233 else
234 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000235
Tim Peters6d6c1a32001-08-02 04:15:00 +0000236 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000237 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000238 return obj;
239}
240
241PyObject *
242PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
243{
244 return type->tp_alloc(type, 0);
245}
246
Guido van Rossum9475a232001-10-05 20:51:39 +0000247/* Helpers for subtyping */
248
249static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000250traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
251{
252 int i, n;
253 PyMemberDef *mp;
254
255 n = type->ob_size;
256 mp = ((etype *)type)->members;
257 for (i = 0; i < n; i++, mp++) {
258 if (mp->type == T_OBJECT_EX) {
259 char *addr = (char *)self + mp->offset;
260 PyObject *obj = *(PyObject **)addr;
261 if (obj != NULL) {
262 int err = visit(obj, arg);
263 if (err)
264 return err;
265 }
266 }
267 }
268 return 0;
269}
270
271static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000272subtype_traverse(PyObject *self, visitproc visit, void *arg)
273{
274 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000275 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000276
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000277 /* Find the nearest base with a different tp_traverse,
278 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000279 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000280 base = type;
281 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
282 if (base->ob_size) {
283 int err = traverse_slots(base, self, visit, arg);
284 if (err)
285 return err;
286 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000287 base = base->tp_base;
288 assert(base);
289 }
290
291 if (type->tp_dictoffset != base->tp_dictoffset) {
292 PyObject **dictptr = _PyObject_GetDictPtr(self);
293 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000294 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000295 if (err)
296 return err;
297 }
298 }
299
Guido van Rossuma3862092002-06-10 15:24:42 +0000300 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
301 /* For a heaptype, the instances count as references
302 to the type. Traverse the type so the collector
303 can find cycles involving this link. */
304 int err = visit((PyObject *)type, arg);
305 if (err)
306 return err;
307 }
308
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000309 if (basetraverse)
310 return basetraverse(self, visit, arg);
311 return 0;
312}
313
314static void
315clear_slots(PyTypeObject *type, PyObject *self)
316{
317 int i, n;
318 PyMemberDef *mp;
319
320 n = type->ob_size;
321 mp = ((etype *)type)->members;
322 for (i = 0; i < n; i++, mp++) {
323 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
324 char *addr = (char *)self + mp->offset;
325 PyObject *obj = *(PyObject **)addr;
326 if (obj != NULL) {
327 Py_DECREF(obj);
328 *(PyObject **)addr = NULL;
329 }
330 }
331 }
332}
333
334static int
335subtype_clear(PyObject *self)
336{
337 PyTypeObject *type, *base;
338 inquiry baseclear;
339
340 /* Find the nearest base with a different tp_clear
341 and clear slots while we're at it */
342 type = self->ob_type;
343 base = type;
344 while ((baseclear = base->tp_clear) == subtype_clear) {
345 if (base->ob_size)
346 clear_slots(base, self);
347 base = base->tp_base;
348 assert(base);
349 }
350
Guido van Rossuma3862092002-06-10 15:24:42 +0000351 /* There's no need to clear the instance dict (if any);
352 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000353
354 if (baseclear)
355 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000356 return 0;
357}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000358
359static void
360subtype_dealloc(PyObject *self)
361{
Guido van Rossum14227b42001-12-06 02:35:58 +0000362 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000363 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000364
Guido van Rossum22b13872002-08-06 21:41:44 +0000365 /* Extract the type; we expect it to be a heap type */
366 type = self->ob_type;
367 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000368
Guido van Rossum22b13872002-08-06 21:41:44 +0000369 /* Test whether the type has GC exactly once */
370
371 if (!PyType_IS_GC(type)) {
372 /* It's really rare to find a dynamic type that doesn't have
373 GC; it can only happen when deriving from 'object' and not
374 adding any slots or instance variables. This allows
375 certain simplifications: there's no need to call
376 clear_slots(), or DECREF the dict, or clear weakrefs. */
377
378 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000379 if (type->tp_del) {
380 type->tp_del(self);
381 if (self->ob_refcnt > 0)
382 return;
383 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000384
385 /* Find the nearest base with a different tp_dealloc */
386 base = type;
387 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
388 assert(base->ob_size == 0);
389 base = base->tp_base;
390 assert(base);
391 }
392
393 /* Call the base tp_dealloc() */
394 assert(basedealloc);
395 basedealloc(self);
396
397 /* Can't reference self beyond this point */
398 Py_DECREF(type);
399
400 /* Done */
401 return;
402 }
403
404 /* We get here only if the type has GC */
405
406 /* UnTrack and re-Track around the trashcan macro, alas */
Guido van Rossum0906e072002-08-07 20:42:09 +0000407 PyObject_GC_UnTrack(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000408 Py_TRASHCAN_SAFE_BEGIN(self);
409 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
410
411 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000412 if (type->tp_del) {
413 type->tp_del(self);
414 if (self->ob_refcnt > 0)
415 goto endlabel;
416 }
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000417
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000418 /* Find the nearest base with a different tp_dealloc
419 and clear slots while we're at it */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000420 base = type;
421 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
422 if (base->ob_size)
423 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000424 base = base->tp_base;
425 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000426 }
427
Tim Peters6d6c1a32001-08-02 04:15:00 +0000428 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000429 if (type->tp_dictoffset && !base->tp_dictoffset) {
430 PyObject **dictptr = _PyObject_GetDictPtr(self);
431 if (dictptr != NULL) {
432 PyObject *dict = *dictptr;
433 if (dict != NULL) {
434 Py_DECREF(dict);
435 *dictptr = NULL;
436 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000437 }
438 }
439
Guido van Rossum9676b222001-08-17 20:32:36 +0000440 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000441 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000442 PyObject_ClearWeakRefs(self);
443
Tim Peters6d6c1a32001-08-02 04:15:00 +0000444 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000445 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000446 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000447
448 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000449 assert(basedealloc);
450 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000451
452 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000453 Py_DECREF(type);
454
Guido van Rossum0906e072002-08-07 20:42:09 +0000455 endlabel:
Guido van Rossum22b13872002-08-06 21:41:44 +0000456 Py_TRASHCAN_SAFE_END(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000457}
458
Jeremy Hylton938ace62002-07-17 16:30:39 +0000459static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000460
Tim Peters6d6c1a32001-08-02 04:15:00 +0000461/* type test with subclassing support */
462
463int
464PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
465{
466 PyObject *mro;
467
Guido van Rossum9478d072001-09-07 18:52:13 +0000468 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
469 return b == a || b == &PyBaseObject_Type;
470
Tim Peters6d6c1a32001-08-02 04:15:00 +0000471 mro = a->tp_mro;
472 if (mro != NULL) {
473 /* Deal with multiple inheritance without recursion
474 by walking the MRO tuple */
475 int i, n;
476 assert(PyTuple_Check(mro));
477 n = PyTuple_GET_SIZE(mro);
478 for (i = 0; i < n; i++) {
479 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
480 return 1;
481 }
482 return 0;
483 }
484 else {
485 /* a is not completely initilized yet; follow tp_base */
486 do {
487 if (a == b)
488 return 1;
489 a = a->tp_base;
490 } while (a != NULL);
491 return b == &PyBaseObject_Type;
492 }
493}
494
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000495/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000496 without looking in the instance dictionary
497 (so we can't use PyObject_GetAttr) but still binding
498 it to the instance. The arguments are the object,
499 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000500 static variable used to cache the interned Python string.
501
502 Two variants:
503
504 - lookup_maybe() returns NULL without raising an exception
505 when the _PyType_Lookup() call fails;
506
507 - lookup_method() always raises an exception upon errors.
508*/
Guido van Rossum60718732001-08-28 17:47:51 +0000509
510static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000511lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000512{
513 PyObject *res;
514
515 if (*attrobj == NULL) {
516 *attrobj = PyString_InternFromString(attrstr);
517 if (*attrobj == NULL)
518 return NULL;
519 }
520 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000521 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000522 descrgetfunc f;
523 if ((f = res->ob_type->tp_descr_get) == NULL)
524 Py_INCREF(res);
525 else
526 res = f(res, self, (PyObject *)(self->ob_type));
527 }
528 return res;
529}
530
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000531static PyObject *
532lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
533{
534 PyObject *res = lookup_maybe(self, attrstr, attrobj);
535 if (res == NULL && !PyErr_Occurred())
536 PyErr_SetObject(PyExc_AttributeError, *attrobj);
537 return res;
538}
539
Guido van Rossum2730b132001-08-28 18:22:14 +0000540/* A variation of PyObject_CallMethod that uses lookup_method()
541 instead of PyObject_GetAttrString(). This uses the same convention
542 as lookup_method to cache the interned name string object. */
543
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000544static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000545call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
546{
547 va_list va;
548 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000549 va_start(va, format);
550
Guido van Rossumda21c012001-10-03 00:50:18 +0000551 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000552 if (func == NULL) {
553 va_end(va);
554 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000555 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000556 return NULL;
557 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000558
559 if (format && *format)
560 args = Py_VaBuildValue(format, va);
561 else
562 args = PyTuple_New(0);
563
564 va_end(va);
565
566 if (args == NULL)
567 return NULL;
568
569 assert(PyTuple_Check(args));
570 retval = PyObject_Call(func, args, NULL);
571
572 Py_DECREF(args);
573 Py_DECREF(func);
574
575 return retval;
576}
577
578/* Clone of call_method() that returns NotImplemented when the lookup fails. */
579
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000580static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000581call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
582{
583 va_list va;
584 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000585 va_start(va, format);
586
Guido van Rossumda21c012001-10-03 00:50:18 +0000587 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000588 if (func == NULL) {
589 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000590 if (!PyErr_Occurred()) {
591 Py_INCREF(Py_NotImplemented);
592 return Py_NotImplemented;
593 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000594 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000595 }
596
597 if (format && *format)
598 args = Py_VaBuildValue(format, va);
599 else
600 args = PyTuple_New(0);
601
602 va_end(va);
603
Guido van Rossum717ce002001-09-14 16:58:08 +0000604 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000605 return NULL;
606
Guido van Rossum717ce002001-09-14 16:58:08 +0000607 assert(PyTuple_Check(args));
608 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000609
610 Py_DECREF(args);
611 Py_DECREF(func);
612
613 return retval;
614}
615
Tim Peters6d6c1a32001-08-02 04:15:00 +0000616/* Method resolution order algorithm from "Putting Metaclasses to Work"
617 by Forman and Danforth (Addison-Wesley 1999). */
618
619static int
620conservative_merge(PyObject *left, PyObject *right)
621{
622 int left_size;
623 int right_size;
624 int i, j, r, ok;
625 PyObject *temp, *rr;
626
627 assert(PyList_Check(left));
628 assert(PyList_Check(right));
629
630 again:
631 left_size = PyList_GET_SIZE(left);
632 right_size = PyList_GET_SIZE(right);
633 for (i = 0; i < left_size; i++) {
634 for (j = 0; j < right_size; j++) {
635 if (PyList_GET_ITEM(left, i) ==
636 PyList_GET_ITEM(right, j)) {
637 /* found a merge point */
638 temp = PyList_New(0);
639 if (temp == NULL)
640 return -1;
641 for (r = 0; r < j; r++) {
642 rr = PyList_GET_ITEM(right, r);
643 ok = PySequence_Contains(left, rr);
644 if (ok < 0) {
645 Py_DECREF(temp);
646 return -1;
647 }
648 if (!ok) {
649 ok = PyList_Append(temp, rr);
650 if (ok < 0) {
651 Py_DECREF(temp);
652 return -1;
653 }
654 }
655 }
656 ok = PyList_SetSlice(left, i, i, temp);
657 Py_DECREF(temp);
658 if (ok < 0)
659 return -1;
660 ok = PyList_SetSlice(right, 0, j+1, NULL);
661 if (ok < 0)
662 return -1;
663 goto again;
664 }
665 }
666 }
667 return PyList_SetSlice(left, left_size, left_size, right);
668}
669
670static int
671serious_order_disagreements(PyObject *left, PyObject *right)
672{
673 return 0; /* XXX later -- for now, we cheat: "don't do that" */
674}
675
Tim Petersa91e9642001-11-14 23:32:33 +0000676static int
677fill_classic_mro(PyObject *mro, PyObject *cls)
678{
679 PyObject *bases, *base;
680 int i, n;
681
682 assert(PyList_Check(mro));
683 assert(PyClass_Check(cls));
684 i = PySequence_Contains(mro, cls);
685 if (i < 0)
686 return -1;
687 if (!i) {
688 if (PyList_Append(mro, cls) < 0)
689 return -1;
690 }
691 bases = ((PyClassObject *)cls)->cl_bases;
692 assert(bases && PyTuple_Check(bases));
693 n = PyTuple_GET_SIZE(bases);
694 for (i = 0; i < n; i++) {
695 base = PyTuple_GET_ITEM(bases, i);
696 if (fill_classic_mro(mro, base) < 0)
697 return -1;
698 }
699 return 0;
700}
701
702static PyObject *
703classic_mro(PyObject *cls)
704{
705 PyObject *mro;
706
707 assert(PyClass_Check(cls));
708 mro = PyList_New(0);
709 if (mro != NULL) {
710 if (fill_classic_mro(mro, cls) == 0)
711 return mro;
712 Py_DECREF(mro);
713 }
714 return NULL;
715}
716
Tim Peters6d6c1a32001-08-02 04:15:00 +0000717static PyObject *
718mro_implementation(PyTypeObject *type)
719{
720 int i, n, ok;
721 PyObject *bases, *result;
722
Guido van Rossum63517572002-06-18 16:44:57 +0000723 if(type->tp_dict == NULL) {
724 if(PyType_Ready(type) < 0)
725 return NULL;
726 }
727
Tim Peters6d6c1a32001-08-02 04:15:00 +0000728 bases = type->tp_bases;
729 n = PyTuple_GET_SIZE(bases);
730 result = Py_BuildValue("[O]", (PyObject *)type);
731 if (result == NULL)
732 return NULL;
733 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000734 PyObject *base = PyTuple_GET_ITEM(bases, i);
735 PyObject *parentMRO;
736 if (PyType_Check(base))
737 parentMRO = PySequence_List(
738 ((PyTypeObject*)base)->tp_mro);
739 else
740 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000741 if (parentMRO == NULL) {
742 Py_DECREF(result);
743 return NULL;
744 }
745 if (serious_order_disagreements(result, parentMRO)) {
746 Py_DECREF(result);
747 return NULL;
748 }
749 ok = conservative_merge(result, parentMRO);
750 Py_DECREF(parentMRO);
751 if (ok < 0) {
752 Py_DECREF(result);
753 return NULL;
754 }
755 }
756 return result;
757}
758
759static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000760mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000761{
762 PyTypeObject *type = (PyTypeObject *)self;
763
Tim Peters6d6c1a32001-08-02 04:15:00 +0000764 return mro_implementation(type);
765}
766
767static int
768mro_internal(PyTypeObject *type)
769{
770 PyObject *mro, *result, *tuple;
771
772 if (type->ob_type == &PyType_Type) {
773 result = mro_implementation(type);
774 }
775 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000776 static PyObject *mro_str;
777 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000778 if (mro == NULL)
779 return -1;
780 result = PyObject_CallObject(mro, NULL);
781 Py_DECREF(mro);
782 }
783 if (result == NULL)
784 return -1;
785 tuple = PySequence_Tuple(result);
786 Py_DECREF(result);
787 type->tp_mro = tuple;
788 return 0;
789}
790
791
792/* Calculate the best base amongst multiple base classes.
793 This is the first one that's on the path to the "solid base". */
794
795static PyTypeObject *
796best_base(PyObject *bases)
797{
798 int i, n;
799 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000800 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000801
802 assert(PyTuple_Check(bases));
803 n = PyTuple_GET_SIZE(bases);
804 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000805 base = NULL;
806 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000807 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000808 base_proto = PyTuple_GET_ITEM(bases, i);
809 if (PyClass_Check(base_proto))
810 continue;
811 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000812 PyErr_SetString(
813 PyExc_TypeError,
814 "bases must be types");
815 return NULL;
816 }
Tim Petersa91e9642001-11-14 23:32:33 +0000817 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000818 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000819 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000820 return NULL;
821 }
822 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000823 if (winner == NULL) {
824 winner = candidate;
825 base = base_i;
826 }
827 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000828 ;
829 else if (PyType_IsSubtype(candidate, winner)) {
830 winner = candidate;
831 base = base_i;
832 }
833 else {
834 PyErr_SetString(
835 PyExc_TypeError,
836 "multiple bases have "
837 "instance lay-out conflict");
838 return NULL;
839 }
840 }
Guido van Rossume54616c2001-12-14 04:19:56 +0000841 if (base == NULL)
842 PyErr_SetString(PyExc_TypeError,
843 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000844 return base;
845}
846
847static int
848extra_ivars(PyTypeObject *type, PyTypeObject *base)
849{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000850 size_t t_size = type->tp_basicsize;
851 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000852
Guido van Rossum9676b222001-08-17 20:32:36 +0000853 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000854 if (type->tp_itemsize || base->tp_itemsize) {
855 /* If itemsize is involved, stricter rules */
856 return t_size != b_size ||
857 type->tp_itemsize != base->tp_itemsize;
858 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000859 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
860 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
861 t_size -= sizeof(PyObject *);
862 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
863 type->tp_dictoffset + sizeof(PyObject *) == t_size)
864 t_size -= sizeof(PyObject *);
865
866 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000867}
868
869static PyTypeObject *
870solid_base(PyTypeObject *type)
871{
872 PyTypeObject *base;
873
874 if (type->tp_base)
875 base = solid_base(type->tp_base);
876 else
877 base = &PyBaseObject_Type;
878 if (extra_ivars(type, base))
879 return type;
880 else
881 return base;
882}
883
Jeremy Hylton938ace62002-07-17 16:30:39 +0000884static void object_dealloc(PyObject *);
885static int object_init(PyObject *, PyObject *, PyObject *);
886static int update_slot(PyTypeObject *, PyObject *);
887static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000888
889static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000890subtype_dict(PyObject *obj, void *context)
891{
892 PyObject **dictptr = _PyObject_GetDictPtr(obj);
893 PyObject *dict;
894
895 if (dictptr == NULL) {
896 PyErr_SetString(PyExc_AttributeError,
897 "This object has no __dict__");
898 return NULL;
899 }
900 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000901 if (dict == NULL)
902 *dictptr = dict = PyDict_New();
903 Py_XINCREF(dict);
904 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000905}
906
Guido van Rossum6661be32001-10-26 04:26:12 +0000907static int
908subtype_setdict(PyObject *obj, PyObject *value, void *context)
909{
910 PyObject **dictptr = _PyObject_GetDictPtr(obj);
911 PyObject *dict;
912
913 if (dictptr == NULL) {
914 PyErr_SetString(PyExc_AttributeError,
915 "This object has no __dict__");
916 return -1;
917 }
Guido van Rossumd331cb52001-12-05 19:46:42 +0000918 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +0000919 PyErr_SetString(PyExc_TypeError,
920 "__dict__ must be set to a dictionary");
921 return -1;
922 }
923 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +0000924 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +0000925 *dictptr = value;
926 Py_XDECREF(dict);
927 return 0;
928}
929
Guido van Rossumad47da02002-08-12 19:05:44 +0000930static PyObject *
931subtype_getweakref(PyObject *obj, void *context)
932{
933 PyObject **weaklistptr;
934 PyObject *result;
935
936 if (obj->ob_type->tp_weaklistoffset == 0) {
937 PyErr_SetString(PyExc_AttributeError,
938 "This object has no __weaklist__");
939 return NULL;
940 }
941 assert(obj->ob_type->tp_weaklistoffset > 0);
942 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +0000943 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +0000944 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +0000945 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +0000946 if (*weaklistptr == NULL)
947 result = Py_None;
948 else
949 result = *weaklistptr;
950 Py_INCREF(result);
951 return result;
952}
953
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000954static PyGetSetDef subtype_getsets[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +0000955 /* Not all objects have these attributes!
956 The descriptor's __get__ method may raise AttributeError. */
957 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +0000958 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +0000959 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +0000960 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +0000961 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000962};
963
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000964/* bozo: __getstate__ that raises TypeError */
965
966static PyObject *
967bozo_func(PyObject *self, PyObject *args)
968{
969 PyErr_SetString(PyExc_TypeError,
970 "a class that defines __slots__ without "
971 "defining __getstate__ cannot be pickled");
972 return NULL;
973}
974
Neal Norwitz93c1e232002-03-31 16:06:11 +0000975static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000976
977static PyObject *bozo_obj = NULL;
978
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000979static int
980valid_identifier(PyObject *s)
981{
Guido van Rossum03013a02002-07-16 14:30:28 +0000982 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000983 int i, n;
984
985 if (!PyString_Check(s)) {
986 PyErr_SetString(PyExc_TypeError,
987 "__slots__ must be strings");
988 return 0;
989 }
Guido van Rossum03013a02002-07-16 14:30:28 +0000990 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000991 n = PyString_GET_SIZE(s);
992 /* We must reject an empty name. As a hack, we bump the
993 length to 1 so that the loop will balk on the trailing \0. */
994 if (n == 0)
995 n = 1;
996 for (i = 0; i < n; i++, p++) {
997 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
998 PyErr_SetString(PyExc_TypeError,
999 "__slots__ must be identifiers");
1000 return 0;
1001 }
1002 }
1003 return 1;
1004}
1005
Martin v. Löwisd919a592002-10-14 21:07:28 +00001006#ifdef Py_USING_UNICODE
1007/* Replace Unicode objects in slots. */
1008
1009static PyObject *
1010_unicode_to_string(PyObject *slots, int nslots)
1011{
1012 PyObject *tmp = slots;
1013 PyObject *o, *o1;
1014 int i;
1015 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1016 for (i = 0; i < nslots; i++) {
1017 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1018 if (tmp == slots) {
1019 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1020 if (tmp == NULL)
1021 return NULL;
1022 }
1023 o1 = _PyUnicode_AsDefaultEncodedString
1024 (o, NULL);
1025 if (o1 == NULL) {
1026 Py_DECREF(tmp);
1027 return 0;
1028 }
1029 Py_INCREF(o1);
1030 Py_DECREF(o);
1031 PyTuple_SET_ITEM(tmp, i, o1);
1032 }
1033 }
1034 return tmp;
1035}
1036#endif
1037
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001038static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001039type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1040{
1041 PyObject *name, *bases, *dict;
1042 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001043 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001044 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001045 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001046 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001047 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001048 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001049
Tim Peters3abca122001-10-27 19:37:48 +00001050 assert(args != NULL && PyTuple_Check(args));
1051 assert(kwds == NULL || PyDict_Check(kwds));
1052
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001053 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001054 {
1055 const int nargs = PyTuple_GET_SIZE(args);
1056 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1057
1058 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1059 PyObject *x = PyTuple_GET_ITEM(args, 0);
1060 Py_INCREF(x->ob_type);
1061 return (PyObject *) x->ob_type;
1062 }
1063
1064 /* SF bug 475327 -- if that didn't trigger, we need 3
1065 arguments. but PyArg_ParseTupleAndKeywords below may give
1066 a msg saying type() needs exactly 3. */
1067 if (nargs + nkwds != 3) {
1068 PyErr_SetString(PyExc_TypeError,
1069 "type() takes 1 or 3 arguments");
1070 return NULL;
1071 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001072 }
1073
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001074 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001075 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1076 &name,
1077 &PyTuple_Type, &bases,
1078 &PyDict_Type, &dict))
1079 return NULL;
1080
1081 /* Determine the proper metatype to deal with this,
1082 and check for metatype conflicts while we're at it.
1083 Note that if some other metatype wins to contract,
1084 it's possible that its instances are not types. */
1085 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001086 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001087 for (i = 0; i < nbases; i++) {
1088 tmp = PyTuple_GET_ITEM(bases, i);
1089 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001090 if (tmptype == &PyClass_Type)
1091 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001092 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001093 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001094 if (PyType_IsSubtype(tmptype, winner)) {
1095 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001096 continue;
1097 }
1098 PyErr_SetString(PyExc_TypeError,
1099 "metatype conflict among bases");
1100 return NULL;
1101 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001102 if (winner != metatype) {
1103 if (winner->tp_new != type_new) /* Pass it to the winner */
1104 return winner->tp_new(winner, args, kwds);
1105 metatype = winner;
1106 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001107
1108 /* Adjust for empty tuple bases */
1109 if (nbases == 0) {
1110 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1111 if (bases == NULL)
1112 return NULL;
1113 nbases = 1;
1114 }
1115 else
1116 Py_INCREF(bases);
1117
1118 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1119
1120 /* Calculate best base, and check that all bases are type objects */
1121 base = best_base(bases);
1122 if (base == NULL)
1123 return NULL;
1124 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1125 PyErr_Format(PyExc_TypeError,
1126 "type '%.100s' is not an acceptable base type",
1127 base->tp_name);
1128 return NULL;
1129 }
1130
Tim Peters6d6c1a32001-08-02 04:15:00 +00001131 /* Check for a __slots__ sequence variable in dict, and count it */
1132 slots = PyDict_GetItemString(dict, "__slots__");
1133 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001134 add_dict = 0;
1135 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001136 may_add_dict = base->tp_dictoffset == 0;
1137 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1138 if (slots == NULL) {
1139 if (may_add_dict) {
1140 add_dict++;
1141 }
1142 if (may_add_weak) {
1143 add_weak++;
1144 }
1145 }
1146 else {
1147 /* Have slots */
1148
Tim Peters6d6c1a32001-08-02 04:15:00 +00001149 /* Make it into a tuple */
1150 if (PyString_Check(slots))
1151 slots = Py_BuildValue("(O)", slots);
1152 else
1153 slots = PySequence_Tuple(slots);
1154 if (slots == NULL)
1155 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001156 assert(PyTuple_Check(slots));
1157
1158 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001159 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001160 if (nslots > 0 && base->tp_itemsize != 0) {
1161 PyErr_Format(PyExc_TypeError,
1162 "nonempty __slots__ "
1163 "not supported for subtype of '%s'",
1164 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001165 bad_slots:
1166 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001167 return NULL;
1168 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001169
Martin v. Löwisd919a592002-10-14 21:07:28 +00001170#ifdef Py_USING_UNICODE
1171 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001172 if (tmp != slots) {
1173 Py_DECREF(slots);
1174 slots = tmp;
1175 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001176 if (!tmp)
1177 return NULL;
1178#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001179 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001180 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001181 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1182 char *s;
1183 if (!valid_identifier(tmp))
1184 goto bad_slots;
1185 assert(PyString_Check(tmp));
1186 s = PyString_AS_STRING(tmp);
1187 if (strcmp(s, "__dict__") == 0) {
1188 if (!may_add_dict || add_dict) {
1189 PyErr_SetString(PyExc_TypeError,
1190 "__dict__ slot disallowed: "
1191 "we already got one");
1192 goto bad_slots;
1193 }
1194 add_dict++;
1195 }
1196 if (strcmp(s, "__weakref__") == 0) {
1197 if (!may_add_weak || add_weak) {
1198 PyErr_SetString(PyExc_TypeError,
1199 "__weakref__ slot disallowed: "
1200 "either we already got one, "
1201 "or __itemsize__ != 0");
1202 goto bad_slots;
1203 }
1204 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001205 }
1206 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001207
Guido van Rossumad47da02002-08-12 19:05:44 +00001208 /* Copy slots into yet another tuple, demangling names */
1209 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001210 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001211 goto bad_slots;
1212 for (i = j = 0; i < nslots; i++) {
1213 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001214 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001215 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001216 s = PyString_AS_STRING(tmp);
1217 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1218 (add_weak && strcmp(s, "__weakref__") == 0))
1219 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001220 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001221 PyString_AS_STRING(tmp),
1222 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001223 {
1224 tmp = PyString_FromString(buffer);
1225 } else {
1226 Py_INCREF(tmp);
1227 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001228 PyTuple_SET_ITEM(newslots, j, tmp);
1229 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001230 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001231 assert(j == nslots - add_dict - add_weak);
1232 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001233 Py_DECREF(slots);
1234 slots = newslots;
1235
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001236 /* See if *this* class defines __getstate__ */
Guido van Rossumad47da02002-08-12 19:05:44 +00001237 if (PyDict_GetItemString(dict, "__getstate__") == NULL) {
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001238 /* If not, provide a bozo that raises TypeError */
1239 if (bozo_obj == NULL) {
1240 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
Guido van Rossumad47da02002-08-12 19:05:44 +00001241 if (bozo_obj == NULL)
1242 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001243 }
1244 if (PyDict_SetItemString(dict,
1245 "__getstate__",
Guido van Rossumad47da02002-08-12 19:05:44 +00001246 bozo_obj) < 0)
1247 {
1248 Py_DECREF(bozo_obj);
1249 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001250 }
1251 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001252
1253 /* Secondary bases may provide weakrefs or dict */
1254 if (nbases > 1 &&
1255 ((may_add_dict && !add_dict) ||
1256 (may_add_weak && !add_weak))) {
1257 for (i = 0; i < nbases; i++) {
1258 tmp = PyTuple_GET_ITEM(bases, i);
1259 if (tmp == (PyObject *)base)
1260 continue; /* Skip primary base */
1261 if (PyClass_Check(tmp)) {
1262 /* Classic base class provides both */
1263 if (may_add_dict && !add_dict)
1264 add_dict++;
1265 if (may_add_weak && !add_weak)
1266 add_weak++;
1267 break;
1268 }
1269 assert(PyType_Check(tmp));
1270 tmptype = (PyTypeObject *)tmp;
1271 if (may_add_dict && !add_dict &&
1272 tmptype->tp_dictoffset != 0)
1273 add_dict++;
1274 if (may_add_weak && !add_weak &&
1275 tmptype->tp_weaklistoffset != 0)
1276 add_weak++;
1277 if (may_add_dict && !add_dict)
1278 continue;
1279 if (may_add_weak && !add_weak)
1280 continue;
1281 /* Nothing more to check */
1282 break;
1283 }
1284 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001285 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001286
1287 /* XXX From here until type is safely allocated,
1288 "return NULL" may leak slots! */
1289
1290 /* Allocate the type object */
1291 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001292 if (type == NULL) {
1293 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001294 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001295 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001296
1297 /* Keep name and slots alive in the extended type object */
1298 et = (etype *)type;
1299 Py_INCREF(name);
1300 et->name = name;
1301 et->slots = slots;
1302
Guido van Rossumdc91b992001-08-08 22:26:22 +00001303 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001304 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1305 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001306 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1307 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001308
1309 /* It's a new-style number unless it specifically inherits any
1310 old-style numeric behavior */
1311 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1312 (base->tp_as_number == NULL))
1313 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1314
1315 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001316 type->tp_as_number = &et->as_number;
1317 type->tp_as_sequence = &et->as_sequence;
1318 type->tp_as_mapping = &et->as_mapping;
1319 type->tp_as_buffer = &et->as_buffer;
1320 type->tp_name = PyString_AS_STRING(name);
1321
1322 /* Set tp_base and tp_bases */
1323 type->tp_bases = bases;
1324 Py_INCREF(base);
1325 type->tp_base = base;
1326
Guido van Rossum687ae002001-10-15 22:03:32 +00001327 /* Initialize tp_dict from passed-in dict */
1328 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001329 if (dict == NULL) {
1330 Py_DECREF(type);
1331 return NULL;
1332 }
1333
Guido van Rossumc3542212001-08-16 09:18:56 +00001334 /* Set __module__ in the dict */
1335 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1336 tmp = PyEval_GetGlobals();
1337 if (tmp != NULL) {
1338 tmp = PyDict_GetItemString(tmp, "__name__");
1339 if (tmp != NULL) {
1340 if (PyDict_SetItemString(dict, "__module__",
1341 tmp) < 0)
1342 return NULL;
1343 }
1344 }
1345 }
1346
Tim Peters2f93e282001-10-04 05:27:00 +00001347 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001348 and is a string. The __doc__ accessor will first look for tp_doc;
1349 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001350 */
1351 {
1352 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1353 if (doc != NULL && PyString_Check(doc)) {
1354 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001355 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001356 if (type->tp_doc == NULL) {
1357 Py_DECREF(type);
1358 return NULL;
1359 }
1360 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1361 }
1362 }
1363
Tim Peters6d6c1a32001-08-02 04:15:00 +00001364 /* Special-case __new__: if it's a plain function,
1365 make it a static function */
1366 tmp = PyDict_GetItemString(dict, "__new__");
1367 if (tmp != NULL && PyFunction_Check(tmp)) {
1368 tmp = PyStaticMethod_New(tmp);
1369 if (tmp == NULL) {
1370 Py_DECREF(type);
1371 return NULL;
1372 }
1373 PyDict_SetItemString(dict, "__new__", tmp);
1374 Py_DECREF(tmp);
1375 }
1376
1377 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1378 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001379 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001380 if (slots != NULL) {
1381 for (i = 0; i < nslots; i++, mp++) {
1382 mp->name = PyString_AS_STRING(
1383 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001384 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001385 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001386 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001387 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001388 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001389 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001390 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001391 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001392 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001393 slotoffset += sizeof(PyObject *);
1394 }
1395 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001396 if (add_dict) {
1397 if (base->tp_itemsize)
1398 type->tp_dictoffset = -(long)sizeof(PyObject *);
1399 else
1400 type->tp_dictoffset = slotoffset;
1401 slotoffset += sizeof(PyObject *);
1402 }
1403 if (add_weak) {
1404 assert(!base->tp_itemsize);
1405 type->tp_weaklistoffset = slotoffset;
1406 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001407 }
1408 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001409 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001410 type->tp_members = et->members;
Guido van Rossumad47da02002-08-12 19:05:44 +00001411 type->tp_getset = subtype_getsets;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001412
1413 /* Special case some slots */
1414 if (type->tp_dictoffset != 0 || nslots > 0) {
1415 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1416 type->tp_getattro = PyObject_GenericGetAttr;
1417 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1418 type->tp_setattro = PyObject_GenericSetAttr;
1419 }
1420 type->tp_dealloc = subtype_dealloc;
1421
Guido van Rossum9475a232001-10-05 20:51:39 +00001422 /* Enable GC unless there are really no instance variables possible */
1423 if (!(type->tp_basicsize == sizeof(PyObject) &&
1424 type->tp_itemsize == 0))
1425 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1426
Tim Peters6d6c1a32001-08-02 04:15:00 +00001427 /* Always override allocation strategy to use regular heap */
1428 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001429 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001430 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001431 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001432 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001433 }
1434 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001435 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001436
1437 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001438 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001439 Py_DECREF(type);
1440 return NULL;
1441 }
1442
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001443 /* Put the proper slots in place */
1444 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001445
Tim Peters6d6c1a32001-08-02 04:15:00 +00001446 return (PyObject *)type;
1447}
1448
1449/* Internal API to look for a name through the MRO.
1450 This returns a borrowed reference, and doesn't set an exception! */
1451PyObject *
1452_PyType_Lookup(PyTypeObject *type, PyObject *name)
1453{
1454 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001455 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001456
Guido van Rossum687ae002001-10-15 22:03:32 +00001457 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001458 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001459
1460 /* If mro is NULL, the type is either not yet initialized
1461 by PyType_Ready(), or already cleared by type_clear().
1462 Either way the safest thing to do is to return NULL. */
1463 if (mro == NULL)
1464 return NULL;
1465
Tim Peters6d6c1a32001-08-02 04:15:00 +00001466 assert(PyTuple_Check(mro));
1467 n = PyTuple_GET_SIZE(mro);
1468 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001469 base = PyTuple_GET_ITEM(mro, i);
1470 if (PyClass_Check(base))
1471 dict = ((PyClassObject *)base)->cl_dict;
1472 else {
1473 assert(PyType_Check(base));
1474 dict = ((PyTypeObject *)base)->tp_dict;
1475 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001476 assert(dict && PyDict_Check(dict));
1477 res = PyDict_GetItem(dict, name);
1478 if (res != NULL)
1479 return res;
1480 }
1481 return NULL;
1482}
1483
1484/* This is similar to PyObject_GenericGetAttr(),
1485 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1486static PyObject *
1487type_getattro(PyTypeObject *type, PyObject *name)
1488{
1489 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001490 PyObject *meta_attribute, *attribute;
1491 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001492
1493 /* Initialize this type (we'll assume the metatype is initialized) */
1494 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001495 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001496 return NULL;
1497 }
1498
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001499 /* No readable descriptor found yet */
1500 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001501
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001502 /* Look for the attribute in the metatype */
1503 meta_attribute = _PyType_Lookup(metatype, name);
1504
1505 if (meta_attribute != NULL) {
1506 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001507
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001508 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1509 /* Data descriptors implement tp_descr_set to intercept
1510 * writes. Assume the attribute is not overridden in
1511 * type's tp_dict (and bases): call the descriptor now.
1512 */
1513 return meta_get(meta_attribute, (PyObject *)type,
1514 (PyObject *)metatype);
1515 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001516 }
1517
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001518 /* No data descriptor found on metatype. Look in tp_dict of this
1519 * type and its bases */
1520 attribute = _PyType_Lookup(type, name);
1521 if (attribute != NULL) {
1522 /* Implement descriptor functionality, if any */
1523 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1524 if (local_get != NULL) {
1525 /* NULL 2nd argument indicates the descriptor was
1526 * found on the target object itself (or a base) */
1527 return local_get(attribute, (PyObject *)NULL,
1528 (PyObject *)type);
1529 }
Tim Peters34592512002-07-11 06:23:50 +00001530
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001531 Py_INCREF(attribute);
1532 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001533 }
1534
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001535 /* No attribute found in local __dict__ (or bases): use the
1536 * descriptor from the metatype, if any */
1537 if (meta_get != NULL)
1538 return meta_get(meta_attribute, (PyObject *)type,
1539 (PyObject *)metatype);
1540
1541 /* If an ordinary attribute was found on the metatype, return it now */
1542 if (meta_attribute != NULL) {
1543 Py_INCREF(meta_attribute);
1544 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001545 }
1546
1547 /* Give up */
1548 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001549 "type object '%.50s' has no attribute '%.400s'",
1550 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001551 return NULL;
1552}
1553
1554static int
1555type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1556{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001557 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1558 PyErr_Format(
1559 PyExc_TypeError,
1560 "can't set attributes of built-in/extension type '%s'",
1561 type->tp_name);
1562 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001563 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001564 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1565 return -1;
1566 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001567}
1568
1569static void
1570type_dealloc(PyTypeObject *type)
1571{
1572 etype *et;
1573
1574 /* Assert this is a heap-allocated type object */
1575 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001576 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001577 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001578 et = (etype *)type;
1579 Py_XDECREF(type->tp_base);
1580 Py_XDECREF(type->tp_dict);
1581 Py_XDECREF(type->tp_bases);
1582 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001583 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001584 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00001585 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001586 Py_XDECREF(et->name);
1587 Py_XDECREF(et->slots);
1588 type->ob_type->tp_free((PyObject *)type);
1589}
1590
Guido van Rossum1c450732001-10-08 15:18:27 +00001591static PyObject *
1592type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1593{
1594 PyObject *list, *raw, *ref;
1595 int i, n;
1596
1597 list = PyList_New(0);
1598 if (list == NULL)
1599 return NULL;
1600 raw = type->tp_subclasses;
1601 if (raw == NULL)
1602 return list;
1603 assert(PyList_Check(raw));
1604 n = PyList_GET_SIZE(raw);
1605 for (i = 0; i < n; i++) {
1606 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001607 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001608 ref = PyWeakref_GET_OBJECT(ref);
1609 if (ref != Py_None) {
1610 if (PyList_Append(list, ref) < 0) {
1611 Py_DECREF(list);
1612 return NULL;
1613 }
1614 }
1615 }
1616 return list;
1617}
1618
Tim Peters6d6c1a32001-08-02 04:15:00 +00001619static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001620 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00001621 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00001622 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00001623 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001624 {0}
1625};
1626
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001627PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001628"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001629"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001630
Guido van Rossum048eb752001-10-02 21:24:57 +00001631static int
1632type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1633{
Guido van Rossum048eb752001-10-02 21:24:57 +00001634 int err;
1635
Guido van Rossuma3862092002-06-10 15:24:42 +00001636 /* Because of type_is_gc(), the collector only calls this
1637 for heaptypes. */
1638 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001639
1640#define VISIT(SLOT) \
1641 if (SLOT) { \
1642 err = visit((PyObject *)(SLOT), arg); \
1643 if (err) \
1644 return err; \
1645 }
1646
1647 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001648 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001649 VISIT(type->tp_mro);
1650 VISIT(type->tp_bases);
1651 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00001652
1653 /* There's no need to visit type->tp_subclasses or
1654 ((etype *)type)->slots, because they can't be involved
1655 in cycles; tp_subclasses is a list of weak references,
1656 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00001657
1658#undef VISIT
1659
1660 return 0;
1661}
1662
1663static int
1664type_clear(PyTypeObject *type)
1665{
Guido van Rossum048eb752001-10-02 21:24:57 +00001666 PyObject *tmp;
1667
Guido van Rossuma3862092002-06-10 15:24:42 +00001668 /* Because of type_is_gc(), the collector only calls this
1669 for heaptypes. */
1670 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001671
1672#define CLEAR(SLOT) \
1673 if (SLOT) { \
1674 tmp = (PyObject *)(SLOT); \
1675 SLOT = NULL; \
1676 Py_DECREF(tmp); \
1677 }
1678
Guido van Rossuma3862092002-06-10 15:24:42 +00001679 /* The only field we need to clear is tp_mro, which is part of a
1680 hard cycle (its first element is the class itself) that won't
1681 be broken otherwise (it's a tuple and tuples don't have a
1682 tp_clear handler). None of the other fields need to be
1683 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00001684
Guido van Rossuma3862092002-06-10 15:24:42 +00001685 tp_dict:
1686 It is a dict, so the collector will call its tp_clear.
1687
1688 tp_cache:
1689 Not used; if it were, it would be a dict.
1690
1691 tp_bases, tp_base:
1692 If these are involved in a cycle, there must be at least
1693 one other, mutable object in the cycle, e.g. a base
1694 class's dict; the cycle will be broken that way.
1695
1696 tp_subclasses:
1697 A list of weak references can't be part of a cycle; and
1698 lists have their own tp_clear.
1699
1700 slots (in etype):
1701 A tuple of strings can't be part of a cycle.
1702 */
1703
1704 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00001705
Guido van Rossum048eb752001-10-02 21:24:57 +00001706#undef CLEAR
1707
1708 return 0;
1709}
1710
1711static int
1712type_is_gc(PyTypeObject *type)
1713{
1714 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1715}
1716
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001717PyTypeObject PyType_Type = {
1718 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001719 0, /* ob_size */
1720 "type", /* tp_name */
1721 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001722 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001723 (destructor)type_dealloc, /* tp_dealloc */
1724 0, /* tp_print */
1725 0, /* tp_getattr */
1726 0, /* tp_setattr */
1727 type_compare, /* tp_compare */
1728 (reprfunc)type_repr, /* tp_repr */
1729 0, /* tp_as_number */
1730 0, /* tp_as_sequence */
1731 0, /* tp_as_mapping */
1732 (hashfunc)_Py_HashPointer, /* tp_hash */
1733 (ternaryfunc)type_call, /* tp_call */
1734 0, /* tp_str */
1735 (getattrofunc)type_getattro, /* tp_getattro */
1736 (setattrofunc)type_setattro, /* tp_setattro */
1737 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001738 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1739 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001740 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001741 (traverseproc)type_traverse, /* tp_traverse */
1742 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001743 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001744 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001745 0, /* tp_iter */
1746 0, /* tp_iternext */
1747 type_methods, /* tp_methods */
1748 type_members, /* tp_members */
1749 type_getsets, /* tp_getset */
1750 0, /* tp_base */
1751 0, /* tp_dict */
1752 0, /* tp_descr_get */
1753 0, /* tp_descr_set */
1754 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1755 0, /* tp_init */
1756 0, /* tp_alloc */
1757 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001758 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00001759 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001760};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001761
1762
1763/* The base type of all types (eventually)... except itself. */
1764
1765static int
1766object_init(PyObject *self, PyObject *args, PyObject *kwds)
1767{
1768 return 0;
1769}
1770
1771static void
1772object_dealloc(PyObject *self)
1773{
1774 self->ob_type->tp_free(self);
1775}
1776
Guido van Rossum8e248182001-08-12 05:17:56 +00001777static PyObject *
1778object_repr(PyObject *self)
1779{
Guido van Rossum76e69632001-08-16 18:52:43 +00001780 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001781 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001782
Guido van Rossum76e69632001-08-16 18:52:43 +00001783 type = self->ob_type;
1784 mod = type_module(type, NULL);
1785 if (mod == NULL)
1786 PyErr_Clear();
1787 else if (!PyString_Check(mod)) {
1788 Py_DECREF(mod);
1789 mod = NULL;
1790 }
1791 name = type_name(type, NULL);
1792 if (name == NULL)
1793 return NULL;
1794 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001795 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001796 PyString_AS_STRING(mod),
1797 PyString_AS_STRING(name),
1798 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001799 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001800 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001801 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001802 Py_XDECREF(mod);
1803 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001804 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001805}
1806
Guido van Rossumb8f63662001-08-15 23:57:02 +00001807static PyObject *
1808object_str(PyObject *self)
1809{
1810 unaryfunc f;
1811
1812 f = self->ob_type->tp_repr;
1813 if (f == NULL)
1814 f = object_repr;
1815 return f(self);
1816}
1817
Guido van Rossum8e248182001-08-12 05:17:56 +00001818static long
1819object_hash(PyObject *self)
1820{
1821 return _Py_HashPointer(self);
1822}
Guido van Rossum8e248182001-08-12 05:17:56 +00001823
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001824static PyObject *
1825object_get_class(PyObject *self, void *closure)
1826{
1827 Py_INCREF(self->ob_type);
1828 return (PyObject *)(self->ob_type);
1829}
1830
1831static int
1832equiv_structs(PyTypeObject *a, PyTypeObject *b)
1833{
1834 return a == b ||
1835 (a != NULL &&
1836 b != NULL &&
1837 a->tp_basicsize == b->tp_basicsize &&
1838 a->tp_itemsize == b->tp_itemsize &&
1839 a->tp_dictoffset == b->tp_dictoffset &&
1840 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1841 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1842 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1843}
1844
1845static int
1846same_slots_added(PyTypeObject *a, PyTypeObject *b)
1847{
1848 PyTypeObject *base = a->tp_base;
1849 int size;
1850
1851 if (base != b->tp_base)
1852 return 0;
1853 if (equiv_structs(a, base) && equiv_structs(b, base))
1854 return 1;
1855 size = base->tp_basicsize;
1856 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1857 size += sizeof(PyObject *);
1858 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1859 size += sizeof(PyObject *);
1860 return size == a->tp_basicsize && size == b->tp_basicsize;
1861}
1862
1863static int
1864object_set_class(PyObject *self, PyObject *value, void *closure)
1865{
1866 PyTypeObject *old = self->ob_type;
1867 PyTypeObject *new, *newbase, *oldbase;
1868
Guido van Rossumb6b89422002-04-15 01:03:30 +00001869 if (value == NULL) {
1870 PyErr_SetString(PyExc_TypeError,
1871 "can't delete __class__ attribute");
1872 return -1;
1873 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001874 if (!PyType_Check(value)) {
1875 PyErr_Format(PyExc_TypeError,
1876 "__class__ must be set to new-style class, not '%s' object",
1877 value->ob_type->tp_name);
1878 return -1;
1879 }
1880 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00001881 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
1882 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
1883 {
1884 PyErr_Format(PyExc_TypeError,
1885 "__class__ assignment: only for heap types");
1886 return -1;
1887 }
Guido van Rossum9ee4b942002-05-24 18:47:47 +00001888 if (new->tp_dealloc != old->tp_dealloc ||
1889 new->tp_free != old->tp_free)
1890 {
1891 PyErr_Format(PyExc_TypeError,
1892 "__class__ assignment: "
1893 "'%s' deallocator differs from '%s'",
1894 new->tp_name,
1895 old->tp_name);
1896 return -1;
1897 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001898 newbase = new;
1899 oldbase = old;
1900 while (equiv_structs(newbase, newbase->tp_base))
1901 newbase = newbase->tp_base;
1902 while (equiv_structs(oldbase, oldbase->tp_base))
1903 oldbase = oldbase->tp_base;
1904 if (newbase != oldbase &&
1905 (newbase->tp_base != oldbase->tp_base ||
1906 !same_slots_added(newbase, oldbase))) {
1907 PyErr_Format(PyExc_TypeError,
1908 "__class__ assignment: "
1909 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001910 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001911 old->tp_name);
1912 return -1;
1913 }
Guido van Rossum40af8892002-08-10 05:42:07 +00001914 Py_INCREF(new);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001915 self->ob_type = new;
Guido van Rossum40af8892002-08-10 05:42:07 +00001916 Py_DECREF(old);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001917 return 0;
1918}
1919
1920static PyGetSetDef object_getsets[] = {
1921 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001922 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001923 {0}
1924};
1925
Guido van Rossum3926a632001-09-25 16:25:58 +00001926static PyObject *
1927object_reduce(PyObject *self, PyObject *args)
1928{
1929 /* Call copy_reg._reduce(self) */
1930 static PyObject *copy_reg_str;
1931 PyObject *copy_reg, *res;
1932
1933 if (!copy_reg_str) {
1934 copy_reg_str = PyString_InternFromString("copy_reg");
1935 if (copy_reg_str == NULL)
1936 return NULL;
1937 }
1938 copy_reg = PyImport_Import(copy_reg_str);
1939 if (!copy_reg)
1940 return NULL;
1941 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1942 Py_DECREF(copy_reg);
1943 return res;
1944}
1945
1946static PyMethodDef object_methods[] = {
Neal Norwitz5dc2a372002-08-13 22:19:13 +00001947 {"__reduce__", object_reduce, METH_NOARGS,
1948 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00001949 {0}
1950};
1951
Tim Peters6d6c1a32001-08-02 04:15:00 +00001952PyTypeObject PyBaseObject_Type = {
1953 PyObject_HEAD_INIT(&PyType_Type)
1954 0, /* ob_size */
1955 "object", /* tp_name */
1956 sizeof(PyObject), /* tp_basicsize */
1957 0, /* tp_itemsize */
1958 (destructor)object_dealloc, /* tp_dealloc */
1959 0, /* tp_print */
1960 0, /* tp_getattr */
1961 0, /* tp_setattr */
1962 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001963 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001964 0, /* tp_as_number */
1965 0, /* tp_as_sequence */
1966 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001967 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001968 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001969 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001970 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001971 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001972 0, /* tp_as_buffer */
1973 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00001974 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001975 0, /* tp_traverse */
1976 0, /* tp_clear */
1977 0, /* tp_richcompare */
1978 0, /* tp_weaklistoffset */
1979 0, /* tp_iter */
1980 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001981 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001982 0, /* tp_members */
1983 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001984 0, /* tp_base */
1985 0, /* tp_dict */
1986 0, /* tp_descr_get */
1987 0, /* tp_descr_set */
1988 0, /* tp_dictoffset */
1989 object_init, /* tp_init */
1990 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001991 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001992 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001993};
1994
1995
1996/* Initialize the __dict__ in a type object */
1997
Fred Drake7bf97152002-03-28 05:33:33 +00001998static PyObject *
1999create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
2000{
2001 PyObject *cfunc;
2002 PyObject *result;
2003
2004 cfunc = PyCFunction_New(meth, NULL);
2005 if (cfunc == NULL)
2006 return NULL;
2007 result = func(cfunc);
2008 Py_DECREF(cfunc);
2009 return result;
2010}
2011
Tim Peters6d6c1a32001-08-02 04:15:00 +00002012static int
2013add_methods(PyTypeObject *type, PyMethodDef *meth)
2014{
Guido van Rossum687ae002001-10-15 22:03:32 +00002015 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002016
2017 for (; meth->ml_name != NULL; meth++) {
2018 PyObject *descr;
2019 if (PyDict_GetItemString(dict, meth->ml_name))
2020 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002021 if (meth->ml_flags & METH_CLASS) {
2022 if (meth->ml_flags & METH_STATIC) {
2023 PyErr_SetString(PyExc_ValueError,
2024 "method cannot be both class and static");
2025 return -1;
2026 }
2027 descr = create_specialmethod(meth, PyClassMethod_New);
2028 }
2029 else if (meth->ml_flags & METH_STATIC) {
2030 descr = create_specialmethod(meth, PyStaticMethod_New);
2031 }
2032 else {
2033 descr = PyDescr_NewMethod(type, meth);
2034 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002035 if (descr == NULL)
2036 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002037 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002038 return -1;
2039 Py_DECREF(descr);
2040 }
2041 return 0;
2042}
2043
2044static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002045add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002046{
Guido van Rossum687ae002001-10-15 22:03:32 +00002047 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002048
2049 for (; memb->name != NULL; memb++) {
2050 PyObject *descr;
2051 if (PyDict_GetItemString(dict, memb->name))
2052 continue;
2053 descr = PyDescr_NewMember(type, memb);
2054 if (descr == NULL)
2055 return -1;
2056 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2057 return -1;
2058 Py_DECREF(descr);
2059 }
2060 return 0;
2061}
2062
2063static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002064add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002065{
Guido van Rossum687ae002001-10-15 22:03:32 +00002066 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002067
2068 for (; gsp->name != NULL; gsp++) {
2069 PyObject *descr;
2070 if (PyDict_GetItemString(dict, gsp->name))
2071 continue;
2072 descr = PyDescr_NewGetSet(type, gsp);
2073
2074 if (descr == NULL)
2075 return -1;
2076 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2077 return -1;
2078 Py_DECREF(descr);
2079 }
2080 return 0;
2081}
2082
Guido van Rossum13d52f02001-08-10 21:24:08 +00002083static void
2084inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002085{
2086 int oldsize, newsize;
2087
Guido van Rossum13d52f02001-08-10 21:24:08 +00002088 /* Special flag magic */
2089 if (!type->tp_as_buffer && base->tp_as_buffer) {
2090 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2091 type->tp_flags |=
2092 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2093 }
2094 if (!type->tp_as_sequence && base->tp_as_sequence) {
2095 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2096 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2097 }
2098 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2099 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2100 if ((!type->tp_as_number && base->tp_as_number) ||
2101 (!type->tp_as_sequence && base->tp_as_sequence)) {
2102 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2103 if (!type->tp_as_number && !type->tp_as_sequence) {
2104 type->tp_flags |= base->tp_flags &
2105 Py_TPFLAGS_HAVE_INPLACEOPS;
2106 }
2107 }
2108 /* Wow */
2109 }
2110 if (!type->tp_as_number && base->tp_as_number) {
2111 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2112 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2113 }
2114
2115 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002116 oldsize = base->tp_basicsize;
2117 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2118 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2119 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002120 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2121 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002122 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002123 if (type->tp_traverse == NULL)
2124 type->tp_traverse = base->tp_traverse;
2125 if (type->tp_clear == NULL)
2126 type->tp_clear = base->tp_clear;
2127 }
2128 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002129 /* The condition below could use some explanation.
2130 It appears that tp_new is not inherited for static types
2131 whose base class is 'object'; this seems to be a precaution
2132 so that old extension types don't suddenly become
2133 callable (object.__new__ wouldn't insure the invariants
2134 that the extension type's own factory function ensures).
2135 Heap types, of course, are under our control, so they do
2136 inherit tp_new; static extension types that specify some
2137 other built-in type as the default are considered
2138 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002139 if (base != &PyBaseObject_Type ||
2140 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2141 if (type->tp_new == NULL)
2142 type->tp_new = base->tp_new;
2143 }
2144 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002145 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002146
2147 /* Copy other non-function slots */
2148
2149#undef COPYVAL
2150#define COPYVAL(SLOT) \
2151 if (type->SLOT == 0) type->SLOT = base->SLOT
2152
2153 COPYVAL(tp_itemsize);
2154 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2155 COPYVAL(tp_weaklistoffset);
2156 }
2157 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2158 COPYVAL(tp_dictoffset);
2159 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002160}
2161
2162static void
2163inherit_slots(PyTypeObject *type, PyTypeObject *base)
2164{
2165 PyTypeObject *basebase;
2166
2167#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002168#undef COPYSLOT
2169#undef COPYNUM
2170#undef COPYSEQ
2171#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002172#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002173
2174#define SLOTDEFINED(SLOT) \
2175 (base->SLOT != 0 && \
2176 (basebase == NULL || base->SLOT != basebase->SLOT))
2177
Tim Peters6d6c1a32001-08-02 04:15:00 +00002178#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002179 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002180
2181#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2182#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2183#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002184#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002185
Guido van Rossum13d52f02001-08-10 21:24:08 +00002186 /* This won't inherit indirect slots (from tp_as_number etc.)
2187 if type doesn't provide the space. */
2188
2189 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2190 basebase = base->tp_base;
2191 if (basebase->tp_as_number == NULL)
2192 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002193 COPYNUM(nb_add);
2194 COPYNUM(nb_subtract);
2195 COPYNUM(nb_multiply);
2196 COPYNUM(nb_divide);
2197 COPYNUM(nb_remainder);
2198 COPYNUM(nb_divmod);
2199 COPYNUM(nb_power);
2200 COPYNUM(nb_negative);
2201 COPYNUM(nb_positive);
2202 COPYNUM(nb_absolute);
2203 COPYNUM(nb_nonzero);
2204 COPYNUM(nb_invert);
2205 COPYNUM(nb_lshift);
2206 COPYNUM(nb_rshift);
2207 COPYNUM(nb_and);
2208 COPYNUM(nb_xor);
2209 COPYNUM(nb_or);
2210 COPYNUM(nb_coerce);
2211 COPYNUM(nb_int);
2212 COPYNUM(nb_long);
2213 COPYNUM(nb_float);
2214 COPYNUM(nb_oct);
2215 COPYNUM(nb_hex);
2216 COPYNUM(nb_inplace_add);
2217 COPYNUM(nb_inplace_subtract);
2218 COPYNUM(nb_inplace_multiply);
2219 COPYNUM(nb_inplace_divide);
2220 COPYNUM(nb_inplace_remainder);
2221 COPYNUM(nb_inplace_power);
2222 COPYNUM(nb_inplace_lshift);
2223 COPYNUM(nb_inplace_rshift);
2224 COPYNUM(nb_inplace_and);
2225 COPYNUM(nb_inplace_xor);
2226 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002227 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2228 COPYNUM(nb_true_divide);
2229 COPYNUM(nb_floor_divide);
2230 COPYNUM(nb_inplace_true_divide);
2231 COPYNUM(nb_inplace_floor_divide);
2232 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002233 }
2234
Guido van Rossum13d52f02001-08-10 21:24:08 +00002235 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2236 basebase = base->tp_base;
2237 if (basebase->tp_as_sequence == NULL)
2238 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002239 COPYSEQ(sq_length);
2240 COPYSEQ(sq_concat);
2241 COPYSEQ(sq_repeat);
2242 COPYSEQ(sq_item);
2243 COPYSEQ(sq_slice);
2244 COPYSEQ(sq_ass_item);
2245 COPYSEQ(sq_ass_slice);
2246 COPYSEQ(sq_contains);
2247 COPYSEQ(sq_inplace_concat);
2248 COPYSEQ(sq_inplace_repeat);
2249 }
2250
Guido van Rossum13d52f02001-08-10 21:24:08 +00002251 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2252 basebase = base->tp_base;
2253 if (basebase->tp_as_mapping == NULL)
2254 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002255 COPYMAP(mp_length);
2256 COPYMAP(mp_subscript);
2257 COPYMAP(mp_ass_subscript);
2258 }
2259
Tim Petersfc57ccb2001-10-12 02:38:24 +00002260 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2261 basebase = base->tp_base;
2262 if (basebase->tp_as_buffer == NULL)
2263 basebase = NULL;
2264 COPYBUF(bf_getreadbuffer);
2265 COPYBUF(bf_getwritebuffer);
2266 COPYBUF(bf_getsegcount);
2267 COPYBUF(bf_getcharbuffer);
2268 }
2269
Guido van Rossum13d52f02001-08-10 21:24:08 +00002270 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002271
Tim Peters6d6c1a32001-08-02 04:15:00 +00002272 COPYSLOT(tp_dealloc);
2273 COPYSLOT(tp_print);
2274 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2275 type->tp_getattr = base->tp_getattr;
2276 type->tp_getattro = base->tp_getattro;
2277 }
2278 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2279 type->tp_setattr = base->tp_setattr;
2280 type->tp_setattro = base->tp_setattro;
2281 }
2282 /* tp_compare see tp_richcompare */
2283 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002284 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002285 COPYSLOT(tp_call);
2286 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002287 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002288 if (type->tp_compare == NULL &&
2289 type->tp_richcompare == NULL &&
2290 type->tp_hash == NULL)
2291 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002292 type->tp_compare = base->tp_compare;
2293 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002294 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002295 }
2296 }
2297 else {
2298 COPYSLOT(tp_compare);
2299 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002300 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2301 COPYSLOT(tp_iter);
2302 COPYSLOT(tp_iternext);
2303 }
2304 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2305 COPYSLOT(tp_descr_get);
2306 COPYSLOT(tp_descr_set);
2307 COPYSLOT(tp_dictoffset);
2308 COPYSLOT(tp_init);
2309 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002310 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002311 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002312 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002313}
2314
Jeremy Hylton938ace62002-07-17 16:30:39 +00002315static int add_operators(PyTypeObject *);
2316static int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002317
Tim Peters6d6c1a32001-08-02 04:15:00 +00002318int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002319PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002320{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002321 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002322 PyTypeObject *base;
2323 int i, n;
2324
Guido van Rossumcab05802002-06-10 15:29:03 +00002325 if (type->tp_flags & Py_TPFLAGS_READY) {
2326 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002327 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002328 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002329 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002330
2331 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002332
2333 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2334 base = type->tp_base;
2335 if (base == NULL && type != &PyBaseObject_Type)
2336 base = type->tp_base = &PyBaseObject_Type;
2337
Guido van Rossum323a9cf2002-08-14 17:26:30 +00002338 /* Initialize the base class */
2339 if (base && base->tp_dict == NULL) {
2340 if (PyType_Ready(base) < 0)
2341 goto error;
2342 }
2343
Guido van Rossum0986d822002-04-08 01:38:42 +00002344 /* Initialize ob_type if NULL. This means extensions that want to be
2345 compilable separately on Windows can call PyType_Ready() instead of
2346 initializing the ob_type field of their type objects. */
2347 if (type->ob_type == NULL)
2348 type->ob_type = base->ob_type;
2349
Tim Peters6d6c1a32001-08-02 04:15:00 +00002350 /* Initialize tp_bases */
2351 bases = type->tp_bases;
2352 if (bases == NULL) {
2353 if (base == NULL)
2354 bases = PyTuple_New(0);
2355 else
2356 bases = Py_BuildValue("(O)", base);
2357 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002358 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002359 type->tp_bases = bases;
2360 }
2361
Guido van Rossum687ae002001-10-15 22:03:32 +00002362 /* Initialize tp_dict */
2363 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002364 if (dict == NULL) {
2365 dict = PyDict_New();
2366 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002367 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002368 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002369 }
2370
Guido van Rossum687ae002001-10-15 22:03:32 +00002371 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002372 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002373 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002374 if (type->tp_methods != NULL) {
2375 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002376 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002377 }
2378 if (type->tp_members != NULL) {
2379 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002380 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002381 }
2382 if (type->tp_getset != NULL) {
2383 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002384 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002385 }
2386
Tim Peters6d6c1a32001-08-02 04:15:00 +00002387 /* Calculate method resolution order */
2388 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002389 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002390 }
2391
Guido van Rossum13d52f02001-08-10 21:24:08 +00002392 /* Inherit special flags from dominant base */
2393 if (type->tp_base != NULL)
2394 inherit_special(type, type->tp_base);
2395
Tim Peters6d6c1a32001-08-02 04:15:00 +00002396 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002397 bases = type->tp_mro;
2398 assert(bases != NULL);
2399 assert(PyTuple_Check(bases));
2400 n = PyTuple_GET_SIZE(bases);
2401 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002402 PyObject *b = PyTuple_GET_ITEM(bases, i);
2403 if (PyType_Check(b))
2404 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002405 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002406
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002407 /* if the type dictionary doesn't contain a __doc__, set it from
2408 the tp_doc slot.
2409 */
2410 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2411 if (type->tp_doc != NULL) {
2412 PyObject *doc = PyString_FromString(type->tp_doc);
2413 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2414 Py_DECREF(doc);
2415 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002416 PyDict_SetItemString(type->tp_dict,
2417 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002418 }
2419 }
2420
Guido van Rossum13d52f02001-08-10 21:24:08 +00002421 /* Some more special stuff */
2422 base = type->tp_base;
2423 if (base != NULL) {
2424 if (type->tp_as_number == NULL)
2425 type->tp_as_number = base->tp_as_number;
2426 if (type->tp_as_sequence == NULL)
2427 type->tp_as_sequence = base->tp_as_sequence;
2428 if (type->tp_as_mapping == NULL)
2429 type->tp_as_mapping = base->tp_as_mapping;
2430 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002431
Guido van Rossum1c450732001-10-08 15:18:27 +00002432 /* Link into each base class's list of subclasses */
2433 bases = type->tp_bases;
2434 n = PyTuple_GET_SIZE(bases);
2435 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002436 PyObject *b = PyTuple_GET_ITEM(bases, i);
2437 if (PyType_Check(b) &&
2438 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002439 goto error;
2440 }
2441
Guido van Rossum13d52f02001-08-10 21:24:08 +00002442 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002443 assert(type->tp_dict != NULL);
2444 type->tp_flags =
2445 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002446 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002447
2448 error:
2449 type->tp_flags &= ~Py_TPFLAGS_READYING;
2450 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002451}
2452
Guido van Rossum1c450732001-10-08 15:18:27 +00002453static int
2454add_subclass(PyTypeObject *base, PyTypeObject *type)
2455{
2456 int i;
2457 PyObject *list, *ref, *new;
2458
2459 list = base->tp_subclasses;
2460 if (list == NULL) {
2461 base->tp_subclasses = list = PyList_New(0);
2462 if (list == NULL)
2463 return -1;
2464 }
2465 assert(PyList_Check(list));
2466 new = PyWeakref_NewRef((PyObject *)type, NULL);
2467 i = PyList_GET_SIZE(list);
2468 while (--i >= 0) {
2469 ref = PyList_GET_ITEM(list, i);
2470 assert(PyWeakref_CheckRef(ref));
Guido van Rossum72297bb2002-10-18 13:41:47 +00002471 if (PyWeakref_GET_OBJECT(ref) == Py_None) {
2472 i = PyList_SetItem(list, i, new);
2473 Py_DECREF(new);
2474 return i;
2475 }
Guido van Rossum1c450732001-10-08 15:18:27 +00002476 }
2477 i = PyList_Append(list, new);
2478 Py_DECREF(new);
2479 return i;
2480}
2481
Tim Peters6d6c1a32001-08-02 04:15:00 +00002482
2483/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2484
2485/* There's a wrapper *function* for each distinct function typedef used
2486 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2487 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2488 Most tables have only one entry; the tables for binary operators have two
2489 entries, one regular and one with reversed arguments. */
2490
2491static PyObject *
2492wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2493{
2494 inquiry func = (inquiry)wrapped;
2495 int res;
2496
2497 if (!PyArg_ParseTuple(args, ""))
2498 return NULL;
2499 res = (*func)(self);
2500 if (res == -1 && PyErr_Occurred())
2501 return NULL;
2502 return PyInt_FromLong((long)res);
2503}
2504
Tim Peters6d6c1a32001-08-02 04:15:00 +00002505static PyObject *
2506wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2507{
2508 binaryfunc func = (binaryfunc)wrapped;
2509 PyObject *other;
2510
2511 if (!PyArg_ParseTuple(args, "O", &other))
2512 return NULL;
2513 return (*func)(self, other);
2514}
2515
2516static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002517wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2518{
2519 binaryfunc func = (binaryfunc)wrapped;
2520 PyObject *other;
2521
2522 if (!PyArg_ParseTuple(args, "O", &other))
2523 return NULL;
2524 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002525 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002526 Py_INCREF(Py_NotImplemented);
2527 return Py_NotImplemented;
2528 }
2529 return (*func)(self, other);
2530}
2531
2532static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002533wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2534{
2535 binaryfunc func = (binaryfunc)wrapped;
2536 PyObject *other;
2537
2538 if (!PyArg_ParseTuple(args, "O", &other))
2539 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002540 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002541 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002542 Py_INCREF(Py_NotImplemented);
2543 return Py_NotImplemented;
2544 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002545 return (*func)(other, self);
2546}
2547
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002548static PyObject *
2549wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2550{
2551 coercion func = (coercion)wrapped;
2552 PyObject *other, *res;
2553 int ok;
2554
2555 if (!PyArg_ParseTuple(args, "O", &other))
2556 return NULL;
2557 ok = func(&self, &other);
2558 if (ok < 0)
2559 return NULL;
2560 if (ok > 0) {
2561 Py_INCREF(Py_NotImplemented);
2562 return Py_NotImplemented;
2563 }
2564 res = PyTuple_New(2);
2565 if (res == NULL) {
2566 Py_DECREF(self);
2567 Py_DECREF(other);
2568 return NULL;
2569 }
2570 PyTuple_SET_ITEM(res, 0, self);
2571 PyTuple_SET_ITEM(res, 1, other);
2572 return res;
2573}
2574
Tim Peters6d6c1a32001-08-02 04:15:00 +00002575static PyObject *
2576wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2577{
2578 ternaryfunc func = (ternaryfunc)wrapped;
2579 PyObject *other;
2580 PyObject *third = Py_None;
2581
2582 /* Note: This wrapper only works for __pow__() */
2583
2584 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2585 return NULL;
2586 return (*func)(self, other, third);
2587}
2588
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002589static PyObject *
2590wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2591{
2592 ternaryfunc func = (ternaryfunc)wrapped;
2593 PyObject *other;
2594 PyObject *third = Py_None;
2595
2596 /* Note: This wrapper only works for __pow__() */
2597
2598 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2599 return NULL;
2600 return (*func)(other, self, third);
2601}
2602
Tim Peters6d6c1a32001-08-02 04:15:00 +00002603static PyObject *
2604wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2605{
2606 unaryfunc func = (unaryfunc)wrapped;
2607
2608 if (!PyArg_ParseTuple(args, ""))
2609 return NULL;
2610 return (*func)(self);
2611}
2612
Tim Peters6d6c1a32001-08-02 04:15:00 +00002613static PyObject *
2614wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2615{
2616 intargfunc func = (intargfunc)wrapped;
2617 int i;
2618
2619 if (!PyArg_ParseTuple(args, "i", &i))
2620 return NULL;
2621 return (*func)(self, i);
2622}
2623
Guido van Rossum5d815f32001-08-17 21:57:47 +00002624static int
2625getindex(PyObject *self, PyObject *arg)
2626{
2627 int i;
2628
2629 i = PyInt_AsLong(arg);
2630 if (i == -1 && PyErr_Occurred())
2631 return -1;
2632 if (i < 0) {
2633 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2634 if (sq && sq->sq_length) {
2635 int n = (*sq->sq_length)(self);
2636 if (n < 0)
2637 return -1;
2638 i += n;
2639 }
2640 }
2641 return i;
2642}
2643
2644static PyObject *
2645wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2646{
2647 intargfunc func = (intargfunc)wrapped;
2648 PyObject *arg;
2649 int i;
2650
Guido van Rossumf4593e02001-10-03 12:09:30 +00002651 if (PyTuple_GET_SIZE(args) == 1) {
2652 arg = PyTuple_GET_ITEM(args, 0);
2653 i = getindex(self, arg);
2654 if (i == -1 && PyErr_Occurred())
2655 return NULL;
2656 return (*func)(self, i);
2657 }
2658 PyArg_ParseTuple(args, "O", &arg);
2659 assert(PyErr_Occurred());
2660 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002661}
2662
Tim Peters6d6c1a32001-08-02 04:15:00 +00002663static PyObject *
2664wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2665{
2666 intintargfunc func = (intintargfunc)wrapped;
2667 int i, j;
2668
2669 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2670 return NULL;
2671 return (*func)(self, i, j);
2672}
2673
Tim Peters6d6c1a32001-08-02 04:15:00 +00002674static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002675wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002676{
2677 intobjargproc func = (intobjargproc)wrapped;
2678 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002679 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002680
Guido van Rossum5d815f32001-08-17 21:57:47 +00002681 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2682 return NULL;
2683 i = getindex(self, arg);
2684 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002685 return NULL;
2686 res = (*func)(self, i, value);
2687 if (res == -1 && PyErr_Occurred())
2688 return NULL;
2689 Py_INCREF(Py_None);
2690 return Py_None;
2691}
2692
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002693static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002694wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002695{
2696 intobjargproc func = (intobjargproc)wrapped;
2697 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002698 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002699
Guido van Rossum5d815f32001-08-17 21:57:47 +00002700 if (!PyArg_ParseTuple(args, "O", &arg))
2701 return NULL;
2702 i = getindex(self, arg);
2703 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002704 return NULL;
2705 res = (*func)(self, i, NULL);
2706 if (res == -1 && PyErr_Occurred())
2707 return NULL;
2708 Py_INCREF(Py_None);
2709 return Py_None;
2710}
2711
Tim Peters6d6c1a32001-08-02 04:15:00 +00002712static PyObject *
2713wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2714{
2715 intintobjargproc func = (intintobjargproc)wrapped;
2716 int i, j, res;
2717 PyObject *value;
2718
2719 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2720 return NULL;
2721 res = (*func)(self, i, j, value);
2722 if (res == -1 && PyErr_Occurred())
2723 return NULL;
2724 Py_INCREF(Py_None);
2725 return Py_None;
2726}
2727
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002728static PyObject *
2729wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2730{
2731 intintobjargproc func = (intintobjargproc)wrapped;
2732 int i, j, res;
2733
2734 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2735 return NULL;
2736 res = (*func)(self, i, j, NULL);
2737 if (res == -1 && PyErr_Occurred())
2738 return NULL;
2739 Py_INCREF(Py_None);
2740 return Py_None;
2741}
2742
Tim Peters6d6c1a32001-08-02 04:15:00 +00002743/* XXX objobjproc is a misnomer; should be objargpred */
2744static PyObject *
2745wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2746{
2747 objobjproc func = (objobjproc)wrapped;
2748 int res;
2749 PyObject *value;
2750
2751 if (!PyArg_ParseTuple(args, "O", &value))
2752 return NULL;
2753 res = (*func)(self, value);
2754 if (res == -1 && PyErr_Occurred())
2755 return NULL;
2756 return PyInt_FromLong((long)res);
2757}
2758
Tim Peters6d6c1a32001-08-02 04:15:00 +00002759static PyObject *
2760wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2761{
2762 objobjargproc func = (objobjargproc)wrapped;
2763 int res;
2764 PyObject *key, *value;
2765
2766 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2767 return NULL;
2768 res = (*func)(self, key, value);
2769 if (res == -1 && PyErr_Occurred())
2770 return NULL;
2771 Py_INCREF(Py_None);
2772 return Py_None;
2773}
2774
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002775static PyObject *
2776wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2777{
2778 objobjargproc func = (objobjargproc)wrapped;
2779 int res;
2780 PyObject *key;
2781
2782 if (!PyArg_ParseTuple(args, "O", &key))
2783 return NULL;
2784 res = (*func)(self, key, NULL);
2785 if (res == -1 && PyErr_Occurred())
2786 return NULL;
2787 Py_INCREF(Py_None);
2788 return Py_None;
2789}
2790
Tim Peters6d6c1a32001-08-02 04:15:00 +00002791static PyObject *
2792wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2793{
2794 cmpfunc func = (cmpfunc)wrapped;
2795 int res;
2796 PyObject *other;
2797
2798 if (!PyArg_ParseTuple(args, "O", &other))
2799 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002800 if (other->ob_type->tp_compare != func &&
2801 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002802 PyErr_Format(
2803 PyExc_TypeError,
2804 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2805 self->ob_type->tp_name,
2806 self->ob_type->tp_name,
2807 other->ob_type->tp_name);
2808 return NULL;
2809 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002810 res = (*func)(self, other);
2811 if (PyErr_Occurred())
2812 return NULL;
2813 return PyInt_FromLong((long)res);
2814}
2815
Tim Peters6d6c1a32001-08-02 04:15:00 +00002816static PyObject *
2817wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2818{
2819 setattrofunc func = (setattrofunc)wrapped;
2820 int res;
2821 PyObject *name, *value;
2822
2823 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2824 return NULL;
2825 res = (*func)(self, name, value);
2826 if (res < 0)
2827 return NULL;
2828 Py_INCREF(Py_None);
2829 return Py_None;
2830}
2831
2832static PyObject *
2833wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2834{
2835 setattrofunc func = (setattrofunc)wrapped;
2836 int res;
2837 PyObject *name;
2838
2839 if (!PyArg_ParseTuple(args, "O", &name))
2840 return NULL;
2841 res = (*func)(self, name, NULL);
2842 if (res < 0)
2843 return NULL;
2844 Py_INCREF(Py_None);
2845 return Py_None;
2846}
2847
Tim Peters6d6c1a32001-08-02 04:15:00 +00002848static PyObject *
2849wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2850{
2851 hashfunc func = (hashfunc)wrapped;
2852 long res;
2853
2854 if (!PyArg_ParseTuple(args, ""))
2855 return NULL;
2856 res = (*func)(self);
2857 if (res == -1 && PyErr_Occurred())
2858 return NULL;
2859 return PyInt_FromLong(res);
2860}
2861
Tim Peters6d6c1a32001-08-02 04:15:00 +00002862static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002863wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002864{
2865 ternaryfunc func = (ternaryfunc)wrapped;
2866
Guido van Rossumc8e56452001-10-22 00:43:43 +00002867 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002868}
2869
Tim Peters6d6c1a32001-08-02 04:15:00 +00002870static PyObject *
2871wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2872{
2873 richcmpfunc func = (richcmpfunc)wrapped;
2874 PyObject *other;
2875
2876 if (!PyArg_ParseTuple(args, "O", &other))
2877 return NULL;
2878 return (*func)(self, other, op);
2879}
2880
2881#undef RICHCMP_WRAPPER
2882#define RICHCMP_WRAPPER(NAME, OP) \
2883static PyObject * \
2884richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2885{ \
2886 return wrap_richcmpfunc(self, args, wrapped, OP); \
2887}
2888
Jack Jansen8e938b42001-08-08 15:29:49 +00002889RICHCMP_WRAPPER(lt, Py_LT)
2890RICHCMP_WRAPPER(le, Py_LE)
2891RICHCMP_WRAPPER(eq, Py_EQ)
2892RICHCMP_WRAPPER(ne, Py_NE)
2893RICHCMP_WRAPPER(gt, Py_GT)
2894RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002895
Tim Peters6d6c1a32001-08-02 04:15:00 +00002896static PyObject *
2897wrap_next(PyObject *self, PyObject *args, void *wrapped)
2898{
2899 unaryfunc func = (unaryfunc)wrapped;
2900 PyObject *res;
2901
2902 if (!PyArg_ParseTuple(args, ""))
2903 return NULL;
2904 res = (*func)(self);
2905 if (res == NULL && !PyErr_Occurred())
2906 PyErr_SetNone(PyExc_StopIteration);
2907 return res;
2908}
2909
Tim Peters6d6c1a32001-08-02 04:15:00 +00002910static PyObject *
2911wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2912{
2913 descrgetfunc func = (descrgetfunc)wrapped;
2914 PyObject *obj;
2915 PyObject *type = NULL;
2916
2917 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2918 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002919 return (*func)(self, obj, type);
2920}
2921
Tim Peters6d6c1a32001-08-02 04:15:00 +00002922static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002923wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002924{
2925 descrsetfunc func = (descrsetfunc)wrapped;
2926 PyObject *obj, *value;
2927 int ret;
2928
2929 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2930 return NULL;
2931 ret = (*func)(self, obj, value);
2932 if (ret < 0)
2933 return NULL;
2934 Py_INCREF(Py_None);
2935 return Py_None;
2936}
Guido van Rossum22b13872002-08-06 21:41:44 +00002937
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00002938static PyObject *
2939wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
2940{
2941 descrsetfunc func = (descrsetfunc)wrapped;
2942 PyObject *obj;
2943 int ret;
2944
2945 if (!PyArg_ParseTuple(args, "O", &obj))
2946 return NULL;
2947 ret = (*func)(self, obj, NULL);
2948 if (ret < 0)
2949 return NULL;
2950 Py_INCREF(Py_None);
2951 return Py_None;
2952}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002953
Tim Peters6d6c1a32001-08-02 04:15:00 +00002954static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002955wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002956{
2957 initproc func = (initproc)wrapped;
2958
Guido van Rossumc8e56452001-10-22 00:43:43 +00002959 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002960 return NULL;
2961 Py_INCREF(Py_None);
2962 return Py_None;
2963}
2964
Tim Peters6d6c1a32001-08-02 04:15:00 +00002965static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002966tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002967{
Barry Warsaw60f01882001-08-22 19:24:42 +00002968 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002969 PyObject *arg0, *res;
2970
2971 if (self == NULL || !PyType_Check(self))
2972 Py_FatalError("__new__() called with non-type 'self'");
2973 type = (PyTypeObject *)self;
2974 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002975 PyErr_Format(PyExc_TypeError,
2976 "%s.__new__(): not enough arguments",
2977 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002978 return NULL;
2979 }
2980 arg0 = PyTuple_GET_ITEM(args, 0);
2981 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002982 PyErr_Format(PyExc_TypeError,
2983 "%s.__new__(X): X is not a type object (%s)",
2984 type->tp_name,
2985 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002986 return NULL;
2987 }
2988 subtype = (PyTypeObject *)arg0;
2989 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002990 PyErr_Format(PyExc_TypeError,
2991 "%s.__new__(%s): %s is not a subtype of %s",
2992 type->tp_name,
2993 subtype->tp_name,
2994 subtype->tp_name,
2995 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002996 return NULL;
2997 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002998
2999 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003000 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003001 most derived base that's not a heap type is this type. */
3002 staticbase = subtype;
3003 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3004 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003005 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003006 PyErr_Format(PyExc_TypeError,
3007 "%s.__new__(%s) is not safe, use %s.__new__()",
3008 type->tp_name,
3009 subtype->tp_name,
3010 staticbase == NULL ? "?" : staticbase->tp_name);
3011 return NULL;
3012 }
3013
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003014 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3015 if (args == NULL)
3016 return NULL;
3017 res = type->tp_new(subtype, args, kwds);
3018 Py_DECREF(args);
3019 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003020}
3021
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003022static struct PyMethodDef tp_new_methoddef[] = {
3023 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003024 PyDoc_STR("T.__new__(S, ...) -> "
3025 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003026 {0}
3027};
3028
3029static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003030add_tp_new_wrapper(PyTypeObject *type)
3031{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003032 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003033
Guido van Rossum687ae002001-10-15 22:03:32 +00003034 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003035 return 0;
3036 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003037 if (func == NULL)
3038 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003039 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003040}
3041
Guido van Rossumf040ede2001-08-07 16:40:56 +00003042/* Slot wrappers that call the corresponding __foo__ slot. See comments
3043 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003044
Guido van Rossumdc91b992001-08-08 22:26:22 +00003045#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003046static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003047FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003048{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003049 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003050 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003051}
3052
Guido van Rossumdc91b992001-08-08 22:26:22 +00003053#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003054static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003055FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003056{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003057 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003058 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003059}
3060
Guido van Rossumdc91b992001-08-08 22:26:22 +00003061
3062#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003063static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003064FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003065{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003066 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003067 int do_other = self->ob_type != other->ob_type && \
3068 other->ob_type->tp_as_number != NULL && \
3069 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003070 if (self->ob_type->tp_as_number != NULL && \
3071 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3072 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003073 if (do_other && \
3074 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
3075 r = call_maybe( \
3076 other, ROPSTR, &rcache_str, "(O)", self); \
3077 if (r != Py_NotImplemented) \
3078 return r; \
3079 Py_DECREF(r); \
3080 do_other = 0; \
3081 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003082 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003083 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003084 if (r != Py_NotImplemented || \
3085 other->ob_type == self->ob_type) \
3086 return r; \
3087 Py_DECREF(r); \
3088 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003089 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003090 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003091 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003092 } \
3093 Py_INCREF(Py_NotImplemented); \
3094 return Py_NotImplemented; \
3095}
3096
3097#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3098 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3099
3100#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3101static PyObject * \
3102FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3103{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003104 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003105 return call_method(self, OPSTR, &cache_str, \
3106 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003107}
3108
3109static int
3110slot_sq_length(PyObject *self)
3111{
Guido van Rossum2730b132001-08-28 18:22:14 +00003112 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003113 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003114 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003115
3116 if (res == NULL)
3117 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003118 len = (int)PyInt_AsLong(res);
3119 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003120 if (len == -1 && PyErr_Occurred())
3121 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003122 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003123 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003124 "__len__() should return >= 0");
3125 return -1;
3126 }
Guido van Rossum26111622001-10-01 16:42:49 +00003127 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003128}
3129
Guido van Rossumdc91b992001-08-08 22:26:22 +00003130SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3131SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003132
3133/* Super-optimized version of slot_sq_item.
3134 Other slots could do the same... */
3135static PyObject *
3136slot_sq_item(PyObject *self, int i)
3137{
3138 static PyObject *getitem_str;
3139 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3140 descrgetfunc f;
3141
3142 if (getitem_str == NULL) {
3143 getitem_str = PyString_InternFromString("__getitem__");
3144 if (getitem_str == NULL)
3145 return NULL;
3146 }
3147 func = _PyType_Lookup(self->ob_type, getitem_str);
3148 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003149 if ((f = func->ob_type->tp_descr_get) == NULL)
3150 Py_INCREF(func);
3151 else
3152 func = f(func, self, (PyObject *)(self->ob_type));
3153 ival = PyInt_FromLong(i);
3154 if (ival != NULL) {
3155 args = PyTuple_New(1);
3156 if (args != NULL) {
3157 PyTuple_SET_ITEM(args, 0, ival);
3158 retval = PyObject_Call(func, args, NULL);
3159 Py_XDECREF(args);
3160 Py_XDECREF(func);
3161 return retval;
3162 }
3163 }
3164 }
3165 else {
3166 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3167 }
3168 Py_XDECREF(args);
3169 Py_XDECREF(ival);
3170 Py_XDECREF(func);
3171 return NULL;
3172}
3173
Guido van Rossumdc91b992001-08-08 22:26:22 +00003174SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003175
3176static int
3177slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3178{
3179 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003180 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003181
3182 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003183 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003184 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003185 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003186 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003187 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003188 if (res == NULL)
3189 return -1;
3190 Py_DECREF(res);
3191 return 0;
3192}
3193
3194static int
3195slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3196{
3197 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003198 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003199
3200 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003201 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003202 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003203 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003204 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003205 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003206 if (res == NULL)
3207 return -1;
3208 Py_DECREF(res);
3209 return 0;
3210}
3211
3212static int
3213slot_sq_contains(PyObject *self, PyObject *value)
3214{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003215 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003216 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003217
Guido van Rossum55f20992001-10-01 17:18:22 +00003218 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003219
3220 if (func != NULL) {
3221 args = Py_BuildValue("(O)", value);
3222 if (args == NULL)
3223 res = NULL;
3224 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003225 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003226 Py_DECREF(args);
3227 }
3228 Py_DECREF(func);
3229 if (res == NULL)
3230 return -1;
3231 return PyObject_IsTrue(res);
3232 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003233 else if (PyErr_Occurred())
3234 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003235 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003236 return _PySequence_IterSearch(self, value,
3237 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003238 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003239}
3240
Guido van Rossumdc91b992001-08-08 22:26:22 +00003241SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3242SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003243
3244#define slot_mp_length slot_sq_length
3245
Guido van Rossumdc91b992001-08-08 22:26:22 +00003246SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003247
3248static int
3249slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3250{
3251 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003252 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003253
3254 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003255 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003256 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003257 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003258 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003259 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003260 if (res == NULL)
3261 return -1;
3262 Py_DECREF(res);
3263 return 0;
3264}
3265
Guido van Rossumdc91b992001-08-08 22:26:22 +00003266SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3267SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3268SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3269SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3270SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3271SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3272
Jeremy Hylton938ace62002-07-17 16:30:39 +00003273static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003274
3275SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3276 nb_power, "__pow__", "__rpow__")
3277
3278static PyObject *
3279slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3280{
Guido van Rossum2730b132001-08-28 18:22:14 +00003281 static PyObject *pow_str;
3282
Guido van Rossumdc91b992001-08-08 22:26:22 +00003283 if (modulus == Py_None)
3284 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003285 /* Three-arg power doesn't use __rpow__. But ternary_op
3286 can call this when the second argument's type uses
3287 slot_nb_power, so check before calling self.__pow__. */
3288 if (self->ob_type->tp_as_number != NULL &&
3289 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3290 return call_method(self, "__pow__", &pow_str,
3291 "(OO)", other, modulus);
3292 }
3293 Py_INCREF(Py_NotImplemented);
3294 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003295}
3296
3297SLOT0(slot_nb_negative, "__neg__")
3298SLOT0(slot_nb_positive, "__pos__")
3299SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003300
3301static int
3302slot_nb_nonzero(PyObject *self)
3303{
Guido van Rossum84b2bed2002-08-16 17:01:09 +00003304 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003305 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003306
Guido van Rossum55f20992001-10-01 17:18:22 +00003307 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003308 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003309 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003310 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003311 func = lookup_maybe(self, "__len__", &len_str);
3312 if (func == NULL) {
3313 if (PyErr_Occurred())
3314 return -1;
3315 else
3316 return 1;
3317 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003318 }
Guido van Rossum84b2bed2002-08-16 17:01:09 +00003319 args = res = PyTuple_New(0);
3320 if (args != NULL) {
3321 res = PyObject_Call(func, args, NULL);
3322 Py_DECREF(args);
3323 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003324 Py_DECREF(func);
3325 if (res == NULL)
3326 return -1;
3327 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003328}
3329
Guido van Rossumdc91b992001-08-08 22:26:22 +00003330SLOT0(slot_nb_invert, "__invert__")
3331SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3332SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3333SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3334SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3335SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003336
3337static int
3338slot_nb_coerce(PyObject **a, PyObject **b)
3339{
3340 static PyObject *coerce_str;
3341 PyObject *self = *a, *other = *b;
3342
3343 if (self->ob_type->tp_as_number != NULL &&
3344 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3345 PyObject *r;
3346 r = call_maybe(
3347 self, "__coerce__", &coerce_str, "(O)", other);
3348 if (r == NULL)
3349 return -1;
3350 if (r == Py_NotImplemented) {
3351 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003352 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003353 else {
3354 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3355 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003356 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003357 Py_DECREF(r);
3358 return -1;
3359 }
3360 *a = PyTuple_GET_ITEM(r, 0);
3361 Py_INCREF(*a);
3362 *b = PyTuple_GET_ITEM(r, 1);
3363 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003364 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003365 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003366 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003367 }
3368 if (other->ob_type->tp_as_number != NULL &&
3369 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3370 PyObject *r;
3371 r = call_maybe(
3372 other, "__coerce__", &coerce_str, "(O)", self);
3373 if (r == NULL)
3374 return -1;
3375 if (r == Py_NotImplemented) {
3376 Py_DECREF(r);
3377 return 1;
3378 }
3379 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3380 PyErr_SetString(PyExc_TypeError,
3381 "__coerce__ didn't return a 2-tuple");
3382 Py_DECREF(r);
3383 return -1;
3384 }
3385 *a = PyTuple_GET_ITEM(r, 1);
3386 Py_INCREF(*a);
3387 *b = PyTuple_GET_ITEM(r, 0);
3388 Py_INCREF(*b);
3389 Py_DECREF(r);
3390 return 0;
3391 }
3392 return 1;
3393}
3394
Guido van Rossumdc91b992001-08-08 22:26:22 +00003395SLOT0(slot_nb_int, "__int__")
3396SLOT0(slot_nb_long, "__long__")
3397SLOT0(slot_nb_float, "__float__")
3398SLOT0(slot_nb_oct, "__oct__")
3399SLOT0(slot_nb_hex, "__hex__")
3400SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3401SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3402SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3403SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3404SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003405SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00003406SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3407SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3408SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3409SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3410SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3411SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3412 "__floordiv__", "__rfloordiv__")
3413SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3414SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3415SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003416
3417static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003418half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003419{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003420 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003421 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003422 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003423
Guido van Rossum60718732001-08-28 17:47:51 +00003424 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003425 if (func == NULL) {
3426 PyErr_Clear();
3427 }
3428 else {
3429 args = Py_BuildValue("(O)", other);
3430 if (args == NULL)
3431 res = NULL;
3432 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003433 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003434 Py_DECREF(args);
3435 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00003436 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003437 if (res != Py_NotImplemented) {
3438 if (res == NULL)
3439 return -2;
3440 c = PyInt_AsLong(res);
3441 Py_DECREF(res);
3442 if (c == -1 && PyErr_Occurred())
3443 return -2;
3444 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3445 }
3446 Py_DECREF(res);
3447 }
3448 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003449}
3450
Guido van Rossumab3b0342001-09-18 20:38:53 +00003451/* This slot is published for the benefit of try_3way_compare in object.c */
3452int
3453_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003454{
3455 int c;
3456
Guido van Rossumab3b0342001-09-18 20:38:53 +00003457 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003458 c = half_compare(self, other);
3459 if (c <= 1)
3460 return c;
3461 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003462 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003463 c = half_compare(other, self);
3464 if (c < -1)
3465 return -2;
3466 if (c <= 1)
3467 return -c;
3468 }
3469 return (void *)self < (void *)other ? -1 :
3470 (void *)self > (void *)other ? 1 : 0;
3471}
3472
3473static PyObject *
3474slot_tp_repr(PyObject *self)
3475{
3476 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003477 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003478
Guido van Rossum60718732001-08-28 17:47:51 +00003479 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003480 if (func != NULL) {
3481 res = PyEval_CallObject(func, NULL);
3482 Py_DECREF(func);
3483 return res;
3484 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003485 PyErr_Clear();
3486 return PyString_FromFormat("<%s object at %p>",
3487 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003488}
3489
3490static PyObject *
3491slot_tp_str(PyObject *self)
3492{
3493 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003494 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003495
Guido van Rossum60718732001-08-28 17:47:51 +00003496 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003497 if (func != NULL) {
3498 res = PyEval_CallObject(func, NULL);
3499 Py_DECREF(func);
3500 return res;
3501 }
3502 else {
3503 PyErr_Clear();
3504 return slot_tp_repr(self);
3505 }
3506}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003507
3508static long
3509slot_tp_hash(PyObject *self)
3510{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003511 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003512 static PyObject *hash_str, *eq_str, *cmp_str;
3513
Tim Peters6d6c1a32001-08-02 04:15:00 +00003514 long h;
3515
Guido van Rossum60718732001-08-28 17:47:51 +00003516 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003517
3518 if (func != NULL) {
3519 res = PyEval_CallObject(func, NULL);
3520 Py_DECREF(func);
3521 if (res == NULL)
3522 return -1;
3523 h = PyInt_AsLong(res);
3524 }
3525 else {
3526 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003527 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003528 if (func == NULL) {
3529 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003530 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003531 }
3532 if (func != NULL) {
3533 Py_DECREF(func);
3534 PyErr_SetString(PyExc_TypeError, "unhashable type");
3535 return -1;
3536 }
3537 PyErr_Clear();
3538 h = _Py_HashPointer((void *)self);
3539 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003540 if (h == -1 && !PyErr_Occurred())
3541 h = -2;
3542 return h;
3543}
3544
3545static PyObject *
3546slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3547{
Guido van Rossum60718732001-08-28 17:47:51 +00003548 static PyObject *call_str;
3549 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003550 PyObject *res;
3551
3552 if (meth == NULL)
3553 return NULL;
3554 res = PyObject_Call(meth, args, kwds);
3555 Py_DECREF(meth);
3556 return res;
3557}
3558
Guido van Rossum14a6f832001-10-17 13:59:09 +00003559/* There are two slot dispatch functions for tp_getattro.
3560
3561 - slot_tp_getattro() is used when __getattribute__ is overridden
3562 but no __getattr__ hook is present;
3563
3564 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3565
Guido van Rossumc334df52002-04-04 23:44:47 +00003566 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3567 detects the absence of __getattr__ and then installs the simpler slot if
3568 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003569
Tim Peters6d6c1a32001-08-02 04:15:00 +00003570static PyObject *
3571slot_tp_getattro(PyObject *self, PyObject *name)
3572{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003573 static PyObject *getattribute_str = NULL;
3574 return call_method(self, "__getattribute__", &getattribute_str,
3575 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003576}
3577
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003578static PyObject *
3579slot_tp_getattr_hook(PyObject *self, PyObject *name)
3580{
3581 PyTypeObject *tp = self->ob_type;
3582 PyObject *getattr, *getattribute, *res;
3583 static PyObject *getattribute_str = NULL;
3584 static PyObject *getattr_str = NULL;
3585
3586 if (getattr_str == NULL) {
3587 getattr_str = PyString_InternFromString("__getattr__");
3588 if (getattr_str == NULL)
3589 return NULL;
3590 }
3591 if (getattribute_str == NULL) {
3592 getattribute_str =
3593 PyString_InternFromString("__getattribute__");
3594 if (getattribute_str == NULL)
3595 return NULL;
3596 }
3597 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003598 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003599 /* No __getattr__ hook: use a simpler dispatcher */
3600 tp->tp_getattro = slot_tp_getattro;
3601 return slot_tp_getattro(self, name);
3602 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003603 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003604 if (getattribute == NULL ||
3605 (getattribute->ob_type == &PyWrapperDescr_Type &&
3606 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3607 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003608 res = PyObject_GenericGetAttr(self, name);
3609 else
3610 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003611 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003612 PyErr_Clear();
3613 res = PyObject_CallFunction(getattr, "OO", self, name);
3614 }
3615 return res;
3616}
3617
Tim Peters6d6c1a32001-08-02 04:15:00 +00003618static int
3619slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3620{
3621 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003622 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003623
3624 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003625 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003626 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003627 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003628 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003629 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003630 if (res == NULL)
3631 return -1;
3632 Py_DECREF(res);
3633 return 0;
3634}
3635
3636/* Map rich comparison operators to their __xx__ namesakes */
3637static char *name_op[] = {
3638 "__lt__",
3639 "__le__",
3640 "__eq__",
3641 "__ne__",
3642 "__gt__",
3643 "__ge__",
3644};
3645
3646static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003647half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003648{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003649 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003650 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003651
Guido van Rossum60718732001-08-28 17:47:51 +00003652 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003653 if (func == NULL) {
3654 PyErr_Clear();
3655 Py_INCREF(Py_NotImplemented);
3656 return Py_NotImplemented;
3657 }
3658 args = Py_BuildValue("(O)", other);
3659 if (args == NULL)
3660 res = NULL;
3661 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003662 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003663 Py_DECREF(args);
3664 }
3665 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003666 return res;
3667}
3668
Guido van Rossumb8f63662001-08-15 23:57:02 +00003669/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3670static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3671
3672static PyObject *
3673slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3674{
3675 PyObject *res;
3676
3677 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3678 res = half_richcompare(self, other, op);
3679 if (res != Py_NotImplemented)
3680 return res;
3681 Py_DECREF(res);
3682 }
3683 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3684 res = half_richcompare(other, self, swapped_op[op]);
3685 if (res != Py_NotImplemented) {
3686 return res;
3687 }
3688 Py_DECREF(res);
3689 }
3690 Py_INCREF(Py_NotImplemented);
3691 return Py_NotImplemented;
3692}
3693
3694static PyObject *
3695slot_tp_iter(PyObject *self)
3696{
3697 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003698 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003699
Guido van Rossum60718732001-08-28 17:47:51 +00003700 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003701 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00003702 PyObject *args;
3703 args = res = PyTuple_New(0);
3704 if (args != NULL) {
3705 res = PyObject_Call(func, args, NULL);
3706 Py_DECREF(args);
3707 }
3708 Py_DECREF(func);
3709 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003710 }
3711 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003712 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003713 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003714 PyErr_SetString(PyExc_TypeError,
3715 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003716 return NULL;
3717 }
3718 Py_DECREF(func);
3719 return PySeqIter_New(self);
3720}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003721
3722static PyObject *
3723slot_tp_iternext(PyObject *self)
3724{
Guido van Rossum2730b132001-08-28 18:22:14 +00003725 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003726 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003727}
3728
Guido van Rossum1a493502001-08-17 16:47:50 +00003729static PyObject *
3730slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3731{
3732 PyTypeObject *tp = self->ob_type;
3733 PyObject *get;
3734 static PyObject *get_str = NULL;
3735
3736 if (get_str == NULL) {
3737 get_str = PyString_InternFromString("__get__");
3738 if (get_str == NULL)
3739 return NULL;
3740 }
3741 get = _PyType_Lookup(tp, get_str);
3742 if (get == NULL) {
3743 /* Avoid further slowdowns */
3744 if (tp->tp_descr_get == slot_tp_descr_get)
3745 tp->tp_descr_get = NULL;
3746 Py_INCREF(self);
3747 return self;
3748 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003749 if (obj == NULL)
3750 obj = Py_None;
3751 if (type == NULL)
3752 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003753 return PyObject_CallFunction(get, "OOO", self, obj, type);
3754}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003755
3756static int
3757slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3758{
Guido van Rossum2c252392001-08-24 10:13:31 +00003759 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003760 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003761
3762 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003763 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003764 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003765 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003766 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003767 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003768 if (res == NULL)
3769 return -1;
3770 Py_DECREF(res);
3771 return 0;
3772}
3773
3774static int
3775slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3776{
Guido van Rossum60718732001-08-28 17:47:51 +00003777 static PyObject *init_str;
3778 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003779 PyObject *res;
3780
3781 if (meth == NULL)
3782 return -1;
3783 res = PyObject_Call(meth, args, kwds);
3784 Py_DECREF(meth);
3785 if (res == NULL)
3786 return -1;
3787 Py_DECREF(res);
3788 return 0;
3789}
3790
3791static PyObject *
3792slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3793{
Guido van Rossum7bed2132002-08-08 21:57:53 +00003794 static PyObject *new_str;
3795 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003796 PyObject *newargs, *x;
3797 int i, n;
3798
Guido van Rossum7bed2132002-08-08 21:57:53 +00003799 if (new_str == NULL) {
3800 new_str = PyString_InternFromString("__new__");
3801 if (new_str == NULL)
3802 return NULL;
3803 }
3804 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003805 if (func == NULL)
3806 return NULL;
3807 assert(PyTuple_Check(args));
3808 n = PyTuple_GET_SIZE(args);
3809 newargs = PyTuple_New(n+1);
3810 if (newargs == NULL)
3811 return NULL;
3812 Py_INCREF(type);
3813 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3814 for (i = 0; i < n; i++) {
3815 x = PyTuple_GET_ITEM(args, i);
3816 Py_INCREF(x);
3817 PyTuple_SET_ITEM(newargs, i+1, x);
3818 }
3819 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003820 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003821 Py_DECREF(func);
3822 return x;
3823}
3824
Guido van Rossumfebd61d2002-08-08 20:55:20 +00003825static void
3826slot_tp_del(PyObject *self)
3827{
3828 static PyObject *del_str = NULL;
3829 PyObject *del, *res;
3830 PyObject *error_type, *error_value, *error_traceback;
3831
3832 /* Temporarily resurrect the object. */
3833 assert(self->ob_refcnt == 0);
3834 self->ob_refcnt = 1;
3835
3836 /* Save the current exception, if any. */
3837 PyErr_Fetch(&error_type, &error_value, &error_traceback);
3838
3839 /* Execute __del__ method, if any. */
3840 del = lookup_maybe(self, "__del__", &del_str);
3841 if (del != NULL) {
3842 res = PyEval_CallObject(del, NULL);
3843 if (res == NULL)
3844 PyErr_WriteUnraisable(del);
3845 else
3846 Py_DECREF(res);
3847 Py_DECREF(del);
3848 }
3849
3850 /* Restore the saved exception. */
3851 PyErr_Restore(error_type, error_value, error_traceback);
3852
3853 /* Undo the temporary resurrection; can't use DECREF here, it would
3854 * cause a recursive call.
3855 */
3856 assert(self->ob_refcnt > 0);
3857 if (--self->ob_refcnt == 0)
3858 return; /* this is the normal path out */
3859
3860 /* __del__ resurrected it! Make it look like the original Py_DECREF
3861 * never happened.
3862 */
3863 {
3864 int refcnt = self->ob_refcnt;
3865 _Py_NewReference(self);
3866 self->ob_refcnt = refcnt;
3867 }
3868 assert(!PyType_IS_GC(self->ob_type) ||
3869 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
3870 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
3871 * _Py_NewReference bumped it again, so that's a wash.
3872 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
3873 * chain, so no more to do there either.
3874 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
3875 * _Py_NewReference bumped tp_allocs: both of those need to be
3876 * undone.
3877 */
3878#ifdef COUNT_ALLOCS
3879 --self->ob_type->tp_frees;
3880 --self->ob_type->tp_allocs;
3881#endif
3882}
3883
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003884
3885/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3886 functions. The offsets here are relative to the 'etype' structure, which
3887 incorporates the additional structures used for numbers, sequences and
3888 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3889 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00003890 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3891 terminated with an all-zero entry. (This table is further initialized and
3892 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003893
Guido van Rossum6d204072001-10-21 00:44:31 +00003894typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003895
3896#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003897#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003898#undef ETSLOT
3899#undef SQSLOT
3900#undef MPSLOT
3901#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003902#undef UNSLOT
3903#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003904#undef BINSLOT
3905#undef RBINSLOT
3906
Guido van Rossum6d204072001-10-21 00:44:31 +00003907#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00003908 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3909 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003910#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3911 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00003912 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003913#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00003914 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, \
3915 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00003916#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3917 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3918#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3919 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3920#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3921 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3922#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3923 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3924 "x." NAME "() <==> " DOC)
3925#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3926 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3927 "x." NAME "(y) <==> x" DOC "y")
3928#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3929 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3930 "x." NAME "(y) <==> x" DOC "y")
3931#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3932 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3933 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003934
3935static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003936 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3937 "x.__len__() <==> len(x)"),
3938 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3939 "x.__add__(y) <==> x+y"),
3940 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3941 "x.__mul__(n) <==> x*n"),
3942 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3943 "x.__rmul__(n) <==> n*x"),
3944 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3945 "x.__getitem__(y) <==> x[y]"),
3946 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3947 "x.__getslice__(i, j) <==> x[i:j]"),
3948 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3949 "x.__setitem__(i, y) <==> x[i]=y"),
3950 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3951 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003952 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003953 wrap_intintobjargproc,
3954 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3955 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3956 "x.__delslice__(i, j) <==> del x[i:j]"),
3957 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3958 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003959 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003960 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003961 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003962 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003963
Guido van Rossum6d204072001-10-21 00:44:31 +00003964 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3965 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003966 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003967 wrap_binaryfunc,
3968 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003969 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003970 wrap_objobjargproc,
3971 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003972 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003973 wrap_delitem,
3974 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003975
Guido van Rossum6d204072001-10-21 00:44:31 +00003976 BINSLOT("__add__", nb_add, slot_nb_add,
3977 "+"),
3978 RBINSLOT("__radd__", nb_add, slot_nb_add,
3979 "+"),
3980 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3981 "-"),
3982 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3983 "-"),
3984 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3985 "*"),
3986 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3987 "*"),
3988 BINSLOT("__div__", nb_divide, slot_nb_divide,
3989 "/"),
3990 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3991 "/"),
3992 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3993 "%"),
3994 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3995 "%"),
3996 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3997 "divmod(x, y)"),
3998 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3999 "divmod(y, x)"),
4000 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4001 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4002 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4003 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4004 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4005 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4006 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4007 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004008 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004009 "x != 0"),
4010 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4011 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4012 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4013 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4014 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4015 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4016 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4017 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4018 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4019 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4020 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4021 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4022 "x.__coerce__(y) <==> coerce(x, y)"),
4023 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4024 "int(x)"),
4025 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4026 "long(x)"),
4027 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4028 "float(x)"),
4029 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4030 "oct(x)"),
4031 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4032 "hex(x)"),
4033 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4034 wrap_binaryfunc, "+"),
4035 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4036 wrap_binaryfunc, "-"),
4037 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4038 wrap_binaryfunc, "*"),
4039 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4040 wrap_binaryfunc, "/"),
4041 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4042 wrap_binaryfunc, "%"),
4043 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004044 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004045 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4046 wrap_binaryfunc, "<<"),
4047 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4048 wrap_binaryfunc, ">>"),
4049 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4050 wrap_binaryfunc, "&"),
4051 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4052 wrap_binaryfunc, "^"),
4053 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4054 wrap_binaryfunc, "|"),
4055 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4056 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4057 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4058 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4059 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4060 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4061 IBSLOT("__itruediv__", nb_inplace_true_divide,
4062 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004063
Guido van Rossum6d204072001-10-21 00:44:31 +00004064 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4065 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004066 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004067 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4068 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004069 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004070 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4071 "x.__cmp__(y) <==> cmp(x,y)"),
4072 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4073 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004074 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4075 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004076 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004077 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4078 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4079 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4080 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4081 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4082 "x.__setattr__('name', value) <==> x.name = value"),
4083 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4084 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4085 "x.__delattr__('name') <==> del x.name"),
4086 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4087 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4088 "x.__lt__(y) <==> x<y"),
4089 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4090 "x.__le__(y) <==> x<=y"),
4091 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4092 "x.__eq__(y) <==> x==y"),
4093 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4094 "x.__ne__(y) <==> x!=y"),
4095 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4096 "x.__gt__(y) <==> x>y"),
4097 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4098 "x.__ge__(y) <==> x>=y"),
4099 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4100 "x.__iter__() <==> iter(x)"),
4101 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4102 "x.next() -> the next value, or raise StopIteration"),
4103 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4104 "descr.__get__(obj[, type]) -> value"),
4105 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4106 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004107 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4108 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004109 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004110 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004111 "see x.__class__.__doc__ for signature",
4112 PyWrapperFlag_KEYWORDS),
4113 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004114 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004115 {NULL}
4116};
4117
Guido van Rossumc334df52002-04-04 23:44:47 +00004118/* Given a type pointer and an offset gotten from a slotdef entry, return a
4119 pointer to the actual slot. This is not quite the same as simply adding
4120 the offset to the type pointer, since it takes care to indirect through the
4121 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4122 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004123static void **
4124slotptr(PyTypeObject *type, int offset)
4125{
4126 char *ptr;
4127
Guido van Rossum09638c12002-06-13 19:17:46 +00004128 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004129 assert(offset >= 0);
4130 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00004131 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004132 ptr = (void *)type->tp_as_sequence;
4133 offset -= offsetof(etype, as_sequence);
4134 }
Guido van Rossum09638c12002-06-13 19:17:46 +00004135 else if (offset >= offsetof(etype, as_mapping)) {
4136 ptr = (void *)type->tp_as_mapping;
4137 offset -= offsetof(etype, as_mapping);
4138 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004139 else if (offset >= offsetof(etype, as_number)) {
4140 ptr = (void *)type->tp_as_number;
4141 offset -= offsetof(etype, as_number);
4142 }
4143 else {
4144 ptr = (void *)type;
4145 }
4146 if (ptr != NULL)
4147 ptr += offset;
4148 return (void **)ptr;
4149}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004150
Guido van Rossumc334df52002-04-04 23:44:47 +00004151/* Length of array of slotdef pointers used to store slots with the
4152 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4153 the same __name__, for any __name__. Since that's a static property, it is
4154 appropriate to declare fixed-size arrays for this. */
4155#define MAX_EQUIV 10
4156
4157/* Return a slot pointer for a given name, but ONLY if the attribute has
4158 exactly one slot function. The name must be an interned string. */
4159static void **
4160resolve_slotdups(PyTypeObject *type, PyObject *name)
4161{
4162 /* XXX Maybe this could be optimized more -- but is it worth it? */
4163
4164 /* pname and ptrs act as a little cache */
4165 static PyObject *pname;
4166 static slotdef *ptrs[MAX_EQUIV];
4167 slotdef *p, **pp;
4168 void **res, **ptr;
4169
4170 if (pname != name) {
4171 /* Collect all slotdefs that match name into ptrs. */
4172 pname = name;
4173 pp = ptrs;
4174 for (p = slotdefs; p->name_strobj; p++) {
4175 if (p->name_strobj == name)
4176 *pp++ = p;
4177 }
4178 *pp = NULL;
4179 }
4180
4181 /* Look in all matching slots of the type; if exactly one of these has
4182 a filled-in slot, return its value. Otherwise return NULL. */
4183 res = NULL;
4184 for (pp = ptrs; *pp; pp++) {
4185 ptr = slotptr(type, (*pp)->offset);
4186 if (ptr == NULL || *ptr == NULL)
4187 continue;
4188 if (res != NULL)
4189 return NULL;
4190 res = ptr;
4191 }
4192 return res;
4193}
4194
4195/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4196 does some incredibly complex thinking and then sticks something into the
4197 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
4198 interests, and then stores a generic wrapper or a specific function into
4199 the slot.) Return a pointer to the next slotdef with a different offset,
4200 because that's convenient for fixup_slot_dispatchers(). */
4201static slotdef *
4202update_one_slot(PyTypeObject *type, slotdef *p)
4203{
4204 PyObject *descr;
4205 PyWrapperDescrObject *d;
4206 void *generic = NULL, *specific = NULL;
4207 int use_generic = 0;
4208 int offset = p->offset;
4209 void **ptr = slotptr(type, offset);
4210
4211 if (ptr == NULL) {
4212 do {
4213 ++p;
4214 } while (p->offset == offset);
4215 return p;
4216 }
4217 do {
4218 descr = _PyType_Lookup(type, p->name_strobj);
4219 if (descr == NULL)
4220 continue;
4221 if (descr->ob_type == &PyWrapperDescr_Type) {
4222 void **tptr = resolve_slotdups(type, p->name_strobj);
4223 if (tptr == NULL || tptr == ptr)
4224 generic = p->function;
4225 d = (PyWrapperDescrObject *)descr;
4226 if (d->d_base->wrapper == p->wrapper &&
4227 PyType_IsSubtype(type, d->d_type))
4228 {
4229 if (specific == NULL ||
4230 specific == d->d_wrapped)
4231 specific = d->d_wrapped;
4232 else
4233 use_generic = 1;
4234 }
4235 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00004236 else if (descr->ob_type == &PyCFunction_Type &&
4237 PyCFunction_GET_FUNCTION(descr) ==
4238 (PyCFunction)tp_new_wrapper &&
4239 strcmp(p->name, "__new__") == 0)
4240 {
4241 /* The __new__ wrapper is not a wrapper descriptor,
4242 so must be special-cased differently.
4243 If we don't do this, creating an instance will
4244 always use slot_tp_new which will look up
4245 __new__ in the MRO which will call tp_new_wrapper
4246 which will look through the base classes looking
4247 for a static base and call its tp_new (usually
4248 PyType_GenericNew), after performing various
4249 sanity checks and constructing a new argument
4250 list. Cut all that nonsense short -- this speeds
4251 up instance creation tremendously. */
4252 specific = type->tp_new;
4253 /* XXX I'm not 100% sure that there isn't a hole
4254 in this reasoning that requires additional
4255 sanity checks. I'll buy the first person to
4256 point out a bug in this reasoning a beer. */
4257 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004258 else {
4259 use_generic = 1;
4260 generic = p->function;
4261 }
4262 } while ((++p)->offset == offset);
4263 if (specific && !use_generic)
4264 *ptr = specific;
4265 else
4266 *ptr = generic;
4267 return p;
4268}
4269
Guido van Rossum22b13872002-08-06 21:41:44 +00004270static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00004271 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004272
Guido van Rossumc334df52002-04-04 23:44:47 +00004273/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4274 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004275static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004276update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004277{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004278 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004279
Guido van Rossumc334df52002-04-04 23:44:47 +00004280 for (pp = pp0; *pp; pp++)
4281 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004282 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004283}
4284
Guido van Rossumc334df52002-04-04 23:44:47 +00004285/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4286 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004287static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004288recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004289{
4290 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004291 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004292 int i, n;
4293
4294 subclasses = type->tp_subclasses;
4295 if (subclasses == NULL)
4296 return 0;
4297 assert(PyList_Check(subclasses));
4298 n = PyList_GET_SIZE(subclasses);
4299 for (i = 0; i < n; i++) {
4300 ref = PyList_GET_ITEM(subclasses, i);
4301 assert(PyWeakref_CheckRef(ref));
4302 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004303 assert(subclass != NULL);
4304 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004305 continue;
4306 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004307 /* Avoid recursing down into unaffected classes */
4308 dict = subclass->tp_dict;
4309 if (dict != NULL && PyDict_Check(dict) &&
4310 PyDict_GetItem(dict, name) != NULL)
4311 continue;
4312 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004313 return -1;
4314 }
4315 return 0;
4316}
4317
Guido van Rossumc334df52002-04-04 23:44:47 +00004318/* Comparison function for qsort() to compare slotdefs by their offset, and
4319 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004320static int
4321slotdef_cmp(const void *aa, const void *bb)
4322{
4323 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4324 int c = a->offset - b->offset;
4325 if (c != 0)
4326 return c;
4327 else
4328 return a - b;
4329}
4330
Guido van Rossumc334df52002-04-04 23:44:47 +00004331/* Initialize the slotdefs table by adding interned string objects for the
4332 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004333static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004334init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004335{
4336 slotdef *p;
4337 static int initialized = 0;
4338
4339 if (initialized)
4340 return;
4341 for (p = slotdefs; p->name; p++) {
4342 p->name_strobj = PyString_InternFromString(p->name);
4343 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004344 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004345 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004346 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4347 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004348 initialized = 1;
4349}
4350
Guido van Rossumc334df52002-04-04 23:44:47 +00004351/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004352static int
4353update_slot(PyTypeObject *type, PyObject *name)
4354{
Guido van Rossumc334df52002-04-04 23:44:47 +00004355 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004356 slotdef *p;
4357 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004358 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004359
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004360 init_slotdefs();
4361 pp = ptrs;
4362 for (p = slotdefs; p->name; p++) {
4363 /* XXX assume name is interned! */
4364 if (p->name_strobj == name)
4365 *pp++ = p;
4366 }
4367 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004368 for (pp = ptrs; *pp; pp++) {
4369 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004370 offset = p->offset;
4371 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004372 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004373 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004374 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004375 if (ptrs[0] == NULL)
4376 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004377 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004378}
4379
Guido van Rossumc334df52002-04-04 23:44:47 +00004380/* Store the proper functions in the slot dispatches at class (type)
4381 definition time, based upon which operations the class overrides in its
4382 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004383static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004384fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004385{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004386 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004387
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004388 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004389 for (p = slotdefs; p->name; )
4390 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004391}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004392
Guido van Rossum6d204072001-10-21 00:44:31 +00004393/* This function is called by PyType_Ready() to populate the type's
4394 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004395 function slot (like tp_repr) that's defined in the type, one or more
4396 corresponding descriptors are added in the type's tp_dict dictionary
4397 under the appropriate name (like __repr__). Some function slots
4398 cause more than one descriptor to be added (for example, the nb_add
4399 slot adds both __add__ and __radd__ descriptors) and some function
4400 slots compete for the same descriptor (for example both sq_item and
4401 mp_subscript generate a __getitem__ descriptor).
4402
4403 In the latter case, the first slotdef entry encoutered wins. Since
4404 slotdef entries are sorted by the offset of the slot in the etype
4405 struct, this gives us some control over disambiguating between
4406 competing slots: the members of struct etype are listed from most
4407 general to least general, so the most general slot is preferred. In
4408 particular, because as_mapping comes before as_sequence, for a type
4409 that defines both mp_subscript and sq_item, mp_subscript wins.
4410
4411 This only adds new descriptors and doesn't overwrite entries in
4412 tp_dict that were previously defined. The descriptors contain a
4413 reference to the C function they must call, so that it's safe if they
4414 are copied into a subtype's __dict__ and the subtype has a different
4415 C function in its slot -- calling the method defined by the
4416 descriptor will call the C function that was used to create it,
4417 rather than the C function present in the slot when it is called.
4418 (This is important because a subtype may have a C function in the
4419 slot that calls the method from the dictionary, and we want to avoid
4420 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004421
4422static int
4423add_operators(PyTypeObject *type)
4424{
4425 PyObject *dict = type->tp_dict;
4426 slotdef *p;
4427 PyObject *descr;
4428 void **ptr;
4429
4430 init_slotdefs();
4431 for (p = slotdefs; p->name; p++) {
4432 if (p->wrapper == NULL)
4433 continue;
4434 ptr = slotptr(type, p->offset);
4435 if (!ptr || !*ptr)
4436 continue;
4437 if (PyDict_GetItem(dict, p->name_strobj))
4438 continue;
4439 descr = PyDescr_NewWrapper(type, p, *ptr);
4440 if (descr == NULL)
4441 return -1;
4442 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4443 return -1;
4444 Py_DECREF(descr);
4445 }
4446 if (type->tp_new != NULL) {
4447 if (add_tp_new_wrapper(type) < 0)
4448 return -1;
4449 }
4450 return 0;
4451}
4452
Guido van Rossum705f0f52001-08-24 16:47:00 +00004453
4454/* Cooperative 'super' */
4455
4456typedef struct {
4457 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004458 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004459 PyObject *obj;
4460} superobject;
4461
Guido van Rossum6f799372001-09-20 20:46:19 +00004462static PyMemberDef super_members[] = {
4463 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4464 "the class invoking super()"},
4465 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4466 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004467 {0}
4468};
4469
Guido van Rossum705f0f52001-08-24 16:47:00 +00004470static void
4471super_dealloc(PyObject *self)
4472{
4473 superobject *su = (superobject *)self;
4474
Guido van Rossum048eb752001-10-02 21:24:57 +00004475 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004476 Py_XDECREF(su->obj);
4477 Py_XDECREF(su->type);
4478 self->ob_type->tp_free(self);
4479}
4480
4481static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004482super_repr(PyObject *self)
4483{
4484 superobject *su = (superobject *)self;
4485
4486 if (su->obj)
4487 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004488 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004489 su->type ? su->type->tp_name : "NULL",
4490 su->obj->ob_type->tp_name);
4491 else
4492 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004493 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004494 su->type ? su->type->tp_name : "NULL");
4495}
4496
4497static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004498super_getattro(PyObject *self, PyObject *name)
4499{
4500 superobject *su = (superobject *)self;
4501
4502 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004503 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004504 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004505 descrgetfunc f;
4506 int i, n;
4507
Guido van Rossum155db9a2002-04-02 17:53:47 +00004508 starttype = su->obj->ob_type;
4509 mro = starttype->tp_mro;
4510
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004511 if (mro == NULL)
4512 n = 0;
4513 else {
4514 assert(PyTuple_Check(mro));
4515 n = PyTuple_GET_SIZE(mro);
4516 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004517 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004518 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004519 break;
4520 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004521 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004522 starttype = (PyTypeObject *)(su->obj);
4523 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004524 if (mro == NULL)
4525 n = 0;
4526 else {
4527 assert(PyTuple_Check(mro));
4528 n = PyTuple_GET_SIZE(mro);
4529 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004530 for (i = 0; i < n; i++) {
4531 if ((PyObject *)(su->type) ==
4532 PyTuple_GET_ITEM(mro, i))
4533 break;
4534 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004535 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004536 i++;
4537 res = NULL;
4538 for (; i < n; i++) {
4539 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004540 if (PyType_Check(tmp))
4541 dict = ((PyTypeObject *)tmp)->tp_dict;
4542 else if (PyClass_Check(tmp))
4543 dict = ((PyClassObject *)tmp)->cl_dict;
4544 else
4545 continue;
4546 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004547 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004548 Py_INCREF(res);
4549 f = res->ob_type->tp_descr_get;
4550 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004551 tmp = f(res, su->obj,
4552 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004553 Py_DECREF(res);
4554 res = tmp;
4555 }
4556 return res;
4557 }
4558 }
4559 }
4560 return PyObject_GenericGetAttr(self, name);
4561}
4562
Guido van Rossum5b443c62001-12-03 15:38:28 +00004563static int
4564supercheck(PyTypeObject *type, PyObject *obj)
4565{
4566 if (!PyType_IsSubtype(obj->ob_type, type) &&
4567 !(PyType_Check(obj) &&
4568 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4569 PyErr_SetString(PyExc_TypeError,
4570 "super(type, obj): "
4571 "obj must be an instance or subtype of type");
4572 return -1;
4573 }
4574 else
4575 return 0;
4576}
4577
Guido van Rossum705f0f52001-08-24 16:47:00 +00004578static PyObject *
4579super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4580{
4581 superobject *su = (superobject *)self;
4582 superobject *new;
4583
4584 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4585 /* Not binding to an object, or already bound */
4586 Py_INCREF(self);
4587 return self;
4588 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004589 if (su->ob_type != &PySuper_Type)
4590 /* If su is an instance of a subclass of super,
4591 call its type */
4592 return PyObject_CallFunction((PyObject *)su->ob_type,
4593 "OO", su->type, obj);
4594 else {
4595 /* Inline the common case */
4596 if (supercheck(su->type, obj) < 0)
4597 return NULL;
4598 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4599 NULL, NULL);
4600 if (new == NULL)
4601 return NULL;
4602 Py_INCREF(su->type);
4603 Py_INCREF(obj);
4604 new->type = su->type;
4605 new->obj = obj;
4606 return (PyObject *)new;
4607 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004608}
4609
4610static int
4611super_init(PyObject *self, PyObject *args, PyObject *kwds)
4612{
4613 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004614 PyTypeObject *type;
4615 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004616
4617 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4618 return -1;
4619 if (obj == Py_None)
4620 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004621 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004622 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004623 Py_INCREF(type);
4624 Py_XINCREF(obj);
4625 su->type = type;
4626 su->obj = obj;
4627 return 0;
4628}
4629
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004630PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00004631"super(type) -> unbound super object\n"
4632"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004633"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004634"Typical use to call a cooperative superclass method:\n"
4635"class C(B):\n"
4636" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004637" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00004638
Guido van Rossum048eb752001-10-02 21:24:57 +00004639static int
4640super_traverse(PyObject *self, visitproc visit, void *arg)
4641{
4642 superobject *su = (superobject *)self;
4643 int err;
4644
4645#define VISIT(SLOT) \
4646 if (SLOT) { \
4647 err = visit((PyObject *)(SLOT), arg); \
4648 if (err) \
4649 return err; \
4650 }
4651
4652 VISIT(su->obj);
4653 VISIT(su->type);
4654
4655#undef VISIT
4656
4657 return 0;
4658}
4659
Guido van Rossum705f0f52001-08-24 16:47:00 +00004660PyTypeObject PySuper_Type = {
4661 PyObject_HEAD_INIT(&PyType_Type)
4662 0, /* ob_size */
4663 "super", /* tp_name */
4664 sizeof(superobject), /* tp_basicsize */
4665 0, /* tp_itemsize */
4666 /* methods */
4667 super_dealloc, /* tp_dealloc */
4668 0, /* tp_print */
4669 0, /* tp_getattr */
4670 0, /* tp_setattr */
4671 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004672 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004673 0, /* tp_as_number */
4674 0, /* tp_as_sequence */
4675 0, /* tp_as_mapping */
4676 0, /* tp_hash */
4677 0, /* tp_call */
4678 0, /* tp_str */
4679 super_getattro, /* tp_getattro */
4680 0, /* tp_setattro */
4681 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004682 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4683 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004684 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004685 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004686 0, /* tp_clear */
4687 0, /* tp_richcompare */
4688 0, /* tp_weaklistoffset */
4689 0, /* tp_iter */
4690 0, /* tp_iternext */
4691 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004692 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004693 0, /* tp_getset */
4694 0, /* tp_base */
4695 0, /* tp_dict */
4696 super_descr_get, /* tp_descr_get */
4697 0, /* tp_descr_set */
4698 0, /* tp_dictoffset */
4699 super_init, /* tp_init */
4700 PyType_GenericAlloc, /* tp_alloc */
4701 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00004702 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004703};