blob: d49434448ab6996839f4c0c3abc73b6c6a083b52 [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
Jeremy Hylton938ace62002-07-17 16:30:39 +0000359static PyObject *lookup_maybe(PyObject *, char *, PyObject **);
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000360
361static int
362call_finalizer(PyObject *self)
363{
364 static PyObject *del_str = NULL;
365 PyObject *del, *res;
366 PyObject *error_type, *error_value, *error_traceback;
367
368 /* Temporarily resurrect the object. */
Tim Peters34592512002-07-11 06:23:50 +0000369 assert(self->ob_refcnt == 0);
370 self->ob_refcnt = 1;
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000371
372 /* Save the current exception, if any. */
373 PyErr_Fetch(&error_type, &error_value, &error_traceback);
374
375 /* Execute __del__ method, if any. */
376 del = lookup_maybe(self, "__del__", &del_str);
377 if (del != NULL) {
378 res = PyEval_CallObject(del, NULL);
379 if (res == NULL)
380 PyErr_WriteUnraisable(del);
381 else
382 Py_DECREF(res);
383 Py_DECREF(del);
384 }
385
386 /* Restore the saved exception. */
387 PyErr_Restore(error_type, error_value, error_traceback);
388
389 /* Undo the temporary resurrection; can't use DECREF here, it would
390 * cause a recursive call.
391 */
Tim Peters34592512002-07-11 06:23:50 +0000392 assert(self->ob_refcnt > 0);
393 if (--self->ob_refcnt == 0)
394 return 0; /* this is the normal path out */
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000395
Tim Peters34592512002-07-11 06:23:50 +0000396 /* __del__ resurrected it! Make it look like the original Py_DECREF
397 * never happened.
398 */
399 {
400 int refcnt = self->ob_refcnt;
401 _Py_NewReference(self);
402 self->ob_refcnt = refcnt;
403 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000404 assert(!PyType_IS_GC(self->ob_type) ||
405 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Tim Peters34592512002-07-11 06:23:50 +0000406 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
407 * _Py_NewReference bumped it again, so that's a wash.
408 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
409 * chain, so no more to do there either.
410 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
411 * _Py_NewReference bumped tp_allocs: both of those need to be
412 * undone.
413 */
414#ifdef COUNT_ALLOCS
415 --self->ob_type->tp_frees;
416 --self->ob_type->tp_allocs;
417#endif
418 return -1; /* __del__ added a reference; don't delete now */
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000419}
420
Tim Peters6d6c1a32001-08-02 04:15:00 +0000421static void
422subtype_dealloc(PyObject *self)
423{
Guido van Rossum14227b42001-12-06 02:35:58 +0000424 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000425 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000426
Guido van Rossum22b13872002-08-06 21:41:44 +0000427 /* Extract the type; we expect it to be a heap type */
428 type = self->ob_type;
429 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000430
Guido van Rossum22b13872002-08-06 21:41:44 +0000431 /* Test whether the type has GC exactly once */
432
433 if (!PyType_IS_GC(type)) {
434 /* It's really rare to find a dynamic type that doesn't have
435 GC; it can only happen when deriving from 'object' and not
436 adding any slots or instance variables. This allows
437 certain simplifications: there's no need to call
438 clear_slots(), or DECREF the dict, or clear weakrefs. */
439
440 /* Maybe call finalizer; exit early if resurrected */
441 if (call_finalizer(self) < 0)
442 return;
443
444 /* Find the nearest base with a different tp_dealloc */
445 base = type;
446 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
447 assert(base->ob_size == 0);
448 base = base->tp_base;
449 assert(base);
450 }
451
452 /* Call the base tp_dealloc() */
453 assert(basedealloc);
454 basedealloc(self);
455
456 /* Can't reference self beyond this point */
457 Py_DECREF(type);
458
459 /* Done */
460 return;
461 }
462
463 /* We get here only if the type has GC */
464
465 /* UnTrack and re-Track around the trashcan macro, alas */
Guido van Rossum0906e072002-08-07 20:42:09 +0000466 PyObject_GC_UnTrack(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000467 Py_TRASHCAN_SAFE_BEGIN(self);
468 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
469
470 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000471 if (call_finalizer(self) < 0)
Guido van Rossum0906e072002-08-07 20:42:09 +0000472 goto endlabel;
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000473
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000474 /* Find the nearest base with a different tp_dealloc
475 and clear slots while we're at it */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000476 base = type;
477 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
478 if (base->ob_size)
479 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000480 base = base->tp_base;
481 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000482 }
483
Tim Peters6d6c1a32001-08-02 04:15:00 +0000484 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000485 if (type->tp_dictoffset && !base->tp_dictoffset) {
486 PyObject **dictptr = _PyObject_GetDictPtr(self);
487 if (dictptr != NULL) {
488 PyObject *dict = *dictptr;
489 if (dict != NULL) {
490 Py_DECREF(dict);
491 *dictptr = NULL;
492 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000493 }
494 }
495
Guido van Rossum9676b222001-08-17 20:32:36 +0000496 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000497 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000498 PyObject_ClearWeakRefs(self);
499
Tim Peters6d6c1a32001-08-02 04:15:00 +0000500 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000501 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000502 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000503
504 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000505 assert(basedealloc);
506 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000507
508 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000509 Py_DECREF(type);
510
Guido van Rossum0906e072002-08-07 20:42:09 +0000511 endlabel:
Guido van Rossum22b13872002-08-06 21:41:44 +0000512 Py_TRASHCAN_SAFE_END(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000513}
514
Jeremy Hylton938ace62002-07-17 16:30:39 +0000515static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000516
Tim Peters6d6c1a32001-08-02 04:15:00 +0000517/* type test with subclassing support */
518
519int
520PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
521{
522 PyObject *mro;
523
Guido van Rossum9478d072001-09-07 18:52:13 +0000524 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
525 return b == a || b == &PyBaseObject_Type;
526
Tim Peters6d6c1a32001-08-02 04:15:00 +0000527 mro = a->tp_mro;
528 if (mro != NULL) {
529 /* Deal with multiple inheritance without recursion
530 by walking the MRO tuple */
531 int i, n;
532 assert(PyTuple_Check(mro));
533 n = PyTuple_GET_SIZE(mro);
534 for (i = 0; i < n; i++) {
535 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
536 return 1;
537 }
538 return 0;
539 }
540 else {
541 /* a is not completely initilized yet; follow tp_base */
542 do {
543 if (a == b)
544 return 1;
545 a = a->tp_base;
546 } while (a != NULL);
547 return b == &PyBaseObject_Type;
548 }
549}
550
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000551/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000552 without looking in the instance dictionary
553 (so we can't use PyObject_GetAttr) but still binding
554 it to the instance. The arguments are the object,
555 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000556 static variable used to cache the interned Python string.
557
558 Two variants:
559
560 - lookup_maybe() returns NULL without raising an exception
561 when the _PyType_Lookup() call fails;
562
563 - lookup_method() always raises an exception upon errors.
564*/
Guido van Rossum60718732001-08-28 17:47:51 +0000565
566static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000567lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000568{
569 PyObject *res;
570
571 if (*attrobj == NULL) {
572 *attrobj = PyString_InternFromString(attrstr);
573 if (*attrobj == NULL)
574 return NULL;
575 }
576 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000577 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000578 descrgetfunc f;
579 if ((f = res->ob_type->tp_descr_get) == NULL)
580 Py_INCREF(res);
581 else
582 res = f(res, self, (PyObject *)(self->ob_type));
583 }
584 return res;
585}
586
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000587static PyObject *
588lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
589{
590 PyObject *res = lookup_maybe(self, attrstr, attrobj);
591 if (res == NULL && !PyErr_Occurred())
592 PyErr_SetObject(PyExc_AttributeError, *attrobj);
593 return res;
594}
595
Guido van Rossum2730b132001-08-28 18:22:14 +0000596/* A variation of PyObject_CallMethod that uses lookup_method()
597 instead of PyObject_GetAttrString(). This uses the same convention
598 as lookup_method to cache the interned name string object. */
599
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000600static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000601call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
602{
603 va_list va;
604 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000605 va_start(va, format);
606
Guido van Rossumda21c012001-10-03 00:50:18 +0000607 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000608 if (func == NULL) {
609 va_end(va);
610 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000611 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000612 return NULL;
613 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000614
615 if (format && *format)
616 args = Py_VaBuildValue(format, va);
617 else
618 args = PyTuple_New(0);
619
620 va_end(va);
621
622 if (args == NULL)
623 return NULL;
624
625 assert(PyTuple_Check(args));
626 retval = PyObject_Call(func, args, NULL);
627
628 Py_DECREF(args);
629 Py_DECREF(func);
630
631 return retval;
632}
633
634/* Clone of call_method() that returns NotImplemented when the lookup fails. */
635
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000636static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000637call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
638{
639 va_list va;
640 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000641 va_start(va, format);
642
Guido van Rossumda21c012001-10-03 00:50:18 +0000643 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000644 if (func == NULL) {
645 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000646 if (!PyErr_Occurred()) {
647 Py_INCREF(Py_NotImplemented);
648 return Py_NotImplemented;
649 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000650 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000651 }
652
653 if (format && *format)
654 args = Py_VaBuildValue(format, va);
655 else
656 args = PyTuple_New(0);
657
658 va_end(va);
659
Guido van Rossum717ce002001-09-14 16:58:08 +0000660 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000661 return NULL;
662
Guido van Rossum717ce002001-09-14 16:58:08 +0000663 assert(PyTuple_Check(args));
664 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000665
666 Py_DECREF(args);
667 Py_DECREF(func);
668
669 return retval;
670}
671
Tim Peters6d6c1a32001-08-02 04:15:00 +0000672/* Method resolution order algorithm from "Putting Metaclasses to Work"
673 by Forman and Danforth (Addison-Wesley 1999). */
674
675static int
676conservative_merge(PyObject *left, PyObject *right)
677{
678 int left_size;
679 int right_size;
680 int i, j, r, ok;
681 PyObject *temp, *rr;
682
683 assert(PyList_Check(left));
684 assert(PyList_Check(right));
685
686 again:
687 left_size = PyList_GET_SIZE(left);
688 right_size = PyList_GET_SIZE(right);
689 for (i = 0; i < left_size; i++) {
690 for (j = 0; j < right_size; j++) {
691 if (PyList_GET_ITEM(left, i) ==
692 PyList_GET_ITEM(right, j)) {
693 /* found a merge point */
694 temp = PyList_New(0);
695 if (temp == NULL)
696 return -1;
697 for (r = 0; r < j; r++) {
698 rr = PyList_GET_ITEM(right, r);
699 ok = PySequence_Contains(left, rr);
700 if (ok < 0) {
701 Py_DECREF(temp);
702 return -1;
703 }
704 if (!ok) {
705 ok = PyList_Append(temp, rr);
706 if (ok < 0) {
707 Py_DECREF(temp);
708 return -1;
709 }
710 }
711 }
712 ok = PyList_SetSlice(left, i, i, temp);
713 Py_DECREF(temp);
714 if (ok < 0)
715 return -1;
716 ok = PyList_SetSlice(right, 0, j+1, NULL);
717 if (ok < 0)
718 return -1;
719 goto again;
720 }
721 }
722 }
723 return PyList_SetSlice(left, left_size, left_size, right);
724}
725
726static int
727serious_order_disagreements(PyObject *left, PyObject *right)
728{
729 return 0; /* XXX later -- for now, we cheat: "don't do that" */
730}
731
Tim Petersa91e9642001-11-14 23:32:33 +0000732static int
733fill_classic_mro(PyObject *mro, PyObject *cls)
734{
735 PyObject *bases, *base;
736 int i, n;
737
738 assert(PyList_Check(mro));
739 assert(PyClass_Check(cls));
740 i = PySequence_Contains(mro, cls);
741 if (i < 0)
742 return -1;
743 if (!i) {
744 if (PyList_Append(mro, cls) < 0)
745 return -1;
746 }
747 bases = ((PyClassObject *)cls)->cl_bases;
748 assert(bases && PyTuple_Check(bases));
749 n = PyTuple_GET_SIZE(bases);
750 for (i = 0; i < n; i++) {
751 base = PyTuple_GET_ITEM(bases, i);
752 if (fill_classic_mro(mro, base) < 0)
753 return -1;
754 }
755 return 0;
756}
757
758static PyObject *
759classic_mro(PyObject *cls)
760{
761 PyObject *mro;
762
763 assert(PyClass_Check(cls));
764 mro = PyList_New(0);
765 if (mro != NULL) {
766 if (fill_classic_mro(mro, cls) == 0)
767 return mro;
768 Py_DECREF(mro);
769 }
770 return NULL;
771}
772
Tim Peters6d6c1a32001-08-02 04:15:00 +0000773static PyObject *
774mro_implementation(PyTypeObject *type)
775{
776 int i, n, ok;
777 PyObject *bases, *result;
778
Guido van Rossum63517572002-06-18 16:44:57 +0000779 if(type->tp_dict == NULL) {
780 if(PyType_Ready(type) < 0)
781 return NULL;
782 }
783
Tim Peters6d6c1a32001-08-02 04:15:00 +0000784 bases = type->tp_bases;
785 n = PyTuple_GET_SIZE(bases);
786 result = Py_BuildValue("[O]", (PyObject *)type);
787 if (result == NULL)
788 return NULL;
789 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000790 PyObject *base = PyTuple_GET_ITEM(bases, i);
791 PyObject *parentMRO;
792 if (PyType_Check(base))
793 parentMRO = PySequence_List(
794 ((PyTypeObject*)base)->tp_mro);
795 else
796 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000797 if (parentMRO == NULL) {
798 Py_DECREF(result);
799 return NULL;
800 }
801 if (serious_order_disagreements(result, parentMRO)) {
802 Py_DECREF(result);
803 return NULL;
804 }
805 ok = conservative_merge(result, parentMRO);
806 Py_DECREF(parentMRO);
807 if (ok < 0) {
808 Py_DECREF(result);
809 return NULL;
810 }
811 }
812 return result;
813}
814
815static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000816mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000817{
818 PyTypeObject *type = (PyTypeObject *)self;
819
Tim Peters6d6c1a32001-08-02 04:15:00 +0000820 return mro_implementation(type);
821}
822
823static int
824mro_internal(PyTypeObject *type)
825{
826 PyObject *mro, *result, *tuple;
827
828 if (type->ob_type == &PyType_Type) {
829 result = mro_implementation(type);
830 }
831 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000832 static PyObject *mro_str;
833 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000834 if (mro == NULL)
835 return -1;
836 result = PyObject_CallObject(mro, NULL);
837 Py_DECREF(mro);
838 }
839 if (result == NULL)
840 return -1;
841 tuple = PySequence_Tuple(result);
842 Py_DECREF(result);
843 type->tp_mro = tuple;
844 return 0;
845}
846
847
848/* Calculate the best base amongst multiple base classes.
849 This is the first one that's on the path to the "solid base". */
850
851static PyTypeObject *
852best_base(PyObject *bases)
853{
854 int i, n;
855 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000856 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000857
858 assert(PyTuple_Check(bases));
859 n = PyTuple_GET_SIZE(bases);
860 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000861 base = NULL;
862 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000863 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000864 base_proto = PyTuple_GET_ITEM(bases, i);
865 if (PyClass_Check(base_proto))
866 continue;
867 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000868 PyErr_SetString(
869 PyExc_TypeError,
870 "bases must be types");
871 return NULL;
872 }
Tim Petersa91e9642001-11-14 23:32:33 +0000873 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000874 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000875 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000876 return NULL;
877 }
878 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000879 if (winner == NULL) {
880 winner = candidate;
881 base = base_i;
882 }
883 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000884 ;
885 else if (PyType_IsSubtype(candidate, winner)) {
886 winner = candidate;
887 base = base_i;
888 }
889 else {
890 PyErr_SetString(
891 PyExc_TypeError,
892 "multiple bases have "
893 "instance lay-out conflict");
894 return NULL;
895 }
896 }
Guido van Rossume54616c2001-12-14 04:19:56 +0000897 if (base == NULL)
898 PyErr_SetString(PyExc_TypeError,
899 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000900 return base;
901}
902
903static int
904extra_ivars(PyTypeObject *type, PyTypeObject *base)
905{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000906 size_t t_size = type->tp_basicsize;
907 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000908
Guido van Rossum9676b222001-08-17 20:32:36 +0000909 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000910 if (type->tp_itemsize || base->tp_itemsize) {
911 /* If itemsize is involved, stricter rules */
912 return t_size != b_size ||
913 type->tp_itemsize != base->tp_itemsize;
914 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000915 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
916 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
917 t_size -= sizeof(PyObject *);
918 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
919 type->tp_dictoffset + sizeof(PyObject *) == t_size)
920 t_size -= sizeof(PyObject *);
921
922 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000923}
924
925static PyTypeObject *
926solid_base(PyTypeObject *type)
927{
928 PyTypeObject *base;
929
930 if (type->tp_base)
931 base = solid_base(type->tp_base);
932 else
933 base = &PyBaseObject_Type;
934 if (extra_ivars(type, base))
935 return type;
936 else
937 return base;
938}
939
Jeremy Hylton938ace62002-07-17 16:30:39 +0000940static void object_dealloc(PyObject *);
941static int object_init(PyObject *, PyObject *, PyObject *);
942static int update_slot(PyTypeObject *, PyObject *);
943static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000944
945static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000946subtype_dict(PyObject *obj, void *context)
947{
948 PyObject **dictptr = _PyObject_GetDictPtr(obj);
949 PyObject *dict;
950
951 if (dictptr == NULL) {
952 PyErr_SetString(PyExc_AttributeError,
953 "This object has no __dict__");
954 return NULL;
955 }
956 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000957 if (dict == NULL)
958 *dictptr = dict = PyDict_New();
959 Py_XINCREF(dict);
960 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000961}
962
Guido van Rossum6661be32001-10-26 04:26:12 +0000963static int
964subtype_setdict(PyObject *obj, PyObject *value, void *context)
965{
966 PyObject **dictptr = _PyObject_GetDictPtr(obj);
967 PyObject *dict;
968
969 if (dictptr == NULL) {
970 PyErr_SetString(PyExc_AttributeError,
971 "This object has no __dict__");
972 return -1;
973 }
Guido van Rossumd331cb52001-12-05 19:46:42 +0000974 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +0000975 PyErr_SetString(PyExc_TypeError,
976 "__dict__ must be set to a dictionary");
977 return -1;
978 }
979 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +0000980 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +0000981 *dictptr = value;
982 Py_XDECREF(dict);
983 return 0;
984}
985
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000986static PyGetSetDef subtype_getsets[] = {
Guido van Rossum6661be32001-10-26 04:26:12 +0000987 {"__dict__", subtype_dict, subtype_setdict, NULL},
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000988 {0},
989};
990
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000991/* bozo: __getstate__ that raises TypeError */
992
993static PyObject *
994bozo_func(PyObject *self, PyObject *args)
995{
996 PyErr_SetString(PyExc_TypeError,
997 "a class that defines __slots__ without "
998 "defining __getstate__ cannot be pickled");
999 return NULL;
1000}
1001
Neal Norwitz93c1e232002-03-31 16:06:11 +00001002static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001003
1004static PyObject *bozo_obj = NULL;
1005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001006static int
1007valid_identifier(PyObject *s)
1008{
Guido van Rossum03013a02002-07-16 14:30:28 +00001009 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001010 int i, n;
1011
1012 if (!PyString_Check(s)) {
1013 PyErr_SetString(PyExc_TypeError,
1014 "__slots__ must be strings");
1015 return 0;
1016 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001017 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001018 n = PyString_GET_SIZE(s);
1019 /* We must reject an empty name. As a hack, we bump the
1020 length to 1 so that the loop will balk on the trailing \0. */
1021 if (n == 0)
1022 n = 1;
1023 for (i = 0; i < n; i++, p++) {
1024 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1025 PyErr_SetString(PyExc_TypeError,
1026 "__slots__ must be identifiers");
1027 return 0;
1028 }
1029 }
1030 return 1;
1031}
1032
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001033static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001034type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1035{
1036 PyObject *name, *bases, *dict;
1037 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001038 static char buffer[256];
1039 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001040 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001041 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001042 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001043 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001044
Tim Peters3abca122001-10-27 19:37:48 +00001045 assert(args != NULL && PyTuple_Check(args));
1046 assert(kwds == NULL || PyDict_Check(kwds));
1047
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001048 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001049 {
1050 const int nargs = PyTuple_GET_SIZE(args);
1051 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1052
1053 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1054 PyObject *x = PyTuple_GET_ITEM(args, 0);
1055 Py_INCREF(x->ob_type);
1056 return (PyObject *) x->ob_type;
1057 }
1058
1059 /* SF bug 475327 -- if that didn't trigger, we need 3
1060 arguments. but PyArg_ParseTupleAndKeywords below may give
1061 a msg saying type() needs exactly 3. */
1062 if (nargs + nkwds != 3) {
1063 PyErr_SetString(PyExc_TypeError,
1064 "type() takes 1 or 3 arguments");
1065 return NULL;
1066 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001067 }
1068
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001069 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001070 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1071 &name,
1072 &PyTuple_Type, &bases,
1073 &PyDict_Type, &dict))
1074 return NULL;
1075
1076 /* Determine the proper metatype to deal with this,
1077 and check for metatype conflicts while we're at it.
1078 Note that if some other metatype wins to contract,
1079 it's possible that its instances are not types. */
1080 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001081 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001082 for (i = 0; i < nbases; i++) {
1083 tmp = PyTuple_GET_ITEM(bases, i);
1084 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001085 if (tmptype == &PyClass_Type)
1086 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001087 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001088 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001089 if (PyType_IsSubtype(tmptype, winner)) {
1090 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001091 continue;
1092 }
1093 PyErr_SetString(PyExc_TypeError,
1094 "metatype conflict among bases");
1095 return NULL;
1096 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001097 if (winner != metatype) {
1098 if (winner->tp_new != type_new) /* Pass it to the winner */
1099 return winner->tp_new(winner, args, kwds);
1100 metatype = winner;
1101 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001102
1103 /* Adjust for empty tuple bases */
1104 if (nbases == 0) {
1105 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1106 if (bases == NULL)
1107 return NULL;
1108 nbases = 1;
1109 }
1110 else
1111 Py_INCREF(bases);
1112
1113 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1114
1115 /* Calculate best base, and check that all bases are type objects */
1116 base = best_base(bases);
1117 if (base == NULL)
1118 return NULL;
1119 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1120 PyErr_Format(PyExc_TypeError,
1121 "type '%.100s' is not an acceptable base type",
1122 base->tp_name);
1123 return NULL;
1124 }
1125
Tim Peters6d6c1a32001-08-02 04:15:00 +00001126 /* Check for a __slots__ sequence variable in dict, and count it */
1127 slots = PyDict_GetItemString(dict, "__slots__");
1128 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001129 add_dict = 0;
1130 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001131 if (slots != NULL) {
1132 /* Make it into a tuple */
1133 if (PyString_Check(slots))
1134 slots = Py_BuildValue("(O)", slots);
1135 else
1136 slots = PySequence_Tuple(slots);
1137 if (slots == NULL)
1138 return NULL;
1139 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001140 if (nslots > 0 && base->tp_itemsize != 0) {
1141 PyErr_Format(PyExc_TypeError,
1142 "nonempty __slots__ "
1143 "not supported for subtype of '%s'",
1144 base->tp_name);
1145 return NULL;
1146 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001147 for (i = 0; i < nslots; i++) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001148 if (!valid_identifier(PyTuple_GET_ITEM(slots, i))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001149 Py_DECREF(slots);
1150 return NULL;
1151 }
1152 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001153
1154 newslots = PyTuple_New(nslots);
1155 if (newslots == NULL)
1156 return NULL;
1157 for (i = 0; i < nslots; i++) {
1158 tmp = PyTuple_GET_ITEM(slots, i);
1159 if (_Py_Mangle(PyString_AS_STRING(name),
1160 PyString_AS_STRING(tmp),
1161 buffer, sizeof(buffer)))
1162 {
1163 tmp = PyString_FromString(buffer);
1164 } else {
1165 Py_INCREF(tmp);
1166 }
1167 PyTuple_SET_ITEM(newslots, i, tmp);
1168 }
1169 Py_DECREF(slots);
1170 slots = newslots;
1171
Tim Peters6d6c1a32001-08-02 04:15:00 +00001172 }
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001173 if (slots != NULL) {
1174 /* See if *this* class defines __getstate__ */
1175 PyObject *getstate = PyDict_GetItemString(dict,
1176 "__getstate__");
1177 if (getstate == NULL) {
1178 /* If not, provide a bozo that raises TypeError */
1179 if (bozo_obj == NULL) {
1180 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
1181 if (bozo_obj == NULL) {
1182 /* XXX decref various things */
1183 return NULL;
1184 }
1185 }
1186 if (PyDict_SetItemString(dict,
1187 "__getstate__",
1188 bozo_obj) < 0) {
1189 /* XXX decref various things */
1190 return NULL;
1191 }
1192 }
1193 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001194 if (slots == NULL && base->tp_dictoffset == 0 &&
1195 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +00001196 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001197 add_dict++;
1198 }
Guido van Rossumc4141872001-08-30 04:43:35 +00001199 if (slots == NULL && base->tp_weaklistoffset == 0 &&
1200 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001201 nslots++;
1202 add_weak++;
1203 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001204
1205 /* XXX From here until type is safely allocated,
1206 "return NULL" may leak slots! */
1207
1208 /* Allocate the type object */
1209 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
1210 if (type == NULL)
1211 return NULL;
1212
1213 /* Keep name and slots alive in the extended type object */
1214 et = (etype *)type;
1215 Py_INCREF(name);
1216 et->name = name;
1217 et->slots = slots;
1218
Guido van Rossumdc91b992001-08-08 22:26:22 +00001219 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001220 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1221 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001222 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1223 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001224
1225 /* It's a new-style number unless it specifically inherits any
1226 old-style numeric behavior */
1227 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1228 (base->tp_as_number == NULL))
1229 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1230
1231 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001232 type->tp_as_number = &et->as_number;
1233 type->tp_as_sequence = &et->as_sequence;
1234 type->tp_as_mapping = &et->as_mapping;
1235 type->tp_as_buffer = &et->as_buffer;
1236 type->tp_name = PyString_AS_STRING(name);
1237
1238 /* Set tp_base and tp_bases */
1239 type->tp_bases = bases;
1240 Py_INCREF(base);
1241 type->tp_base = base;
1242
Guido van Rossum687ae002001-10-15 22:03:32 +00001243 /* Initialize tp_dict from passed-in dict */
1244 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001245 if (dict == NULL) {
1246 Py_DECREF(type);
1247 return NULL;
1248 }
1249
Guido van Rossumc3542212001-08-16 09:18:56 +00001250 /* Set __module__ in the dict */
1251 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1252 tmp = PyEval_GetGlobals();
1253 if (tmp != NULL) {
1254 tmp = PyDict_GetItemString(tmp, "__name__");
1255 if (tmp != NULL) {
1256 if (PyDict_SetItemString(dict, "__module__",
1257 tmp) < 0)
1258 return NULL;
1259 }
1260 }
1261 }
1262
Tim Peters2f93e282001-10-04 05:27:00 +00001263 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001264 and is a string. The __doc__ accessor will first look for tp_doc;
1265 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001266 */
1267 {
1268 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1269 if (doc != NULL && PyString_Check(doc)) {
1270 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001271 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001272 if (type->tp_doc == NULL) {
1273 Py_DECREF(type);
1274 return NULL;
1275 }
1276 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1277 }
1278 }
1279
Tim Peters6d6c1a32001-08-02 04:15:00 +00001280 /* Special-case __new__: if it's a plain function,
1281 make it a static function */
1282 tmp = PyDict_GetItemString(dict, "__new__");
1283 if (tmp != NULL && PyFunction_Check(tmp)) {
1284 tmp = PyStaticMethod_New(tmp);
1285 if (tmp == NULL) {
1286 Py_DECREF(type);
1287 return NULL;
1288 }
1289 PyDict_SetItemString(dict, "__new__", tmp);
1290 Py_DECREF(tmp);
1291 }
1292
1293 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1294 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001295 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001296 if (slots != NULL) {
1297 for (i = 0; i < nslots; i++, mp++) {
1298 mp->name = PyString_AS_STRING(
1299 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001300 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001301 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001302 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001303 strcmp(mp->name, "__weakref__") == 0) {
1304 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001305 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001306 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001307 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001308 slotoffset += sizeof(PyObject *);
1309 }
1310 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001311 else {
1312 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001313 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +00001314 type->tp_dictoffset =
1315 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001316 else
1317 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001318 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001319 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +00001320 }
1321 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001322 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +00001323 type->tp_weaklistoffset = slotoffset;
1324 mp->name = "__weakref__";
1325 mp->type = T_OBJECT;
1326 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +00001327 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001328 mp++;
1329 slotoffset += sizeof(PyObject *);
1330 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001331 }
1332 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001333 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001334 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001335
1336 /* Special case some slots */
1337 if (type->tp_dictoffset != 0 || nslots > 0) {
1338 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1339 type->tp_getattro = PyObject_GenericGetAttr;
1340 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1341 type->tp_setattro = PyObject_GenericSetAttr;
1342 }
1343 type->tp_dealloc = subtype_dealloc;
1344
Guido van Rossum9475a232001-10-05 20:51:39 +00001345 /* Enable GC unless there are really no instance variables possible */
1346 if (!(type->tp_basicsize == sizeof(PyObject) &&
1347 type->tp_itemsize == 0))
1348 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1349
Tim Peters6d6c1a32001-08-02 04:15:00 +00001350 /* Always override allocation strategy to use regular heap */
1351 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001352 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001353 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001354 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001355 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001356 }
1357 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001358 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001359
1360 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001361 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001362 Py_DECREF(type);
1363 return NULL;
1364 }
1365
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001366 /* Put the proper slots in place */
1367 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001368
Tim Peters6d6c1a32001-08-02 04:15:00 +00001369 return (PyObject *)type;
1370}
1371
1372/* Internal API to look for a name through the MRO.
1373 This returns a borrowed reference, and doesn't set an exception! */
1374PyObject *
1375_PyType_Lookup(PyTypeObject *type, PyObject *name)
1376{
1377 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001378 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001379
Guido van Rossum687ae002001-10-15 22:03:32 +00001380 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001381 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001382
1383 /* If mro is NULL, the type is either not yet initialized
1384 by PyType_Ready(), or already cleared by type_clear().
1385 Either way the safest thing to do is to return NULL. */
1386 if (mro == NULL)
1387 return NULL;
1388
Tim Peters6d6c1a32001-08-02 04:15:00 +00001389 assert(PyTuple_Check(mro));
1390 n = PyTuple_GET_SIZE(mro);
1391 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001392 base = PyTuple_GET_ITEM(mro, i);
1393 if (PyClass_Check(base))
1394 dict = ((PyClassObject *)base)->cl_dict;
1395 else {
1396 assert(PyType_Check(base));
1397 dict = ((PyTypeObject *)base)->tp_dict;
1398 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001399 assert(dict && PyDict_Check(dict));
1400 res = PyDict_GetItem(dict, name);
1401 if (res != NULL)
1402 return res;
1403 }
1404 return NULL;
1405}
1406
1407/* This is similar to PyObject_GenericGetAttr(),
1408 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1409static PyObject *
1410type_getattro(PyTypeObject *type, PyObject *name)
1411{
1412 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001413 PyObject *meta_attribute, *attribute;
1414 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001415
1416 /* Initialize this type (we'll assume the metatype is initialized) */
1417 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001418 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001419 return NULL;
1420 }
1421
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001422 /* No readable descriptor found yet */
1423 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001424
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001425 /* Look for the attribute in the metatype */
1426 meta_attribute = _PyType_Lookup(metatype, name);
1427
1428 if (meta_attribute != NULL) {
1429 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001430
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001431 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1432 /* Data descriptors implement tp_descr_set to intercept
1433 * writes. Assume the attribute is not overridden in
1434 * type's tp_dict (and bases): call the descriptor now.
1435 */
1436 return meta_get(meta_attribute, (PyObject *)type,
1437 (PyObject *)metatype);
1438 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001439 }
1440
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001441 /* No data descriptor found on metatype. Look in tp_dict of this
1442 * type and its bases */
1443 attribute = _PyType_Lookup(type, name);
1444 if (attribute != NULL) {
1445 /* Implement descriptor functionality, if any */
1446 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1447 if (local_get != NULL) {
1448 /* NULL 2nd argument indicates the descriptor was
1449 * found on the target object itself (or a base) */
1450 return local_get(attribute, (PyObject *)NULL,
1451 (PyObject *)type);
1452 }
Tim Peters34592512002-07-11 06:23:50 +00001453
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001454 Py_INCREF(attribute);
1455 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001456 }
1457
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001458 /* No attribute found in local __dict__ (or bases): use the
1459 * descriptor from the metatype, if any */
1460 if (meta_get != NULL)
1461 return meta_get(meta_attribute, (PyObject *)type,
1462 (PyObject *)metatype);
1463
1464 /* If an ordinary attribute was found on the metatype, return it now */
1465 if (meta_attribute != NULL) {
1466 Py_INCREF(meta_attribute);
1467 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001468 }
1469
1470 /* Give up */
1471 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001472 "type object '%.50s' has no attribute '%.400s'",
1473 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001474 return NULL;
1475}
1476
1477static int
1478type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1479{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001480 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1481 PyErr_Format(
1482 PyExc_TypeError,
1483 "can't set attributes of built-in/extension type '%s'",
1484 type->tp_name);
1485 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001486 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001487 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1488 return -1;
1489 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001490}
1491
1492static void
1493type_dealloc(PyTypeObject *type)
1494{
1495 etype *et;
1496
1497 /* Assert this is a heap-allocated type object */
1498 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001499 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001500 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001501 et = (etype *)type;
1502 Py_XDECREF(type->tp_base);
1503 Py_XDECREF(type->tp_dict);
1504 Py_XDECREF(type->tp_bases);
1505 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001506 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001507 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00001508 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001509 Py_XDECREF(et->name);
1510 Py_XDECREF(et->slots);
1511 type->ob_type->tp_free((PyObject *)type);
1512}
1513
Guido van Rossum1c450732001-10-08 15:18:27 +00001514static PyObject *
1515type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1516{
1517 PyObject *list, *raw, *ref;
1518 int i, n;
1519
1520 list = PyList_New(0);
1521 if (list == NULL)
1522 return NULL;
1523 raw = type->tp_subclasses;
1524 if (raw == NULL)
1525 return list;
1526 assert(PyList_Check(raw));
1527 n = PyList_GET_SIZE(raw);
1528 for (i = 0; i < n; i++) {
1529 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001530 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001531 ref = PyWeakref_GET_OBJECT(ref);
1532 if (ref != Py_None) {
1533 if (PyList_Append(list, ref) < 0) {
1534 Py_DECREF(list);
1535 return NULL;
1536 }
1537 }
1538 }
1539 return list;
1540}
1541
Tim Peters6d6c1a32001-08-02 04:15:00 +00001542static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001543 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001544 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001545 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1546 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001547 {0}
1548};
1549
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001550PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001551"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001552"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001553
Guido van Rossum048eb752001-10-02 21:24:57 +00001554static int
1555type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1556{
Guido van Rossum048eb752001-10-02 21:24:57 +00001557 int err;
1558
Guido van Rossuma3862092002-06-10 15:24:42 +00001559 /* Because of type_is_gc(), the collector only calls this
1560 for heaptypes. */
1561 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001562
1563#define VISIT(SLOT) \
1564 if (SLOT) { \
1565 err = visit((PyObject *)(SLOT), arg); \
1566 if (err) \
1567 return err; \
1568 }
1569
1570 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001571 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001572 VISIT(type->tp_mro);
1573 VISIT(type->tp_bases);
1574 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00001575
1576 /* There's no need to visit type->tp_subclasses or
1577 ((etype *)type)->slots, because they can't be involved
1578 in cycles; tp_subclasses is a list of weak references,
1579 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00001580
1581#undef VISIT
1582
1583 return 0;
1584}
1585
1586static int
1587type_clear(PyTypeObject *type)
1588{
Guido van Rossum048eb752001-10-02 21:24:57 +00001589 PyObject *tmp;
1590
Guido van Rossuma3862092002-06-10 15:24:42 +00001591 /* Because of type_is_gc(), the collector only calls this
1592 for heaptypes. */
1593 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001594
1595#define CLEAR(SLOT) \
1596 if (SLOT) { \
1597 tmp = (PyObject *)(SLOT); \
1598 SLOT = NULL; \
1599 Py_DECREF(tmp); \
1600 }
1601
Guido van Rossuma3862092002-06-10 15:24:42 +00001602 /* The only field we need to clear is tp_mro, which is part of a
1603 hard cycle (its first element is the class itself) that won't
1604 be broken otherwise (it's a tuple and tuples don't have a
1605 tp_clear handler). None of the other fields need to be
1606 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00001607
Guido van Rossuma3862092002-06-10 15:24:42 +00001608 tp_dict:
1609 It is a dict, so the collector will call its tp_clear.
1610
1611 tp_cache:
1612 Not used; if it were, it would be a dict.
1613
1614 tp_bases, tp_base:
1615 If these are involved in a cycle, there must be at least
1616 one other, mutable object in the cycle, e.g. a base
1617 class's dict; the cycle will be broken that way.
1618
1619 tp_subclasses:
1620 A list of weak references can't be part of a cycle; and
1621 lists have their own tp_clear.
1622
1623 slots (in etype):
1624 A tuple of strings can't be part of a cycle.
1625 */
1626
1627 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00001628
Guido van Rossum048eb752001-10-02 21:24:57 +00001629#undef CLEAR
1630
1631 return 0;
1632}
1633
1634static int
1635type_is_gc(PyTypeObject *type)
1636{
1637 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1638}
1639
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001640PyTypeObject PyType_Type = {
1641 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001642 0, /* ob_size */
1643 "type", /* tp_name */
1644 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001645 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001646 (destructor)type_dealloc, /* tp_dealloc */
1647 0, /* tp_print */
1648 0, /* tp_getattr */
1649 0, /* tp_setattr */
1650 type_compare, /* tp_compare */
1651 (reprfunc)type_repr, /* tp_repr */
1652 0, /* tp_as_number */
1653 0, /* tp_as_sequence */
1654 0, /* tp_as_mapping */
1655 (hashfunc)_Py_HashPointer, /* tp_hash */
1656 (ternaryfunc)type_call, /* tp_call */
1657 0, /* tp_str */
1658 (getattrofunc)type_getattro, /* tp_getattro */
1659 (setattrofunc)type_setattro, /* tp_setattro */
1660 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001661 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1662 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001663 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001664 (traverseproc)type_traverse, /* tp_traverse */
1665 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001666 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001667 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001668 0, /* tp_iter */
1669 0, /* tp_iternext */
1670 type_methods, /* tp_methods */
1671 type_members, /* tp_members */
1672 type_getsets, /* tp_getset */
1673 0, /* tp_base */
1674 0, /* tp_dict */
1675 0, /* tp_descr_get */
1676 0, /* tp_descr_set */
1677 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1678 0, /* tp_init */
1679 0, /* tp_alloc */
1680 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001681 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00001682 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001683};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001684
1685
1686/* The base type of all types (eventually)... except itself. */
1687
1688static int
1689object_init(PyObject *self, PyObject *args, PyObject *kwds)
1690{
1691 return 0;
1692}
1693
1694static void
1695object_dealloc(PyObject *self)
1696{
1697 self->ob_type->tp_free(self);
1698}
1699
Guido van Rossum8e248182001-08-12 05:17:56 +00001700static PyObject *
1701object_repr(PyObject *self)
1702{
Guido van Rossum76e69632001-08-16 18:52:43 +00001703 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001704 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001705
Guido van Rossum76e69632001-08-16 18:52:43 +00001706 type = self->ob_type;
1707 mod = type_module(type, NULL);
1708 if (mod == NULL)
1709 PyErr_Clear();
1710 else if (!PyString_Check(mod)) {
1711 Py_DECREF(mod);
1712 mod = NULL;
1713 }
1714 name = type_name(type, NULL);
1715 if (name == NULL)
1716 return NULL;
1717 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001718 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001719 PyString_AS_STRING(mod),
1720 PyString_AS_STRING(name),
1721 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001722 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001723 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001724 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001725 Py_XDECREF(mod);
1726 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001727 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001728}
1729
Guido van Rossumb8f63662001-08-15 23:57:02 +00001730static PyObject *
1731object_str(PyObject *self)
1732{
1733 unaryfunc f;
1734
1735 f = self->ob_type->tp_repr;
1736 if (f == NULL)
1737 f = object_repr;
1738 return f(self);
1739}
1740
Guido van Rossum8e248182001-08-12 05:17:56 +00001741static long
1742object_hash(PyObject *self)
1743{
1744 return _Py_HashPointer(self);
1745}
Guido van Rossum8e248182001-08-12 05:17:56 +00001746
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001747static PyObject *
1748object_get_class(PyObject *self, void *closure)
1749{
1750 Py_INCREF(self->ob_type);
1751 return (PyObject *)(self->ob_type);
1752}
1753
1754static int
1755equiv_structs(PyTypeObject *a, PyTypeObject *b)
1756{
1757 return a == b ||
1758 (a != NULL &&
1759 b != NULL &&
1760 a->tp_basicsize == b->tp_basicsize &&
1761 a->tp_itemsize == b->tp_itemsize &&
1762 a->tp_dictoffset == b->tp_dictoffset &&
1763 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1764 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1765 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1766}
1767
1768static int
1769same_slots_added(PyTypeObject *a, PyTypeObject *b)
1770{
1771 PyTypeObject *base = a->tp_base;
1772 int size;
1773
1774 if (base != b->tp_base)
1775 return 0;
1776 if (equiv_structs(a, base) && equiv_structs(b, base))
1777 return 1;
1778 size = base->tp_basicsize;
1779 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1780 size += sizeof(PyObject *);
1781 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1782 size += sizeof(PyObject *);
1783 return size == a->tp_basicsize && size == b->tp_basicsize;
1784}
1785
1786static int
1787object_set_class(PyObject *self, PyObject *value, void *closure)
1788{
1789 PyTypeObject *old = self->ob_type;
1790 PyTypeObject *new, *newbase, *oldbase;
1791
Guido van Rossumb6b89422002-04-15 01:03:30 +00001792 if (value == NULL) {
1793 PyErr_SetString(PyExc_TypeError,
1794 "can't delete __class__ attribute");
1795 return -1;
1796 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001797 if (!PyType_Check(value)) {
1798 PyErr_Format(PyExc_TypeError,
1799 "__class__ must be set to new-style class, not '%s' object",
1800 value->ob_type->tp_name);
1801 return -1;
1802 }
1803 new = (PyTypeObject *)value;
Guido van Rossum9ee4b942002-05-24 18:47:47 +00001804 if (new->tp_dealloc != old->tp_dealloc ||
1805 new->tp_free != old->tp_free)
1806 {
1807 PyErr_Format(PyExc_TypeError,
1808 "__class__ assignment: "
1809 "'%s' deallocator differs from '%s'",
1810 new->tp_name,
1811 old->tp_name);
1812 return -1;
1813 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001814 newbase = new;
1815 oldbase = old;
1816 while (equiv_structs(newbase, newbase->tp_base))
1817 newbase = newbase->tp_base;
1818 while (equiv_structs(oldbase, oldbase->tp_base))
1819 oldbase = oldbase->tp_base;
1820 if (newbase != oldbase &&
1821 (newbase->tp_base != oldbase->tp_base ||
1822 !same_slots_added(newbase, oldbase))) {
1823 PyErr_Format(PyExc_TypeError,
1824 "__class__ assignment: "
1825 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001826 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001827 old->tp_name);
1828 return -1;
1829 }
1830 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1831 Py_INCREF(new);
1832 }
1833 self->ob_type = new;
1834 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1835 Py_DECREF(old);
1836 }
1837 return 0;
1838}
1839
1840static PyGetSetDef object_getsets[] = {
1841 {"__class__", object_get_class, object_set_class,
1842 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001843 {0}
1844};
1845
Guido van Rossum3926a632001-09-25 16:25:58 +00001846static PyObject *
1847object_reduce(PyObject *self, PyObject *args)
1848{
1849 /* Call copy_reg._reduce(self) */
1850 static PyObject *copy_reg_str;
1851 PyObject *copy_reg, *res;
1852
1853 if (!copy_reg_str) {
1854 copy_reg_str = PyString_InternFromString("copy_reg");
1855 if (copy_reg_str == NULL)
1856 return NULL;
1857 }
1858 copy_reg = PyImport_Import(copy_reg_str);
1859 if (!copy_reg)
1860 return NULL;
1861 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1862 Py_DECREF(copy_reg);
1863 return res;
1864}
1865
1866static PyMethodDef object_methods[] = {
1867 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1868 {0}
1869};
1870
Tim Peters6d6c1a32001-08-02 04:15:00 +00001871PyTypeObject PyBaseObject_Type = {
1872 PyObject_HEAD_INIT(&PyType_Type)
1873 0, /* ob_size */
1874 "object", /* tp_name */
1875 sizeof(PyObject), /* tp_basicsize */
1876 0, /* tp_itemsize */
1877 (destructor)object_dealloc, /* tp_dealloc */
1878 0, /* tp_print */
1879 0, /* tp_getattr */
1880 0, /* tp_setattr */
1881 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001882 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001883 0, /* tp_as_number */
1884 0, /* tp_as_sequence */
1885 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001886 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001887 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001888 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001889 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001890 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001891 0, /* tp_as_buffer */
1892 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1893 "The most base type", /* tp_doc */
1894 0, /* tp_traverse */
1895 0, /* tp_clear */
1896 0, /* tp_richcompare */
1897 0, /* tp_weaklistoffset */
1898 0, /* tp_iter */
1899 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001900 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001901 0, /* tp_members */
1902 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001903 0, /* tp_base */
1904 0, /* tp_dict */
1905 0, /* tp_descr_get */
1906 0, /* tp_descr_set */
1907 0, /* tp_dictoffset */
1908 object_init, /* tp_init */
1909 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001910 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001911 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001912};
1913
1914
1915/* Initialize the __dict__ in a type object */
1916
Fred Drake7bf97152002-03-28 05:33:33 +00001917static PyObject *
1918create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
1919{
1920 PyObject *cfunc;
1921 PyObject *result;
1922
1923 cfunc = PyCFunction_New(meth, NULL);
1924 if (cfunc == NULL)
1925 return NULL;
1926 result = func(cfunc);
1927 Py_DECREF(cfunc);
1928 return result;
1929}
1930
Tim Peters6d6c1a32001-08-02 04:15:00 +00001931static int
1932add_methods(PyTypeObject *type, PyMethodDef *meth)
1933{
Guido van Rossum687ae002001-10-15 22:03:32 +00001934 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001935
1936 for (; meth->ml_name != NULL; meth++) {
1937 PyObject *descr;
1938 if (PyDict_GetItemString(dict, meth->ml_name))
1939 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00001940 if (meth->ml_flags & METH_CLASS) {
1941 if (meth->ml_flags & METH_STATIC) {
1942 PyErr_SetString(PyExc_ValueError,
1943 "method cannot be both class and static");
1944 return -1;
1945 }
1946 descr = create_specialmethod(meth, PyClassMethod_New);
1947 }
1948 else if (meth->ml_flags & METH_STATIC) {
1949 descr = create_specialmethod(meth, PyStaticMethod_New);
1950 }
1951 else {
1952 descr = PyDescr_NewMethod(type, meth);
1953 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001954 if (descr == NULL)
1955 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00001956 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001957 return -1;
1958 Py_DECREF(descr);
1959 }
1960 return 0;
1961}
1962
1963static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001964add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001965{
Guido van Rossum687ae002001-10-15 22:03:32 +00001966 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001967
1968 for (; memb->name != NULL; memb++) {
1969 PyObject *descr;
1970 if (PyDict_GetItemString(dict, memb->name))
1971 continue;
1972 descr = PyDescr_NewMember(type, memb);
1973 if (descr == NULL)
1974 return -1;
1975 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1976 return -1;
1977 Py_DECREF(descr);
1978 }
1979 return 0;
1980}
1981
1982static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001983add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001984{
Guido van Rossum687ae002001-10-15 22:03:32 +00001985 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001986
1987 for (; gsp->name != NULL; gsp++) {
1988 PyObject *descr;
1989 if (PyDict_GetItemString(dict, gsp->name))
1990 continue;
1991 descr = PyDescr_NewGetSet(type, gsp);
1992
1993 if (descr == NULL)
1994 return -1;
1995 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1996 return -1;
1997 Py_DECREF(descr);
1998 }
1999 return 0;
2000}
2001
Guido van Rossum13d52f02001-08-10 21:24:08 +00002002static void
2003inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002004{
2005 int oldsize, newsize;
2006
Guido van Rossum13d52f02001-08-10 21:24:08 +00002007 /* Special flag magic */
2008 if (!type->tp_as_buffer && base->tp_as_buffer) {
2009 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2010 type->tp_flags |=
2011 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2012 }
2013 if (!type->tp_as_sequence && base->tp_as_sequence) {
2014 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2015 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2016 }
2017 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2018 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2019 if ((!type->tp_as_number && base->tp_as_number) ||
2020 (!type->tp_as_sequence && base->tp_as_sequence)) {
2021 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2022 if (!type->tp_as_number && !type->tp_as_sequence) {
2023 type->tp_flags |= base->tp_flags &
2024 Py_TPFLAGS_HAVE_INPLACEOPS;
2025 }
2026 }
2027 /* Wow */
2028 }
2029 if (!type->tp_as_number && base->tp_as_number) {
2030 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2031 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2032 }
2033
2034 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002035 oldsize = base->tp_basicsize;
2036 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2037 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2038 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002039 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2040 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002041 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002042 if (type->tp_traverse == NULL)
2043 type->tp_traverse = base->tp_traverse;
2044 if (type->tp_clear == NULL)
2045 type->tp_clear = base->tp_clear;
2046 }
2047 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002048 /* The condition below could use some explanation.
2049 It appears that tp_new is not inherited for static types
2050 whose base class is 'object'; this seems to be a precaution
2051 so that old extension types don't suddenly become
2052 callable (object.__new__ wouldn't insure the invariants
2053 that the extension type's own factory function ensures).
2054 Heap types, of course, are under our control, so they do
2055 inherit tp_new; static extension types that specify some
2056 other built-in type as the default are considered
2057 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002058 if (base != &PyBaseObject_Type ||
2059 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2060 if (type->tp_new == NULL)
2061 type->tp_new = base->tp_new;
2062 }
2063 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002064 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002065
2066 /* Copy other non-function slots */
2067
2068#undef COPYVAL
2069#define COPYVAL(SLOT) \
2070 if (type->SLOT == 0) type->SLOT = base->SLOT
2071
2072 COPYVAL(tp_itemsize);
2073 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2074 COPYVAL(tp_weaklistoffset);
2075 }
2076 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2077 COPYVAL(tp_dictoffset);
2078 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002079}
2080
2081static void
2082inherit_slots(PyTypeObject *type, PyTypeObject *base)
2083{
2084 PyTypeObject *basebase;
2085
2086#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002087#undef COPYSLOT
2088#undef COPYNUM
2089#undef COPYSEQ
2090#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002091#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002092
2093#define SLOTDEFINED(SLOT) \
2094 (base->SLOT != 0 && \
2095 (basebase == NULL || base->SLOT != basebase->SLOT))
2096
Tim Peters6d6c1a32001-08-02 04:15:00 +00002097#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002098 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002099
2100#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2101#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2102#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002103#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002104
Guido van Rossum13d52f02001-08-10 21:24:08 +00002105 /* This won't inherit indirect slots (from tp_as_number etc.)
2106 if type doesn't provide the space. */
2107
2108 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2109 basebase = base->tp_base;
2110 if (basebase->tp_as_number == NULL)
2111 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002112 COPYNUM(nb_add);
2113 COPYNUM(nb_subtract);
2114 COPYNUM(nb_multiply);
2115 COPYNUM(nb_divide);
2116 COPYNUM(nb_remainder);
2117 COPYNUM(nb_divmod);
2118 COPYNUM(nb_power);
2119 COPYNUM(nb_negative);
2120 COPYNUM(nb_positive);
2121 COPYNUM(nb_absolute);
2122 COPYNUM(nb_nonzero);
2123 COPYNUM(nb_invert);
2124 COPYNUM(nb_lshift);
2125 COPYNUM(nb_rshift);
2126 COPYNUM(nb_and);
2127 COPYNUM(nb_xor);
2128 COPYNUM(nb_or);
2129 COPYNUM(nb_coerce);
2130 COPYNUM(nb_int);
2131 COPYNUM(nb_long);
2132 COPYNUM(nb_float);
2133 COPYNUM(nb_oct);
2134 COPYNUM(nb_hex);
2135 COPYNUM(nb_inplace_add);
2136 COPYNUM(nb_inplace_subtract);
2137 COPYNUM(nb_inplace_multiply);
2138 COPYNUM(nb_inplace_divide);
2139 COPYNUM(nb_inplace_remainder);
2140 COPYNUM(nb_inplace_power);
2141 COPYNUM(nb_inplace_lshift);
2142 COPYNUM(nb_inplace_rshift);
2143 COPYNUM(nb_inplace_and);
2144 COPYNUM(nb_inplace_xor);
2145 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002146 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2147 COPYNUM(nb_true_divide);
2148 COPYNUM(nb_floor_divide);
2149 COPYNUM(nb_inplace_true_divide);
2150 COPYNUM(nb_inplace_floor_divide);
2151 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002152 }
2153
Guido van Rossum13d52f02001-08-10 21:24:08 +00002154 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2155 basebase = base->tp_base;
2156 if (basebase->tp_as_sequence == NULL)
2157 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002158 COPYSEQ(sq_length);
2159 COPYSEQ(sq_concat);
2160 COPYSEQ(sq_repeat);
2161 COPYSEQ(sq_item);
2162 COPYSEQ(sq_slice);
2163 COPYSEQ(sq_ass_item);
2164 COPYSEQ(sq_ass_slice);
2165 COPYSEQ(sq_contains);
2166 COPYSEQ(sq_inplace_concat);
2167 COPYSEQ(sq_inplace_repeat);
2168 }
2169
Guido van Rossum13d52f02001-08-10 21:24:08 +00002170 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2171 basebase = base->tp_base;
2172 if (basebase->tp_as_mapping == NULL)
2173 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002174 COPYMAP(mp_length);
2175 COPYMAP(mp_subscript);
2176 COPYMAP(mp_ass_subscript);
2177 }
2178
Tim Petersfc57ccb2001-10-12 02:38:24 +00002179 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2180 basebase = base->tp_base;
2181 if (basebase->tp_as_buffer == NULL)
2182 basebase = NULL;
2183 COPYBUF(bf_getreadbuffer);
2184 COPYBUF(bf_getwritebuffer);
2185 COPYBUF(bf_getsegcount);
2186 COPYBUF(bf_getcharbuffer);
2187 }
2188
Guido van Rossum13d52f02001-08-10 21:24:08 +00002189 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002190
Tim Peters6d6c1a32001-08-02 04:15:00 +00002191 COPYSLOT(tp_dealloc);
2192 COPYSLOT(tp_print);
2193 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2194 type->tp_getattr = base->tp_getattr;
2195 type->tp_getattro = base->tp_getattro;
2196 }
2197 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2198 type->tp_setattr = base->tp_setattr;
2199 type->tp_setattro = base->tp_setattro;
2200 }
2201 /* tp_compare see tp_richcompare */
2202 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002203 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002204 COPYSLOT(tp_call);
2205 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002206 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002207 if (type->tp_compare == NULL &&
2208 type->tp_richcompare == NULL &&
2209 type->tp_hash == NULL)
2210 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002211 type->tp_compare = base->tp_compare;
2212 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002213 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002214 }
2215 }
2216 else {
2217 COPYSLOT(tp_compare);
2218 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002219 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2220 COPYSLOT(tp_iter);
2221 COPYSLOT(tp_iternext);
2222 }
2223 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2224 COPYSLOT(tp_descr_get);
2225 COPYSLOT(tp_descr_set);
2226 COPYSLOT(tp_dictoffset);
2227 COPYSLOT(tp_init);
2228 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002229 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002230 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002231 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002232}
2233
Jeremy Hylton938ace62002-07-17 16:30:39 +00002234static int add_operators(PyTypeObject *);
2235static int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002236
Tim Peters6d6c1a32001-08-02 04:15:00 +00002237int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002238PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002239{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002240 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002241 PyTypeObject *base;
2242 int i, n;
2243
Guido van Rossumcab05802002-06-10 15:29:03 +00002244 if (type->tp_flags & Py_TPFLAGS_READY) {
2245 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002246 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002247 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002248 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002249
2250 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002251
2252 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2253 base = type->tp_base;
2254 if (base == NULL && type != &PyBaseObject_Type)
2255 base = type->tp_base = &PyBaseObject_Type;
2256
Guido van Rossum0986d822002-04-08 01:38:42 +00002257 /* Initialize ob_type if NULL. This means extensions that want to be
2258 compilable separately on Windows can call PyType_Ready() instead of
2259 initializing the ob_type field of their type objects. */
2260 if (type->ob_type == NULL)
2261 type->ob_type = base->ob_type;
2262
Tim Peters6d6c1a32001-08-02 04:15:00 +00002263 /* Initialize tp_bases */
2264 bases = type->tp_bases;
2265 if (bases == NULL) {
2266 if (base == NULL)
2267 bases = PyTuple_New(0);
2268 else
2269 bases = Py_BuildValue("(O)", base);
2270 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002271 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002272 type->tp_bases = bases;
2273 }
2274
2275 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002276 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002277 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002278 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002279 }
2280
Guido van Rossum687ae002001-10-15 22:03:32 +00002281 /* Initialize tp_dict */
2282 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002283 if (dict == NULL) {
2284 dict = PyDict_New();
2285 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002286 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002287 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002288 }
2289
Guido van Rossum687ae002001-10-15 22:03:32 +00002290 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002291 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002292 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002293 if (type->tp_methods != NULL) {
2294 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002295 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002296 }
2297 if (type->tp_members != NULL) {
2298 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002299 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002300 }
2301 if (type->tp_getset != NULL) {
2302 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002303 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002304 }
2305
Tim Peters6d6c1a32001-08-02 04:15:00 +00002306 /* Calculate method resolution order */
2307 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002308 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002309 }
2310
Guido van Rossum13d52f02001-08-10 21:24:08 +00002311 /* Inherit special flags from dominant base */
2312 if (type->tp_base != NULL)
2313 inherit_special(type, type->tp_base);
2314
Tim Peters6d6c1a32001-08-02 04:15:00 +00002315 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002316 bases = type->tp_mro;
2317 assert(bases != NULL);
2318 assert(PyTuple_Check(bases));
2319 n = PyTuple_GET_SIZE(bases);
2320 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002321 PyObject *b = PyTuple_GET_ITEM(bases, i);
2322 if (PyType_Check(b))
2323 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002324 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002325
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002326 /* if the type dictionary doesn't contain a __doc__, set it from
2327 the tp_doc slot.
2328 */
2329 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2330 if (type->tp_doc != NULL) {
2331 PyObject *doc = PyString_FromString(type->tp_doc);
2332 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2333 Py_DECREF(doc);
2334 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002335 PyDict_SetItemString(type->tp_dict,
2336 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002337 }
2338 }
2339
Guido van Rossum13d52f02001-08-10 21:24:08 +00002340 /* Some more special stuff */
2341 base = type->tp_base;
2342 if (base != NULL) {
2343 if (type->tp_as_number == NULL)
2344 type->tp_as_number = base->tp_as_number;
2345 if (type->tp_as_sequence == NULL)
2346 type->tp_as_sequence = base->tp_as_sequence;
2347 if (type->tp_as_mapping == NULL)
2348 type->tp_as_mapping = base->tp_as_mapping;
2349 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002350
Guido van Rossum1c450732001-10-08 15:18:27 +00002351 /* Link into each base class's list of subclasses */
2352 bases = type->tp_bases;
2353 n = PyTuple_GET_SIZE(bases);
2354 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002355 PyObject *b = PyTuple_GET_ITEM(bases, i);
2356 if (PyType_Check(b) &&
2357 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002358 goto error;
2359 }
2360
Guido van Rossum13d52f02001-08-10 21:24:08 +00002361 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002362 assert(type->tp_dict != NULL);
2363 type->tp_flags =
2364 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002365 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002366
2367 error:
2368 type->tp_flags &= ~Py_TPFLAGS_READYING;
2369 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002370}
2371
Guido van Rossum1c450732001-10-08 15:18:27 +00002372static int
2373add_subclass(PyTypeObject *base, PyTypeObject *type)
2374{
2375 int i;
2376 PyObject *list, *ref, *new;
2377
2378 list = base->tp_subclasses;
2379 if (list == NULL) {
2380 base->tp_subclasses = list = PyList_New(0);
2381 if (list == NULL)
2382 return -1;
2383 }
2384 assert(PyList_Check(list));
2385 new = PyWeakref_NewRef((PyObject *)type, NULL);
2386 i = PyList_GET_SIZE(list);
2387 while (--i >= 0) {
2388 ref = PyList_GET_ITEM(list, i);
2389 assert(PyWeakref_CheckRef(ref));
2390 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2391 return PyList_SetItem(list, i, new);
2392 }
2393 i = PyList_Append(list, new);
2394 Py_DECREF(new);
2395 return i;
2396}
2397
Tim Peters6d6c1a32001-08-02 04:15:00 +00002398
2399/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2400
2401/* There's a wrapper *function* for each distinct function typedef used
2402 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2403 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2404 Most tables have only one entry; the tables for binary operators have two
2405 entries, one regular and one with reversed arguments. */
2406
2407static PyObject *
2408wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2409{
2410 inquiry func = (inquiry)wrapped;
2411 int res;
2412
2413 if (!PyArg_ParseTuple(args, ""))
2414 return NULL;
2415 res = (*func)(self);
2416 if (res == -1 && PyErr_Occurred())
2417 return NULL;
2418 return PyInt_FromLong((long)res);
2419}
2420
Tim Peters6d6c1a32001-08-02 04:15:00 +00002421static PyObject *
2422wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2423{
2424 binaryfunc func = (binaryfunc)wrapped;
2425 PyObject *other;
2426
2427 if (!PyArg_ParseTuple(args, "O", &other))
2428 return NULL;
2429 return (*func)(self, other);
2430}
2431
2432static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002433wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2434{
2435 binaryfunc func = (binaryfunc)wrapped;
2436 PyObject *other;
2437
2438 if (!PyArg_ParseTuple(args, "O", &other))
2439 return NULL;
2440 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002441 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002442 Py_INCREF(Py_NotImplemented);
2443 return Py_NotImplemented;
2444 }
2445 return (*func)(self, other);
2446}
2447
2448static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002449wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2450{
2451 binaryfunc func = (binaryfunc)wrapped;
2452 PyObject *other;
2453
2454 if (!PyArg_ParseTuple(args, "O", &other))
2455 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002456 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002457 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002458 Py_INCREF(Py_NotImplemented);
2459 return Py_NotImplemented;
2460 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002461 return (*func)(other, self);
2462}
2463
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002464static PyObject *
2465wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2466{
2467 coercion func = (coercion)wrapped;
2468 PyObject *other, *res;
2469 int ok;
2470
2471 if (!PyArg_ParseTuple(args, "O", &other))
2472 return NULL;
2473 ok = func(&self, &other);
2474 if (ok < 0)
2475 return NULL;
2476 if (ok > 0) {
2477 Py_INCREF(Py_NotImplemented);
2478 return Py_NotImplemented;
2479 }
2480 res = PyTuple_New(2);
2481 if (res == NULL) {
2482 Py_DECREF(self);
2483 Py_DECREF(other);
2484 return NULL;
2485 }
2486 PyTuple_SET_ITEM(res, 0, self);
2487 PyTuple_SET_ITEM(res, 1, other);
2488 return res;
2489}
2490
Tim Peters6d6c1a32001-08-02 04:15:00 +00002491static PyObject *
2492wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2493{
2494 ternaryfunc func = (ternaryfunc)wrapped;
2495 PyObject *other;
2496 PyObject *third = Py_None;
2497
2498 /* Note: This wrapper only works for __pow__() */
2499
2500 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2501 return NULL;
2502 return (*func)(self, other, third);
2503}
2504
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002505static PyObject *
2506wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2507{
2508 ternaryfunc func = (ternaryfunc)wrapped;
2509 PyObject *other;
2510 PyObject *third = Py_None;
2511
2512 /* Note: This wrapper only works for __pow__() */
2513
2514 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2515 return NULL;
2516 return (*func)(other, self, third);
2517}
2518
Tim Peters6d6c1a32001-08-02 04:15:00 +00002519static PyObject *
2520wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2521{
2522 unaryfunc func = (unaryfunc)wrapped;
2523
2524 if (!PyArg_ParseTuple(args, ""))
2525 return NULL;
2526 return (*func)(self);
2527}
2528
Tim Peters6d6c1a32001-08-02 04:15:00 +00002529static PyObject *
2530wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2531{
2532 intargfunc func = (intargfunc)wrapped;
2533 int i;
2534
2535 if (!PyArg_ParseTuple(args, "i", &i))
2536 return NULL;
2537 return (*func)(self, i);
2538}
2539
Guido van Rossum5d815f32001-08-17 21:57:47 +00002540static int
2541getindex(PyObject *self, PyObject *arg)
2542{
2543 int i;
2544
2545 i = PyInt_AsLong(arg);
2546 if (i == -1 && PyErr_Occurred())
2547 return -1;
2548 if (i < 0) {
2549 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2550 if (sq && sq->sq_length) {
2551 int n = (*sq->sq_length)(self);
2552 if (n < 0)
2553 return -1;
2554 i += n;
2555 }
2556 }
2557 return i;
2558}
2559
2560static PyObject *
2561wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2562{
2563 intargfunc func = (intargfunc)wrapped;
2564 PyObject *arg;
2565 int i;
2566
Guido van Rossumf4593e02001-10-03 12:09:30 +00002567 if (PyTuple_GET_SIZE(args) == 1) {
2568 arg = PyTuple_GET_ITEM(args, 0);
2569 i = getindex(self, arg);
2570 if (i == -1 && PyErr_Occurred())
2571 return NULL;
2572 return (*func)(self, i);
2573 }
2574 PyArg_ParseTuple(args, "O", &arg);
2575 assert(PyErr_Occurred());
2576 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002577}
2578
Tim Peters6d6c1a32001-08-02 04:15:00 +00002579static PyObject *
2580wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2581{
2582 intintargfunc func = (intintargfunc)wrapped;
2583 int i, j;
2584
2585 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2586 return NULL;
2587 return (*func)(self, i, j);
2588}
2589
Tim Peters6d6c1a32001-08-02 04:15:00 +00002590static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002591wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002592{
2593 intobjargproc func = (intobjargproc)wrapped;
2594 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002595 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002596
Guido van Rossum5d815f32001-08-17 21:57:47 +00002597 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2598 return NULL;
2599 i = getindex(self, arg);
2600 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002601 return NULL;
2602 res = (*func)(self, i, value);
2603 if (res == -1 && PyErr_Occurred())
2604 return NULL;
2605 Py_INCREF(Py_None);
2606 return Py_None;
2607}
2608
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002609static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002610wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002611{
2612 intobjargproc func = (intobjargproc)wrapped;
2613 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002614 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002615
Guido van Rossum5d815f32001-08-17 21:57:47 +00002616 if (!PyArg_ParseTuple(args, "O", &arg))
2617 return NULL;
2618 i = getindex(self, arg);
2619 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002620 return NULL;
2621 res = (*func)(self, i, NULL);
2622 if (res == -1 && PyErr_Occurred())
2623 return NULL;
2624 Py_INCREF(Py_None);
2625 return Py_None;
2626}
2627
Tim Peters6d6c1a32001-08-02 04:15:00 +00002628static PyObject *
2629wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2630{
2631 intintobjargproc func = (intintobjargproc)wrapped;
2632 int i, j, res;
2633 PyObject *value;
2634
2635 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2636 return NULL;
2637 res = (*func)(self, i, j, value);
2638 if (res == -1 && PyErr_Occurred())
2639 return NULL;
2640 Py_INCREF(Py_None);
2641 return Py_None;
2642}
2643
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002644static PyObject *
2645wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2646{
2647 intintobjargproc func = (intintobjargproc)wrapped;
2648 int i, j, res;
2649
2650 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2651 return NULL;
2652 res = (*func)(self, i, j, NULL);
2653 if (res == -1 && PyErr_Occurred())
2654 return NULL;
2655 Py_INCREF(Py_None);
2656 return Py_None;
2657}
2658
Tim Peters6d6c1a32001-08-02 04:15:00 +00002659/* XXX objobjproc is a misnomer; should be objargpred */
2660static PyObject *
2661wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2662{
2663 objobjproc func = (objobjproc)wrapped;
2664 int res;
2665 PyObject *value;
2666
2667 if (!PyArg_ParseTuple(args, "O", &value))
2668 return NULL;
2669 res = (*func)(self, value);
2670 if (res == -1 && PyErr_Occurred())
2671 return NULL;
2672 return PyInt_FromLong((long)res);
2673}
2674
Tim Peters6d6c1a32001-08-02 04:15:00 +00002675static PyObject *
2676wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2677{
2678 objobjargproc func = (objobjargproc)wrapped;
2679 int res;
2680 PyObject *key, *value;
2681
2682 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2683 return NULL;
2684 res = (*func)(self, key, value);
2685 if (res == -1 && PyErr_Occurred())
2686 return NULL;
2687 Py_INCREF(Py_None);
2688 return Py_None;
2689}
2690
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002691static PyObject *
2692wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2693{
2694 objobjargproc func = (objobjargproc)wrapped;
2695 int res;
2696 PyObject *key;
2697
2698 if (!PyArg_ParseTuple(args, "O", &key))
2699 return NULL;
2700 res = (*func)(self, key, NULL);
2701 if (res == -1 && PyErr_Occurred())
2702 return NULL;
2703 Py_INCREF(Py_None);
2704 return Py_None;
2705}
2706
Tim Peters6d6c1a32001-08-02 04:15:00 +00002707static PyObject *
2708wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2709{
2710 cmpfunc func = (cmpfunc)wrapped;
2711 int res;
2712 PyObject *other;
2713
2714 if (!PyArg_ParseTuple(args, "O", &other))
2715 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002716 if (other->ob_type->tp_compare != func &&
2717 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002718 PyErr_Format(
2719 PyExc_TypeError,
2720 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2721 self->ob_type->tp_name,
2722 self->ob_type->tp_name,
2723 other->ob_type->tp_name);
2724 return NULL;
2725 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002726 res = (*func)(self, other);
2727 if (PyErr_Occurred())
2728 return NULL;
2729 return PyInt_FromLong((long)res);
2730}
2731
Tim Peters6d6c1a32001-08-02 04:15:00 +00002732static PyObject *
2733wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2734{
2735 setattrofunc func = (setattrofunc)wrapped;
2736 int res;
2737 PyObject *name, *value;
2738
2739 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2740 return NULL;
2741 res = (*func)(self, name, value);
2742 if (res < 0)
2743 return NULL;
2744 Py_INCREF(Py_None);
2745 return Py_None;
2746}
2747
2748static PyObject *
2749wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2750{
2751 setattrofunc func = (setattrofunc)wrapped;
2752 int res;
2753 PyObject *name;
2754
2755 if (!PyArg_ParseTuple(args, "O", &name))
2756 return NULL;
2757 res = (*func)(self, name, NULL);
2758 if (res < 0)
2759 return NULL;
2760 Py_INCREF(Py_None);
2761 return Py_None;
2762}
2763
Tim Peters6d6c1a32001-08-02 04:15:00 +00002764static PyObject *
2765wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2766{
2767 hashfunc func = (hashfunc)wrapped;
2768 long res;
2769
2770 if (!PyArg_ParseTuple(args, ""))
2771 return NULL;
2772 res = (*func)(self);
2773 if (res == -1 && PyErr_Occurred())
2774 return NULL;
2775 return PyInt_FromLong(res);
2776}
2777
Tim Peters6d6c1a32001-08-02 04:15:00 +00002778static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002779wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002780{
2781 ternaryfunc func = (ternaryfunc)wrapped;
2782
Guido van Rossumc8e56452001-10-22 00:43:43 +00002783 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002784}
2785
Tim Peters6d6c1a32001-08-02 04:15:00 +00002786static PyObject *
2787wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2788{
2789 richcmpfunc func = (richcmpfunc)wrapped;
2790 PyObject *other;
2791
2792 if (!PyArg_ParseTuple(args, "O", &other))
2793 return NULL;
2794 return (*func)(self, other, op);
2795}
2796
2797#undef RICHCMP_WRAPPER
2798#define RICHCMP_WRAPPER(NAME, OP) \
2799static PyObject * \
2800richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2801{ \
2802 return wrap_richcmpfunc(self, args, wrapped, OP); \
2803}
2804
Jack Jansen8e938b42001-08-08 15:29:49 +00002805RICHCMP_WRAPPER(lt, Py_LT)
2806RICHCMP_WRAPPER(le, Py_LE)
2807RICHCMP_WRAPPER(eq, Py_EQ)
2808RICHCMP_WRAPPER(ne, Py_NE)
2809RICHCMP_WRAPPER(gt, Py_GT)
2810RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002811
Tim Peters6d6c1a32001-08-02 04:15:00 +00002812static PyObject *
2813wrap_next(PyObject *self, PyObject *args, void *wrapped)
2814{
2815 unaryfunc func = (unaryfunc)wrapped;
2816 PyObject *res;
2817
2818 if (!PyArg_ParseTuple(args, ""))
2819 return NULL;
2820 res = (*func)(self);
2821 if (res == NULL && !PyErr_Occurred())
2822 PyErr_SetNone(PyExc_StopIteration);
2823 return res;
2824}
2825
Tim Peters6d6c1a32001-08-02 04:15:00 +00002826static PyObject *
2827wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2828{
2829 descrgetfunc func = (descrgetfunc)wrapped;
2830 PyObject *obj;
2831 PyObject *type = NULL;
2832
2833 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2834 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002835 return (*func)(self, obj, type);
2836}
2837
Tim Peters6d6c1a32001-08-02 04:15:00 +00002838static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002839wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002840{
2841 descrsetfunc func = (descrsetfunc)wrapped;
2842 PyObject *obj, *value;
2843 int ret;
2844
2845 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2846 return NULL;
2847 ret = (*func)(self, obj, value);
2848 if (ret < 0)
2849 return NULL;
2850 Py_INCREF(Py_None);
2851 return Py_None;
2852}
Guido van Rossum22b13872002-08-06 21:41:44 +00002853
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00002854static PyObject *
2855wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
2856{
2857 descrsetfunc func = (descrsetfunc)wrapped;
2858 PyObject *obj;
2859 int ret;
2860
2861 if (!PyArg_ParseTuple(args, "O", &obj))
2862 return NULL;
2863 ret = (*func)(self, obj, NULL);
2864 if (ret < 0)
2865 return NULL;
2866 Py_INCREF(Py_None);
2867 return Py_None;
2868}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002869
Tim Peters6d6c1a32001-08-02 04:15:00 +00002870static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002871wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002872{
2873 initproc func = (initproc)wrapped;
2874
Guido van Rossumc8e56452001-10-22 00:43:43 +00002875 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002876 return NULL;
2877 Py_INCREF(Py_None);
2878 return Py_None;
2879}
2880
Tim Peters6d6c1a32001-08-02 04:15:00 +00002881static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002882tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002883{
Barry Warsaw60f01882001-08-22 19:24:42 +00002884 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002885 PyObject *arg0, *res;
2886
2887 if (self == NULL || !PyType_Check(self))
2888 Py_FatalError("__new__() called with non-type 'self'");
2889 type = (PyTypeObject *)self;
2890 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002891 PyErr_Format(PyExc_TypeError,
2892 "%s.__new__(): not enough arguments",
2893 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002894 return NULL;
2895 }
2896 arg0 = PyTuple_GET_ITEM(args, 0);
2897 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002898 PyErr_Format(PyExc_TypeError,
2899 "%s.__new__(X): X is not a type object (%s)",
2900 type->tp_name,
2901 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002902 return NULL;
2903 }
2904 subtype = (PyTypeObject *)arg0;
2905 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002906 PyErr_Format(PyExc_TypeError,
2907 "%s.__new__(%s): %s is not a subtype of %s",
2908 type->tp_name,
2909 subtype->tp_name,
2910 subtype->tp_name,
2911 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002912 return NULL;
2913 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002914
2915 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002916 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002917 most derived base that's not a heap type is this type. */
2918 staticbase = subtype;
2919 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2920 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002921 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002922 PyErr_Format(PyExc_TypeError,
2923 "%s.__new__(%s) is not safe, use %s.__new__()",
2924 type->tp_name,
2925 subtype->tp_name,
2926 staticbase == NULL ? "?" : staticbase->tp_name);
2927 return NULL;
2928 }
2929
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002930 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2931 if (args == NULL)
2932 return NULL;
2933 res = type->tp_new(subtype, args, kwds);
2934 Py_DECREF(args);
2935 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002936}
2937
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002938static struct PyMethodDef tp_new_methoddef[] = {
2939 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2940 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002941 {0}
2942};
2943
2944static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002945add_tp_new_wrapper(PyTypeObject *type)
2946{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002947 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002948
Guido van Rossum687ae002001-10-15 22:03:32 +00002949 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002950 return 0;
2951 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002952 if (func == NULL)
2953 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002954 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002955}
2956
Guido van Rossumf040ede2001-08-07 16:40:56 +00002957/* Slot wrappers that call the corresponding __foo__ slot. See comments
2958 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002959
Guido van Rossumdc91b992001-08-08 22:26:22 +00002960#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002961static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002962FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002963{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002964 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002965 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002966}
2967
Guido van Rossumdc91b992001-08-08 22:26:22 +00002968#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002969static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002970FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002971{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002972 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002973 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002974}
2975
Guido van Rossumdc91b992001-08-08 22:26:22 +00002976
2977#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002978static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002979FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002980{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002981 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002982 int do_other = self->ob_type != other->ob_type && \
2983 other->ob_type->tp_as_number != NULL && \
2984 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002985 if (self->ob_type->tp_as_number != NULL && \
2986 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2987 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002988 if (do_other && \
2989 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2990 r = call_maybe( \
2991 other, ROPSTR, &rcache_str, "(O)", self); \
2992 if (r != Py_NotImplemented) \
2993 return r; \
2994 Py_DECREF(r); \
2995 do_other = 0; \
2996 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002997 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002998 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002999 if (r != Py_NotImplemented || \
3000 other->ob_type == self->ob_type) \
3001 return r; \
3002 Py_DECREF(r); \
3003 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003004 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003005 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003006 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003007 } \
3008 Py_INCREF(Py_NotImplemented); \
3009 return Py_NotImplemented; \
3010}
3011
3012#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3013 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3014
3015#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3016static PyObject * \
3017FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3018{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003019 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003020 return call_method(self, OPSTR, &cache_str, \
3021 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003022}
3023
3024static int
3025slot_sq_length(PyObject *self)
3026{
Guido van Rossum2730b132001-08-28 18:22:14 +00003027 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003028 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003029 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003030
3031 if (res == NULL)
3032 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003033 len = (int)PyInt_AsLong(res);
3034 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003035 if (len == -1 && PyErr_Occurred())
3036 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003037 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003038 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003039 "__len__() should return >= 0");
3040 return -1;
3041 }
Guido van Rossum26111622001-10-01 16:42:49 +00003042 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003043}
3044
Guido van Rossumdc91b992001-08-08 22:26:22 +00003045SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3046SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003047
3048/* Super-optimized version of slot_sq_item.
3049 Other slots could do the same... */
3050static PyObject *
3051slot_sq_item(PyObject *self, int i)
3052{
3053 static PyObject *getitem_str;
3054 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3055 descrgetfunc f;
3056
3057 if (getitem_str == NULL) {
3058 getitem_str = PyString_InternFromString("__getitem__");
3059 if (getitem_str == NULL)
3060 return NULL;
3061 }
3062 func = _PyType_Lookup(self->ob_type, getitem_str);
3063 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003064 if ((f = func->ob_type->tp_descr_get) == NULL)
3065 Py_INCREF(func);
3066 else
3067 func = f(func, self, (PyObject *)(self->ob_type));
3068 ival = PyInt_FromLong(i);
3069 if (ival != NULL) {
3070 args = PyTuple_New(1);
3071 if (args != NULL) {
3072 PyTuple_SET_ITEM(args, 0, ival);
3073 retval = PyObject_Call(func, args, NULL);
3074 Py_XDECREF(args);
3075 Py_XDECREF(func);
3076 return retval;
3077 }
3078 }
3079 }
3080 else {
3081 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3082 }
3083 Py_XDECREF(args);
3084 Py_XDECREF(ival);
3085 Py_XDECREF(func);
3086 return NULL;
3087}
3088
Guido van Rossumdc91b992001-08-08 22:26:22 +00003089SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003090
3091static int
3092slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3093{
3094 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003095 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003096
3097 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003098 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003099 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003100 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003101 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003102 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003103 if (res == NULL)
3104 return -1;
3105 Py_DECREF(res);
3106 return 0;
3107}
3108
3109static int
3110slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3111{
3112 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003113 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003114
3115 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003116 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003117 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003118 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003119 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003120 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003121 if (res == NULL)
3122 return -1;
3123 Py_DECREF(res);
3124 return 0;
3125}
3126
3127static int
3128slot_sq_contains(PyObject *self, PyObject *value)
3129{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003130 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003131 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003132
Guido van Rossum55f20992001-10-01 17:18:22 +00003133 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003134
3135 if (func != NULL) {
3136 args = Py_BuildValue("(O)", value);
3137 if (args == NULL)
3138 res = NULL;
3139 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003140 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003141 Py_DECREF(args);
3142 }
3143 Py_DECREF(func);
3144 if (res == NULL)
3145 return -1;
3146 return PyObject_IsTrue(res);
3147 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003148 else if (PyErr_Occurred())
3149 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003150 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003151 return _PySequence_IterSearch(self, value,
3152 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003153 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003154}
3155
Guido van Rossumdc91b992001-08-08 22:26:22 +00003156SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3157SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003158
3159#define slot_mp_length slot_sq_length
3160
Guido van Rossumdc91b992001-08-08 22:26:22 +00003161SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003162
3163static int
3164slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3165{
3166 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003167 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003168
3169 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003170 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003171 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003172 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003173 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003174 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003175 if (res == NULL)
3176 return -1;
3177 Py_DECREF(res);
3178 return 0;
3179}
3180
Guido van Rossumdc91b992001-08-08 22:26:22 +00003181SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3182SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3183SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3184SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3185SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3186SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3187
Jeremy Hylton938ace62002-07-17 16:30:39 +00003188static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003189
3190SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3191 nb_power, "__pow__", "__rpow__")
3192
3193static PyObject *
3194slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3195{
Guido van Rossum2730b132001-08-28 18:22:14 +00003196 static PyObject *pow_str;
3197
Guido van Rossumdc91b992001-08-08 22:26:22 +00003198 if (modulus == Py_None)
3199 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003200 /* Three-arg power doesn't use __rpow__. But ternary_op
3201 can call this when the second argument's type uses
3202 slot_nb_power, so check before calling self.__pow__. */
3203 if (self->ob_type->tp_as_number != NULL &&
3204 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3205 return call_method(self, "__pow__", &pow_str,
3206 "(OO)", other, modulus);
3207 }
3208 Py_INCREF(Py_NotImplemented);
3209 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003210}
3211
3212SLOT0(slot_nb_negative, "__neg__")
3213SLOT0(slot_nb_positive, "__pos__")
3214SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003215
3216static int
3217slot_nb_nonzero(PyObject *self)
3218{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003219 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003220 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003221
Guido van Rossum55f20992001-10-01 17:18:22 +00003222 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003223 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003224 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003225 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003226 func = lookup_maybe(self, "__len__", &len_str);
3227 if (func == NULL) {
3228 if (PyErr_Occurred())
3229 return -1;
3230 else
3231 return 1;
3232 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003233 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003234 res = PyObject_CallObject(func, NULL);
3235 Py_DECREF(func);
3236 if (res == NULL)
3237 return -1;
3238 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003239}
3240
Guido van Rossumdc91b992001-08-08 22:26:22 +00003241SLOT0(slot_nb_invert, "__invert__")
3242SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3243SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3244SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3245SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3246SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003247
3248static int
3249slot_nb_coerce(PyObject **a, PyObject **b)
3250{
3251 static PyObject *coerce_str;
3252 PyObject *self = *a, *other = *b;
3253
3254 if (self->ob_type->tp_as_number != NULL &&
3255 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3256 PyObject *r;
3257 r = call_maybe(
3258 self, "__coerce__", &coerce_str, "(O)", other);
3259 if (r == NULL)
3260 return -1;
3261 if (r == Py_NotImplemented) {
3262 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003263 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003264 else {
3265 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3266 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003267 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003268 Py_DECREF(r);
3269 return -1;
3270 }
3271 *a = PyTuple_GET_ITEM(r, 0);
3272 Py_INCREF(*a);
3273 *b = PyTuple_GET_ITEM(r, 1);
3274 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003275 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003276 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003277 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003278 }
3279 if (other->ob_type->tp_as_number != NULL &&
3280 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3281 PyObject *r;
3282 r = call_maybe(
3283 other, "__coerce__", &coerce_str, "(O)", self);
3284 if (r == NULL)
3285 return -1;
3286 if (r == Py_NotImplemented) {
3287 Py_DECREF(r);
3288 return 1;
3289 }
3290 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3291 PyErr_SetString(PyExc_TypeError,
3292 "__coerce__ didn't return a 2-tuple");
3293 Py_DECREF(r);
3294 return -1;
3295 }
3296 *a = PyTuple_GET_ITEM(r, 1);
3297 Py_INCREF(*a);
3298 *b = PyTuple_GET_ITEM(r, 0);
3299 Py_INCREF(*b);
3300 Py_DECREF(r);
3301 return 0;
3302 }
3303 return 1;
3304}
3305
Guido van Rossumdc91b992001-08-08 22:26:22 +00003306SLOT0(slot_nb_int, "__int__")
3307SLOT0(slot_nb_long, "__long__")
3308SLOT0(slot_nb_float, "__float__")
3309SLOT0(slot_nb_oct, "__oct__")
3310SLOT0(slot_nb_hex, "__hex__")
3311SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3312SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3313SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3314SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3315SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3316SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3317SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3318SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3319SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3320SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3321SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3322SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3323 "__floordiv__", "__rfloordiv__")
3324SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3325SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3326SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003327
3328static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003329half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003330{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003331 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003332 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003333 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003334
Guido van Rossum60718732001-08-28 17:47:51 +00003335 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003336 if (func == NULL) {
3337 PyErr_Clear();
3338 }
3339 else {
3340 args = Py_BuildValue("(O)", other);
3341 if (args == NULL)
3342 res = NULL;
3343 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003344 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003345 Py_DECREF(args);
3346 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00003347 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003348 if (res != Py_NotImplemented) {
3349 if (res == NULL)
3350 return -2;
3351 c = PyInt_AsLong(res);
3352 Py_DECREF(res);
3353 if (c == -1 && PyErr_Occurred())
3354 return -2;
3355 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3356 }
3357 Py_DECREF(res);
3358 }
3359 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003360}
3361
Guido van Rossumab3b0342001-09-18 20:38:53 +00003362/* This slot is published for the benefit of try_3way_compare in object.c */
3363int
3364_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003365{
3366 int c;
3367
Guido van Rossumab3b0342001-09-18 20:38:53 +00003368 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003369 c = half_compare(self, other);
3370 if (c <= 1)
3371 return c;
3372 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003373 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003374 c = half_compare(other, self);
3375 if (c < -1)
3376 return -2;
3377 if (c <= 1)
3378 return -c;
3379 }
3380 return (void *)self < (void *)other ? -1 :
3381 (void *)self > (void *)other ? 1 : 0;
3382}
3383
3384static PyObject *
3385slot_tp_repr(PyObject *self)
3386{
3387 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003388 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003389
Guido van Rossum60718732001-08-28 17:47:51 +00003390 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003391 if (func != NULL) {
3392 res = PyEval_CallObject(func, NULL);
3393 Py_DECREF(func);
3394 return res;
3395 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003396 PyErr_Clear();
3397 return PyString_FromFormat("<%s object at %p>",
3398 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003399}
3400
3401static PyObject *
3402slot_tp_str(PyObject *self)
3403{
3404 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003405 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003406
Guido van Rossum60718732001-08-28 17:47:51 +00003407 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003408 if (func != NULL) {
3409 res = PyEval_CallObject(func, NULL);
3410 Py_DECREF(func);
3411 return res;
3412 }
3413 else {
3414 PyErr_Clear();
3415 return slot_tp_repr(self);
3416 }
3417}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003418
3419static long
3420slot_tp_hash(PyObject *self)
3421{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003422 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003423 static PyObject *hash_str, *eq_str, *cmp_str;
3424
Tim Peters6d6c1a32001-08-02 04:15:00 +00003425 long h;
3426
Guido van Rossum60718732001-08-28 17:47:51 +00003427 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003428
3429 if (func != NULL) {
3430 res = PyEval_CallObject(func, NULL);
3431 Py_DECREF(func);
3432 if (res == NULL)
3433 return -1;
3434 h = PyInt_AsLong(res);
3435 }
3436 else {
3437 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003438 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003439 if (func == NULL) {
3440 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003441 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003442 }
3443 if (func != NULL) {
3444 Py_DECREF(func);
3445 PyErr_SetString(PyExc_TypeError, "unhashable type");
3446 return -1;
3447 }
3448 PyErr_Clear();
3449 h = _Py_HashPointer((void *)self);
3450 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003451 if (h == -1 && !PyErr_Occurred())
3452 h = -2;
3453 return h;
3454}
3455
3456static PyObject *
3457slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3458{
Guido van Rossum60718732001-08-28 17:47:51 +00003459 static PyObject *call_str;
3460 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003461 PyObject *res;
3462
3463 if (meth == NULL)
3464 return NULL;
3465 res = PyObject_Call(meth, args, kwds);
3466 Py_DECREF(meth);
3467 return res;
3468}
3469
Guido van Rossum14a6f832001-10-17 13:59:09 +00003470/* There are two slot dispatch functions for tp_getattro.
3471
3472 - slot_tp_getattro() is used when __getattribute__ is overridden
3473 but no __getattr__ hook is present;
3474
3475 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3476
Guido van Rossumc334df52002-04-04 23:44:47 +00003477 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3478 detects the absence of __getattr__ and then installs the simpler slot if
3479 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003480
Tim Peters6d6c1a32001-08-02 04:15:00 +00003481static PyObject *
3482slot_tp_getattro(PyObject *self, PyObject *name)
3483{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003484 static PyObject *getattribute_str = NULL;
3485 return call_method(self, "__getattribute__", &getattribute_str,
3486 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003487}
3488
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003489static PyObject *
3490slot_tp_getattr_hook(PyObject *self, PyObject *name)
3491{
3492 PyTypeObject *tp = self->ob_type;
3493 PyObject *getattr, *getattribute, *res;
3494 static PyObject *getattribute_str = NULL;
3495 static PyObject *getattr_str = NULL;
3496
3497 if (getattr_str == NULL) {
3498 getattr_str = PyString_InternFromString("__getattr__");
3499 if (getattr_str == NULL)
3500 return NULL;
3501 }
3502 if (getattribute_str == NULL) {
3503 getattribute_str =
3504 PyString_InternFromString("__getattribute__");
3505 if (getattribute_str == NULL)
3506 return NULL;
3507 }
3508 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003509 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003510 /* No __getattr__ hook: use a simpler dispatcher */
3511 tp->tp_getattro = slot_tp_getattro;
3512 return slot_tp_getattro(self, name);
3513 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003514 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003515 if (getattribute == NULL ||
3516 (getattribute->ob_type == &PyWrapperDescr_Type &&
3517 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3518 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003519 res = PyObject_GenericGetAttr(self, name);
3520 else
3521 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003522 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003523 PyErr_Clear();
3524 res = PyObject_CallFunction(getattr, "OO", self, name);
3525 }
3526 return res;
3527}
3528
Tim Peters6d6c1a32001-08-02 04:15:00 +00003529static int
3530slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3531{
3532 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003533 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003534
3535 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003536 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003537 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003538 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003539 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003540 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003541 if (res == NULL)
3542 return -1;
3543 Py_DECREF(res);
3544 return 0;
3545}
3546
3547/* Map rich comparison operators to their __xx__ namesakes */
3548static char *name_op[] = {
3549 "__lt__",
3550 "__le__",
3551 "__eq__",
3552 "__ne__",
3553 "__gt__",
3554 "__ge__",
3555};
3556
3557static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003558half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003559{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003560 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003561 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003562
Guido van Rossum60718732001-08-28 17:47:51 +00003563 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003564 if (func == NULL) {
3565 PyErr_Clear();
3566 Py_INCREF(Py_NotImplemented);
3567 return Py_NotImplemented;
3568 }
3569 args = Py_BuildValue("(O)", other);
3570 if (args == NULL)
3571 res = NULL;
3572 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003573 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003574 Py_DECREF(args);
3575 }
3576 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003577 return res;
3578}
3579
Guido van Rossumb8f63662001-08-15 23:57:02 +00003580/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3581static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3582
3583static PyObject *
3584slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3585{
3586 PyObject *res;
3587
3588 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3589 res = half_richcompare(self, other, op);
3590 if (res != Py_NotImplemented)
3591 return res;
3592 Py_DECREF(res);
3593 }
3594 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3595 res = half_richcompare(other, self, swapped_op[op]);
3596 if (res != Py_NotImplemented) {
3597 return res;
3598 }
3599 Py_DECREF(res);
3600 }
3601 Py_INCREF(Py_NotImplemented);
3602 return Py_NotImplemented;
3603}
3604
3605static PyObject *
3606slot_tp_iter(PyObject *self)
3607{
3608 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003609 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003610
Guido van Rossum60718732001-08-28 17:47:51 +00003611 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003612 if (func != NULL) {
3613 res = PyObject_CallObject(func, NULL);
3614 Py_DECREF(func);
3615 return res;
3616 }
3617 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003618 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003619 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003620 PyErr_SetString(PyExc_TypeError,
3621 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003622 return NULL;
3623 }
3624 Py_DECREF(func);
3625 return PySeqIter_New(self);
3626}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003627
3628static PyObject *
3629slot_tp_iternext(PyObject *self)
3630{
Guido van Rossum2730b132001-08-28 18:22:14 +00003631 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003632 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003633}
3634
Guido van Rossum1a493502001-08-17 16:47:50 +00003635static PyObject *
3636slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3637{
3638 PyTypeObject *tp = self->ob_type;
3639 PyObject *get;
3640 static PyObject *get_str = NULL;
3641
3642 if (get_str == NULL) {
3643 get_str = PyString_InternFromString("__get__");
3644 if (get_str == NULL)
3645 return NULL;
3646 }
3647 get = _PyType_Lookup(tp, get_str);
3648 if (get == NULL) {
3649 /* Avoid further slowdowns */
3650 if (tp->tp_descr_get == slot_tp_descr_get)
3651 tp->tp_descr_get = NULL;
3652 Py_INCREF(self);
3653 return self;
3654 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003655 if (obj == NULL)
3656 obj = Py_None;
3657 if (type == NULL)
3658 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003659 return PyObject_CallFunction(get, "OOO", self, obj, type);
3660}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003661
3662static int
3663slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3664{
Guido van Rossum2c252392001-08-24 10:13:31 +00003665 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003666 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003667
3668 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003669 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003670 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003671 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003672 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003673 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003674 if (res == NULL)
3675 return -1;
3676 Py_DECREF(res);
3677 return 0;
3678}
3679
3680static int
3681slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3682{
Guido van Rossum60718732001-08-28 17:47:51 +00003683 static PyObject *init_str;
3684 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003685 PyObject *res;
3686
3687 if (meth == NULL)
3688 return -1;
3689 res = PyObject_Call(meth, args, kwds);
3690 Py_DECREF(meth);
3691 if (res == NULL)
3692 return -1;
3693 Py_DECREF(res);
3694 return 0;
3695}
3696
3697static PyObject *
3698slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3699{
3700 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3701 PyObject *newargs, *x;
3702 int i, n;
3703
3704 if (func == NULL)
3705 return NULL;
3706 assert(PyTuple_Check(args));
3707 n = PyTuple_GET_SIZE(args);
3708 newargs = PyTuple_New(n+1);
3709 if (newargs == NULL)
3710 return NULL;
3711 Py_INCREF(type);
3712 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3713 for (i = 0; i < n; i++) {
3714 x = PyTuple_GET_ITEM(args, i);
3715 Py_INCREF(x);
3716 PyTuple_SET_ITEM(newargs, i+1, x);
3717 }
3718 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003719 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003720 Py_DECREF(func);
3721 return x;
3722}
3723
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003724
3725/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3726 functions. The offsets here are relative to the 'etype' structure, which
3727 incorporates the additional structures used for numbers, sequences and
3728 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3729 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00003730 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3731 terminated with an all-zero entry. (This table is further initialized and
3732 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003733
Guido van Rossum6d204072001-10-21 00:44:31 +00003734typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003735
3736#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003737#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003738#undef ETSLOT
3739#undef SQSLOT
3740#undef MPSLOT
3741#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003742#undef UNSLOT
3743#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003744#undef BINSLOT
3745#undef RBINSLOT
3746
Guido van Rossum6d204072001-10-21 00:44:31 +00003747#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3748 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003749#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3750 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3751 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003752#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3753 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3754#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3755 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3756#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3757 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3758#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3759 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3760#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3761 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3762 "x." NAME "() <==> " DOC)
3763#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3764 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3765 "x." NAME "(y) <==> x" DOC "y")
3766#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3767 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3768 "x." NAME "(y) <==> x" DOC "y")
3769#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3770 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3771 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003772
3773static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003774 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3775 "x.__len__() <==> len(x)"),
3776 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3777 "x.__add__(y) <==> x+y"),
3778 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3779 "x.__mul__(n) <==> x*n"),
3780 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3781 "x.__rmul__(n) <==> n*x"),
3782 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3783 "x.__getitem__(y) <==> x[y]"),
3784 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3785 "x.__getslice__(i, j) <==> x[i:j]"),
3786 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3787 "x.__setitem__(i, y) <==> x[i]=y"),
3788 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3789 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003790 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003791 wrap_intintobjargproc,
3792 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3793 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3794 "x.__delslice__(i, j) <==> del x[i:j]"),
3795 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3796 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003797 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003798 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003799 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003800 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003801
Guido van Rossum6d204072001-10-21 00:44:31 +00003802 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3803 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003804 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003805 wrap_binaryfunc,
3806 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003807 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003808 wrap_objobjargproc,
3809 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003810 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003811 wrap_delitem,
3812 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003813
Guido van Rossum6d204072001-10-21 00:44:31 +00003814 BINSLOT("__add__", nb_add, slot_nb_add,
3815 "+"),
3816 RBINSLOT("__radd__", nb_add, slot_nb_add,
3817 "+"),
3818 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3819 "-"),
3820 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3821 "-"),
3822 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3823 "*"),
3824 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3825 "*"),
3826 BINSLOT("__div__", nb_divide, slot_nb_divide,
3827 "/"),
3828 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3829 "/"),
3830 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3831 "%"),
3832 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3833 "%"),
3834 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3835 "divmod(x, y)"),
3836 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3837 "divmod(y, x)"),
3838 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3839 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3840 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3841 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3842 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3843 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3844 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3845 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003846 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003847 "x != 0"),
3848 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3849 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3850 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3851 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3852 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3853 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3854 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3855 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3856 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3857 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3858 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3859 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3860 "x.__coerce__(y) <==> coerce(x, y)"),
3861 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3862 "int(x)"),
3863 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3864 "long(x)"),
3865 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3866 "float(x)"),
3867 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3868 "oct(x)"),
3869 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3870 "hex(x)"),
3871 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3872 wrap_binaryfunc, "+"),
3873 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3874 wrap_binaryfunc, "-"),
3875 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3876 wrap_binaryfunc, "*"),
3877 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3878 wrap_binaryfunc, "/"),
3879 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3880 wrap_binaryfunc, "%"),
3881 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3882 wrap_ternaryfunc, "**"),
3883 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3884 wrap_binaryfunc, "<<"),
3885 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3886 wrap_binaryfunc, ">>"),
3887 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3888 wrap_binaryfunc, "&"),
3889 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3890 wrap_binaryfunc, "^"),
3891 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3892 wrap_binaryfunc, "|"),
3893 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3894 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3895 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3896 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3897 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3898 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3899 IBSLOT("__itruediv__", nb_inplace_true_divide,
3900 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003901
Guido van Rossum6d204072001-10-21 00:44:31 +00003902 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3903 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003904 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003905 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3906 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003907 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003908 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3909 "x.__cmp__(y) <==> cmp(x,y)"),
3910 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3911 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003912 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3913 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003914 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003915 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3916 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3917 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3918 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3919 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3920 "x.__setattr__('name', value) <==> x.name = value"),
3921 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3922 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3923 "x.__delattr__('name') <==> del x.name"),
3924 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3925 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3926 "x.__lt__(y) <==> x<y"),
3927 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3928 "x.__le__(y) <==> x<=y"),
3929 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3930 "x.__eq__(y) <==> x==y"),
3931 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3932 "x.__ne__(y) <==> x!=y"),
3933 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3934 "x.__gt__(y) <==> x>y"),
3935 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3936 "x.__ge__(y) <==> x>=y"),
3937 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3938 "x.__iter__() <==> iter(x)"),
3939 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3940 "x.next() -> the next value, or raise StopIteration"),
3941 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3942 "descr.__get__(obj[, type]) -> value"),
3943 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3944 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003945 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
3946 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003947 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003948 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003949 "see x.__class__.__doc__ for signature",
3950 PyWrapperFlag_KEYWORDS),
3951 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003952 {NULL}
3953};
3954
Guido van Rossumc334df52002-04-04 23:44:47 +00003955/* Given a type pointer and an offset gotten from a slotdef entry, return a
3956 pointer to the actual slot. This is not quite the same as simply adding
3957 the offset to the type pointer, since it takes care to indirect through the
3958 proper indirection pointer (as_buffer, etc.); it returns NULL if the
3959 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003960static void **
3961slotptr(PyTypeObject *type, int offset)
3962{
3963 char *ptr;
3964
Guido van Rossum09638c12002-06-13 19:17:46 +00003965 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003966 assert(offset >= 0);
3967 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00003968 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003969 ptr = (void *)type->tp_as_sequence;
3970 offset -= offsetof(etype, as_sequence);
3971 }
Guido van Rossum09638c12002-06-13 19:17:46 +00003972 else if (offset >= offsetof(etype, as_mapping)) {
3973 ptr = (void *)type->tp_as_mapping;
3974 offset -= offsetof(etype, as_mapping);
3975 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003976 else if (offset >= offsetof(etype, as_number)) {
3977 ptr = (void *)type->tp_as_number;
3978 offset -= offsetof(etype, as_number);
3979 }
3980 else {
3981 ptr = (void *)type;
3982 }
3983 if (ptr != NULL)
3984 ptr += offset;
3985 return (void **)ptr;
3986}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003987
Guido van Rossumc334df52002-04-04 23:44:47 +00003988/* Length of array of slotdef pointers used to store slots with the
3989 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
3990 the same __name__, for any __name__. Since that's a static property, it is
3991 appropriate to declare fixed-size arrays for this. */
3992#define MAX_EQUIV 10
3993
3994/* Return a slot pointer for a given name, but ONLY if the attribute has
3995 exactly one slot function. The name must be an interned string. */
3996static void **
3997resolve_slotdups(PyTypeObject *type, PyObject *name)
3998{
3999 /* XXX Maybe this could be optimized more -- but is it worth it? */
4000
4001 /* pname and ptrs act as a little cache */
4002 static PyObject *pname;
4003 static slotdef *ptrs[MAX_EQUIV];
4004 slotdef *p, **pp;
4005 void **res, **ptr;
4006
4007 if (pname != name) {
4008 /* Collect all slotdefs that match name into ptrs. */
4009 pname = name;
4010 pp = ptrs;
4011 for (p = slotdefs; p->name_strobj; p++) {
4012 if (p->name_strobj == name)
4013 *pp++ = p;
4014 }
4015 *pp = NULL;
4016 }
4017
4018 /* Look in all matching slots of the type; if exactly one of these has
4019 a filled-in slot, return its value. Otherwise return NULL. */
4020 res = NULL;
4021 for (pp = ptrs; *pp; pp++) {
4022 ptr = slotptr(type, (*pp)->offset);
4023 if (ptr == NULL || *ptr == NULL)
4024 continue;
4025 if (res != NULL)
4026 return NULL;
4027 res = ptr;
4028 }
4029 return res;
4030}
4031
4032/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4033 does some incredibly complex thinking and then sticks something into the
4034 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
4035 interests, and then stores a generic wrapper or a specific function into
4036 the slot.) Return a pointer to the next slotdef with a different offset,
4037 because that's convenient for fixup_slot_dispatchers(). */
4038static slotdef *
4039update_one_slot(PyTypeObject *type, slotdef *p)
4040{
4041 PyObject *descr;
4042 PyWrapperDescrObject *d;
4043 void *generic = NULL, *specific = NULL;
4044 int use_generic = 0;
4045 int offset = p->offset;
4046 void **ptr = slotptr(type, offset);
4047
4048 if (ptr == NULL) {
4049 do {
4050 ++p;
4051 } while (p->offset == offset);
4052 return p;
4053 }
4054 do {
4055 descr = _PyType_Lookup(type, p->name_strobj);
4056 if (descr == NULL)
4057 continue;
4058 if (descr->ob_type == &PyWrapperDescr_Type) {
4059 void **tptr = resolve_slotdups(type, p->name_strobj);
4060 if (tptr == NULL || tptr == ptr)
4061 generic = p->function;
4062 d = (PyWrapperDescrObject *)descr;
4063 if (d->d_base->wrapper == p->wrapper &&
4064 PyType_IsSubtype(type, d->d_type))
4065 {
4066 if (specific == NULL ||
4067 specific == d->d_wrapped)
4068 specific = d->d_wrapped;
4069 else
4070 use_generic = 1;
4071 }
4072 }
4073 else {
4074 use_generic = 1;
4075 generic = p->function;
4076 }
4077 } while ((++p)->offset == offset);
4078 if (specific && !use_generic)
4079 *ptr = specific;
4080 else
4081 *ptr = generic;
4082 return p;
4083}
4084
Guido van Rossum22b13872002-08-06 21:41:44 +00004085static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00004086 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004087
Guido van Rossumc334df52002-04-04 23:44:47 +00004088/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4089 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004090static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004091update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004092{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004093 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004094
Guido van Rossumc334df52002-04-04 23:44:47 +00004095 for (pp = pp0; *pp; pp++)
4096 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004097 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004098}
4099
Guido van Rossumc334df52002-04-04 23:44:47 +00004100/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4101 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004102static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004103recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004104{
4105 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004106 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004107 int i, n;
4108
4109 subclasses = type->tp_subclasses;
4110 if (subclasses == NULL)
4111 return 0;
4112 assert(PyList_Check(subclasses));
4113 n = PyList_GET_SIZE(subclasses);
4114 for (i = 0; i < n; i++) {
4115 ref = PyList_GET_ITEM(subclasses, i);
4116 assert(PyWeakref_CheckRef(ref));
4117 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004118 assert(subclass != NULL);
4119 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004120 continue;
4121 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004122 /* Avoid recursing down into unaffected classes */
4123 dict = subclass->tp_dict;
4124 if (dict != NULL && PyDict_Check(dict) &&
4125 PyDict_GetItem(dict, name) != NULL)
4126 continue;
4127 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004128 return -1;
4129 }
4130 return 0;
4131}
4132
Guido van Rossumc334df52002-04-04 23:44:47 +00004133/* Comparison function for qsort() to compare slotdefs by their offset, and
4134 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004135static int
4136slotdef_cmp(const void *aa, const void *bb)
4137{
4138 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4139 int c = a->offset - b->offset;
4140 if (c != 0)
4141 return c;
4142 else
4143 return a - b;
4144}
4145
Guido van Rossumc334df52002-04-04 23:44:47 +00004146/* Initialize the slotdefs table by adding interned string objects for the
4147 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004148static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004149init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004150{
4151 slotdef *p;
4152 static int initialized = 0;
4153
4154 if (initialized)
4155 return;
4156 for (p = slotdefs; p->name; p++) {
4157 p->name_strobj = PyString_InternFromString(p->name);
4158 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004159 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004160 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004161 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4162 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004163 initialized = 1;
4164}
4165
Guido van Rossumc334df52002-04-04 23:44:47 +00004166/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004167static int
4168update_slot(PyTypeObject *type, PyObject *name)
4169{
Guido van Rossumc334df52002-04-04 23:44:47 +00004170 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004171 slotdef *p;
4172 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004173 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004174
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004175 init_slotdefs();
4176 pp = ptrs;
4177 for (p = slotdefs; p->name; p++) {
4178 /* XXX assume name is interned! */
4179 if (p->name_strobj == name)
4180 *pp++ = p;
4181 }
4182 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004183 for (pp = ptrs; *pp; pp++) {
4184 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004185 offset = p->offset;
4186 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004187 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004188 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004189 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004190 if (ptrs[0] == NULL)
4191 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004192 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004193}
4194
Guido van Rossumc334df52002-04-04 23:44:47 +00004195/* Store the proper functions in the slot dispatches at class (type)
4196 definition time, based upon which operations the class overrides in its
4197 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004198static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004199fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004200{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004201 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004202
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004203 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004204 for (p = slotdefs; p->name; )
4205 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004206}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004207
Guido van Rossum6d204072001-10-21 00:44:31 +00004208/* This function is called by PyType_Ready() to populate the type's
4209 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004210 function slot (like tp_repr) that's defined in the type, one or more
4211 corresponding descriptors are added in the type's tp_dict dictionary
4212 under the appropriate name (like __repr__). Some function slots
4213 cause more than one descriptor to be added (for example, the nb_add
4214 slot adds both __add__ and __radd__ descriptors) and some function
4215 slots compete for the same descriptor (for example both sq_item and
4216 mp_subscript generate a __getitem__ descriptor).
4217
4218 In the latter case, the first slotdef entry encoutered wins. Since
4219 slotdef entries are sorted by the offset of the slot in the etype
4220 struct, this gives us some control over disambiguating between
4221 competing slots: the members of struct etype are listed from most
4222 general to least general, so the most general slot is preferred. In
4223 particular, because as_mapping comes before as_sequence, for a type
4224 that defines both mp_subscript and sq_item, mp_subscript wins.
4225
4226 This only adds new descriptors and doesn't overwrite entries in
4227 tp_dict that were previously defined. The descriptors contain a
4228 reference to the C function they must call, so that it's safe if they
4229 are copied into a subtype's __dict__ and the subtype has a different
4230 C function in its slot -- calling the method defined by the
4231 descriptor will call the C function that was used to create it,
4232 rather than the C function present in the slot when it is called.
4233 (This is important because a subtype may have a C function in the
4234 slot that calls the method from the dictionary, and we want to avoid
4235 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004236
4237static int
4238add_operators(PyTypeObject *type)
4239{
4240 PyObject *dict = type->tp_dict;
4241 slotdef *p;
4242 PyObject *descr;
4243 void **ptr;
4244
4245 init_slotdefs();
4246 for (p = slotdefs; p->name; p++) {
4247 if (p->wrapper == NULL)
4248 continue;
4249 ptr = slotptr(type, p->offset);
4250 if (!ptr || !*ptr)
4251 continue;
4252 if (PyDict_GetItem(dict, p->name_strobj))
4253 continue;
4254 descr = PyDescr_NewWrapper(type, p, *ptr);
4255 if (descr == NULL)
4256 return -1;
4257 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4258 return -1;
4259 Py_DECREF(descr);
4260 }
4261 if (type->tp_new != NULL) {
4262 if (add_tp_new_wrapper(type) < 0)
4263 return -1;
4264 }
4265 return 0;
4266}
4267
Guido van Rossum705f0f52001-08-24 16:47:00 +00004268
4269/* Cooperative 'super' */
4270
4271typedef struct {
4272 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004273 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004274 PyObject *obj;
4275} superobject;
4276
Guido van Rossum6f799372001-09-20 20:46:19 +00004277static PyMemberDef super_members[] = {
4278 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4279 "the class invoking super()"},
4280 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4281 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004282 {0}
4283};
4284
Guido van Rossum705f0f52001-08-24 16:47:00 +00004285static void
4286super_dealloc(PyObject *self)
4287{
4288 superobject *su = (superobject *)self;
4289
Guido van Rossum048eb752001-10-02 21:24:57 +00004290 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004291 Py_XDECREF(su->obj);
4292 Py_XDECREF(su->type);
4293 self->ob_type->tp_free(self);
4294}
4295
4296static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004297super_repr(PyObject *self)
4298{
4299 superobject *su = (superobject *)self;
4300
4301 if (su->obj)
4302 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004303 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004304 su->type ? su->type->tp_name : "NULL",
4305 su->obj->ob_type->tp_name);
4306 else
4307 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004308 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004309 su->type ? su->type->tp_name : "NULL");
4310}
4311
4312static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004313super_getattro(PyObject *self, PyObject *name)
4314{
4315 superobject *su = (superobject *)self;
4316
4317 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004318 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004319 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004320 descrgetfunc f;
4321 int i, n;
4322
Guido van Rossum155db9a2002-04-02 17:53:47 +00004323 starttype = su->obj->ob_type;
4324 mro = starttype->tp_mro;
4325
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004326 if (mro == NULL)
4327 n = 0;
4328 else {
4329 assert(PyTuple_Check(mro));
4330 n = PyTuple_GET_SIZE(mro);
4331 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004332 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004333 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004334 break;
4335 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004336 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004337 starttype = (PyTypeObject *)(su->obj);
4338 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004339 if (mro == NULL)
4340 n = 0;
4341 else {
4342 assert(PyTuple_Check(mro));
4343 n = PyTuple_GET_SIZE(mro);
4344 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004345 for (i = 0; i < n; i++) {
4346 if ((PyObject *)(su->type) ==
4347 PyTuple_GET_ITEM(mro, i))
4348 break;
4349 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004350 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004351 i++;
4352 res = NULL;
4353 for (; i < n; i++) {
4354 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004355 if (PyType_Check(tmp))
4356 dict = ((PyTypeObject *)tmp)->tp_dict;
4357 else if (PyClass_Check(tmp))
4358 dict = ((PyClassObject *)tmp)->cl_dict;
4359 else
4360 continue;
4361 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004362 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004363 Py_INCREF(res);
4364 f = res->ob_type->tp_descr_get;
4365 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004366 tmp = f(res, su->obj,
4367 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004368 Py_DECREF(res);
4369 res = tmp;
4370 }
4371 return res;
4372 }
4373 }
4374 }
4375 return PyObject_GenericGetAttr(self, name);
4376}
4377
Guido van Rossum5b443c62001-12-03 15:38:28 +00004378static int
4379supercheck(PyTypeObject *type, PyObject *obj)
4380{
4381 if (!PyType_IsSubtype(obj->ob_type, type) &&
4382 !(PyType_Check(obj) &&
4383 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4384 PyErr_SetString(PyExc_TypeError,
4385 "super(type, obj): "
4386 "obj must be an instance or subtype of type");
4387 return -1;
4388 }
4389 else
4390 return 0;
4391}
4392
Guido van Rossum705f0f52001-08-24 16:47:00 +00004393static PyObject *
4394super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4395{
4396 superobject *su = (superobject *)self;
4397 superobject *new;
4398
4399 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4400 /* Not binding to an object, or already bound */
4401 Py_INCREF(self);
4402 return self;
4403 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004404 if (su->ob_type != &PySuper_Type)
4405 /* If su is an instance of a subclass of super,
4406 call its type */
4407 return PyObject_CallFunction((PyObject *)su->ob_type,
4408 "OO", su->type, obj);
4409 else {
4410 /* Inline the common case */
4411 if (supercheck(su->type, obj) < 0)
4412 return NULL;
4413 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4414 NULL, NULL);
4415 if (new == NULL)
4416 return NULL;
4417 Py_INCREF(su->type);
4418 Py_INCREF(obj);
4419 new->type = su->type;
4420 new->obj = obj;
4421 return (PyObject *)new;
4422 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004423}
4424
4425static int
4426super_init(PyObject *self, PyObject *args, PyObject *kwds)
4427{
4428 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004429 PyTypeObject *type;
4430 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004431
4432 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4433 return -1;
4434 if (obj == Py_None)
4435 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004436 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004437 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004438 Py_INCREF(type);
4439 Py_XINCREF(obj);
4440 su->type = type;
4441 su->obj = obj;
4442 return 0;
4443}
4444
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004445PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00004446"super(type) -> unbound super object\n"
4447"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004448"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004449"Typical use to call a cooperative superclass method:\n"
4450"class C(B):\n"
4451" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004452" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00004453
Guido van Rossum048eb752001-10-02 21:24:57 +00004454static int
4455super_traverse(PyObject *self, visitproc visit, void *arg)
4456{
4457 superobject *su = (superobject *)self;
4458 int err;
4459
4460#define VISIT(SLOT) \
4461 if (SLOT) { \
4462 err = visit((PyObject *)(SLOT), arg); \
4463 if (err) \
4464 return err; \
4465 }
4466
4467 VISIT(su->obj);
4468 VISIT(su->type);
4469
4470#undef VISIT
4471
4472 return 0;
4473}
4474
Guido van Rossum705f0f52001-08-24 16:47:00 +00004475PyTypeObject PySuper_Type = {
4476 PyObject_HEAD_INIT(&PyType_Type)
4477 0, /* ob_size */
4478 "super", /* tp_name */
4479 sizeof(superobject), /* tp_basicsize */
4480 0, /* tp_itemsize */
4481 /* methods */
4482 super_dealloc, /* tp_dealloc */
4483 0, /* tp_print */
4484 0, /* tp_getattr */
4485 0, /* tp_setattr */
4486 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004487 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004488 0, /* tp_as_number */
4489 0, /* tp_as_sequence */
4490 0, /* tp_as_mapping */
4491 0, /* tp_hash */
4492 0, /* tp_call */
4493 0, /* tp_str */
4494 super_getattro, /* tp_getattro */
4495 0, /* tp_setattro */
4496 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004497 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4498 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004499 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004500 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004501 0, /* tp_clear */
4502 0, /* tp_richcompare */
4503 0, /* tp_weaklistoffset */
4504 0, /* tp_iter */
4505 0, /* tp_iternext */
4506 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004507 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004508 0, /* tp_getset */
4509 0, /* tp_base */
4510 0, /* tp_dict */
4511 super_descr_get, /* tp_descr_get */
4512 0, /* tp_descr_set */
4513 0, /* tp_dictoffset */
4514 super_init, /* tp_init */
4515 PyType_GenericAlloc, /* tp_alloc */
4516 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00004517 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004518};