blob: b7edb143b9254a8d12512afa9b1ae8e3a24464be [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 */
466 _PyObject_GC_UNTRACK(self);
467 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)
472 return;
473
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
511 Py_TRASHCAN_SAFE_END(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000512}
513
Jeremy Hylton938ace62002-07-17 16:30:39 +0000514static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000515
Tim Peters6d6c1a32001-08-02 04:15:00 +0000516/* type test with subclassing support */
517
518int
519PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
520{
521 PyObject *mro;
522
Guido van Rossum9478d072001-09-07 18:52:13 +0000523 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
524 return b == a || b == &PyBaseObject_Type;
525
Tim Peters6d6c1a32001-08-02 04:15:00 +0000526 mro = a->tp_mro;
527 if (mro != NULL) {
528 /* Deal with multiple inheritance without recursion
529 by walking the MRO tuple */
530 int i, n;
531 assert(PyTuple_Check(mro));
532 n = PyTuple_GET_SIZE(mro);
533 for (i = 0; i < n; i++) {
534 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
535 return 1;
536 }
537 return 0;
538 }
539 else {
540 /* a is not completely initilized yet; follow tp_base */
541 do {
542 if (a == b)
543 return 1;
544 a = a->tp_base;
545 } while (a != NULL);
546 return b == &PyBaseObject_Type;
547 }
548}
549
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000550/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000551 without looking in the instance dictionary
552 (so we can't use PyObject_GetAttr) but still binding
553 it to the instance. The arguments are the object,
554 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000555 static variable used to cache the interned Python string.
556
557 Two variants:
558
559 - lookup_maybe() returns NULL without raising an exception
560 when the _PyType_Lookup() call fails;
561
562 - lookup_method() always raises an exception upon errors.
563*/
Guido van Rossum60718732001-08-28 17:47:51 +0000564
565static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000566lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000567{
568 PyObject *res;
569
570 if (*attrobj == NULL) {
571 *attrobj = PyString_InternFromString(attrstr);
572 if (*attrobj == NULL)
573 return NULL;
574 }
575 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000576 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000577 descrgetfunc f;
578 if ((f = res->ob_type->tp_descr_get) == NULL)
579 Py_INCREF(res);
580 else
581 res = f(res, self, (PyObject *)(self->ob_type));
582 }
583 return res;
584}
585
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000586static PyObject *
587lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
588{
589 PyObject *res = lookup_maybe(self, attrstr, attrobj);
590 if (res == NULL && !PyErr_Occurred())
591 PyErr_SetObject(PyExc_AttributeError, *attrobj);
592 return res;
593}
594
Guido van Rossum2730b132001-08-28 18:22:14 +0000595/* A variation of PyObject_CallMethod that uses lookup_method()
596 instead of PyObject_GetAttrString(). This uses the same convention
597 as lookup_method to cache the interned name string object. */
598
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000599static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000600call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
601{
602 va_list va;
603 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000604 va_start(va, format);
605
Guido van Rossumda21c012001-10-03 00:50:18 +0000606 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000607 if (func == NULL) {
608 va_end(va);
609 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000610 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000611 return NULL;
612 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000613
614 if (format && *format)
615 args = Py_VaBuildValue(format, va);
616 else
617 args = PyTuple_New(0);
618
619 va_end(va);
620
621 if (args == NULL)
622 return NULL;
623
624 assert(PyTuple_Check(args));
625 retval = PyObject_Call(func, args, NULL);
626
627 Py_DECREF(args);
628 Py_DECREF(func);
629
630 return retval;
631}
632
633/* Clone of call_method() that returns NotImplemented when the lookup fails. */
634
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000635static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000636call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
637{
638 va_list va;
639 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000640 va_start(va, format);
641
Guido van Rossumda21c012001-10-03 00:50:18 +0000642 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000643 if (func == NULL) {
644 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000645 if (!PyErr_Occurred()) {
646 Py_INCREF(Py_NotImplemented);
647 return Py_NotImplemented;
648 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000649 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000650 }
651
652 if (format && *format)
653 args = Py_VaBuildValue(format, va);
654 else
655 args = PyTuple_New(0);
656
657 va_end(va);
658
Guido van Rossum717ce002001-09-14 16:58:08 +0000659 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000660 return NULL;
661
Guido van Rossum717ce002001-09-14 16:58:08 +0000662 assert(PyTuple_Check(args));
663 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000664
665 Py_DECREF(args);
666 Py_DECREF(func);
667
668 return retval;
669}
670
Tim Peters6d6c1a32001-08-02 04:15:00 +0000671/* Method resolution order algorithm from "Putting Metaclasses to Work"
672 by Forman and Danforth (Addison-Wesley 1999). */
673
674static int
675conservative_merge(PyObject *left, PyObject *right)
676{
677 int left_size;
678 int right_size;
679 int i, j, r, ok;
680 PyObject *temp, *rr;
681
682 assert(PyList_Check(left));
683 assert(PyList_Check(right));
684
685 again:
686 left_size = PyList_GET_SIZE(left);
687 right_size = PyList_GET_SIZE(right);
688 for (i = 0; i < left_size; i++) {
689 for (j = 0; j < right_size; j++) {
690 if (PyList_GET_ITEM(left, i) ==
691 PyList_GET_ITEM(right, j)) {
692 /* found a merge point */
693 temp = PyList_New(0);
694 if (temp == NULL)
695 return -1;
696 for (r = 0; r < j; r++) {
697 rr = PyList_GET_ITEM(right, r);
698 ok = PySequence_Contains(left, rr);
699 if (ok < 0) {
700 Py_DECREF(temp);
701 return -1;
702 }
703 if (!ok) {
704 ok = PyList_Append(temp, rr);
705 if (ok < 0) {
706 Py_DECREF(temp);
707 return -1;
708 }
709 }
710 }
711 ok = PyList_SetSlice(left, i, i, temp);
712 Py_DECREF(temp);
713 if (ok < 0)
714 return -1;
715 ok = PyList_SetSlice(right, 0, j+1, NULL);
716 if (ok < 0)
717 return -1;
718 goto again;
719 }
720 }
721 }
722 return PyList_SetSlice(left, left_size, left_size, right);
723}
724
725static int
726serious_order_disagreements(PyObject *left, PyObject *right)
727{
728 return 0; /* XXX later -- for now, we cheat: "don't do that" */
729}
730
Tim Petersa91e9642001-11-14 23:32:33 +0000731static int
732fill_classic_mro(PyObject *mro, PyObject *cls)
733{
734 PyObject *bases, *base;
735 int i, n;
736
737 assert(PyList_Check(mro));
738 assert(PyClass_Check(cls));
739 i = PySequence_Contains(mro, cls);
740 if (i < 0)
741 return -1;
742 if (!i) {
743 if (PyList_Append(mro, cls) < 0)
744 return -1;
745 }
746 bases = ((PyClassObject *)cls)->cl_bases;
747 assert(bases && PyTuple_Check(bases));
748 n = PyTuple_GET_SIZE(bases);
749 for (i = 0; i < n; i++) {
750 base = PyTuple_GET_ITEM(bases, i);
751 if (fill_classic_mro(mro, base) < 0)
752 return -1;
753 }
754 return 0;
755}
756
757static PyObject *
758classic_mro(PyObject *cls)
759{
760 PyObject *mro;
761
762 assert(PyClass_Check(cls));
763 mro = PyList_New(0);
764 if (mro != NULL) {
765 if (fill_classic_mro(mro, cls) == 0)
766 return mro;
767 Py_DECREF(mro);
768 }
769 return NULL;
770}
771
Tim Peters6d6c1a32001-08-02 04:15:00 +0000772static PyObject *
773mro_implementation(PyTypeObject *type)
774{
775 int i, n, ok;
776 PyObject *bases, *result;
777
Guido van Rossum63517572002-06-18 16:44:57 +0000778 if(type->tp_dict == NULL) {
779 if(PyType_Ready(type) < 0)
780 return NULL;
781 }
782
Tim Peters6d6c1a32001-08-02 04:15:00 +0000783 bases = type->tp_bases;
784 n = PyTuple_GET_SIZE(bases);
785 result = Py_BuildValue("[O]", (PyObject *)type);
786 if (result == NULL)
787 return NULL;
788 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000789 PyObject *base = PyTuple_GET_ITEM(bases, i);
790 PyObject *parentMRO;
791 if (PyType_Check(base))
792 parentMRO = PySequence_List(
793 ((PyTypeObject*)base)->tp_mro);
794 else
795 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000796 if (parentMRO == NULL) {
797 Py_DECREF(result);
798 return NULL;
799 }
800 if (serious_order_disagreements(result, parentMRO)) {
801 Py_DECREF(result);
802 return NULL;
803 }
804 ok = conservative_merge(result, parentMRO);
805 Py_DECREF(parentMRO);
806 if (ok < 0) {
807 Py_DECREF(result);
808 return NULL;
809 }
810 }
811 return result;
812}
813
814static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000815mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000816{
817 PyTypeObject *type = (PyTypeObject *)self;
818
Tim Peters6d6c1a32001-08-02 04:15:00 +0000819 return mro_implementation(type);
820}
821
822static int
823mro_internal(PyTypeObject *type)
824{
825 PyObject *mro, *result, *tuple;
826
827 if (type->ob_type == &PyType_Type) {
828 result = mro_implementation(type);
829 }
830 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000831 static PyObject *mro_str;
832 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000833 if (mro == NULL)
834 return -1;
835 result = PyObject_CallObject(mro, NULL);
836 Py_DECREF(mro);
837 }
838 if (result == NULL)
839 return -1;
840 tuple = PySequence_Tuple(result);
841 Py_DECREF(result);
842 type->tp_mro = tuple;
843 return 0;
844}
845
846
847/* Calculate the best base amongst multiple base classes.
848 This is the first one that's on the path to the "solid base". */
849
850static PyTypeObject *
851best_base(PyObject *bases)
852{
853 int i, n;
854 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000855 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000856
857 assert(PyTuple_Check(bases));
858 n = PyTuple_GET_SIZE(bases);
859 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000860 base = NULL;
861 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000862 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000863 base_proto = PyTuple_GET_ITEM(bases, i);
864 if (PyClass_Check(base_proto))
865 continue;
866 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000867 PyErr_SetString(
868 PyExc_TypeError,
869 "bases must be types");
870 return NULL;
871 }
Tim Petersa91e9642001-11-14 23:32:33 +0000872 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000873 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000874 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000875 return NULL;
876 }
877 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000878 if (winner == NULL) {
879 winner = candidate;
880 base = base_i;
881 }
882 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000883 ;
884 else if (PyType_IsSubtype(candidate, winner)) {
885 winner = candidate;
886 base = base_i;
887 }
888 else {
889 PyErr_SetString(
890 PyExc_TypeError,
891 "multiple bases have "
892 "instance lay-out conflict");
893 return NULL;
894 }
895 }
Guido van Rossume54616c2001-12-14 04:19:56 +0000896 if (base == NULL)
897 PyErr_SetString(PyExc_TypeError,
898 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000899 return base;
900}
901
902static int
903extra_ivars(PyTypeObject *type, PyTypeObject *base)
904{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000905 size_t t_size = type->tp_basicsize;
906 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000907
Guido van Rossum9676b222001-08-17 20:32:36 +0000908 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000909 if (type->tp_itemsize || base->tp_itemsize) {
910 /* If itemsize is involved, stricter rules */
911 return t_size != b_size ||
912 type->tp_itemsize != base->tp_itemsize;
913 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000914 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
915 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
916 t_size -= sizeof(PyObject *);
917 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
918 type->tp_dictoffset + sizeof(PyObject *) == t_size)
919 t_size -= sizeof(PyObject *);
920
921 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000922}
923
924static PyTypeObject *
925solid_base(PyTypeObject *type)
926{
927 PyTypeObject *base;
928
929 if (type->tp_base)
930 base = solid_base(type->tp_base);
931 else
932 base = &PyBaseObject_Type;
933 if (extra_ivars(type, base))
934 return type;
935 else
936 return base;
937}
938
Jeremy Hylton938ace62002-07-17 16:30:39 +0000939static void object_dealloc(PyObject *);
940static int object_init(PyObject *, PyObject *, PyObject *);
941static int update_slot(PyTypeObject *, PyObject *);
942static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000943
944static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000945subtype_dict(PyObject *obj, void *context)
946{
947 PyObject **dictptr = _PyObject_GetDictPtr(obj);
948 PyObject *dict;
949
950 if (dictptr == NULL) {
951 PyErr_SetString(PyExc_AttributeError,
952 "This object has no __dict__");
953 return NULL;
954 }
955 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000956 if (dict == NULL)
957 *dictptr = dict = PyDict_New();
958 Py_XINCREF(dict);
959 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000960}
961
Guido van Rossum6661be32001-10-26 04:26:12 +0000962static int
963subtype_setdict(PyObject *obj, PyObject *value, void *context)
964{
965 PyObject **dictptr = _PyObject_GetDictPtr(obj);
966 PyObject *dict;
967
968 if (dictptr == NULL) {
969 PyErr_SetString(PyExc_AttributeError,
970 "This object has no __dict__");
971 return -1;
972 }
Guido van Rossumd331cb52001-12-05 19:46:42 +0000973 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +0000974 PyErr_SetString(PyExc_TypeError,
975 "__dict__ must be set to a dictionary");
976 return -1;
977 }
978 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +0000979 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +0000980 *dictptr = value;
981 Py_XDECREF(dict);
982 return 0;
983}
984
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000985static PyGetSetDef subtype_getsets[] = {
Guido van Rossum6661be32001-10-26 04:26:12 +0000986 {"__dict__", subtype_dict, subtype_setdict, NULL},
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000987 {0},
988};
989
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000990/* bozo: __getstate__ that raises TypeError */
991
992static PyObject *
993bozo_func(PyObject *self, PyObject *args)
994{
995 PyErr_SetString(PyExc_TypeError,
996 "a class that defines __slots__ without "
997 "defining __getstate__ cannot be pickled");
998 return NULL;
999}
1000
Neal Norwitz93c1e232002-03-31 16:06:11 +00001001static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001002
1003static PyObject *bozo_obj = NULL;
1004
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001005static int
1006valid_identifier(PyObject *s)
1007{
Guido van Rossum03013a02002-07-16 14:30:28 +00001008 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001009 int i, n;
1010
1011 if (!PyString_Check(s)) {
1012 PyErr_SetString(PyExc_TypeError,
1013 "__slots__ must be strings");
1014 return 0;
1015 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001016 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001017 n = PyString_GET_SIZE(s);
1018 /* We must reject an empty name. As a hack, we bump the
1019 length to 1 so that the loop will balk on the trailing \0. */
1020 if (n == 0)
1021 n = 1;
1022 for (i = 0; i < n; i++, p++) {
1023 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1024 PyErr_SetString(PyExc_TypeError,
1025 "__slots__ must be identifiers");
1026 return 0;
1027 }
1028 }
1029 return 1;
1030}
1031
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001032static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001033type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1034{
1035 PyObject *name, *bases, *dict;
1036 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001037 static char buffer[256];
1038 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001039 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001040 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001041 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001042 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001043
Tim Peters3abca122001-10-27 19:37:48 +00001044 assert(args != NULL && PyTuple_Check(args));
1045 assert(kwds == NULL || PyDict_Check(kwds));
1046
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001047 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001048 {
1049 const int nargs = PyTuple_GET_SIZE(args);
1050 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1051
1052 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1053 PyObject *x = PyTuple_GET_ITEM(args, 0);
1054 Py_INCREF(x->ob_type);
1055 return (PyObject *) x->ob_type;
1056 }
1057
1058 /* SF bug 475327 -- if that didn't trigger, we need 3
1059 arguments. but PyArg_ParseTupleAndKeywords below may give
1060 a msg saying type() needs exactly 3. */
1061 if (nargs + nkwds != 3) {
1062 PyErr_SetString(PyExc_TypeError,
1063 "type() takes 1 or 3 arguments");
1064 return NULL;
1065 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001066 }
1067
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001068 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001069 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1070 &name,
1071 &PyTuple_Type, &bases,
1072 &PyDict_Type, &dict))
1073 return NULL;
1074
1075 /* Determine the proper metatype to deal with this,
1076 and check for metatype conflicts while we're at it.
1077 Note that if some other metatype wins to contract,
1078 it's possible that its instances are not types. */
1079 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001080 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001081 for (i = 0; i < nbases; i++) {
1082 tmp = PyTuple_GET_ITEM(bases, i);
1083 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001084 if (tmptype == &PyClass_Type)
1085 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001086 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001087 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001088 if (PyType_IsSubtype(tmptype, winner)) {
1089 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001090 continue;
1091 }
1092 PyErr_SetString(PyExc_TypeError,
1093 "metatype conflict among bases");
1094 return NULL;
1095 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001096 if (winner != metatype) {
1097 if (winner->tp_new != type_new) /* Pass it to the winner */
1098 return winner->tp_new(winner, args, kwds);
1099 metatype = winner;
1100 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001101
1102 /* Adjust for empty tuple bases */
1103 if (nbases == 0) {
1104 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1105 if (bases == NULL)
1106 return NULL;
1107 nbases = 1;
1108 }
1109 else
1110 Py_INCREF(bases);
1111
1112 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1113
1114 /* Calculate best base, and check that all bases are type objects */
1115 base = best_base(bases);
1116 if (base == NULL)
1117 return NULL;
1118 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1119 PyErr_Format(PyExc_TypeError,
1120 "type '%.100s' is not an acceptable base type",
1121 base->tp_name);
1122 return NULL;
1123 }
1124
Tim Peters6d6c1a32001-08-02 04:15:00 +00001125 /* Check for a __slots__ sequence variable in dict, and count it */
1126 slots = PyDict_GetItemString(dict, "__slots__");
1127 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001128 add_dict = 0;
1129 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001130 if (slots != NULL) {
1131 /* Make it into a tuple */
1132 if (PyString_Check(slots))
1133 slots = Py_BuildValue("(O)", slots);
1134 else
1135 slots = PySequence_Tuple(slots);
1136 if (slots == NULL)
1137 return NULL;
1138 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001139 if (nslots > 0 && base->tp_itemsize != 0) {
1140 PyErr_Format(PyExc_TypeError,
1141 "nonempty __slots__ "
1142 "not supported for subtype of '%s'",
1143 base->tp_name);
1144 return NULL;
1145 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001146 for (i = 0; i < nslots; i++) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001147 if (!valid_identifier(PyTuple_GET_ITEM(slots, i))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001148 Py_DECREF(slots);
1149 return NULL;
1150 }
1151 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001152
1153 newslots = PyTuple_New(nslots);
1154 if (newslots == NULL)
1155 return NULL;
1156 for (i = 0; i < nslots; i++) {
1157 tmp = PyTuple_GET_ITEM(slots, i);
1158 if (_Py_Mangle(PyString_AS_STRING(name),
1159 PyString_AS_STRING(tmp),
1160 buffer, sizeof(buffer)))
1161 {
1162 tmp = PyString_FromString(buffer);
1163 } else {
1164 Py_INCREF(tmp);
1165 }
1166 PyTuple_SET_ITEM(newslots, i, tmp);
1167 }
1168 Py_DECREF(slots);
1169 slots = newslots;
1170
Tim Peters6d6c1a32001-08-02 04:15:00 +00001171 }
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001172 if (slots != NULL) {
1173 /* See if *this* class defines __getstate__ */
1174 PyObject *getstate = PyDict_GetItemString(dict,
1175 "__getstate__");
1176 if (getstate == NULL) {
1177 /* If not, provide a bozo that raises TypeError */
1178 if (bozo_obj == NULL) {
1179 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
1180 if (bozo_obj == NULL) {
1181 /* XXX decref various things */
1182 return NULL;
1183 }
1184 }
1185 if (PyDict_SetItemString(dict,
1186 "__getstate__",
1187 bozo_obj) < 0) {
1188 /* XXX decref various things */
1189 return NULL;
1190 }
1191 }
1192 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001193 if (slots == NULL && base->tp_dictoffset == 0 &&
1194 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +00001195 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001196 add_dict++;
1197 }
Guido van Rossumc4141872001-08-30 04:43:35 +00001198 if (slots == NULL && base->tp_weaklistoffset == 0 &&
1199 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001200 nslots++;
1201 add_weak++;
1202 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001203
1204 /* XXX From here until type is safely allocated,
1205 "return NULL" may leak slots! */
1206
1207 /* Allocate the type object */
1208 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
1209 if (type == NULL)
1210 return NULL;
1211
1212 /* Keep name and slots alive in the extended type object */
1213 et = (etype *)type;
1214 Py_INCREF(name);
1215 et->name = name;
1216 et->slots = slots;
1217
Guido van Rossumdc91b992001-08-08 22:26:22 +00001218 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001219 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1220 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001221 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1222 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001223
1224 /* It's a new-style number unless it specifically inherits any
1225 old-style numeric behavior */
1226 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1227 (base->tp_as_number == NULL))
1228 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1229
1230 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001231 type->tp_as_number = &et->as_number;
1232 type->tp_as_sequence = &et->as_sequence;
1233 type->tp_as_mapping = &et->as_mapping;
1234 type->tp_as_buffer = &et->as_buffer;
1235 type->tp_name = PyString_AS_STRING(name);
1236
1237 /* Set tp_base and tp_bases */
1238 type->tp_bases = bases;
1239 Py_INCREF(base);
1240 type->tp_base = base;
1241
Guido van Rossum687ae002001-10-15 22:03:32 +00001242 /* Initialize tp_dict from passed-in dict */
1243 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001244 if (dict == NULL) {
1245 Py_DECREF(type);
1246 return NULL;
1247 }
1248
Guido van Rossumc3542212001-08-16 09:18:56 +00001249 /* Set __module__ in the dict */
1250 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1251 tmp = PyEval_GetGlobals();
1252 if (tmp != NULL) {
1253 tmp = PyDict_GetItemString(tmp, "__name__");
1254 if (tmp != NULL) {
1255 if (PyDict_SetItemString(dict, "__module__",
1256 tmp) < 0)
1257 return NULL;
1258 }
1259 }
1260 }
1261
Tim Peters2f93e282001-10-04 05:27:00 +00001262 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001263 and is a string. The __doc__ accessor will first look for tp_doc;
1264 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001265 */
1266 {
1267 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1268 if (doc != NULL && PyString_Check(doc)) {
1269 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001270 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001271 if (type->tp_doc == NULL) {
1272 Py_DECREF(type);
1273 return NULL;
1274 }
1275 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1276 }
1277 }
1278
Tim Peters6d6c1a32001-08-02 04:15:00 +00001279 /* Special-case __new__: if it's a plain function,
1280 make it a static function */
1281 tmp = PyDict_GetItemString(dict, "__new__");
1282 if (tmp != NULL && PyFunction_Check(tmp)) {
1283 tmp = PyStaticMethod_New(tmp);
1284 if (tmp == NULL) {
1285 Py_DECREF(type);
1286 return NULL;
1287 }
1288 PyDict_SetItemString(dict, "__new__", tmp);
1289 Py_DECREF(tmp);
1290 }
1291
1292 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1293 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001294 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001295 if (slots != NULL) {
1296 for (i = 0; i < nslots; i++, mp++) {
1297 mp->name = PyString_AS_STRING(
1298 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001299 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001300 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001301 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001302 strcmp(mp->name, "__weakref__") == 0) {
1303 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001304 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001305 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001306 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001307 slotoffset += sizeof(PyObject *);
1308 }
1309 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001310 else {
1311 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001312 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +00001313 type->tp_dictoffset =
1314 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001315 else
1316 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001317 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001318 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +00001319 }
1320 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001321 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +00001322 type->tp_weaklistoffset = slotoffset;
1323 mp->name = "__weakref__";
1324 mp->type = T_OBJECT;
1325 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +00001326 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001327 mp++;
1328 slotoffset += sizeof(PyObject *);
1329 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001330 }
1331 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001332 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001333 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001334
1335 /* Special case some slots */
1336 if (type->tp_dictoffset != 0 || nslots > 0) {
1337 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1338 type->tp_getattro = PyObject_GenericGetAttr;
1339 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1340 type->tp_setattro = PyObject_GenericSetAttr;
1341 }
1342 type->tp_dealloc = subtype_dealloc;
1343
Guido van Rossum9475a232001-10-05 20:51:39 +00001344 /* Enable GC unless there are really no instance variables possible */
1345 if (!(type->tp_basicsize == sizeof(PyObject) &&
1346 type->tp_itemsize == 0))
1347 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1348
Tim Peters6d6c1a32001-08-02 04:15:00 +00001349 /* Always override allocation strategy to use regular heap */
1350 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001351 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001352 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001353 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001354 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001355 }
1356 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001357 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001358
1359 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001360 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001361 Py_DECREF(type);
1362 return NULL;
1363 }
1364
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001365 /* Put the proper slots in place */
1366 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001367
Tim Peters6d6c1a32001-08-02 04:15:00 +00001368 return (PyObject *)type;
1369}
1370
1371/* Internal API to look for a name through the MRO.
1372 This returns a borrowed reference, and doesn't set an exception! */
1373PyObject *
1374_PyType_Lookup(PyTypeObject *type, PyObject *name)
1375{
1376 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001377 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001378
Guido van Rossum687ae002001-10-15 22:03:32 +00001379 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001380 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001381
1382 /* If mro is NULL, the type is either not yet initialized
1383 by PyType_Ready(), or already cleared by type_clear().
1384 Either way the safest thing to do is to return NULL. */
1385 if (mro == NULL)
1386 return NULL;
1387
Tim Peters6d6c1a32001-08-02 04:15:00 +00001388 assert(PyTuple_Check(mro));
1389 n = PyTuple_GET_SIZE(mro);
1390 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001391 base = PyTuple_GET_ITEM(mro, i);
1392 if (PyClass_Check(base))
1393 dict = ((PyClassObject *)base)->cl_dict;
1394 else {
1395 assert(PyType_Check(base));
1396 dict = ((PyTypeObject *)base)->tp_dict;
1397 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001398 assert(dict && PyDict_Check(dict));
1399 res = PyDict_GetItem(dict, name);
1400 if (res != NULL)
1401 return res;
1402 }
1403 return NULL;
1404}
1405
1406/* This is similar to PyObject_GenericGetAttr(),
1407 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1408static PyObject *
1409type_getattro(PyTypeObject *type, PyObject *name)
1410{
1411 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001412 PyObject *meta_attribute, *attribute;
1413 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001414
1415 /* Initialize this type (we'll assume the metatype is initialized) */
1416 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001417 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001418 return NULL;
1419 }
1420
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001421 /* No readable descriptor found yet */
1422 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001423
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001424 /* Look for the attribute in the metatype */
1425 meta_attribute = _PyType_Lookup(metatype, name);
1426
1427 if (meta_attribute != NULL) {
1428 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001429
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001430 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1431 /* Data descriptors implement tp_descr_set to intercept
1432 * writes. Assume the attribute is not overridden in
1433 * type's tp_dict (and bases): call the descriptor now.
1434 */
1435 return meta_get(meta_attribute, (PyObject *)type,
1436 (PyObject *)metatype);
1437 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001438 }
1439
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001440 /* No data descriptor found on metatype. Look in tp_dict of this
1441 * type and its bases */
1442 attribute = _PyType_Lookup(type, name);
1443 if (attribute != NULL) {
1444 /* Implement descriptor functionality, if any */
1445 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1446 if (local_get != NULL) {
1447 /* NULL 2nd argument indicates the descriptor was
1448 * found on the target object itself (or a base) */
1449 return local_get(attribute, (PyObject *)NULL,
1450 (PyObject *)type);
1451 }
Tim Peters34592512002-07-11 06:23:50 +00001452
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001453 Py_INCREF(attribute);
1454 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001455 }
1456
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001457 /* No attribute found in local __dict__ (or bases): use the
1458 * descriptor from the metatype, if any */
1459 if (meta_get != NULL)
1460 return meta_get(meta_attribute, (PyObject *)type,
1461 (PyObject *)metatype);
1462
1463 /* If an ordinary attribute was found on the metatype, return it now */
1464 if (meta_attribute != NULL) {
1465 Py_INCREF(meta_attribute);
1466 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001467 }
1468
1469 /* Give up */
1470 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001471 "type object '%.50s' has no attribute '%.400s'",
1472 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001473 return NULL;
1474}
1475
1476static int
1477type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1478{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001479 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1480 PyErr_Format(
1481 PyExc_TypeError,
1482 "can't set attributes of built-in/extension type '%s'",
1483 type->tp_name);
1484 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001485 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001486 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1487 return -1;
1488 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001489}
1490
1491static void
1492type_dealloc(PyTypeObject *type)
1493{
1494 etype *et;
1495
1496 /* Assert this is a heap-allocated type object */
1497 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001498 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001499 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001500 et = (etype *)type;
1501 Py_XDECREF(type->tp_base);
1502 Py_XDECREF(type->tp_dict);
1503 Py_XDECREF(type->tp_bases);
1504 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001505 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001506 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00001507 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001508 Py_XDECREF(et->name);
1509 Py_XDECREF(et->slots);
1510 type->ob_type->tp_free((PyObject *)type);
1511}
1512
Guido van Rossum1c450732001-10-08 15:18:27 +00001513static PyObject *
1514type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1515{
1516 PyObject *list, *raw, *ref;
1517 int i, n;
1518
1519 list = PyList_New(0);
1520 if (list == NULL)
1521 return NULL;
1522 raw = type->tp_subclasses;
1523 if (raw == NULL)
1524 return list;
1525 assert(PyList_Check(raw));
1526 n = PyList_GET_SIZE(raw);
1527 for (i = 0; i < n; i++) {
1528 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001529 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001530 ref = PyWeakref_GET_OBJECT(ref);
1531 if (ref != Py_None) {
1532 if (PyList_Append(list, ref) < 0) {
1533 Py_DECREF(list);
1534 return NULL;
1535 }
1536 }
1537 }
1538 return list;
1539}
1540
Tim Peters6d6c1a32001-08-02 04:15:00 +00001541static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001542 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001543 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001544 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1545 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001546 {0}
1547};
1548
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001549PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001550"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001551"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001552
Guido van Rossum048eb752001-10-02 21:24:57 +00001553static int
1554type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1555{
Guido van Rossum048eb752001-10-02 21:24:57 +00001556 int err;
1557
Guido van Rossuma3862092002-06-10 15:24:42 +00001558 /* Because of type_is_gc(), the collector only calls this
1559 for heaptypes. */
1560 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001561
1562#define VISIT(SLOT) \
1563 if (SLOT) { \
1564 err = visit((PyObject *)(SLOT), arg); \
1565 if (err) \
1566 return err; \
1567 }
1568
1569 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001570 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001571 VISIT(type->tp_mro);
1572 VISIT(type->tp_bases);
1573 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00001574
1575 /* There's no need to visit type->tp_subclasses or
1576 ((etype *)type)->slots, because they can't be involved
1577 in cycles; tp_subclasses is a list of weak references,
1578 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00001579
1580#undef VISIT
1581
1582 return 0;
1583}
1584
1585static int
1586type_clear(PyTypeObject *type)
1587{
Guido van Rossum048eb752001-10-02 21:24:57 +00001588 PyObject *tmp;
1589
Guido van Rossuma3862092002-06-10 15:24:42 +00001590 /* Because of type_is_gc(), the collector only calls this
1591 for heaptypes. */
1592 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001593
1594#define CLEAR(SLOT) \
1595 if (SLOT) { \
1596 tmp = (PyObject *)(SLOT); \
1597 SLOT = NULL; \
1598 Py_DECREF(tmp); \
1599 }
1600
Guido van Rossuma3862092002-06-10 15:24:42 +00001601 /* The only field we need to clear is tp_mro, which is part of a
1602 hard cycle (its first element is the class itself) that won't
1603 be broken otherwise (it's a tuple and tuples don't have a
1604 tp_clear handler). None of the other fields need to be
1605 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00001606
Guido van Rossuma3862092002-06-10 15:24:42 +00001607 tp_dict:
1608 It is a dict, so the collector will call its tp_clear.
1609
1610 tp_cache:
1611 Not used; if it were, it would be a dict.
1612
1613 tp_bases, tp_base:
1614 If these are involved in a cycle, there must be at least
1615 one other, mutable object in the cycle, e.g. a base
1616 class's dict; the cycle will be broken that way.
1617
1618 tp_subclasses:
1619 A list of weak references can't be part of a cycle; and
1620 lists have their own tp_clear.
1621
1622 slots (in etype):
1623 A tuple of strings can't be part of a cycle.
1624 */
1625
1626 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00001627
Guido van Rossum048eb752001-10-02 21:24:57 +00001628#undef CLEAR
1629
1630 return 0;
1631}
1632
1633static int
1634type_is_gc(PyTypeObject *type)
1635{
1636 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1637}
1638
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001639PyTypeObject PyType_Type = {
1640 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001641 0, /* ob_size */
1642 "type", /* tp_name */
1643 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001644 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001645 (destructor)type_dealloc, /* tp_dealloc */
1646 0, /* tp_print */
1647 0, /* tp_getattr */
1648 0, /* tp_setattr */
1649 type_compare, /* tp_compare */
1650 (reprfunc)type_repr, /* tp_repr */
1651 0, /* tp_as_number */
1652 0, /* tp_as_sequence */
1653 0, /* tp_as_mapping */
1654 (hashfunc)_Py_HashPointer, /* tp_hash */
1655 (ternaryfunc)type_call, /* tp_call */
1656 0, /* tp_str */
1657 (getattrofunc)type_getattro, /* tp_getattro */
1658 (setattrofunc)type_setattro, /* tp_setattro */
1659 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001660 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1661 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001662 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001663 (traverseproc)type_traverse, /* tp_traverse */
1664 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001665 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001666 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001667 0, /* tp_iter */
1668 0, /* tp_iternext */
1669 type_methods, /* tp_methods */
1670 type_members, /* tp_members */
1671 type_getsets, /* tp_getset */
1672 0, /* tp_base */
1673 0, /* tp_dict */
1674 0, /* tp_descr_get */
1675 0, /* tp_descr_set */
1676 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1677 0, /* tp_init */
1678 0, /* tp_alloc */
1679 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001680 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00001681 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001682};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001683
1684
1685/* The base type of all types (eventually)... except itself. */
1686
1687static int
1688object_init(PyObject *self, PyObject *args, PyObject *kwds)
1689{
1690 return 0;
1691}
1692
1693static void
1694object_dealloc(PyObject *self)
1695{
1696 self->ob_type->tp_free(self);
1697}
1698
Guido van Rossum8e248182001-08-12 05:17:56 +00001699static PyObject *
1700object_repr(PyObject *self)
1701{
Guido van Rossum76e69632001-08-16 18:52:43 +00001702 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001703 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001704
Guido van Rossum76e69632001-08-16 18:52:43 +00001705 type = self->ob_type;
1706 mod = type_module(type, NULL);
1707 if (mod == NULL)
1708 PyErr_Clear();
1709 else if (!PyString_Check(mod)) {
1710 Py_DECREF(mod);
1711 mod = NULL;
1712 }
1713 name = type_name(type, NULL);
1714 if (name == NULL)
1715 return NULL;
1716 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001717 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001718 PyString_AS_STRING(mod),
1719 PyString_AS_STRING(name),
1720 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001721 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001722 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001723 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001724 Py_XDECREF(mod);
1725 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001726 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001727}
1728
Guido van Rossumb8f63662001-08-15 23:57:02 +00001729static PyObject *
1730object_str(PyObject *self)
1731{
1732 unaryfunc f;
1733
1734 f = self->ob_type->tp_repr;
1735 if (f == NULL)
1736 f = object_repr;
1737 return f(self);
1738}
1739
Guido van Rossum8e248182001-08-12 05:17:56 +00001740static long
1741object_hash(PyObject *self)
1742{
1743 return _Py_HashPointer(self);
1744}
Guido van Rossum8e248182001-08-12 05:17:56 +00001745
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001746static PyObject *
1747object_get_class(PyObject *self, void *closure)
1748{
1749 Py_INCREF(self->ob_type);
1750 return (PyObject *)(self->ob_type);
1751}
1752
1753static int
1754equiv_structs(PyTypeObject *a, PyTypeObject *b)
1755{
1756 return a == b ||
1757 (a != NULL &&
1758 b != NULL &&
1759 a->tp_basicsize == b->tp_basicsize &&
1760 a->tp_itemsize == b->tp_itemsize &&
1761 a->tp_dictoffset == b->tp_dictoffset &&
1762 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1763 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1764 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1765}
1766
1767static int
1768same_slots_added(PyTypeObject *a, PyTypeObject *b)
1769{
1770 PyTypeObject *base = a->tp_base;
1771 int size;
1772
1773 if (base != b->tp_base)
1774 return 0;
1775 if (equiv_structs(a, base) && equiv_structs(b, base))
1776 return 1;
1777 size = base->tp_basicsize;
1778 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1779 size += sizeof(PyObject *);
1780 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1781 size += sizeof(PyObject *);
1782 return size == a->tp_basicsize && size == b->tp_basicsize;
1783}
1784
1785static int
1786object_set_class(PyObject *self, PyObject *value, void *closure)
1787{
1788 PyTypeObject *old = self->ob_type;
1789 PyTypeObject *new, *newbase, *oldbase;
1790
Guido van Rossumb6b89422002-04-15 01:03:30 +00001791 if (value == NULL) {
1792 PyErr_SetString(PyExc_TypeError,
1793 "can't delete __class__ attribute");
1794 return -1;
1795 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001796 if (!PyType_Check(value)) {
1797 PyErr_Format(PyExc_TypeError,
1798 "__class__ must be set to new-style class, not '%s' object",
1799 value->ob_type->tp_name);
1800 return -1;
1801 }
1802 new = (PyTypeObject *)value;
Guido van Rossum9ee4b942002-05-24 18:47:47 +00001803 if (new->tp_dealloc != old->tp_dealloc ||
1804 new->tp_free != old->tp_free)
1805 {
1806 PyErr_Format(PyExc_TypeError,
1807 "__class__ assignment: "
1808 "'%s' deallocator differs from '%s'",
1809 new->tp_name,
1810 old->tp_name);
1811 return -1;
1812 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001813 newbase = new;
1814 oldbase = old;
1815 while (equiv_structs(newbase, newbase->tp_base))
1816 newbase = newbase->tp_base;
1817 while (equiv_structs(oldbase, oldbase->tp_base))
1818 oldbase = oldbase->tp_base;
1819 if (newbase != oldbase &&
1820 (newbase->tp_base != oldbase->tp_base ||
1821 !same_slots_added(newbase, oldbase))) {
1822 PyErr_Format(PyExc_TypeError,
1823 "__class__ assignment: "
1824 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001825 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001826 old->tp_name);
1827 return -1;
1828 }
1829 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1830 Py_INCREF(new);
1831 }
1832 self->ob_type = new;
1833 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1834 Py_DECREF(old);
1835 }
1836 return 0;
1837}
1838
1839static PyGetSetDef object_getsets[] = {
1840 {"__class__", object_get_class, object_set_class,
1841 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001842 {0}
1843};
1844
Guido van Rossum3926a632001-09-25 16:25:58 +00001845static PyObject *
1846object_reduce(PyObject *self, PyObject *args)
1847{
1848 /* Call copy_reg._reduce(self) */
1849 static PyObject *copy_reg_str;
1850 PyObject *copy_reg, *res;
1851
1852 if (!copy_reg_str) {
1853 copy_reg_str = PyString_InternFromString("copy_reg");
1854 if (copy_reg_str == NULL)
1855 return NULL;
1856 }
1857 copy_reg = PyImport_Import(copy_reg_str);
1858 if (!copy_reg)
1859 return NULL;
1860 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1861 Py_DECREF(copy_reg);
1862 return res;
1863}
1864
1865static PyMethodDef object_methods[] = {
1866 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1867 {0}
1868};
1869
Tim Peters6d6c1a32001-08-02 04:15:00 +00001870PyTypeObject PyBaseObject_Type = {
1871 PyObject_HEAD_INIT(&PyType_Type)
1872 0, /* ob_size */
1873 "object", /* tp_name */
1874 sizeof(PyObject), /* tp_basicsize */
1875 0, /* tp_itemsize */
1876 (destructor)object_dealloc, /* tp_dealloc */
1877 0, /* tp_print */
1878 0, /* tp_getattr */
1879 0, /* tp_setattr */
1880 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001881 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001882 0, /* tp_as_number */
1883 0, /* tp_as_sequence */
1884 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001885 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001886 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001887 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001888 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001889 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001890 0, /* tp_as_buffer */
1891 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1892 "The most base type", /* tp_doc */
1893 0, /* tp_traverse */
1894 0, /* tp_clear */
1895 0, /* tp_richcompare */
1896 0, /* tp_weaklistoffset */
1897 0, /* tp_iter */
1898 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001899 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001900 0, /* tp_members */
1901 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001902 0, /* tp_base */
1903 0, /* tp_dict */
1904 0, /* tp_descr_get */
1905 0, /* tp_descr_set */
1906 0, /* tp_dictoffset */
1907 object_init, /* tp_init */
1908 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001909 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001910 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001911};
1912
1913
1914/* Initialize the __dict__ in a type object */
1915
Fred Drake7bf97152002-03-28 05:33:33 +00001916static PyObject *
1917create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
1918{
1919 PyObject *cfunc;
1920 PyObject *result;
1921
1922 cfunc = PyCFunction_New(meth, NULL);
1923 if (cfunc == NULL)
1924 return NULL;
1925 result = func(cfunc);
1926 Py_DECREF(cfunc);
1927 return result;
1928}
1929
Tim Peters6d6c1a32001-08-02 04:15:00 +00001930static int
1931add_methods(PyTypeObject *type, PyMethodDef *meth)
1932{
Guido van Rossum687ae002001-10-15 22:03:32 +00001933 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001934
1935 for (; meth->ml_name != NULL; meth++) {
1936 PyObject *descr;
1937 if (PyDict_GetItemString(dict, meth->ml_name))
1938 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00001939 if (meth->ml_flags & METH_CLASS) {
1940 if (meth->ml_flags & METH_STATIC) {
1941 PyErr_SetString(PyExc_ValueError,
1942 "method cannot be both class and static");
1943 return -1;
1944 }
1945 descr = create_specialmethod(meth, PyClassMethod_New);
1946 }
1947 else if (meth->ml_flags & METH_STATIC) {
1948 descr = create_specialmethod(meth, PyStaticMethod_New);
1949 }
1950 else {
1951 descr = PyDescr_NewMethod(type, meth);
1952 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001953 if (descr == NULL)
1954 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00001955 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001956 return -1;
1957 Py_DECREF(descr);
1958 }
1959 return 0;
1960}
1961
1962static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001963add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001964{
Guido van Rossum687ae002001-10-15 22:03:32 +00001965 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001966
1967 for (; memb->name != NULL; memb++) {
1968 PyObject *descr;
1969 if (PyDict_GetItemString(dict, memb->name))
1970 continue;
1971 descr = PyDescr_NewMember(type, memb);
1972 if (descr == NULL)
1973 return -1;
1974 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1975 return -1;
1976 Py_DECREF(descr);
1977 }
1978 return 0;
1979}
1980
1981static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001982add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001983{
Guido van Rossum687ae002001-10-15 22:03:32 +00001984 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001985
1986 for (; gsp->name != NULL; gsp++) {
1987 PyObject *descr;
1988 if (PyDict_GetItemString(dict, gsp->name))
1989 continue;
1990 descr = PyDescr_NewGetSet(type, gsp);
1991
1992 if (descr == NULL)
1993 return -1;
1994 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1995 return -1;
1996 Py_DECREF(descr);
1997 }
1998 return 0;
1999}
2000
Guido van Rossum13d52f02001-08-10 21:24:08 +00002001static void
2002inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002003{
2004 int oldsize, newsize;
2005
Guido van Rossum13d52f02001-08-10 21:24:08 +00002006 /* Special flag magic */
2007 if (!type->tp_as_buffer && base->tp_as_buffer) {
2008 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2009 type->tp_flags |=
2010 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2011 }
2012 if (!type->tp_as_sequence && base->tp_as_sequence) {
2013 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2014 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2015 }
2016 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2017 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2018 if ((!type->tp_as_number && base->tp_as_number) ||
2019 (!type->tp_as_sequence && base->tp_as_sequence)) {
2020 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2021 if (!type->tp_as_number && !type->tp_as_sequence) {
2022 type->tp_flags |= base->tp_flags &
2023 Py_TPFLAGS_HAVE_INPLACEOPS;
2024 }
2025 }
2026 /* Wow */
2027 }
2028 if (!type->tp_as_number && base->tp_as_number) {
2029 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2030 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2031 }
2032
2033 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002034 oldsize = base->tp_basicsize;
2035 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2036 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2037 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002038 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2039 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002040 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002041 if (type->tp_traverse == NULL)
2042 type->tp_traverse = base->tp_traverse;
2043 if (type->tp_clear == NULL)
2044 type->tp_clear = base->tp_clear;
2045 }
2046 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002047 /* The condition below could use some explanation.
2048 It appears that tp_new is not inherited for static types
2049 whose base class is 'object'; this seems to be a precaution
2050 so that old extension types don't suddenly become
2051 callable (object.__new__ wouldn't insure the invariants
2052 that the extension type's own factory function ensures).
2053 Heap types, of course, are under our control, so they do
2054 inherit tp_new; static extension types that specify some
2055 other built-in type as the default are considered
2056 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002057 if (base != &PyBaseObject_Type ||
2058 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2059 if (type->tp_new == NULL)
2060 type->tp_new = base->tp_new;
2061 }
2062 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002063 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002064
2065 /* Copy other non-function slots */
2066
2067#undef COPYVAL
2068#define COPYVAL(SLOT) \
2069 if (type->SLOT == 0) type->SLOT = base->SLOT
2070
2071 COPYVAL(tp_itemsize);
2072 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2073 COPYVAL(tp_weaklistoffset);
2074 }
2075 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2076 COPYVAL(tp_dictoffset);
2077 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002078}
2079
2080static void
2081inherit_slots(PyTypeObject *type, PyTypeObject *base)
2082{
2083 PyTypeObject *basebase;
2084
2085#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002086#undef COPYSLOT
2087#undef COPYNUM
2088#undef COPYSEQ
2089#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002090#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002091
2092#define SLOTDEFINED(SLOT) \
2093 (base->SLOT != 0 && \
2094 (basebase == NULL || base->SLOT != basebase->SLOT))
2095
Tim Peters6d6c1a32001-08-02 04:15:00 +00002096#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002097 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002098
2099#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2100#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2101#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002102#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002103
Guido van Rossum13d52f02001-08-10 21:24:08 +00002104 /* This won't inherit indirect slots (from tp_as_number etc.)
2105 if type doesn't provide the space. */
2106
2107 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2108 basebase = base->tp_base;
2109 if (basebase->tp_as_number == NULL)
2110 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002111 COPYNUM(nb_add);
2112 COPYNUM(nb_subtract);
2113 COPYNUM(nb_multiply);
2114 COPYNUM(nb_divide);
2115 COPYNUM(nb_remainder);
2116 COPYNUM(nb_divmod);
2117 COPYNUM(nb_power);
2118 COPYNUM(nb_negative);
2119 COPYNUM(nb_positive);
2120 COPYNUM(nb_absolute);
2121 COPYNUM(nb_nonzero);
2122 COPYNUM(nb_invert);
2123 COPYNUM(nb_lshift);
2124 COPYNUM(nb_rshift);
2125 COPYNUM(nb_and);
2126 COPYNUM(nb_xor);
2127 COPYNUM(nb_or);
2128 COPYNUM(nb_coerce);
2129 COPYNUM(nb_int);
2130 COPYNUM(nb_long);
2131 COPYNUM(nb_float);
2132 COPYNUM(nb_oct);
2133 COPYNUM(nb_hex);
2134 COPYNUM(nb_inplace_add);
2135 COPYNUM(nb_inplace_subtract);
2136 COPYNUM(nb_inplace_multiply);
2137 COPYNUM(nb_inplace_divide);
2138 COPYNUM(nb_inplace_remainder);
2139 COPYNUM(nb_inplace_power);
2140 COPYNUM(nb_inplace_lshift);
2141 COPYNUM(nb_inplace_rshift);
2142 COPYNUM(nb_inplace_and);
2143 COPYNUM(nb_inplace_xor);
2144 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002145 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2146 COPYNUM(nb_true_divide);
2147 COPYNUM(nb_floor_divide);
2148 COPYNUM(nb_inplace_true_divide);
2149 COPYNUM(nb_inplace_floor_divide);
2150 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002151 }
2152
Guido van Rossum13d52f02001-08-10 21:24:08 +00002153 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2154 basebase = base->tp_base;
2155 if (basebase->tp_as_sequence == NULL)
2156 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002157 COPYSEQ(sq_length);
2158 COPYSEQ(sq_concat);
2159 COPYSEQ(sq_repeat);
2160 COPYSEQ(sq_item);
2161 COPYSEQ(sq_slice);
2162 COPYSEQ(sq_ass_item);
2163 COPYSEQ(sq_ass_slice);
2164 COPYSEQ(sq_contains);
2165 COPYSEQ(sq_inplace_concat);
2166 COPYSEQ(sq_inplace_repeat);
2167 }
2168
Guido van Rossum13d52f02001-08-10 21:24:08 +00002169 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2170 basebase = base->tp_base;
2171 if (basebase->tp_as_mapping == NULL)
2172 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002173 COPYMAP(mp_length);
2174 COPYMAP(mp_subscript);
2175 COPYMAP(mp_ass_subscript);
2176 }
2177
Tim Petersfc57ccb2001-10-12 02:38:24 +00002178 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2179 basebase = base->tp_base;
2180 if (basebase->tp_as_buffer == NULL)
2181 basebase = NULL;
2182 COPYBUF(bf_getreadbuffer);
2183 COPYBUF(bf_getwritebuffer);
2184 COPYBUF(bf_getsegcount);
2185 COPYBUF(bf_getcharbuffer);
2186 }
2187
Guido van Rossum13d52f02001-08-10 21:24:08 +00002188 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002189
Tim Peters6d6c1a32001-08-02 04:15:00 +00002190 COPYSLOT(tp_dealloc);
2191 COPYSLOT(tp_print);
2192 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2193 type->tp_getattr = base->tp_getattr;
2194 type->tp_getattro = base->tp_getattro;
2195 }
2196 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2197 type->tp_setattr = base->tp_setattr;
2198 type->tp_setattro = base->tp_setattro;
2199 }
2200 /* tp_compare see tp_richcompare */
2201 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002202 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002203 COPYSLOT(tp_call);
2204 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002205 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002206 if (type->tp_compare == NULL &&
2207 type->tp_richcompare == NULL &&
2208 type->tp_hash == NULL)
2209 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002210 type->tp_compare = base->tp_compare;
2211 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002212 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002213 }
2214 }
2215 else {
2216 COPYSLOT(tp_compare);
2217 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002218 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2219 COPYSLOT(tp_iter);
2220 COPYSLOT(tp_iternext);
2221 }
2222 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2223 COPYSLOT(tp_descr_get);
2224 COPYSLOT(tp_descr_set);
2225 COPYSLOT(tp_dictoffset);
2226 COPYSLOT(tp_init);
2227 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002228 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002229 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002230 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002231}
2232
Jeremy Hylton938ace62002-07-17 16:30:39 +00002233static int add_operators(PyTypeObject *);
2234static int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002235
Tim Peters6d6c1a32001-08-02 04:15:00 +00002236int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002237PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002238{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002239 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002240 PyTypeObject *base;
2241 int i, n;
2242
Guido van Rossumcab05802002-06-10 15:29:03 +00002243 if (type->tp_flags & Py_TPFLAGS_READY) {
2244 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002245 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002246 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002247 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002248
2249 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002250
2251 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2252 base = type->tp_base;
2253 if (base == NULL && type != &PyBaseObject_Type)
2254 base = type->tp_base = &PyBaseObject_Type;
2255
Guido van Rossum0986d822002-04-08 01:38:42 +00002256 /* Initialize ob_type if NULL. This means extensions that want to be
2257 compilable separately on Windows can call PyType_Ready() instead of
2258 initializing the ob_type field of their type objects. */
2259 if (type->ob_type == NULL)
2260 type->ob_type = base->ob_type;
2261
Tim Peters6d6c1a32001-08-02 04:15:00 +00002262 /* Initialize tp_bases */
2263 bases = type->tp_bases;
2264 if (bases == NULL) {
2265 if (base == NULL)
2266 bases = PyTuple_New(0);
2267 else
2268 bases = Py_BuildValue("(O)", base);
2269 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002270 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002271 type->tp_bases = bases;
2272 }
2273
2274 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002275 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002276 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002277 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002278 }
2279
Guido van Rossum687ae002001-10-15 22:03:32 +00002280 /* Initialize tp_dict */
2281 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002282 if (dict == NULL) {
2283 dict = PyDict_New();
2284 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002285 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002286 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002287 }
2288
Guido van Rossum687ae002001-10-15 22:03:32 +00002289 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002290 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002291 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002292 if (type->tp_methods != NULL) {
2293 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002294 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002295 }
2296 if (type->tp_members != NULL) {
2297 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002298 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002299 }
2300 if (type->tp_getset != NULL) {
2301 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002302 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002303 }
2304
Tim Peters6d6c1a32001-08-02 04:15:00 +00002305 /* Calculate method resolution order */
2306 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002307 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002308 }
2309
Guido van Rossum13d52f02001-08-10 21:24:08 +00002310 /* Inherit special flags from dominant base */
2311 if (type->tp_base != NULL)
2312 inherit_special(type, type->tp_base);
2313
Tim Peters6d6c1a32001-08-02 04:15:00 +00002314 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002315 bases = type->tp_mro;
2316 assert(bases != NULL);
2317 assert(PyTuple_Check(bases));
2318 n = PyTuple_GET_SIZE(bases);
2319 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002320 PyObject *b = PyTuple_GET_ITEM(bases, i);
2321 if (PyType_Check(b))
2322 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002323 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002324
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002325 /* if the type dictionary doesn't contain a __doc__, set it from
2326 the tp_doc slot.
2327 */
2328 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2329 if (type->tp_doc != NULL) {
2330 PyObject *doc = PyString_FromString(type->tp_doc);
2331 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2332 Py_DECREF(doc);
2333 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002334 PyDict_SetItemString(type->tp_dict,
2335 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002336 }
2337 }
2338
Guido van Rossum13d52f02001-08-10 21:24:08 +00002339 /* Some more special stuff */
2340 base = type->tp_base;
2341 if (base != NULL) {
2342 if (type->tp_as_number == NULL)
2343 type->tp_as_number = base->tp_as_number;
2344 if (type->tp_as_sequence == NULL)
2345 type->tp_as_sequence = base->tp_as_sequence;
2346 if (type->tp_as_mapping == NULL)
2347 type->tp_as_mapping = base->tp_as_mapping;
2348 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002349
Guido van Rossum1c450732001-10-08 15:18:27 +00002350 /* Link into each base class's list of subclasses */
2351 bases = type->tp_bases;
2352 n = PyTuple_GET_SIZE(bases);
2353 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002354 PyObject *b = PyTuple_GET_ITEM(bases, i);
2355 if (PyType_Check(b) &&
2356 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002357 goto error;
2358 }
2359
Guido van Rossum13d52f02001-08-10 21:24:08 +00002360 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002361 assert(type->tp_dict != NULL);
2362 type->tp_flags =
2363 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002364 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002365
2366 error:
2367 type->tp_flags &= ~Py_TPFLAGS_READYING;
2368 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002369}
2370
Guido van Rossum1c450732001-10-08 15:18:27 +00002371static int
2372add_subclass(PyTypeObject *base, PyTypeObject *type)
2373{
2374 int i;
2375 PyObject *list, *ref, *new;
2376
2377 list = base->tp_subclasses;
2378 if (list == NULL) {
2379 base->tp_subclasses = list = PyList_New(0);
2380 if (list == NULL)
2381 return -1;
2382 }
2383 assert(PyList_Check(list));
2384 new = PyWeakref_NewRef((PyObject *)type, NULL);
2385 i = PyList_GET_SIZE(list);
2386 while (--i >= 0) {
2387 ref = PyList_GET_ITEM(list, i);
2388 assert(PyWeakref_CheckRef(ref));
2389 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2390 return PyList_SetItem(list, i, new);
2391 }
2392 i = PyList_Append(list, new);
2393 Py_DECREF(new);
2394 return i;
2395}
2396
Tim Peters6d6c1a32001-08-02 04:15:00 +00002397
2398/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2399
2400/* There's a wrapper *function* for each distinct function typedef used
2401 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2402 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2403 Most tables have only one entry; the tables for binary operators have two
2404 entries, one regular and one with reversed arguments. */
2405
2406static PyObject *
2407wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2408{
2409 inquiry func = (inquiry)wrapped;
2410 int res;
2411
2412 if (!PyArg_ParseTuple(args, ""))
2413 return NULL;
2414 res = (*func)(self);
2415 if (res == -1 && PyErr_Occurred())
2416 return NULL;
2417 return PyInt_FromLong((long)res);
2418}
2419
Tim Peters6d6c1a32001-08-02 04:15:00 +00002420static PyObject *
2421wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2422{
2423 binaryfunc func = (binaryfunc)wrapped;
2424 PyObject *other;
2425
2426 if (!PyArg_ParseTuple(args, "O", &other))
2427 return NULL;
2428 return (*func)(self, other);
2429}
2430
2431static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002432wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2433{
2434 binaryfunc func = (binaryfunc)wrapped;
2435 PyObject *other;
2436
2437 if (!PyArg_ParseTuple(args, "O", &other))
2438 return NULL;
2439 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002440 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002441 Py_INCREF(Py_NotImplemented);
2442 return Py_NotImplemented;
2443 }
2444 return (*func)(self, other);
2445}
2446
2447static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002448wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2449{
2450 binaryfunc func = (binaryfunc)wrapped;
2451 PyObject *other;
2452
2453 if (!PyArg_ParseTuple(args, "O", &other))
2454 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002455 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002456 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002457 Py_INCREF(Py_NotImplemented);
2458 return Py_NotImplemented;
2459 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002460 return (*func)(other, self);
2461}
2462
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002463static PyObject *
2464wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2465{
2466 coercion func = (coercion)wrapped;
2467 PyObject *other, *res;
2468 int ok;
2469
2470 if (!PyArg_ParseTuple(args, "O", &other))
2471 return NULL;
2472 ok = func(&self, &other);
2473 if (ok < 0)
2474 return NULL;
2475 if (ok > 0) {
2476 Py_INCREF(Py_NotImplemented);
2477 return Py_NotImplemented;
2478 }
2479 res = PyTuple_New(2);
2480 if (res == NULL) {
2481 Py_DECREF(self);
2482 Py_DECREF(other);
2483 return NULL;
2484 }
2485 PyTuple_SET_ITEM(res, 0, self);
2486 PyTuple_SET_ITEM(res, 1, other);
2487 return res;
2488}
2489
Tim Peters6d6c1a32001-08-02 04:15:00 +00002490static PyObject *
2491wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2492{
2493 ternaryfunc func = (ternaryfunc)wrapped;
2494 PyObject *other;
2495 PyObject *third = Py_None;
2496
2497 /* Note: This wrapper only works for __pow__() */
2498
2499 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2500 return NULL;
2501 return (*func)(self, other, third);
2502}
2503
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002504static PyObject *
2505wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2506{
2507 ternaryfunc func = (ternaryfunc)wrapped;
2508 PyObject *other;
2509 PyObject *third = Py_None;
2510
2511 /* Note: This wrapper only works for __pow__() */
2512
2513 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2514 return NULL;
2515 return (*func)(other, self, third);
2516}
2517
Tim Peters6d6c1a32001-08-02 04:15:00 +00002518static PyObject *
2519wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2520{
2521 unaryfunc func = (unaryfunc)wrapped;
2522
2523 if (!PyArg_ParseTuple(args, ""))
2524 return NULL;
2525 return (*func)(self);
2526}
2527
Tim Peters6d6c1a32001-08-02 04:15:00 +00002528static PyObject *
2529wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2530{
2531 intargfunc func = (intargfunc)wrapped;
2532 int i;
2533
2534 if (!PyArg_ParseTuple(args, "i", &i))
2535 return NULL;
2536 return (*func)(self, i);
2537}
2538
Guido van Rossum5d815f32001-08-17 21:57:47 +00002539static int
2540getindex(PyObject *self, PyObject *arg)
2541{
2542 int i;
2543
2544 i = PyInt_AsLong(arg);
2545 if (i == -1 && PyErr_Occurred())
2546 return -1;
2547 if (i < 0) {
2548 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2549 if (sq && sq->sq_length) {
2550 int n = (*sq->sq_length)(self);
2551 if (n < 0)
2552 return -1;
2553 i += n;
2554 }
2555 }
2556 return i;
2557}
2558
2559static PyObject *
2560wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2561{
2562 intargfunc func = (intargfunc)wrapped;
2563 PyObject *arg;
2564 int i;
2565
Guido van Rossumf4593e02001-10-03 12:09:30 +00002566 if (PyTuple_GET_SIZE(args) == 1) {
2567 arg = PyTuple_GET_ITEM(args, 0);
2568 i = getindex(self, arg);
2569 if (i == -1 && PyErr_Occurred())
2570 return NULL;
2571 return (*func)(self, i);
2572 }
2573 PyArg_ParseTuple(args, "O", &arg);
2574 assert(PyErr_Occurred());
2575 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002576}
2577
Tim Peters6d6c1a32001-08-02 04:15:00 +00002578static PyObject *
2579wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2580{
2581 intintargfunc func = (intintargfunc)wrapped;
2582 int i, j;
2583
2584 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2585 return NULL;
2586 return (*func)(self, i, j);
2587}
2588
Tim Peters6d6c1a32001-08-02 04:15:00 +00002589static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002590wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002591{
2592 intobjargproc func = (intobjargproc)wrapped;
2593 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002594 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002595
Guido van Rossum5d815f32001-08-17 21:57:47 +00002596 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2597 return NULL;
2598 i = getindex(self, arg);
2599 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002600 return NULL;
2601 res = (*func)(self, i, value);
2602 if (res == -1 && PyErr_Occurred())
2603 return NULL;
2604 Py_INCREF(Py_None);
2605 return Py_None;
2606}
2607
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002608static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002609wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002610{
2611 intobjargproc func = (intobjargproc)wrapped;
2612 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002613 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002614
Guido van Rossum5d815f32001-08-17 21:57:47 +00002615 if (!PyArg_ParseTuple(args, "O", &arg))
2616 return NULL;
2617 i = getindex(self, arg);
2618 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002619 return NULL;
2620 res = (*func)(self, i, NULL);
2621 if (res == -1 && PyErr_Occurred())
2622 return NULL;
2623 Py_INCREF(Py_None);
2624 return Py_None;
2625}
2626
Tim Peters6d6c1a32001-08-02 04:15:00 +00002627static PyObject *
2628wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2629{
2630 intintobjargproc func = (intintobjargproc)wrapped;
2631 int i, j, res;
2632 PyObject *value;
2633
2634 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2635 return NULL;
2636 res = (*func)(self, i, j, value);
2637 if (res == -1 && PyErr_Occurred())
2638 return NULL;
2639 Py_INCREF(Py_None);
2640 return Py_None;
2641}
2642
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002643static PyObject *
2644wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2645{
2646 intintobjargproc func = (intintobjargproc)wrapped;
2647 int i, j, res;
2648
2649 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2650 return NULL;
2651 res = (*func)(self, i, j, NULL);
2652 if (res == -1 && PyErr_Occurred())
2653 return NULL;
2654 Py_INCREF(Py_None);
2655 return Py_None;
2656}
2657
Tim Peters6d6c1a32001-08-02 04:15:00 +00002658/* XXX objobjproc is a misnomer; should be objargpred */
2659static PyObject *
2660wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2661{
2662 objobjproc func = (objobjproc)wrapped;
2663 int res;
2664 PyObject *value;
2665
2666 if (!PyArg_ParseTuple(args, "O", &value))
2667 return NULL;
2668 res = (*func)(self, value);
2669 if (res == -1 && PyErr_Occurred())
2670 return NULL;
2671 return PyInt_FromLong((long)res);
2672}
2673
Tim Peters6d6c1a32001-08-02 04:15:00 +00002674static PyObject *
2675wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2676{
2677 objobjargproc func = (objobjargproc)wrapped;
2678 int res;
2679 PyObject *key, *value;
2680
2681 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2682 return NULL;
2683 res = (*func)(self, key, value);
2684 if (res == -1 && PyErr_Occurred())
2685 return NULL;
2686 Py_INCREF(Py_None);
2687 return Py_None;
2688}
2689
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002690static PyObject *
2691wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2692{
2693 objobjargproc func = (objobjargproc)wrapped;
2694 int res;
2695 PyObject *key;
2696
2697 if (!PyArg_ParseTuple(args, "O", &key))
2698 return NULL;
2699 res = (*func)(self, key, NULL);
2700 if (res == -1 && PyErr_Occurred())
2701 return NULL;
2702 Py_INCREF(Py_None);
2703 return Py_None;
2704}
2705
Tim Peters6d6c1a32001-08-02 04:15:00 +00002706static PyObject *
2707wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2708{
2709 cmpfunc func = (cmpfunc)wrapped;
2710 int res;
2711 PyObject *other;
2712
2713 if (!PyArg_ParseTuple(args, "O", &other))
2714 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002715 if (other->ob_type->tp_compare != func &&
2716 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002717 PyErr_Format(
2718 PyExc_TypeError,
2719 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2720 self->ob_type->tp_name,
2721 self->ob_type->tp_name,
2722 other->ob_type->tp_name);
2723 return NULL;
2724 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002725 res = (*func)(self, other);
2726 if (PyErr_Occurred())
2727 return NULL;
2728 return PyInt_FromLong((long)res);
2729}
2730
Tim Peters6d6c1a32001-08-02 04:15:00 +00002731static PyObject *
2732wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2733{
2734 setattrofunc func = (setattrofunc)wrapped;
2735 int res;
2736 PyObject *name, *value;
2737
2738 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2739 return NULL;
2740 res = (*func)(self, name, value);
2741 if (res < 0)
2742 return NULL;
2743 Py_INCREF(Py_None);
2744 return Py_None;
2745}
2746
2747static PyObject *
2748wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2749{
2750 setattrofunc func = (setattrofunc)wrapped;
2751 int res;
2752 PyObject *name;
2753
2754 if (!PyArg_ParseTuple(args, "O", &name))
2755 return NULL;
2756 res = (*func)(self, name, NULL);
2757 if (res < 0)
2758 return NULL;
2759 Py_INCREF(Py_None);
2760 return Py_None;
2761}
2762
Tim Peters6d6c1a32001-08-02 04:15:00 +00002763static PyObject *
2764wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2765{
2766 hashfunc func = (hashfunc)wrapped;
2767 long res;
2768
2769 if (!PyArg_ParseTuple(args, ""))
2770 return NULL;
2771 res = (*func)(self);
2772 if (res == -1 && PyErr_Occurred())
2773 return NULL;
2774 return PyInt_FromLong(res);
2775}
2776
Tim Peters6d6c1a32001-08-02 04:15:00 +00002777static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002778wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002779{
2780 ternaryfunc func = (ternaryfunc)wrapped;
2781
Guido van Rossumc8e56452001-10-22 00:43:43 +00002782 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002783}
2784
Tim Peters6d6c1a32001-08-02 04:15:00 +00002785static PyObject *
2786wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2787{
2788 richcmpfunc func = (richcmpfunc)wrapped;
2789 PyObject *other;
2790
2791 if (!PyArg_ParseTuple(args, "O", &other))
2792 return NULL;
2793 return (*func)(self, other, op);
2794}
2795
2796#undef RICHCMP_WRAPPER
2797#define RICHCMP_WRAPPER(NAME, OP) \
2798static PyObject * \
2799richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2800{ \
2801 return wrap_richcmpfunc(self, args, wrapped, OP); \
2802}
2803
Jack Jansen8e938b42001-08-08 15:29:49 +00002804RICHCMP_WRAPPER(lt, Py_LT)
2805RICHCMP_WRAPPER(le, Py_LE)
2806RICHCMP_WRAPPER(eq, Py_EQ)
2807RICHCMP_WRAPPER(ne, Py_NE)
2808RICHCMP_WRAPPER(gt, Py_GT)
2809RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002810
Tim Peters6d6c1a32001-08-02 04:15:00 +00002811static PyObject *
2812wrap_next(PyObject *self, PyObject *args, void *wrapped)
2813{
2814 unaryfunc func = (unaryfunc)wrapped;
2815 PyObject *res;
2816
2817 if (!PyArg_ParseTuple(args, ""))
2818 return NULL;
2819 res = (*func)(self);
2820 if (res == NULL && !PyErr_Occurred())
2821 PyErr_SetNone(PyExc_StopIteration);
2822 return res;
2823}
2824
Tim Peters6d6c1a32001-08-02 04:15:00 +00002825static PyObject *
2826wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2827{
2828 descrgetfunc func = (descrgetfunc)wrapped;
2829 PyObject *obj;
2830 PyObject *type = NULL;
2831
2832 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2833 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002834 return (*func)(self, obj, type);
2835}
2836
Tim Peters6d6c1a32001-08-02 04:15:00 +00002837static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002838wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002839{
2840 descrsetfunc func = (descrsetfunc)wrapped;
2841 PyObject *obj, *value;
2842 int ret;
2843
2844 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2845 return NULL;
2846 ret = (*func)(self, obj, value);
2847 if (ret < 0)
2848 return NULL;
2849 Py_INCREF(Py_None);
2850 return Py_None;
2851}
Guido van Rossum22b13872002-08-06 21:41:44 +00002852
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00002853static PyObject *
2854wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
2855{
2856 descrsetfunc func = (descrsetfunc)wrapped;
2857 PyObject *obj;
2858 int ret;
2859
2860 if (!PyArg_ParseTuple(args, "O", &obj))
2861 return NULL;
2862 ret = (*func)(self, obj, NULL);
2863 if (ret < 0)
2864 return NULL;
2865 Py_INCREF(Py_None);
2866 return Py_None;
2867}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002868
Tim Peters6d6c1a32001-08-02 04:15:00 +00002869static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002870wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002871{
2872 initproc func = (initproc)wrapped;
2873
Guido van Rossumc8e56452001-10-22 00:43:43 +00002874 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002875 return NULL;
2876 Py_INCREF(Py_None);
2877 return Py_None;
2878}
2879
Tim Peters6d6c1a32001-08-02 04:15:00 +00002880static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002881tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002882{
Barry Warsaw60f01882001-08-22 19:24:42 +00002883 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002884 PyObject *arg0, *res;
2885
2886 if (self == NULL || !PyType_Check(self))
2887 Py_FatalError("__new__() called with non-type 'self'");
2888 type = (PyTypeObject *)self;
2889 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002890 PyErr_Format(PyExc_TypeError,
2891 "%s.__new__(): not enough arguments",
2892 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002893 return NULL;
2894 }
2895 arg0 = PyTuple_GET_ITEM(args, 0);
2896 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002897 PyErr_Format(PyExc_TypeError,
2898 "%s.__new__(X): X is not a type object (%s)",
2899 type->tp_name,
2900 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002901 return NULL;
2902 }
2903 subtype = (PyTypeObject *)arg0;
2904 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002905 PyErr_Format(PyExc_TypeError,
2906 "%s.__new__(%s): %s is not a subtype of %s",
2907 type->tp_name,
2908 subtype->tp_name,
2909 subtype->tp_name,
2910 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002911 return NULL;
2912 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002913
2914 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002915 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002916 most derived base that's not a heap type is this type. */
2917 staticbase = subtype;
2918 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2919 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002920 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002921 PyErr_Format(PyExc_TypeError,
2922 "%s.__new__(%s) is not safe, use %s.__new__()",
2923 type->tp_name,
2924 subtype->tp_name,
2925 staticbase == NULL ? "?" : staticbase->tp_name);
2926 return NULL;
2927 }
2928
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002929 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2930 if (args == NULL)
2931 return NULL;
2932 res = type->tp_new(subtype, args, kwds);
2933 Py_DECREF(args);
2934 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002935}
2936
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002937static struct PyMethodDef tp_new_methoddef[] = {
2938 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2939 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002940 {0}
2941};
2942
2943static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002944add_tp_new_wrapper(PyTypeObject *type)
2945{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002946 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002947
Guido van Rossum687ae002001-10-15 22:03:32 +00002948 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002949 return 0;
2950 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002951 if (func == NULL)
2952 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002953 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002954}
2955
Guido van Rossumf040ede2001-08-07 16:40:56 +00002956/* Slot wrappers that call the corresponding __foo__ slot. See comments
2957 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002958
Guido van Rossumdc91b992001-08-08 22:26:22 +00002959#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002960static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002961FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002962{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002963 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002964 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002965}
2966
Guido van Rossumdc91b992001-08-08 22:26:22 +00002967#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002968static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002969FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002970{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002971 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002972 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002973}
2974
Guido van Rossumdc91b992001-08-08 22:26:22 +00002975
2976#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002977static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002978FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002979{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002980 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002981 int do_other = self->ob_type != other->ob_type && \
2982 other->ob_type->tp_as_number != NULL && \
2983 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002984 if (self->ob_type->tp_as_number != NULL && \
2985 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2986 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002987 if (do_other && \
2988 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2989 r = call_maybe( \
2990 other, ROPSTR, &rcache_str, "(O)", self); \
2991 if (r != Py_NotImplemented) \
2992 return r; \
2993 Py_DECREF(r); \
2994 do_other = 0; \
2995 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002996 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002997 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002998 if (r != Py_NotImplemented || \
2999 other->ob_type == self->ob_type) \
3000 return r; \
3001 Py_DECREF(r); \
3002 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003003 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003004 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003005 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003006 } \
3007 Py_INCREF(Py_NotImplemented); \
3008 return Py_NotImplemented; \
3009}
3010
3011#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3012 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3013
3014#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3015static PyObject * \
3016FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3017{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003018 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003019 return call_method(self, OPSTR, &cache_str, \
3020 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003021}
3022
3023static int
3024slot_sq_length(PyObject *self)
3025{
Guido van Rossum2730b132001-08-28 18:22:14 +00003026 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003027 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003028 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003029
3030 if (res == NULL)
3031 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003032 len = (int)PyInt_AsLong(res);
3033 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003034 if (len == -1 && PyErr_Occurred())
3035 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003036 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003037 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003038 "__len__() should return >= 0");
3039 return -1;
3040 }
Guido van Rossum26111622001-10-01 16:42:49 +00003041 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003042}
3043
Guido van Rossumdc91b992001-08-08 22:26:22 +00003044SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3045SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003046
3047/* Super-optimized version of slot_sq_item.
3048 Other slots could do the same... */
3049static PyObject *
3050slot_sq_item(PyObject *self, int i)
3051{
3052 static PyObject *getitem_str;
3053 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3054 descrgetfunc f;
3055
3056 if (getitem_str == NULL) {
3057 getitem_str = PyString_InternFromString("__getitem__");
3058 if (getitem_str == NULL)
3059 return NULL;
3060 }
3061 func = _PyType_Lookup(self->ob_type, getitem_str);
3062 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003063 if ((f = func->ob_type->tp_descr_get) == NULL)
3064 Py_INCREF(func);
3065 else
3066 func = f(func, self, (PyObject *)(self->ob_type));
3067 ival = PyInt_FromLong(i);
3068 if (ival != NULL) {
3069 args = PyTuple_New(1);
3070 if (args != NULL) {
3071 PyTuple_SET_ITEM(args, 0, ival);
3072 retval = PyObject_Call(func, args, NULL);
3073 Py_XDECREF(args);
3074 Py_XDECREF(func);
3075 return retval;
3076 }
3077 }
3078 }
3079 else {
3080 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3081 }
3082 Py_XDECREF(args);
3083 Py_XDECREF(ival);
3084 Py_XDECREF(func);
3085 return NULL;
3086}
3087
Guido van Rossumdc91b992001-08-08 22:26:22 +00003088SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003089
3090static int
3091slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3092{
3093 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003094 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003095
3096 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003097 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003098 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003099 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003100 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003101 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003102 if (res == NULL)
3103 return -1;
3104 Py_DECREF(res);
3105 return 0;
3106}
3107
3108static int
3109slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3110{
3111 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003112 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003113
3114 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003115 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003116 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003117 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003118 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003119 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003120 if (res == NULL)
3121 return -1;
3122 Py_DECREF(res);
3123 return 0;
3124}
3125
3126static int
3127slot_sq_contains(PyObject *self, PyObject *value)
3128{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003129 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003130 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003131
Guido van Rossum55f20992001-10-01 17:18:22 +00003132 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003133
3134 if (func != NULL) {
3135 args = Py_BuildValue("(O)", value);
3136 if (args == NULL)
3137 res = NULL;
3138 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003139 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003140 Py_DECREF(args);
3141 }
3142 Py_DECREF(func);
3143 if (res == NULL)
3144 return -1;
3145 return PyObject_IsTrue(res);
3146 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003147 else if (PyErr_Occurred())
3148 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003149 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003150 return _PySequence_IterSearch(self, value,
3151 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003152 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003153}
3154
Guido van Rossumdc91b992001-08-08 22:26:22 +00003155SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3156SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003157
3158#define slot_mp_length slot_sq_length
3159
Guido van Rossumdc91b992001-08-08 22:26:22 +00003160SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003161
3162static int
3163slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3164{
3165 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003166 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003167
3168 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003169 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003170 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003171 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003172 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003173 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003174 if (res == NULL)
3175 return -1;
3176 Py_DECREF(res);
3177 return 0;
3178}
3179
Guido van Rossumdc91b992001-08-08 22:26:22 +00003180SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3181SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3182SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3183SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3184SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3185SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3186
Jeremy Hylton938ace62002-07-17 16:30:39 +00003187static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003188
3189SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3190 nb_power, "__pow__", "__rpow__")
3191
3192static PyObject *
3193slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3194{
Guido van Rossum2730b132001-08-28 18:22:14 +00003195 static PyObject *pow_str;
3196
Guido van Rossumdc91b992001-08-08 22:26:22 +00003197 if (modulus == Py_None)
3198 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003199 /* Three-arg power doesn't use __rpow__. But ternary_op
3200 can call this when the second argument's type uses
3201 slot_nb_power, so check before calling self.__pow__. */
3202 if (self->ob_type->tp_as_number != NULL &&
3203 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3204 return call_method(self, "__pow__", &pow_str,
3205 "(OO)", other, modulus);
3206 }
3207 Py_INCREF(Py_NotImplemented);
3208 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003209}
3210
3211SLOT0(slot_nb_negative, "__neg__")
3212SLOT0(slot_nb_positive, "__pos__")
3213SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003214
3215static int
3216slot_nb_nonzero(PyObject *self)
3217{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003218 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003219 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003220
Guido van Rossum55f20992001-10-01 17:18:22 +00003221 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003222 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003223 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003224 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003225 func = lookup_maybe(self, "__len__", &len_str);
3226 if (func == NULL) {
3227 if (PyErr_Occurred())
3228 return -1;
3229 else
3230 return 1;
3231 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003232 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003233 res = PyObject_CallObject(func, NULL);
3234 Py_DECREF(func);
3235 if (res == NULL)
3236 return -1;
3237 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003238}
3239
Guido van Rossumdc91b992001-08-08 22:26:22 +00003240SLOT0(slot_nb_invert, "__invert__")
3241SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3242SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3243SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3244SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3245SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003246
3247static int
3248slot_nb_coerce(PyObject **a, PyObject **b)
3249{
3250 static PyObject *coerce_str;
3251 PyObject *self = *a, *other = *b;
3252
3253 if (self->ob_type->tp_as_number != NULL &&
3254 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3255 PyObject *r;
3256 r = call_maybe(
3257 self, "__coerce__", &coerce_str, "(O)", other);
3258 if (r == NULL)
3259 return -1;
3260 if (r == Py_NotImplemented) {
3261 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003262 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003263 else {
3264 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3265 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003266 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003267 Py_DECREF(r);
3268 return -1;
3269 }
3270 *a = PyTuple_GET_ITEM(r, 0);
3271 Py_INCREF(*a);
3272 *b = PyTuple_GET_ITEM(r, 1);
3273 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003274 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003275 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003276 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003277 }
3278 if (other->ob_type->tp_as_number != NULL &&
3279 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3280 PyObject *r;
3281 r = call_maybe(
3282 other, "__coerce__", &coerce_str, "(O)", self);
3283 if (r == NULL)
3284 return -1;
3285 if (r == Py_NotImplemented) {
3286 Py_DECREF(r);
3287 return 1;
3288 }
3289 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3290 PyErr_SetString(PyExc_TypeError,
3291 "__coerce__ didn't return a 2-tuple");
3292 Py_DECREF(r);
3293 return -1;
3294 }
3295 *a = PyTuple_GET_ITEM(r, 1);
3296 Py_INCREF(*a);
3297 *b = PyTuple_GET_ITEM(r, 0);
3298 Py_INCREF(*b);
3299 Py_DECREF(r);
3300 return 0;
3301 }
3302 return 1;
3303}
3304
Guido van Rossumdc91b992001-08-08 22:26:22 +00003305SLOT0(slot_nb_int, "__int__")
3306SLOT0(slot_nb_long, "__long__")
3307SLOT0(slot_nb_float, "__float__")
3308SLOT0(slot_nb_oct, "__oct__")
3309SLOT0(slot_nb_hex, "__hex__")
3310SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3311SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3312SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3313SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3314SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3315SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3316SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3317SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3318SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3319SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3320SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3321SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3322 "__floordiv__", "__rfloordiv__")
3323SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3324SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3325SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003326
3327static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003328half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003329{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003330 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003331 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003332 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003333
Guido van Rossum60718732001-08-28 17:47:51 +00003334 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003335 if (func == NULL) {
3336 PyErr_Clear();
3337 }
3338 else {
3339 args = Py_BuildValue("(O)", other);
3340 if (args == NULL)
3341 res = NULL;
3342 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003343 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003344 Py_DECREF(args);
3345 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00003346 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003347 if (res != Py_NotImplemented) {
3348 if (res == NULL)
3349 return -2;
3350 c = PyInt_AsLong(res);
3351 Py_DECREF(res);
3352 if (c == -1 && PyErr_Occurred())
3353 return -2;
3354 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3355 }
3356 Py_DECREF(res);
3357 }
3358 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003359}
3360
Guido van Rossumab3b0342001-09-18 20:38:53 +00003361/* This slot is published for the benefit of try_3way_compare in object.c */
3362int
3363_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003364{
3365 int c;
3366
Guido van Rossumab3b0342001-09-18 20:38:53 +00003367 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003368 c = half_compare(self, other);
3369 if (c <= 1)
3370 return c;
3371 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003372 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003373 c = half_compare(other, self);
3374 if (c < -1)
3375 return -2;
3376 if (c <= 1)
3377 return -c;
3378 }
3379 return (void *)self < (void *)other ? -1 :
3380 (void *)self > (void *)other ? 1 : 0;
3381}
3382
3383static PyObject *
3384slot_tp_repr(PyObject *self)
3385{
3386 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003387 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003388
Guido van Rossum60718732001-08-28 17:47:51 +00003389 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003390 if (func != NULL) {
3391 res = PyEval_CallObject(func, NULL);
3392 Py_DECREF(func);
3393 return res;
3394 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003395 PyErr_Clear();
3396 return PyString_FromFormat("<%s object at %p>",
3397 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003398}
3399
3400static PyObject *
3401slot_tp_str(PyObject *self)
3402{
3403 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003404 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003405
Guido van Rossum60718732001-08-28 17:47:51 +00003406 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003407 if (func != NULL) {
3408 res = PyEval_CallObject(func, NULL);
3409 Py_DECREF(func);
3410 return res;
3411 }
3412 else {
3413 PyErr_Clear();
3414 return slot_tp_repr(self);
3415 }
3416}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003417
3418static long
3419slot_tp_hash(PyObject *self)
3420{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003421 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003422 static PyObject *hash_str, *eq_str, *cmp_str;
3423
Tim Peters6d6c1a32001-08-02 04:15:00 +00003424 long h;
3425
Guido van Rossum60718732001-08-28 17:47:51 +00003426 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003427
3428 if (func != NULL) {
3429 res = PyEval_CallObject(func, NULL);
3430 Py_DECREF(func);
3431 if (res == NULL)
3432 return -1;
3433 h = PyInt_AsLong(res);
3434 }
3435 else {
3436 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003437 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003438 if (func == NULL) {
3439 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003440 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003441 }
3442 if (func != NULL) {
3443 Py_DECREF(func);
3444 PyErr_SetString(PyExc_TypeError, "unhashable type");
3445 return -1;
3446 }
3447 PyErr_Clear();
3448 h = _Py_HashPointer((void *)self);
3449 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003450 if (h == -1 && !PyErr_Occurred())
3451 h = -2;
3452 return h;
3453}
3454
3455static PyObject *
3456slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3457{
Guido van Rossum60718732001-08-28 17:47:51 +00003458 static PyObject *call_str;
3459 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003460 PyObject *res;
3461
3462 if (meth == NULL)
3463 return NULL;
3464 res = PyObject_Call(meth, args, kwds);
3465 Py_DECREF(meth);
3466 return res;
3467}
3468
Guido van Rossum14a6f832001-10-17 13:59:09 +00003469/* There are two slot dispatch functions for tp_getattro.
3470
3471 - slot_tp_getattro() is used when __getattribute__ is overridden
3472 but no __getattr__ hook is present;
3473
3474 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3475
Guido van Rossumc334df52002-04-04 23:44:47 +00003476 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3477 detects the absence of __getattr__ and then installs the simpler slot if
3478 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003479
Tim Peters6d6c1a32001-08-02 04:15:00 +00003480static PyObject *
3481slot_tp_getattro(PyObject *self, PyObject *name)
3482{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003483 static PyObject *getattribute_str = NULL;
3484 return call_method(self, "__getattribute__", &getattribute_str,
3485 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003486}
3487
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003488static PyObject *
3489slot_tp_getattr_hook(PyObject *self, PyObject *name)
3490{
3491 PyTypeObject *tp = self->ob_type;
3492 PyObject *getattr, *getattribute, *res;
3493 static PyObject *getattribute_str = NULL;
3494 static PyObject *getattr_str = NULL;
3495
3496 if (getattr_str == NULL) {
3497 getattr_str = PyString_InternFromString("__getattr__");
3498 if (getattr_str == NULL)
3499 return NULL;
3500 }
3501 if (getattribute_str == NULL) {
3502 getattribute_str =
3503 PyString_InternFromString("__getattribute__");
3504 if (getattribute_str == NULL)
3505 return NULL;
3506 }
3507 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003508 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003509 /* No __getattr__ hook: use a simpler dispatcher */
3510 tp->tp_getattro = slot_tp_getattro;
3511 return slot_tp_getattro(self, name);
3512 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003513 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003514 if (getattribute == NULL ||
3515 (getattribute->ob_type == &PyWrapperDescr_Type &&
3516 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3517 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003518 res = PyObject_GenericGetAttr(self, name);
3519 else
3520 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003521 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003522 PyErr_Clear();
3523 res = PyObject_CallFunction(getattr, "OO", self, name);
3524 }
3525 return res;
3526}
3527
Tim Peters6d6c1a32001-08-02 04:15:00 +00003528static int
3529slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3530{
3531 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003532 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003533
3534 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003535 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003536 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003537 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003538 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003539 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003540 if (res == NULL)
3541 return -1;
3542 Py_DECREF(res);
3543 return 0;
3544}
3545
3546/* Map rich comparison operators to their __xx__ namesakes */
3547static char *name_op[] = {
3548 "__lt__",
3549 "__le__",
3550 "__eq__",
3551 "__ne__",
3552 "__gt__",
3553 "__ge__",
3554};
3555
3556static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003557half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003558{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003559 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003560 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003561
Guido van Rossum60718732001-08-28 17:47:51 +00003562 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003563 if (func == NULL) {
3564 PyErr_Clear();
3565 Py_INCREF(Py_NotImplemented);
3566 return Py_NotImplemented;
3567 }
3568 args = Py_BuildValue("(O)", other);
3569 if (args == NULL)
3570 res = NULL;
3571 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003572 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003573 Py_DECREF(args);
3574 }
3575 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003576 return res;
3577}
3578
Guido van Rossumb8f63662001-08-15 23:57:02 +00003579/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3580static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3581
3582static PyObject *
3583slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3584{
3585 PyObject *res;
3586
3587 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3588 res = half_richcompare(self, other, op);
3589 if (res != Py_NotImplemented)
3590 return res;
3591 Py_DECREF(res);
3592 }
3593 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3594 res = half_richcompare(other, self, swapped_op[op]);
3595 if (res != Py_NotImplemented) {
3596 return res;
3597 }
3598 Py_DECREF(res);
3599 }
3600 Py_INCREF(Py_NotImplemented);
3601 return Py_NotImplemented;
3602}
3603
3604static PyObject *
3605slot_tp_iter(PyObject *self)
3606{
3607 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003608 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003609
Guido van Rossum60718732001-08-28 17:47:51 +00003610 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003611 if (func != NULL) {
3612 res = PyObject_CallObject(func, NULL);
3613 Py_DECREF(func);
3614 return res;
3615 }
3616 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003617 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003618 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003619 PyErr_SetString(PyExc_TypeError,
3620 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003621 return NULL;
3622 }
3623 Py_DECREF(func);
3624 return PySeqIter_New(self);
3625}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003626
3627static PyObject *
3628slot_tp_iternext(PyObject *self)
3629{
Guido van Rossum2730b132001-08-28 18:22:14 +00003630 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003631 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003632}
3633
Guido van Rossum1a493502001-08-17 16:47:50 +00003634static PyObject *
3635slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3636{
3637 PyTypeObject *tp = self->ob_type;
3638 PyObject *get;
3639 static PyObject *get_str = NULL;
3640
3641 if (get_str == NULL) {
3642 get_str = PyString_InternFromString("__get__");
3643 if (get_str == NULL)
3644 return NULL;
3645 }
3646 get = _PyType_Lookup(tp, get_str);
3647 if (get == NULL) {
3648 /* Avoid further slowdowns */
3649 if (tp->tp_descr_get == slot_tp_descr_get)
3650 tp->tp_descr_get = NULL;
3651 Py_INCREF(self);
3652 return self;
3653 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003654 if (obj == NULL)
3655 obj = Py_None;
3656 if (type == NULL)
3657 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003658 return PyObject_CallFunction(get, "OOO", self, obj, type);
3659}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003660
3661static int
3662slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3663{
Guido van Rossum2c252392001-08-24 10:13:31 +00003664 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003665 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003666
3667 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003668 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003669 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003670 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003671 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003672 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003673 if (res == NULL)
3674 return -1;
3675 Py_DECREF(res);
3676 return 0;
3677}
3678
3679static int
3680slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3681{
Guido van Rossum60718732001-08-28 17:47:51 +00003682 static PyObject *init_str;
3683 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003684 PyObject *res;
3685
3686 if (meth == NULL)
3687 return -1;
3688 res = PyObject_Call(meth, args, kwds);
3689 Py_DECREF(meth);
3690 if (res == NULL)
3691 return -1;
3692 Py_DECREF(res);
3693 return 0;
3694}
3695
3696static PyObject *
3697slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3698{
3699 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3700 PyObject *newargs, *x;
3701 int i, n;
3702
3703 if (func == NULL)
3704 return NULL;
3705 assert(PyTuple_Check(args));
3706 n = PyTuple_GET_SIZE(args);
3707 newargs = PyTuple_New(n+1);
3708 if (newargs == NULL)
3709 return NULL;
3710 Py_INCREF(type);
3711 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3712 for (i = 0; i < n; i++) {
3713 x = PyTuple_GET_ITEM(args, i);
3714 Py_INCREF(x);
3715 PyTuple_SET_ITEM(newargs, i+1, x);
3716 }
3717 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003718 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003719 Py_DECREF(func);
3720 return x;
3721}
3722
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003723
3724/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3725 functions. The offsets here are relative to the 'etype' structure, which
3726 incorporates the additional structures used for numbers, sequences and
3727 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3728 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00003729 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3730 terminated with an all-zero entry. (This table is further initialized and
3731 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003732
Guido van Rossum6d204072001-10-21 00:44:31 +00003733typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003734
3735#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003736#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003737#undef ETSLOT
3738#undef SQSLOT
3739#undef MPSLOT
3740#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003741#undef UNSLOT
3742#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003743#undef BINSLOT
3744#undef RBINSLOT
3745
Guido van Rossum6d204072001-10-21 00:44:31 +00003746#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3747 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003748#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3749 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3750 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003751#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3752 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3753#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3754 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3755#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3756 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3757#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3758 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3759#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3760 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3761 "x." NAME "() <==> " DOC)
3762#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3763 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3764 "x." NAME "(y) <==> x" DOC "y")
3765#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3766 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3767 "x." NAME "(y) <==> x" DOC "y")
3768#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3769 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3770 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003771
3772static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003773 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3774 "x.__len__() <==> len(x)"),
3775 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3776 "x.__add__(y) <==> x+y"),
3777 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3778 "x.__mul__(n) <==> x*n"),
3779 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3780 "x.__rmul__(n) <==> n*x"),
3781 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3782 "x.__getitem__(y) <==> x[y]"),
3783 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3784 "x.__getslice__(i, j) <==> x[i:j]"),
3785 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3786 "x.__setitem__(i, y) <==> x[i]=y"),
3787 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3788 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003789 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003790 wrap_intintobjargproc,
3791 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3792 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3793 "x.__delslice__(i, j) <==> del x[i:j]"),
3794 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3795 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003796 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003797 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003798 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003799 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003800
Guido van Rossum6d204072001-10-21 00:44:31 +00003801 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3802 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003803 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003804 wrap_binaryfunc,
3805 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003806 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003807 wrap_objobjargproc,
3808 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003809 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003810 wrap_delitem,
3811 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003812
Guido van Rossum6d204072001-10-21 00:44:31 +00003813 BINSLOT("__add__", nb_add, slot_nb_add,
3814 "+"),
3815 RBINSLOT("__radd__", nb_add, slot_nb_add,
3816 "+"),
3817 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3818 "-"),
3819 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3820 "-"),
3821 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3822 "*"),
3823 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3824 "*"),
3825 BINSLOT("__div__", nb_divide, slot_nb_divide,
3826 "/"),
3827 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3828 "/"),
3829 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3830 "%"),
3831 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3832 "%"),
3833 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3834 "divmod(x, y)"),
3835 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3836 "divmod(y, x)"),
3837 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3838 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3839 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3840 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3841 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3842 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3843 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3844 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003845 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003846 "x != 0"),
3847 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3848 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3849 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3850 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3851 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3852 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3853 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3854 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3855 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3856 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3857 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3858 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3859 "x.__coerce__(y) <==> coerce(x, y)"),
3860 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3861 "int(x)"),
3862 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3863 "long(x)"),
3864 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3865 "float(x)"),
3866 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3867 "oct(x)"),
3868 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3869 "hex(x)"),
3870 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3871 wrap_binaryfunc, "+"),
3872 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3873 wrap_binaryfunc, "-"),
3874 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3875 wrap_binaryfunc, "*"),
3876 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3877 wrap_binaryfunc, "/"),
3878 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3879 wrap_binaryfunc, "%"),
3880 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3881 wrap_ternaryfunc, "**"),
3882 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3883 wrap_binaryfunc, "<<"),
3884 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3885 wrap_binaryfunc, ">>"),
3886 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3887 wrap_binaryfunc, "&"),
3888 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3889 wrap_binaryfunc, "^"),
3890 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3891 wrap_binaryfunc, "|"),
3892 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3893 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3894 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3895 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3896 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3897 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3898 IBSLOT("__itruediv__", nb_inplace_true_divide,
3899 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003900
Guido van Rossum6d204072001-10-21 00:44:31 +00003901 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3902 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003903 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003904 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3905 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003906 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003907 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3908 "x.__cmp__(y) <==> cmp(x,y)"),
3909 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3910 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003911 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3912 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003913 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003914 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3915 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3916 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3917 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3918 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3919 "x.__setattr__('name', value) <==> x.name = value"),
3920 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3921 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3922 "x.__delattr__('name') <==> del x.name"),
3923 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3924 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3925 "x.__lt__(y) <==> x<y"),
3926 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3927 "x.__le__(y) <==> x<=y"),
3928 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3929 "x.__eq__(y) <==> x==y"),
3930 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3931 "x.__ne__(y) <==> x!=y"),
3932 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3933 "x.__gt__(y) <==> x>y"),
3934 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3935 "x.__ge__(y) <==> x>=y"),
3936 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3937 "x.__iter__() <==> iter(x)"),
3938 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3939 "x.next() -> the next value, or raise StopIteration"),
3940 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3941 "descr.__get__(obj[, type]) -> value"),
3942 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3943 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003944 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
3945 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003946 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003947 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003948 "see x.__class__.__doc__ for signature",
3949 PyWrapperFlag_KEYWORDS),
3950 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003951 {NULL}
3952};
3953
Guido van Rossumc334df52002-04-04 23:44:47 +00003954/* Given a type pointer and an offset gotten from a slotdef entry, return a
3955 pointer to the actual slot. This is not quite the same as simply adding
3956 the offset to the type pointer, since it takes care to indirect through the
3957 proper indirection pointer (as_buffer, etc.); it returns NULL if the
3958 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003959static void **
3960slotptr(PyTypeObject *type, int offset)
3961{
3962 char *ptr;
3963
Guido van Rossum09638c12002-06-13 19:17:46 +00003964 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003965 assert(offset >= 0);
3966 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00003967 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003968 ptr = (void *)type->tp_as_sequence;
3969 offset -= offsetof(etype, as_sequence);
3970 }
Guido van Rossum09638c12002-06-13 19:17:46 +00003971 else if (offset >= offsetof(etype, as_mapping)) {
3972 ptr = (void *)type->tp_as_mapping;
3973 offset -= offsetof(etype, as_mapping);
3974 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003975 else if (offset >= offsetof(etype, as_number)) {
3976 ptr = (void *)type->tp_as_number;
3977 offset -= offsetof(etype, as_number);
3978 }
3979 else {
3980 ptr = (void *)type;
3981 }
3982 if (ptr != NULL)
3983 ptr += offset;
3984 return (void **)ptr;
3985}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003986
Guido van Rossumc334df52002-04-04 23:44:47 +00003987/* Length of array of slotdef pointers used to store slots with the
3988 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
3989 the same __name__, for any __name__. Since that's a static property, it is
3990 appropriate to declare fixed-size arrays for this. */
3991#define MAX_EQUIV 10
3992
3993/* Return a slot pointer for a given name, but ONLY if the attribute has
3994 exactly one slot function. The name must be an interned string. */
3995static void **
3996resolve_slotdups(PyTypeObject *type, PyObject *name)
3997{
3998 /* XXX Maybe this could be optimized more -- but is it worth it? */
3999
4000 /* pname and ptrs act as a little cache */
4001 static PyObject *pname;
4002 static slotdef *ptrs[MAX_EQUIV];
4003 slotdef *p, **pp;
4004 void **res, **ptr;
4005
4006 if (pname != name) {
4007 /* Collect all slotdefs that match name into ptrs. */
4008 pname = name;
4009 pp = ptrs;
4010 for (p = slotdefs; p->name_strobj; p++) {
4011 if (p->name_strobj == name)
4012 *pp++ = p;
4013 }
4014 *pp = NULL;
4015 }
4016
4017 /* Look in all matching slots of the type; if exactly one of these has
4018 a filled-in slot, return its value. Otherwise return NULL. */
4019 res = NULL;
4020 for (pp = ptrs; *pp; pp++) {
4021 ptr = slotptr(type, (*pp)->offset);
4022 if (ptr == NULL || *ptr == NULL)
4023 continue;
4024 if (res != NULL)
4025 return NULL;
4026 res = ptr;
4027 }
4028 return res;
4029}
4030
4031/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4032 does some incredibly complex thinking and then sticks something into the
4033 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
4034 interests, and then stores a generic wrapper or a specific function into
4035 the slot.) Return a pointer to the next slotdef with a different offset,
4036 because that's convenient for fixup_slot_dispatchers(). */
4037static slotdef *
4038update_one_slot(PyTypeObject *type, slotdef *p)
4039{
4040 PyObject *descr;
4041 PyWrapperDescrObject *d;
4042 void *generic = NULL, *specific = NULL;
4043 int use_generic = 0;
4044 int offset = p->offset;
4045 void **ptr = slotptr(type, offset);
4046
4047 if (ptr == NULL) {
4048 do {
4049 ++p;
4050 } while (p->offset == offset);
4051 return p;
4052 }
4053 do {
4054 descr = _PyType_Lookup(type, p->name_strobj);
4055 if (descr == NULL)
4056 continue;
4057 if (descr->ob_type == &PyWrapperDescr_Type) {
4058 void **tptr = resolve_slotdups(type, p->name_strobj);
4059 if (tptr == NULL || tptr == ptr)
4060 generic = p->function;
4061 d = (PyWrapperDescrObject *)descr;
4062 if (d->d_base->wrapper == p->wrapper &&
4063 PyType_IsSubtype(type, d->d_type))
4064 {
4065 if (specific == NULL ||
4066 specific == d->d_wrapped)
4067 specific = d->d_wrapped;
4068 else
4069 use_generic = 1;
4070 }
4071 }
4072 else {
4073 use_generic = 1;
4074 generic = p->function;
4075 }
4076 } while ((++p)->offset == offset);
4077 if (specific && !use_generic)
4078 *ptr = specific;
4079 else
4080 *ptr = generic;
4081 return p;
4082}
4083
Guido van Rossum22b13872002-08-06 21:41:44 +00004084static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00004085 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004086
Guido van Rossumc334df52002-04-04 23:44:47 +00004087/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4088 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004089static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004090update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004091{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004092 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004093
Guido van Rossumc334df52002-04-04 23:44:47 +00004094 for (pp = pp0; *pp; pp++)
4095 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004096 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004097}
4098
Guido van Rossumc334df52002-04-04 23:44:47 +00004099/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4100 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004101static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004102recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004103{
4104 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004105 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004106 int i, n;
4107
4108 subclasses = type->tp_subclasses;
4109 if (subclasses == NULL)
4110 return 0;
4111 assert(PyList_Check(subclasses));
4112 n = PyList_GET_SIZE(subclasses);
4113 for (i = 0; i < n; i++) {
4114 ref = PyList_GET_ITEM(subclasses, i);
4115 assert(PyWeakref_CheckRef(ref));
4116 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004117 assert(subclass != NULL);
4118 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004119 continue;
4120 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004121 /* Avoid recursing down into unaffected classes */
4122 dict = subclass->tp_dict;
4123 if (dict != NULL && PyDict_Check(dict) &&
4124 PyDict_GetItem(dict, name) != NULL)
4125 continue;
4126 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004127 return -1;
4128 }
4129 return 0;
4130}
4131
Guido van Rossumc334df52002-04-04 23:44:47 +00004132/* Comparison function for qsort() to compare slotdefs by their offset, and
4133 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004134static int
4135slotdef_cmp(const void *aa, const void *bb)
4136{
4137 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4138 int c = a->offset - b->offset;
4139 if (c != 0)
4140 return c;
4141 else
4142 return a - b;
4143}
4144
Guido van Rossumc334df52002-04-04 23:44:47 +00004145/* Initialize the slotdefs table by adding interned string objects for the
4146 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004147static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004148init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004149{
4150 slotdef *p;
4151 static int initialized = 0;
4152
4153 if (initialized)
4154 return;
4155 for (p = slotdefs; p->name; p++) {
4156 p->name_strobj = PyString_InternFromString(p->name);
4157 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004158 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004159 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004160 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4161 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004162 initialized = 1;
4163}
4164
Guido van Rossumc334df52002-04-04 23:44:47 +00004165/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004166static int
4167update_slot(PyTypeObject *type, PyObject *name)
4168{
Guido van Rossumc334df52002-04-04 23:44:47 +00004169 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004170 slotdef *p;
4171 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004172 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004173
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004174 init_slotdefs();
4175 pp = ptrs;
4176 for (p = slotdefs; p->name; p++) {
4177 /* XXX assume name is interned! */
4178 if (p->name_strobj == name)
4179 *pp++ = p;
4180 }
4181 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004182 for (pp = ptrs; *pp; pp++) {
4183 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004184 offset = p->offset;
4185 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004186 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004187 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004188 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004189 if (ptrs[0] == NULL)
4190 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004191 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004192}
4193
Guido van Rossumc334df52002-04-04 23:44:47 +00004194/* Store the proper functions in the slot dispatches at class (type)
4195 definition time, based upon which operations the class overrides in its
4196 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004197static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004198fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004199{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004200 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004201
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004202 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004203 for (p = slotdefs; p->name; )
4204 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004205}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004206
Guido van Rossum6d204072001-10-21 00:44:31 +00004207/* This function is called by PyType_Ready() to populate the type's
4208 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004209 function slot (like tp_repr) that's defined in the type, one or more
4210 corresponding descriptors are added in the type's tp_dict dictionary
4211 under the appropriate name (like __repr__). Some function slots
4212 cause more than one descriptor to be added (for example, the nb_add
4213 slot adds both __add__ and __radd__ descriptors) and some function
4214 slots compete for the same descriptor (for example both sq_item and
4215 mp_subscript generate a __getitem__ descriptor).
4216
4217 In the latter case, the first slotdef entry encoutered wins. Since
4218 slotdef entries are sorted by the offset of the slot in the etype
4219 struct, this gives us some control over disambiguating between
4220 competing slots: the members of struct etype are listed from most
4221 general to least general, so the most general slot is preferred. In
4222 particular, because as_mapping comes before as_sequence, for a type
4223 that defines both mp_subscript and sq_item, mp_subscript wins.
4224
4225 This only adds new descriptors and doesn't overwrite entries in
4226 tp_dict that were previously defined. The descriptors contain a
4227 reference to the C function they must call, so that it's safe if they
4228 are copied into a subtype's __dict__ and the subtype has a different
4229 C function in its slot -- calling the method defined by the
4230 descriptor will call the C function that was used to create it,
4231 rather than the C function present in the slot when it is called.
4232 (This is important because a subtype may have a C function in the
4233 slot that calls the method from the dictionary, and we want to avoid
4234 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004235
4236static int
4237add_operators(PyTypeObject *type)
4238{
4239 PyObject *dict = type->tp_dict;
4240 slotdef *p;
4241 PyObject *descr;
4242 void **ptr;
4243
4244 init_slotdefs();
4245 for (p = slotdefs; p->name; p++) {
4246 if (p->wrapper == NULL)
4247 continue;
4248 ptr = slotptr(type, p->offset);
4249 if (!ptr || !*ptr)
4250 continue;
4251 if (PyDict_GetItem(dict, p->name_strobj))
4252 continue;
4253 descr = PyDescr_NewWrapper(type, p, *ptr);
4254 if (descr == NULL)
4255 return -1;
4256 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4257 return -1;
4258 Py_DECREF(descr);
4259 }
4260 if (type->tp_new != NULL) {
4261 if (add_tp_new_wrapper(type) < 0)
4262 return -1;
4263 }
4264 return 0;
4265}
4266
Guido van Rossum705f0f52001-08-24 16:47:00 +00004267
4268/* Cooperative 'super' */
4269
4270typedef struct {
4271 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004272 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004273 PyObject *obj;
4274} superobject;
4275
Guido van Rossum6f799372001-09-20 20:46:19 +00004276static PyMemberDef super_members[] = {
4277 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4278 "the class invoking super()"},
4279 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4280 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004281 {0}
4282};
4283
Guido van Rossum705f0f52001-08-24 16:47:00 +00004284static void
4285super_dealloc(PyObject *self)
4286{
4287 superobject *su = (superobject *)self;
4288
Guido van Rossum048eb752001-10-02 21:24:57 +00004289 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004290 Py_XDECREF(su->obj);
4291 Py_XDECREF(su->type);
4292 self->ob_type->tp_free(self);
4293}
4294
4295static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004296super_repr(PyObject *self)
4297{
4298 superobject *su = (superobject *)self;
4299
4300 if (su->obj)
4301 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004302 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004303 su->type ? su->type->tp_name : "NULL",
4304 su->obj->ob_type->tp_name);
4305 else
4306 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004307 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004308 su->type ? su->type->tp_name : "NULL");
4309}
4310
4311static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004312super_getattro(PyObject *self, PyObject *name)
4313{
4314 superobject *su = (superobject *)self;
4315
4316 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004317 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004318 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004319 descrgetfunc f;
4320 int i, n;
4321
Guido van Rossum155db9a2002-04-02 17:53:47 +00004322 starttype = su->obj->ob_type;
4323 mro = starttype->tp_mro;
4324
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004325 if (mro == NULL)
4326 n = 0;
4327 else {
4328 assert(PyTuple_Check(mro));
4329 n = PyTuple_GET_SIZE(mro);
4330 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004331 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004332 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004333 break;
4334 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004335 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004336 starttype = (PyTypeObject *)(su->obj);
4337 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004338 if (mro == NULL)
4339 n = 0;
4340 else {
4341 assert(PyTuple_Check(mro));
4342 n = PyTuple_GET_SIZE(mro);
4343 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004344 for (i = 0; i < n; i++) {
4345 if ((PyObject *)(su->type) ==
4346 PyTuple_GET_ITEM(mro, i))
4347 break;
4348 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004349 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004350 i++;
4351 res = NULL;
4352 for (; i < n; i++) {
4353 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004354 if (PyType_Check(tmp))
4355 dict = ((PyTypeObject *)tmp)->tp_dict;
4356 else if (PyClass_Check(tmp))
4357 dict = ((PyClassObject *)tmp)->cl_dict;
4358 else
4359 continue;
4360 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004361 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004362 Py_INCREF(res);
4363 f = res->ob_type->tp_descr_get;
4364 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004365 tmp = f(res, su->obj,
4366 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004367 Py_DECREF(res);
4368 res = tmp;
4369 }
4370 return res;
4371 }
4372 }
4373 }
4374 return PyObject_GenericGetAttr(self, name);
4375}
4376
Guido van Rossum5b443c62001-12-03 15:38:28 +00004377static int
4378supercheck(PyTypeObject *type, PyObject *obj)
4379{
4380 if (!PyType_IsSubtype(obj->ob_type, type) &&
4381 !(PyType_Check(obj) &&
4382 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4383 PyErr_SetString(PyExc_TypeError,
4384 "super(type, obj): "
4385 "obj must be an instance or subtype of type");
4386 return -1;
4387 }
4388 else
4389 return 0;
4390}
4391
Guido van Rossum705f0f52001-08-24 16:47:00 +00004392static PyObject *
4393super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4394{
4395 superobject *su = (superobject *)self;
4396 superobject *new;
4397
4398 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4399 /* Not binding to an object, or already bound */
4400 Py_INCREF(self);
4401 return self;
4402 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004403 if (su->ob_type != &PySuper_Type)
4404 /* If su is an instance of a subclass of super,
4405 call its type */
4406 return PyObject_CallFunction((PyObject *)su->ob_type,
4407 "OO", su->type, obj);
4408 else {
4409 /* Inline the common case */
4410 if (supercheck(su->type, obj) < 0)
4411 return NULL;
4412 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4413 NULL, NULL);
4414 if (new == NULL)
4415 return NULL;
4416 Py_INCREF(su->type);
4417 Py_INCREF(obj);
4418 new->type = su->type;
4419 new->obj = obj;
4420 return (PyObject *)new;
4421 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004422}
4423
4424static int
4425super_init(PyObject *self, PyObject *args, PyObject *kwds)
4426{
4427 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004428 PyTypeObject *type;
4429 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004430
4431 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4432 return -1;
4433 if (obj == Py_None)
4434 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004435 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004436 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004437 Py_INCREF(type);
4438 Py_XINCREF(obj);
4439 su->type = type;
4440 su->obj = obj;
4441 return 0;
4442}
4443
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004444PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00004445"super(type) -> unbound super object\n"
4446"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004447"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004448"Typical use to call a cooperative superclass method:\n"
4449"class C(B):\n"
4450" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004451" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00004452
Guido van Rossum048eb752001-10-02 21:24:57 +00004453static int
4454super_traverse(PyObject *self, visitproc visit, void *arg)
4455{
4456 superobject *su = (superobject *)self;
4457 int err;
4458
4459#define VISIT(SLOT) \
4460 if (SLOT) { \
4461 err = visit((PyObject *)(SLOT), arg); \
4462 if (err) \
4463 return err; \
4464 }
4465
4466 VISIT(su->obj);
4467 VISIT(su->type);
4468
4469#undef VISIT
4470
4471 return 0;
4472}
4473
Guido van Rossum705f0f52001-08-24 16:47:00 +00004474PyTypeObject PySuper_Type = {
4475 PyObject_HEAD_INIT(&PyType_Type)
4476 0, /* ob_size */
4477 "super", /* tp_name */
4478 sizeof(superobject), /* tp_basicsize */
4479 0, /* tp_itemsize */
4480 /* methods */
4481 super_dealloc, /* tp_dealloc */
4482 0, /* tp_print */
4483 0, /* tp_getattr */
4484 0, /* tp_setattr */
4485 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004486 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004487 0, /* tp_as_number */
4488 0, /* tp_as_sequence */
4489 0, /* tp_as_mapping */
4490 0, /* tp_hash */
4491 0, /* tp_call */
4492 0, /* tp_str */
4493 super_getattro, /* tp_getattro */
4494 0, /* tp_setattro */
4495 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004496 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4497 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004498 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004499 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004500 0, /* tp_clear */
4501 0, /* tp_richcompare */
4502 0, /* tp_weaklistoffset */
4503 0, /* tp_iter */
4504 0, /* tp_iternext */
4505 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004506 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004507 0, /* tp_getset */
4508 0, /* tp_base */
4509 0, /* tp_dict */
4510 super_descr_get, /* tp_descr_get */
4511 0, /* tp_descr_set */
4512 0, /* tp_dictoffset */
4513 super_init, /* tp_init */
4514 PyType_GenericAlloc, /* tp_alloc */
4515 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00004516 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004517};