blob: 03f1adb1d17345c669c677e7de88fd05616f5ff5 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
Guido van Rossum6f799372001-09-20 20:46:19 +00008static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00009 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
10 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
11 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000017 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
18 {0}
19};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000020
Guido van Rossumc0b618a1997-05-02 03:12:38 +000021static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000022type_name(PyTypeObject *type, void *context)
23{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +000024 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +000025
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000026 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +000027 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +000028
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000029 Py_INCREF(et->name);
30 return et->name;
31 }
32 else {
33 s = strrchr(type->tp_name, '.');
34 if (s == NULL)
35 s = type->tp_name;
36 else
37 s++;
38 return PyString_FromString(s);
39 }
Guido van Rossumc3542212001-08-16 09:18:56 +000040}
41
Michael W. Hudson98bbc492002-11-26 14:47:27 +000042static int
43type_set_name(PyTypeObject *type, PyObject *value, void *context)
44{
Guido van Rossume5c691a2003-03-07 15:13:17 +000045 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000046
47 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
48 PyErr_Format(PyExc_TypeError,
49 "can't set %s.__name__", type->tp_name);
50 return -1;
51 }
52 if (!value) {
53 PyErr_Format(PyExc_TypeError,
54 "can't delete %s.__name__", type->tp_name);
55 return -1;
56 }
57 if (!PyString_Check(value)) {
58 PyErr_Format(PyExc_TypeError,
59 "can only assign string to %s.__name__, not '%s'",
60 type->tp_name, value->ob_type->tp_name);
61 return -1;
62 }
Tim Petersea7f75d2002-12-07 21:39:16 +000063 if (strlen(PyString_AS_STRING(value))
Michael W. Hudson98bbc492002-11-26 14:47:27 +000064 != (size_t)PyString_GET_SIZE(value)) {
65 PyErr_Format(PyExc_ValueError,
66 "__name__ must not contain null bytes");
67 return -1;
68 }
69
Guido van Rossume5c691a2003-03-07 15:13:17 +000070 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000071
72 Py_INCREF(value);
73
74 Py_DECREF(et->name);
75 et->name = value;
76
77 type->tp_name = PyString_AS_STRING(value);
78
79 return 0;
80}
81
Guido van Rossumc3542212001-08-16 09:18:56 +000082static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000083type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000084{
Guido van Rossumc3542212001-08-16 09:18:56 +000085 PyObject *mod;
86 char *s;
87
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000088 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
89 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Anthony Baxter3ecdb252004-06-11 14:41:18 +000090 if (!mod) {
91 PyErr_Format(PyExc_AttributeError, "__module__");
92 return 0;
93 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000094 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +000095 return mod;
96 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000097 else {
98 s = strrchr(type->tp_name, '.');
99 if (s != NULL)
100 return PyString_FromStringAndSize(
101 type->tp_name, (int)(s - type->tp_name));
102 return PyString_FromString("__builtin__");
103 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000104}
105
Guido van Rossum3926a632001-09-25 16:25:58 +0000106static int
107type_set_module(PyTypeObject *type, PyObject *value, void *context)
108{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000109 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000110 PyErr_Format(PyExc_TypeError,
111 "can't set %s.__module__", type->tp_name);
112 return -1;
113 }
114 if (!value) {
115 PyErr_Format(PyExc_TypeError,
116 "can't delete %s.__module__", type->tp_name);
117 return -1;
118 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000119
Guido van Rossum3926a632001-09-25 16:25:58 +0000120 return PyDict_SetItemString(type->tp_dict, "__module__", value);
121}
122
Tim Peters6d6c1a32001-08-02 04:15:00 +0000123static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000124type_get_bases(PyTypeObject *type, void *context)
125{
126 Py_INCREF(type->tp_bases);
127 return type->tp_bases;
128}
129
130static PyTypeObject *best_base(PyObject *);
131static int mro_internal(PyTypeObject *);
132static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
133static int add_subclass(PyTypeObject*, PyTypeObject*);
134static void remove_subclass(PyTypeObject *, PyTypeObject *);
135static void update_all_slots(PyTypeObject *);
136
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000137typedef int (*update_callback)(PyTypeObject *, void *);
138static int update_subclasses(PyTypeObject *type, PyObject *name,
139 update_callback callback, void *data);
140static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
141 update_callback callback, void *data);
142
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000143static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000144mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000145{
146 PyTypeObject *subclass;
147 PyObject *ref, *subclasses, *old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000148 int i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000149
150 subclasses = type->tp_subclasses;
151 if (subclasses == NULL)
152 return 0;
153 assert(PyList_Check(subclasses));
154 n = PyList_GET_SIZE(subclasses);
155 for (i = 0; i < n; i++) {
156 ref = PyList_GET_ITEM(subclasses, i);
157 assert(PyWeakref_CheckRef(ref));
158 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
159 assert(subclass != NULL);
160 if ((PyObject *)subclass == Py_None)
161 continue;
162 assert(PyType_Check(subclass));
163 old_mro = subclass->tp_mro;
164 if (mro_internal(subclass) < 0) {
165 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000166 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000167 }
168 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000169 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000170 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000171 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000172 if (!tuple)
173 return -1;
174 if (PyList_Append(temp, tuple) < 0)
175 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000176 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000177 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000178 if (mro_subclasses(subclass, temp) < 0)
179 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000180 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000181 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000182}
183
184static int
185type_set_bases(PyTypeObject *type, PyObject *value, void *context)
186{
187 int i, r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000188 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000189 PyTypeObject *new_base, *old_base;
190 PyObject *old_bases, *old_mro;
191
192 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
193 PyErr_Format(PyExc_TypeError,
194 "can't set %s.__bases__", type->tp_name);
195 return -1;
196 }
197 if (!value) {
198 PyErr_Format(PyExc_TypeError,
199 "can't delete %s.__bases__", type->tp_name);
200 return -1;
201 }
202 if (!PyTuple_Check(value)) {
203 PyErr_Format(PyExc_TypeError,
204 "can only assign tuple to %s.__bases__, not %s",
205 type->tp_name, value->ob_type->tp_name);
206 return -1;
207 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000208 if (PyTuple_GET_SIZE(value) == 0) {
209 PyErr_Format(PyExc_TypeError,
210 "can only assign non-empty tuple to %s.__bases__, not ()",
211 type->tp_name);
212 return -1;
213 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000214 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
215 ob = PyTuple_GET_ITEM(value, i);
216 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
217 PyErr_Format(
218 PyExc_TypeError,
219 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
220 type->tp_name, ob->ob_type->tp_name);
221 return -1;
222 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000223 if (PyType_Check(ob)) {
224 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
225 PyErr_SetString(PyExc_TypeError,
226 "a __bases__ item causes an inheritance cycle");
227 return -1;
228 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000229 }
230 }
231
232 new_base = best_base(value);
233
234 if (!new_base) {
235 return -1;
236 }
237
238 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
239 return -1;
240
241 Py_INCREF(new_base);
242 Py_INCREF(value);
243
244 old_bases = type->tp_bases;
245 old_base = type->tp_base;
246 old_mro = type->tp_mro;
247
248 type->tp_bases = value;
249 type->tp_base = new_base;
250
251 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000252 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000253 }
254
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000255 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000256 if (!temp)
257 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000258
259 r = mro_subclasses(type, temp);
260
261 if (r < 0) {
262 for (i = 0; i < PyList_Size(temp); i++) {
263 PyTypeObject* cls;
264 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000265 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
266 "", 2, 2, &cls, &mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000267 Py_DECREF(cls->tp_mro);
268 cls->tp_mro = mro;
269 Py_INCREF(cls->tp_mro);
270 }
271 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000272 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000273 }
274
275 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000276
277 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000278 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000279 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000280 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000281
282 /* for now, sod that: just remove from all old_bases,
283 add to all new_bases */
284
285 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
286 ob = PyTuple_GET_ITEM(old_bases, i);
287 if (PyType_Check(ob)) {
288 remove_subclass(
289 (PyTypeObject*)ob, type);
290 }
291 }
292
293 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
294 ob = PyTuple_GET_ITEM(value, i);
295 if (PyType_Check(ob)) {
296 if (add_subclass((PyTypeObject*)ob, type) < 0)
297 r = -1;
298 }
299 }
300
301 update_all_slots(type);
302
303 Py_DECREF(old_bases);
304 Py_DECREF(old_base);
305 Py_DECREF(old_mro);
306
307 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000308
309 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000310 Py_DECREF(type->tp_bases);
311 Py_DECREF(type->tp_base);
312 if (type->tp_mro != old_mro) {
313 Py_DECREF(type->tp_mro);
314 }
315
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000316 type->tp_bases = old_bases;
317 type->tp_base = old_base;
318 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000319
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000320 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000321}
322
323static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000324type_dict(PyTypeObject *type, void *context)
325{
326 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000327 Py_INCREF(Py_None);
328 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000329 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000330 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000331}
332
Tim Peters24008312002-03-17 18:56:20 +0000333static PyObject *
334type_get_doc(PyTypeObject *type, void *context)
335{
336 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000337 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000338 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000339 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000340 if (result == NULL) {
341 result = Py_None;
342 Py_INCREF(result);
343 }
344 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000345 result = result->ob_type->tp_descr_get(result, NULL,
346 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000347 }
348 else {
349 Py_INCREF(result);
350 }
Tim Peters24008312002-03-17 18:56:20 +0000351 return result;
352}
353
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000354static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000355 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
356 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000357 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000358 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000359 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000360 {0}
361};
362
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000363static int
364type_compare(PyObject *v, PyObject *w)
365{
366 /* This is called with type objects only. So we
367 can just compare the addresses. */
368 Py_uintptr_t vv = (Py_uintptr_t)v;
369 Py_uintptr_t ww = (Py_uintptr_t)w;
370 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
371}
372
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000373static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000374type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000375{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000376 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000377 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000378
379 mod = type_module(type, NULL);
380 if (mod == NULL)
381 PyErr_Clear();
382 else if (!PyString_Check(mod)) {
383 Py_DECREF(mod);
384 mod = NULL;
385 }
386 name = type_name(type, NULL);
387 if (name == NULL)
388 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000389
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000390 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
391 kind = "class";
392 else
393 kind = "type";
394
Barry Warsaw7ce36942001-08-24 18:34:26 +0000395 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000396 rtn = PyString_FromFormat("<%s '%s.%s'>",
397 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000398 PyString_AS_STRING(mod),
399 PyString_AS_STRING(name));
400 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000401 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000402 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000403
Guido van Rossumc3542212001-08-16 09:18:56 +0000404 Py_XDECREF(mod);
405 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000406 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000407}
408
Tim Peters6d6c1a32001-08-02 04:15:00 +0000409static PyObject *
410type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
411{
412 PyObject *obj;
413
414 if (type->tp_new == NULL) {
415 PyErr_Format(PyExc_TypeError,
416 "cannot create '%.100s' instances",
417 type->tp_name);
418 return NULL;
419 }
420
Tim Peters3f996e72001-09-13 19:18:27 +0000421 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000422 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000423 /* Ugly exception: when the call was type(something),
424 don't call tp_init on the result. */
425 if (type == &PyType_Type &&
426 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
427 (kwds == NULL ||
428 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
429 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000430 /* If the returned object is not an instance of type,
431 it won't be initialized. */
432 if (!PyType_IsSubtype(obj->ob_type, type))
433 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000434 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000435 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
436 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000437 type->tp_init(obj, args, kwds) < 0) {
438 Py_DECREF(obj);
439 obj = NULL;
440 }
441 }
442 return obj;
443}
444
445PyObject *
446PyType_GenericAlloc(PyTypeObject *type, int nitems)
447{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000448 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000449 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
450 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000451
452 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000453 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000454 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000455 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000456
Neil Schemenauerc806c882001-08-29 23:54:54 +0000457 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000458 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000459
Neil Schemenauerc806c882001-08-29 23:54:54 +0000460 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000461
Tim Peters6d6c1a32001-08-02 04:15:00 +0000462 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
463 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000464
Tim Peters6d6c1a32001-08-02 04:15:00 +0000465 if (type->tp_itemsize == 0)
466 PyObject_INIT(obj, type);
467 else
468 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000469
Tim Peters6d6c1a32001-08-02 04:15:00 +0000470 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000471 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000472 return obj;
473}
474
475PyObject *
476PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
477{
478 return type->tp_alloc(type, 0);
479}
480
Guido van Rossum9475a232001-10-05 20:51:39 +0000481/* Helpers for subtyping */
482
483static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000484traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
485{
486 int i, n;
487 PyMemberDef *mp;
488
489 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000490 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000491 for (i = 0; i < n; i++, mp++) {
492 if (mp->type == T_OBJECT_EX) {
493 char *addr = (char *)self + mp->offset;
494 PyObject *obj = *(PyObject **)addr;
495 if (obj != NULL) {
496 int err = visit(obj, arg);
497 if (err)
498 return err;
499 }
500 }
501 }
502 return 0;
503}
504
505static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000506subtype_traverse(PyObject *self, visitproc visit, void *arg)
507{
508 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000509 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000510
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000511 /* Find the nearest base with a different tp_traverse,
512 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000513 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000514 base = type;
515 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
516 if (base->ob_size) {
517 int err = traverse_slots(base, self, visit, arg);
518 if (err)
519 return err;
520 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000521 base = base->tp_base;
522 assert(base);
523 }
524
525 if (type->tp_dictoffset != base->tp_dictoffset) {
526 PyObject **dictptr = _PyObject_GetDictPtr(self);
527 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000528 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000529 if (err)
530 return err;
531 }
532 }
533
Guido van Rossuma3862092002-06-10 15:24:42 +0000534 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
535 /* For a heaptype, the instances count as references
536 to the type. Traverse the type so the collector
537 can find cycles involving this link. */
538 int err = visit((PyObject *)type, arg);
539 if (err)
540 return err;
541 }
542
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000543 if (basetraverse)
544 return basetraverse(self, visit, arg);
545 return 0;
546}
547
548static void
549clear_slots(PyTypeObject *type, PyObject *self)
550{
551 int i, n;
552 PyMemberDef *mp;
553
554 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000555 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000556 for (i = 0; i < n; i++, mp++) {
557 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
558 char *addr = (char *)self + mp->offset;
559 PyObject *obj = *(PyObject **)addr;
560 if (obj != NULL) {
561 Py_DECREF(obj);
562 *(PyObject **)addr = NULL;
563 }
564 }
565 }
566}
567
568static int
569subtype_clear(PyObject *self)
570{
571 PyTypeObject *type, *base;
572 inquiry baseclear;
573
574 /* Find the nearest base with a different tp_clear
575 and clear slots while we're at it */
576 type = self->ob_type;
577 base = type;
578 while ((baseclear = base->tp_clear) == subtype_clear) {
579 if (base->ob_size)
580 clear_slots(base, self);
581 base = base->tp_base;
582 assert(base);
583 }
584
Guido van Rossuma3862092002-06-10 15:24:42 +0000585 /* There's no need to clear the instance dict (if any);
586 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000587
588 if (baseclear)
589 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000590 return 0;
591}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000592
593static void
594subtype_dealloc(PyObject *self)
595{
Guido van Rossum14227b42001-12-06 02:35:58 +0000596 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000597 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000598
Guido van Rossum22b13872002-08-06 21:41:44 +0000599 /* Extract the type; we expect it to be a heap type */
600 type = self->ob_type;
601 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000602
Guido van Rossum22b13872002-08-06 21:41:44 +0000603 /* Test whether the type has GC exactly once */
604
605 if (!PyType_IS_GC(type)) {
606 /* It's really rare to find a dynamic type that doesn't have
607 GC; it can only happen when deriving from 'object' and not
608 adding any slots or instance variables. This allows
609 certain simplifications: there's no need to call
610 clear_slots(), or DECREF the dict, or clear weakrefs. */
611
612 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000613 if (type->tp_del) {
614 type->tp_del(self);
615 if (self->ob_refcnt > 0)
616 return;
617 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000618
619 /* Find the nearest base with a different tp_dealloc */
620 base = type;
621 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
622 assert(base->ob_size == 0);
623 base = base->tp_base;
624 assert(base);
625 }
626
627 /* Call the base tp_dealloc() */
628 assert(basedealloc);
629 basedealloc(self);
630
631 /* Can't reference self beyond this point */
632 Py_DECREF(type);
633
634 /* Done */
635 return;
636 }
637
638 /* We get here only if the type has GC */
639
640 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000641 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000642 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000643 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000644 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000645 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000646 /* DO NOT restore GC tracking at this point. weakref callbacks
647 * (if any, and whether directly here or indirectly in something we
648 * call) may trigger GC, and if self is tracked at that point, it
649 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000650 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000651
Guido van Rossum59195fd2003-06-13 20:54:40 +0000652 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000653 base = type;
654 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000655 base = base->tp_base;
656 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000657 }
658
Guido van Rossum1987c662003-05-29 14:29:23 +0000659 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000660 the finalizer (__del__), clearing slots, or clearing the instance
661 dict. */
662
Guido van Rossum1987c662003-05-29 14:29:23 +0000663 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
664 PyObject_ClearWeakRefs(self);
665
666 /* Maybe call finalizer; exit early if resurrected */
667 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000668 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000669 type->tp_del(self);
670 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000671 goto endlabel; /* resurrected */
672 else
673 _PyObject_GC_UNTRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000674 }
675
Guido van Rossum59195fd2003-06-13 20:54:40 +0000676 /* Clear slots up to the nearest base with a different tp_dealloc */
677 base = type;
678 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
679 if (base->ob_size)
680 clear_slots(base, self);
681 base = base->tp_base;
682 assert(base);
683 }
684
Tim Peters6d6c1a32001-08-02 04:15:00 +0000685 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000686 if (type->tp_dictoffset && !base->tp_dictoffset) {
687 PyObject **dictptr = _PyObject_GetDictPtr(self);
688 if (dictptr != NULL) {
689 PyObject *dict = *dictptr;
690 if (dict != NULL) {
691 Py_DECREF(dict);
692 *dictptr = NULL;
693 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000694 }
695 }
696
Tim Peters0bd743c2003-11-13 22:50:00 +0000697 /* Call the base tp_dealloc(); first retrack self if
698 * basedealloc knows about gc.
699 */
700 if (PyType_IS_GC(base))
701 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000702 assert(basedealloc);
703 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000704
705 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000706 Py_DECREF(type);
707
Guido van Rossum0906e072002-08-07 20:42:09 +0000708 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000709 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000710 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000711 --_PyTrash_delete_nesting;
712
713 /* Explanation of the weirdness around the trashcan macros:
714
715 Q. What do the trashcan macros do?
716
717 A. Read the comment titled "Trashcan mechanism" in object.h.
718 For one, this explains why there must be a call to GC-untrack
719 before the trashcan begin macro. Without understanding the
720 trashcan code, the answers to the following questions don't make
721 sense.
722
723 Q. Why do we GC-untrack before the trashcan and then immediately
724 GC-track again afterward?
725
726 A. In the case that the base class is GC-aware, the base class
727 probably GC-untracks the object. If it does that using the
728 UNTRACK macro, this will crash when the object is already
729 untracked. Because we don't know what the base class does, the
730 only safe thing is to make sure the object is tracked when we
731 call the base class dealloc. But... The trashcan begin macro
732 requires that the object is *untracked* before it is called. So
733 the dance becomes:
734
735 GC untrack
736 trashcan begin
737 GC track
738
Tim Petersf7f9e992003-11-13 21:59:32 +0000739 Q. Why did the last question say "immediately GC-track again"?
740 It's nowhere near immediately.
741
742 A. Because the code *used* to re-track immediately. Bad Idea.
743 self has a refcount of 0, and if gc ever gets its hands on it
744 (which can happen if any weakref callback gets invoked), it
745 looks like trash to gc too, and gc also tries to delete self
746 then. But we're already deleting self. Double dealloction is
747 a subtle disaster.
748
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000749 Q. Why the bizarre (net-zero) manipulation of
750 _PyTrash_delete_nesting around the trashcan macros?
751
752 A. Some base classes (e.g. list) also use the trashcan mechanism.
753 The following scenario used to be possible:
754
755 - suppose the trashcan level is one below the trashcan limit
756
757 - subtype_dealloc() is called
758
759 - the trashcan limit is not yet reached, so the trashcan level
760 is incremented and the code between trashcan begin and end is
761 executed
762
763 - this destroys much of the object's contents, including its
764 slots and __dict__
765
766 - basedealloc() is called; this is really list_dealloc(), or
767 some other type which also uses the trashcan macros
768
769 - the trashcan limit is now reached, so the object is put on the
770 trashcan's to-be-deleted-later list
771
772 - basedealloc() returns
773
774 - subtype_dealloc() decrefs the object's type
775
776 - subtype_dealloc() returns
777
778 - later, the trashcan code starts deleting the objects from its
779 to-be-deleted-later list
780
781 - subtype_dealloc() is called *AGAIN* for the same object
782
783 - at the very least (if the destroyed slots and __dict__ don't
784 cause problems) the object's type gets decref'ed a second
785 time, which is *BAD*!!!
786
787 The remedy is to make sure that if the code between trashcan
788 begin and end in subtype_dealloc() is called, the code between
789 trashcan begin and end in basedealloc() will also be called.
790 This is done by decrementing the level after passing into the
791 trashcan block, and incrementing it just before leaving the
792 block.
793
794 But now it's possible that a chain of objects consisting solely
795 of objects whose deallocator is subtype_dealloc() will defeat
796 the trashcan mechanism completely: the decremented level means
797 that the effective level never reaches the limit. Therefore, we
798 *increment* the level *before* entering the trashcan block, and
799 matchingly decrement it after leaving. This means the trashcan
800 code will trigger a little early, but that's no big deal.
801
802 Q. Are there any live examples of code in need of all this
803 complexity?
804
805 A. Yes. See SF bug 668433 for code that crashed (when Python was
806 compiled in debug mode) before the trashcan level manipulations
807 were added. For more discussion, see SF patches 581742, 575073
808 and bug 574207.
809 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000810}
811
Jeremy Hylton938ace62002-07-17 16:30:39 +0000812static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000813
Tim Peters6d6c1a32001-08-02 04:15:00 +0000814/* type test with subclassing support */
815
816int
817PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
818{
819 PyObject *mro;
820
Guido van Rossum9478d072001-09-07 18:52:13 +0000821 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
822 return b == a || b == &PyBaseObject_Type;
823
Tim Peters6d6c1a32001-08-02 04:15:00 +0000824 mro = a->tp_mro;
825 if (mro != NULL) {
826 /* Deal with multiple inheritance without recursion
827 by walking the MRO tuple */
828 int i, n;
829 assert(PyTuple_Check(mro));
830 n = PyTuple_GET_SIZE(mro);
831 for (i = 0; i < n; i++) {
832 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
833 return 1;
834 }
835 return 0;
836 }
837 else {
838 /* a is not completely initilized yet; follow tp_base */
839 do {
840 if (a == b)
841 return 1;
842 a = a->tp_base;
843 } while (a != NULL);
844 return b == &PyBaseObject_Type;
845 }
846}
847
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000848/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000849 without looking in the instance dictionary
850 (so we can't use PyObject_GetAttr) but still binding
851 it to the instance. The arguments are the object,
852 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000853 static variable used to cache the interned Python string.
854
855 Two variants:
856
857 - lookup_maybe() returns NULL without raising an exception
858 when the _PyType_Lookup() call fails;
859
860 - lookup_method() always raises an exception upon errors.
861*/
Guido van Rossum60718732001-08-28 17:47:51 +0000862
863static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000864lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000865{
866 PyObject *res;
867
868 if (*attrobj == NULL) {
869 *attrobj = PyString_InternFromString(attrstr);
870 if (*attrobj == NULL)
871 return NULL;
872 }
873 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000874 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000875 descrgetfunc f;
876 if ((f = res->ob_type->tp_descr_get) == NULL)
877 Py_INCREF(res);
878 else
879 res = f(res, self, (PyObject *)(self->ob_type));
880 }
881 return res;
882}
883
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000884static PyObject *
885lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
886{
887 PyObject *res = lookup_maybe(self, attrstr, attrobj);
888 if (res == NULL && !PyErr_Occurred())
889 PyErr_SetObject(PyExc_AttributeError, *attrobj);
890 return res;
891}
892
Guido van Rossum2730b132001-08-28 18:22:14 +0000893/* A variation of PyObject_CallMethod that uses lookup_method()
894 instead of PyObject_GetAttrString(). This uses the same convention
895 as lookup_method to cache the interned name string object. */
896
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000897static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000898call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
899{
900 va_list va;
901 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000902 va_start(va, format);
903
Guido van Rossumda21c012001-10-03 00:50:18 +0000904 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000905 if (func == NULL) {
906 va_end(va);
907 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000908 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000909 return NULL;
910 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000911
912 if (format && *format)
913 args = Py_VaBuildValue(format, va);
914 else
915 args = PyTuple_New(0);
916
917 va_end(va);
918
919 if (args == NULL)
920 return NULL;
921
922 assert(PyTuple_Check(args));
923 retval = PyObject_Call(func, args, NULL);
924
925 Py_DECREF(args);
926 Py_DECREF(func);
927
928 return retval;
929}
930
931/* Clone of call_method() that returns NotImplemented when the lookup fails. */
932
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000933static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000934call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
935{
936 va_list va;
937 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000938 va_start(va, format);
939
Guido van Rossumda21c012001-10-03 00:50:18 +0000940 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000941 if (func == NULL) {
942 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000943 if (!PyErr_Occurred()) {
944 Py_INCREF(Py_NotImplemented);
945 return Py_NotImplemented;
946 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000947 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000948 }
949
950 if (format && *format)
951 args = Py_VaBuildValue(format, va);
952 else
953 args = PyTuple_New(0);
954
955 va_end(va);
956
Guido van Rossum717ce002001-09-14 16:58:08 +0000957 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000958 return NULL;
959
Guido van Rossum717ce002001-09-14 16:58:08 +0000960 assert(PyTuple_Check(args));
961 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000962
963 Py_DECREF(args);
964 Py_DECREF(func);
965
966 return retval;
967}
968
Tim Petersa91e9642001-11-14 23:32:33 +0000969static int
970fill_classic_mro(PyObject *mro, PyObject *cls)
971{
972 PyObject *bases, *base;
973 int i, n;
974
975 assert(PyList_Check(mro));
976 assert(PyClass_Check(cls));
977 i = PySequence_Contains(mro, cls);
978 if (i < 0)
979 return -1;
980 if (!i) {
981 if (PyList_Append(mro, cls) < 0)
982 return -1;
983 }
984 bases = ((PyClassObject *)cls)->cl_bases;
985 assert(bases && PyTuple_Check(bases));
986 n = PyTuple_GET_SIZE(bases);
987 for (i = 0; i < n; i++) {
988 base = PyTuple_GET_ITEM(bases, i);
989 if (fill_classic_mro(mro, base) < 0)
990 return -1;
991 }
992 return 0;
993}
994
995static PyObject *
996classic_mro(PyObject *cls)
997{
998 PyObject *mro;
999
1000 assert(PyClass_Check(cls));
1001 mro = PyList_New(0);
1002 if (mro != NULL) {
1003 if (fill_classic_mro(mro, cls) == 0)
1004 return mro;
1005 Py_DECREF(mro);
1006 }
1007 return NULL;
1008}
1009
Tim Petersea7f75d2002-12-07 21:39:16 +00001010/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001011 Method resolution order algorithm C3 described in
1012 "A Monotonic Superclass Linearization for Dylan",
1013 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001014 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001015 (OOPSLA 1996)
1016
Guido van Rossum98f33732002-11-25 21:36:54 +00001017 Some notes about the rules implied by C3:
1018
Tim Petersea7f75d2002-12-07 21:39:16 +00001019 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001020 It isn't legal to repeat a class in a list of base classes.
1021
1022 The next three properties are the 3 constraints in "C3".
1023
Tim Petersea7f75d2002-12-07 21:39:16 +00001024 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001025 If A precedes B in C's MRO, then A will precede B in the MRO of all
1026 subclasses of C.
1027
1028 Monotonicity.
1029 The MRO of a class must be an extension without reordering of the
1030 MRO of each of its superclasses.
1031
1032 Extended Precedence Graph (EPG).
1033 Linearization is consistent if there is a path in the EPG from
1034 each class to all its successors in the linearization. See
1035 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001036 */
1037
Tim Petersea7f75d2002-12-07 21:39:16 +00001038static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001039tail_contains(PyObject *list, int whence, PyObject *o) {
1040 int j, size;
1041 size = PyList_GET_SIZE(list);
1042
1043 for (j = whence+1; j < size; j++) {
1044 if (PyList_GET_ITEM(list, j) == o)
1045 return 1;
1046 }
1047 return 0;
1048}
1049
Guido van Rossum98f33732002-11-25 21:36:54 +00001050static PyObject *
1051class_name(PyObject *cls)
1052{
1053 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1054 if (name == NULL) {
1055 PyErr_Clear();
1056 Py_XDECREF(name);
1057 name = PyObject_Repr(cls);
1058 }
1059 if (name == NULL)
1060 return NULL;
1061 if (!PyString_Check(name)) {
1062 Py_DECREF(name);
1063 return NULL;
1064 }
1065 return name;
1066}
1067
1068static int
1069check_duplicates(PyObject *list)
1070{
1071 int i, j, n;
1072 /* Let's use a quadratic time algorithm,
1073 assuming that the bases lists is short.
1074 */
1075 n = PyList_GET_SIZE(list);
1076 for (i = 0; i < n; i++) {
1077 PyObject *o = PyList_GET_ITEM(list, i);
1078 for (j = i + 1; j < n; j++) {
1079 if (PyList_GET_ITEM(list, j) == o) {
1080 o = class_name(o);
1081 PyErr_Format(PyExc_TypeError,
1082 "duplicate base class %s",
1083 o ? PyString_AS_STRING(o) : "?");
1084 Py_XDECREF(o);
1085 return -1;
1086 }
1087 }
1088 }
1089 return 0;
1090}
1091
1092/* Raise a TypeError for an MRO order disagreement.
1093
1094 It's hard to produce a good error message. In the absence of better
1095 insight into error reporting, report the classes that were candidates
1096 to be put next into the MRO. There is some conflict between the
1097 order in which they should be put in the MRO, but it's hard to
1098 diagnose what constraint can't be satisfied.
1099*/
1100
1101static void
1102set_mro_error(PyObject *to_merge, int *remain)
1103{
1104 int i, n, off, to_merge_size;
1105 char buf[1000];
1106 PyObject *k, *v;
1107 PyObject *set = PyDict_New();
1108
1109 to_merge_size = PyList_GET_SIZE(to_merge);
1110 for (i = 0; i < to_merge_size; i++) {
1111 PyObject *L = PyList_GET_ITEM(to_merge, i);
1112 if (remain[i] < PyList_GET_SIZE(L)) {
1113 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1114 if (PyDict_SetItem(set, c, Py_None) < 0)
1115 return;
1116 }
1117 }
1118 n = PyDict_Size(set);
1119
Raymond Hettingerf394df42003-04-06 19:13:41 +00001120 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1121consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001122 i = 0;
1123 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1124 PyObject *name = class_name(k);
1125 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1126 name ? PyString_AS_STRING(name) : "?");
1127 Py_XDECREF(name);
1128 if (--n && off+1 < sizeof(buf)) {
1129 buf[off++] = ',';
1130 buf[off] = '\0';
1131 }
1132 }
1133 PyErr_SetString(PyExc_TypeError, buf);
1134 Py_DECREF(set);
1135}
1136
Tim Petersea7f75d2002-12-07 21:39:16 +00001137static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001138pmerge(PyObject *acc, PyObject* to_merge) {
1139 int i, j, to_merge_size;
1140 int *remain;
1141 int ok, empty_cnt;
Tim Petersea7f75d2002-12-07 21:39:16 +00001142
Guido van Rossum1f121312002-11-14 19:49:16 +00001143 to_merge_size = PyList_GET_SIZE(to_merge);
1144
Guido van Rossum98f33732002-11-25 21:36:54 +00001145 /* remain stores an index into each sublist of to_merge.
1146 remain[i] is the index of the next base in to_merge[i]
1147 that is not included in acc.
1148 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001149 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1150 if (remain == NULL)
1151 return -1;
1152 for (i = 0; i < to_merge_size; i++)
1153 remain[i] = 0;
1154
1155 again:
1156 empty_cnt = 0;
1157 for (i = 0; i < to_merge_size; i++) {
1158 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001159
Guido van Rossum1f121312002-11-14 19:49:16 +00001160 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1161
1162 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1163 empty_cnt++;
1164 continue;
1165 }
1166
Guido van Rossum98f33732002-11-25 21:36:54 +00001167 /* Choose next candidate for MRO.
1168
1169 The input sequences alone can determine the choice.
1170 If not, choose the class which appears in the MRO
1171 of the earliest direct superclass of the new class.
1172 */
1173
Guido van Rossum1f121312002-11-14 19:49:16 +00001174 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1175 for (j = 0; j < to_merge_size; j++) {
1176 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001177 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001178 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001179 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001180 }
1181 ok = PyList_Append(acc, candidate);
1182 if (ok < 0) {
1183 PyMem_Free(remain);
1184 return -1;
1185 }
1186 for (j = 0; j < to_merge_size; j++) {
1187 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001188 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1189 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001190 remain[j]++;
1191 }
1192 }
1193 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001194 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001195 }
1196
Guido van Rossum98f33732002-11-25 21:36:54 +00001197 if (empty_cnt == to_merge_size) {
1198 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001199 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001200 }
1201 set_mro_error(to_merge, remain);
1202 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001203 return -1;
1204}
1205
Tim Peters6d6c1a32001-08-02 04:15:00 +00001206static PyObject *
1207mro_implementation(PyTypeObject *type)
1208{
1209 int i, n, ok;
1210 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001211 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001212
Guido van Rossum63517572002-06-18 16:44:57 +00001213 if(type->tp_dict == NULL) {
1214 if(PyType_Ready(type) < 0)
1215 return NULL;
1216 }
1217
Guido van Rossum98f33732002-11-25 21:36:54 +00001218 /* Find a superclass linearization that honors the constraints
1219 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001220 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001221
1222 to_merge is a list of lists, where each list is a superclass
1223 linearization implied by a base class. The last element of
1224 to_merge is the declared list of bases.
1225 */
1226
Tim Peters6d6c1a32001-08-02 04:15:00 +00001227 bases = type->tp_bases;
1228 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001229
1230 to_merge = PyList_New(n+1);
1231 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001232 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001233
Tim Peters6d6c1a32001-08-02 04:15:00 +00001234 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001235 PyObject *base = PyTuple_GET_ITEM(bases, i);
1236 PyObject *parentMRO;
1237 if (PyType_Check(base))
1238 parentMRO = PySequence_List(
1239 ((PyTypeObject*)base)->tp_mro);
1240 else
1241 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001242 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001243 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001244 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001245 }
1246
1247 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001248 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001249
1250 bases_aslist = PySequence_List(bases);
1251 if (bases_aslist == NULL) {
1252 Py_DECREF(to_merge);
1253 return NULL;
1254 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001255 /* This is just a basic sanity check. */
1256 if (check_duplicates(bases_aslist) < 0) {
1257 Py_DECREF(to_merge);
1258 Py_DECREF(bases_aslist);
1259 return NULL;
1260 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001261 PyList_SET_ITEM(to_merge, n, bases_aslist);
1262
1263 result = Py_BuildValue("[O]", (PyObject *)type);
1264 if (result == NULL) {
1265 Py_DECREF(to_merge);
1266 return NULL;
1267 }
1268
1269 ok = pmerge(result, to_merge);
1270 Py_DECREF(to_merge);
1271 if (ok < 0) {
1272 Py_DECREF(result);
1273 return NULL;
1274 }
1275
Tim Peters6d6c1a32001-08-02 04:15:00 +00001276 return result;
1277}
1278
1279static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001280mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001281{
1282 PyTypeObject *type = (PyTypeObject *)self;
1283
Tim Peters6d6c1a32001-08-02 04:15:00 +00001284 return mro_implementation(type);
1285}
1286
1287static int
1288mro_internal(PyTypeObject *type)
1289{
1290 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001291 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001292
1293 if (type->ob_type == &PyType_Type) {
1294 result = mro_implementation(type);
1295 }
1296 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001297 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001298 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001299 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001300 if (mro == NULL)
1301 return -1;
1302 result = PyObject_CallObject(mro, NULL);
1303 Py_DECREF(mro);
1304 }
1305 if (result == NULL)
1306 return -1;
1307 tuple = PySequence_Tuple(result);
1308 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001309 if (tuple == NULL)
1310 return -1;
1311 if (checkit) {
1312 int i, len;
1313 PyObject *cls;
1314 PyTypeObject *solid;
1315
1316 solid = solid_base(type);
1317
1318 len = PyTuple_GET_SIZE(tuple);
1319
1320 for (i = 0; i < len; i++) {
1321 PyTypeObject *t;
1322 cls = PyTuple_GET_ITEM(tuple, i);
1323 if (PyClass_Check(cls))
1324 continue;
1325 else if (!PyType_Check(cls)) {
1326 PyErr_Format(PyExc_TypeError,
1327 "mro() returned a non-class ('%.500s')",
1328 cls->ob_type->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001329 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001330 return -1;
1331 }
1332 t = (PyTypeObject*)cls;
1333 if (!PyType_IsSubtype(solid, solid_base(t))) {
1334 PyErr_Format(PyExc_TypeError,
1335 "mro() returned base with unsuitable layout ('%.500s')",
1336 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001337 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001338 return -1;
1339 }
1340 }
1341 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001342 type->tp_mro = tuple;
1343 return 0;
1344}
1345
1346
1347/* Calculate the best base amongst multiple base classes.
1348 This is the first one that's on the path to the "solid base". */
1349
1350static PyTypeObject *
1351best_base(PyObject *bases)
1352{
1353 int i, n;
1354 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001355 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001356
1357 assert(PyTuple_Check(bases));
1358 n = PyTuple_GET_SIZE(bases);
1359 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001360 base = NULL;
1361 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001362 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001363 base_proto = PyTuple_GET_ITEM(bases, i);
1364 if (PyClass_Check(base_proto))
1365 continue;
1366 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001367 PyErr_SetString(
1368 PyExc_TypeError,
1369 "bases must be types");
1370 return NULL;
1371 }
Tim Petersa91e9642001-11-14 23:32:33 +00001372 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001373 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001374 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001375 return NULL;
1376 }
1377 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001378 if (winner == NULL) {
1379 winner = candidate;
1380 base = base_i;
1381 }
1382 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001383 ;
1384 else if (PyType_IsSubtype(candidate, winner)) {
1385 winner = candidate;
1386 base = base_i;
1387 }
1388 else {
1389 PyErr_SetString(
1390 PyExc_TypeError,
1391 "multiple bases have "
1392 "instance lay-out conflict");
1393 return NULL;
1394 }
1395 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001396 if (base == NULL)
1397 PyErr_SetString(PyExc_TypeError,
1398 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001399 return base;
1400}
1401
1402static int
1403extra_ivars(PyTypeObject *type, PyTypeObject *base)
1404{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001405 size_t t_size = type->tp_basicsize;
1406 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001407
Guido van Rossum9676b222001-08-17 20:32:36 +00001408 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001409 if (type->tp_itemsize || base->tp_itemsize) {
1410 /* If itemsize is involved, stricter rules */
1411 return t_size != b_size ||
1412 type->tp_itemsize != base->tp_itemsize;
1413 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001414 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1415 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1416 t_size -= sizeof(PyObject *);
1417 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1418 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1419 t_size -= sizeof(PyObject *);
1420
1421 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001422}
1423
1424static PyTypeObject *
1425solid_base(PyTypeObject *type)
1426{
1427 PyTypeObject *base;
1428
1429 if (type->tp_base)
1430 base = solid_base(type->tp_base);
1431 else
1432 base = &PyBaseObject_Type;
1433 if (extra_ivars(type, base))
1434 return type;
1435 else
1436 return base;
1437}
1438
Jeremy Hylton938ace62002-07-17 16:30:39 +00001439static void object_dealloc(PyObject *);
1440static int object_init(PyObject *, PyObject *, PyObject *);
1441static int update_slot(PyTypeObject *, PyObject *);
1442static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001443
1444static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001445subtype_dict(PyObject *obj, void *context)
1446{
1447 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1448 PyObject *dict;
1449
1450 if (dictptr == NULL) {
1451 PyErr_SetString(PyExc_AttributeError,
1452 "This object has no __dict__");
1453 return NULL;
1454 }
1455 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001456 if (dict == NULL)
1457 *dictptr = dict = PyDict_New();
1458 Py_XINCREF(dict);
1459 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001460}
1461
Guido van Rossum6661be32001-10-26 04:26:12 +00001462static int
1463subtype_setdict(PyObject *obj, PyObject *value, void *context)
1464{
1465 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1466 PyObject *dict;
1467
1468 if (dictptr == NULL) {
1469 PyErr_SetString(PyExc_AttributeError,
1470 "This object has no __dict__");
1471 return -1;
1472 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001473 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001474 PyErr_SetString(PyExc_TypeError,
1475 "__dict__ must be set to a dictionary");
1476 return -1;
1477 }
1478 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001479 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001480 *dictptr = value;
1481 Py_XDECREF(dict);
1482 return 0;
1483}
1484
Guido van Rossumad47da02002-08-12 19:05:44 +00001485static PyObject *
1486subtype_getweakref(PyObject *obj, void *context)
1487{
1488 PyObject **weaklistptr;
1489 PyObject *result;
1490
1491 if (obj->ob_type->tp_weaklistoffset == 0) {
1492 PyErr_SetString(PyExc_AttributeError,
1493 "This object has no __weaklist__");
1494 return NULL;
1495 }
1496 assert(obj->ob_type->tp_weaklistoffset > 0);
1497 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001498 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001499 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001500 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001501 if (*weaklistptr == NULL)
1502 result = Py_None;
1503 else
1504 result = *weaklistptr;
1505 Py_INCREF(result);
1506 return result;
1507}
1508
Guido van Rossum373c7412003-01-07 13:41:37 +00001509/* Three variants on the subtype_getsets list. */
1510
1511static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001512 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001513 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001514 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001515 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001516 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001517};
1518
Guido van Rossum373c7412003-01-07 13:41:37 +00001519static PyGetSetDef subtype_getsets_dict_only[] = {
1520 {"__dict__", subtype_dict, subtype_setdict,
1521 PyDoc_STR("dictionary for instance variables (if defined)")},
1522 {0}
1523};
1524
1525static PyGetSetDef subtype_getsets_weakref_only[] = {
1526 {"__weakref__", subtype_getweakref, NULL,
1527 PyDoc_STR("list of weak references to the object (if defined)")},
1528 {0}
1529};
1530
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001531static int
1532valid_identifier(PyObject *s)
1533{
Guido van Rossum03013a02002-07-16 14:30:28 +00001534 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001535 int i, n;
1536
1537 if (!PyString_Check(s)) {
1538 PyErr_SetString(PyExc_TypeError,
1539 "__slots__ must be strings");
1540 return 0;
1541 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001542 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001543 n = PyString_GET_SIZE(s);
1544 /* We must reject an empty name. As a hack, we bump the
1545 length to 1 so that the loop will balk on the trailing \0. */
1546 if (n == 0)
1547 n = 1;
1548 for (i = 0; i < n; i++, p++) {
1549 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1550 PyErr_SetString(PyExc_TypeError,
1551 "__slots__ must be identifiers");
1552 return 0;
1553 }
1554 }
1555 return 1;
1556}
1557
Martin v. Löwisd919a592002-10-14 21:07:28 +00001558#ifdef Py_USING_UNICODE
1559/* Replace Unicode objects in slots. */
1560
1561static PyObject *
1562_unicode_to_string(PyObject *slots, int nslots)
1563{
1564 PyObject *tmp = slots;
1565 PyObject *o, *o1;
1566 int i;
1567 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1568 for (i = 0; i < nslots; i++) {
1569 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1570 if (tmp == slots) {
1571 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1572 if (tmp == NULL)
1573 return NULL;
1574 }
1575 o1 = _PyUnicode_AsDefaultEncodedString
1576 (o, NULL);
1577 if (o1 == NULL) {
1578 Py_DECREF(tmp);
1579 return 0;
1580 }
1581 Py_INCREF(o1);
1582 Py_DECREF(o);
1583 PyTuple_SET_ITEM(tmp, i, o1);
1584 }
1585 }
1586 return tmp;
1587}
1588#endif
1589
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001590static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001591type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1592{
1593 PyObject *name, *bases, *dict;
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001594 static const char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001595 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001596 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001597 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001598 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001599 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001600 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001601
Tim Peters3abca122001-10-27 19:37:48 +00001602 assert(args != NULL && PyTuple_Check(args));
1603 assert(kwds == NULL || PyDict_Check(kwds));
1604
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001605 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001606 {
1607 const int nargs = PyTuple_GET_SIZE(args);
1608 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1609
1610 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1611 PyObject *x = PyTuple_GET_ITEM(args, 0);
1612 Py_INCREF(x->ob_type);
1613 return (PyObject *) x->ob_type;
1614 }
1615
1616 /* SF bug 475327 -- if that didn't trigger, we need 3
1617 arguments. but PyArg_ParseTupleAndKeywords below may give
1618 a msg saying type() needs exactly 3. */
1619 if (nargs + nkwds != 3) {
1620 PyErr_SetString(PyExc_TypeError,
1621 "type() takes 1 or 3 arguments");
1622 return NULL;
1623 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001624 }
1625
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001626 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001627 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1628 &name,
1629 &PyTuple_Type, &bases,
1630 &PyDict_Type, &dict))
1631 return NULL;
1632
1633 /* Determine the proper metatype to deal with this,
1634 and check for metatype conflicts while we're at it.
1635 Note that if some other metatype wins to contract,
1636 it's possible that its instances are not types. */
1637 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001638 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001639 for (i = 0; i < nbases; i++) {
1640 tmp = PyTuple_GET_ITEM(bases, i);
1641 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001642 if (tmptype == &PyClass_Type)
1643 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001644 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001645 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001646 if (PyType_IsSubtype(tmptype, winner)) {
1647 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001648 continue;
1649 }
1650 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001651 "metaclass conflict: "
1652 "the metaclass of a derived class "
1653 "must be a (non-strict) subclass "
1654 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001655 return NULL;
1656 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001657 if (winner != metatype) {
1658 if (winner->tp_new != type_new) /* Pass it to the winner */
1659 return winner->tp_new(winner, args, kwds);
1660 metatype = winner;
1661 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001662
1663 /* Adjust for empty tuple bases */
1664 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001665 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001666 if (bases == NULL)
1667 return NULL;
1668 nbases = 1;
1669 }
1670 else
1671 Py_INCREF(bases);
1672
1673 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1674
1675 /* Calculate best base, and check that all bases are type objects */
1676 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001677 if (base == NULL) {
1678 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001679 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001680 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001681 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1682 PyErr_Format(PyExc_TypeError,
1683 "type '%.100s' is not an acceptable base type",
1684 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001685 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001686 return NULL;
1687 }
1688
Tim Peters6d6c1a32001-08-02 04:15:00 +00001689 /* Check for a __slots__ sequence variable in dict, and count it */
1690 slots = PyDict_GetItemString(dict, "__slots__");
1691 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001692 add_dict = 0;
1693 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001694 may_add_dict = base->tp_dictoffset == 0;
1695 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1696 if (slots == NULL) {
1697 if (may_add_dict) {
1698 add_dict++;
1699 }
1700 if (may_add_weak) {
1701 add_weak++;
1702 }
1703 }
1704 else {
1705 /* Have slots */
1706
Tim Peters6d6c1a32001-08-02 04:15:00 +00001707 /* Make it into a tuple */
1708 if (PyString_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001709 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001710 else
1711 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001712 if (slots == NULL) {
1713 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001714 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001715 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001716 assert(PyTuple_Check(slots));
1717
1718 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001719 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001720 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001721 PyErr_Format(PyExc_TypeError,
1722 "nonempty __slots__ "
1723 "not supported for subtype of '%s'",
1724 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001725 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001726 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001727 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001728 return NULL;
1729 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001730
Martin v. Löwisd919a592002-10-14 21:07:28 +00001731#ifdef Py_USING_UNICODE
1732 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001733 if (tmp != slots) {
1734 Py_DECREF(slots);
1735 slots = tmp;
1736 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001737 if (!tmp)
1738 return NULL;
1739#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001740 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001741 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001742 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1743 char *s;
1744 if (!valid_identifier(tmp))
1745 goto bad_slots;
1746 assert(PyString_Check(tmp));
1747 s = PyString_AS_STRING(tmp);
1748 if (strcmp(s, "__dict__") == 0) {
1749 if (!may_add_dict || add_dict) {
1750 PyErr_SetString(PyExc_TypeError,
1751 "__dict__ slot disallowed: "
1752 "we already got one");
1753 goto bad_slots;
1754 }
1755 add_dict++;
1756 }
1757 if (strcmp(s, "__weakref__") == 0) {
1758 if (!may_add_weak || add_weak) {
1759 PyErr_SetString(PyExc_TypeError,
1760 "__weakref__ slot disallowed: "
1761 "either we already got one, "
1762 "or __itemsize__ != 0");
1763 goto bad_slots;
1764 }
1765 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001766 }
1767 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001768
Guido van Rossumad47da02002-08-12 19:05:44 +00001769 /* Copy slots into yet another tuple, demangling names */
1770 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001771 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001772 goto bad_slots;
1773 for (i = j = 0; i < nslots; i++) {
1774 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001775 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001776 s = PyString_AS_STRING(tmp);
1777 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1778 (add_weak && strcmp(s, "__weakref__") == 0))
1779 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001780 tmp =_Py_Mangle(name, tmp);
1781 if (!tmp)
1782 goto bad_slots;
Guido van Rossumad47da02002-08-12 19:05:44 +00001783 PyTuple_SET_ITEM(newslots, j, tmp);
1784 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001785 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001786 assert(j == nslots - add_dict - add_weak);
1787 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001788 Py_DECREF(slots);
1789 slots = newslots;
1790
Guido van Rossumad47da02002-08-12 19:05:44 +00001791 /* Secondary bases may provide weakrefs or dict */
1792 if (nbases > 1 &&
1793 ((may_add_dict && !add_dict) ||
1794 (may_add_weak && !add_weak))) {
1795 for (i = 0; i < nbases; i++) {
1796 tmp = PyTuple_GET_ITEM(bases, i);
1797 if (tmp == (PyObject *)base)
1798 continue; /* Skip primary base */
1799 if (PyClass_Check(tmp)) {
1800 /* Classic base class provides both */
1801 if (may_add_dict && !add_dict)
1802 add_dict++;
1803 if (may_add_weak && !add_weak)
1804 add_weak++;
1805 break;
1806 }
1807 assert(PyType_Check(tmp));
1808 tmptype = (PyTypeObject *)tmp;
1809 if (may_add_dict && !add_dict &&
1810 tmptype->tp_dictoffset != 0)
1811 add_dict++;
1812 if (may_add_weak && !add_weak &&
1813 tmptype->tp_weaklistoffset != 0)
1814 add_weak++;
1815 if (may_add_dict && !add_dict)
1816 continue;
1817 if (may_add_weak && !add_weak)
1818 continue;
1819 /* Nothing more to check */
1820 break;
1821 }
1822 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001823 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001824
1825 /* XXX From here until type is safely allocated,
1826 "return NULL" may leak slots! */
1827
1828 /* Allocate the type object */
1829 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001830 if (type == NULL) {
1831 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001832 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001833 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001834 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001835
1836 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001837 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001838 Py_INCREF(name);
1839 et->name = name;
1840 et->slots = slots;
1841
Guido van Rossumdc91b992001-08-08 22:26:22 +00001842 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001843 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1844 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001845 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1846 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001847
1848 /* It's a new-style number unless it specifically inherits any
1849 old-style numeric behavior */
1850 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1851 (base->tp_as_number == NULL))
1852 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1853
1854 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001855 type->tp_as_number = &et->as_number;
1856 type->tp_as_sequence = &et->as_sequence;
1857 type->tp_as_mapping = &et->as_mapping;
1858 type->tp_as_buffer = &et->as_buffer;
1859 type->tp_name = PyString_AS_STRING(name);
1860
1861 /* Set tp_base and tp_bases */
1862 type->tp_bases = bases;
1863 Py_INCREF(base);
1864 type->tp_base = base;
1865
Guido van Rossum687ae002001-10-15 22:03:32 +00001866 /* Initialize tp_dict from passed-in dict */
1867 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001868 if (dict == NULL) {
1869 Py_DECREF(type);
1870 return NULL;
1871 }
1872
Guido van Rossumc3542212001-08-16 09:18:56 +00001873 /* Set __module__ in the dict */
1874 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1875 tmp = PyEval_GetGlobals();
1876 if (tmp != NULL) {
1877 tmp = PyDict_GetItemString(tmp, "__name__");
1878 if (tmp != NULL) {
1879 if (PyDict_SetItemString(dict, "__module__",
1880 tmp) < 0)
1881 return NULL;
1882 }
1883 }
1884 }
1885
Tim Peters2f93e282001-10-04 05:27:00 +00001886 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001887 and is a string. The __doc__ accessor will first look for tp_doc;
1888 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001889 */
1890 {
1891 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1892 if (doc != NULL && PyString_Check(doc)) {
1893 const size_t n = (size_t)PyString_GET_SIZE(doc);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001894 char *tp_doc = PyObject_MALLOC(n+1);
1895 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00001896 Py_DECREF(type);
1897 return NULL;
1898 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001899 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
1900 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00001901 }
1902 }
1903
Tim Peters6d6c1a32001-08-02 04:15:00 +00001904 /* Special-case __new__: if it's a plain function,
1905 make it a static function */
1906 tmp = PyDict_GetItemString(dict, "__new__");
1907 if (tmp != NULL && PyFunction_Check(tmp)) {
1908 tmp = PyStaticMethod_New(tmp);
1909 if (tmp == NULL) {
1910 Py_DECREF(type);
1911 return NULL;
1912 }
1913 PyDict_SetItemString(dict, "__new__", tmp);
1914 Py_DECREF(tmp);
1915 }
1916
1917 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001918 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001919 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001920 if (slots != NULL) {
1921 for (i = 0; i < nslots; i++, mp++) {
1922 mp->name = PyString_AS_STRING(
1923 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001924 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001925 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001926 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001927 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001928 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001929 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001930 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001931 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001932 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001933 slotoffset += sizeof(PyObject *);
1934 }
1935 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001936 if (add_dict) {
1937 if (base->tp_itemsize)
1938 type->tp_dictoffset = -(long)sizeof(PyObject *);
1939 else
1940 type->tp_dictoffset = slotoffset;
1941 slotoffset += sizeof(PyObject *);
1942 }
1943 if (add_weak) {
1944 assert(!base->tp_itemsize);
1945 type->tp_weaklistoffset = slotoffset;
1946 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001947 }
1948 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001949 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001950 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001951
1952 if (type->tp_weaklistoffset && type->tp_dictoffset)
1953 type->tp_getset = subtype_getsets_full;
1954 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1955 type->tp_getset = subtype_getsets_weakref_only;
1956 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1957 type->tp_getset = subtype_getsets_dict_only;
1958 else
1959 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001960
1961 /* Special case some slots */
1962 if (type->tp_dictoffset != 0 || nslots > 0) {
1963 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1964 type->tp_getattro = PyObject_GenericGetAttr;
1965 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1966 type->tp_setattro = PyObject_GenericSetAttr;
1967 }
1968 type->tp_dealloc = subtype_dealloc;
1969
Guido van Rossum9475a232001-10-05 20:51:39 +00001970 /* Enable GC unless there are really no instance variables possible */
1971 if (!(type->tp_basicsize == sizeof(PyObject) &&
1972 type->tp_itemsize == 0))
1973 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1974
Tim Peters6d6c1a32001-08-02 04:15:00 +00001975 /* Always override allocation strategy to use regular heap */
1976 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001977 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001978 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001979 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001980 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001981 }
1982 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001983 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001984
1985 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001986 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001987 Py_DECREF(type);
1988 return NULL;
1989 }
1990
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001991 /* Put the proper slots in place */
1992 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001993
Tim Peters6d6c1a32001-08-02 04:15:00 +00001994 return (PyObject *)type;
1995}
1996
1997/* Internal API to look for a name through the MRO.
1998 This returns a borrowed reference, and doesn't set an exception! */
1999PyObject *
2000_PyType_Lookup(PyTypeObject *type, PyObject *name)
2001{
2002 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002003 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002004
Guido van Rossum687ae002001-10-15 22:03:32 +00002005 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002006 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002007
2008 /* If mro is NULL, the type is either not yet initialized
2009 by PyType_Ready(), or already cleared by type_clear().
2010 Either way the safest thing to do is to return NULL. */
2011 if (mro == NULL)
2012 return NULL;
2013
Tim Peters6d6c1a32001-08-02 04:15:00 +00002014 assert(PyTuple_Check(mro));
2015 n = PyTuple_GET_SIZE(mro);
2016 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002017 base = PyTuple_GET_ITEM(mro, i);
2018 if (PyClass_Check(base))
2019 dict = ((PyClassObject *)base)->cl_dict;
2020 else {
2021 assert(PyType_Check(base));
2022 dict = ((PyTypeObject *)base)->tp_dict;
2023 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002024 assert(dict && PyDict_Check(dict));
2025 res = PyDict_GetItem(dict, name);
2026 if (res != NULL)
2027 return res;
2028 }
2029 return NULL;
2030}
2031
2032/* This is similar to PyObject_GenericGetAttr(),
2033 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2034static PyObject *
2035type_getattro(PyTypeObject *type, PyObject *name)
2036{
2037 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002038 PyObject *meta_attribute, *attribute;
2039 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002040
2041 /* Initialize this type (we'll assume the metatype is initialized) */
2042 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002043 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002044 return NULL;
2045 }
2046
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002047 /* No readable descriptor found yet */
2048 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002049
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002050 /* Look for the attribute in the metatype */
2051 meta_attribute = _PyType_Lookup(metatype, name);
2052
2053 if (meta_attribute != NULL) {
2054 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002055
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002056 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2057 /* Data descriptors implement tp_descr_set to intercept
2058 * writes. Assume the attribute is not overridden in
2059 * type's tp_dict (and bases): call the descriptor now.
2060 */
2061 return meta_get(meta_attribute, (PyObject *)type,
2062 (PyObject *)metatype);
2063 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002064 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002065 }
2066
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002067 /* No data descriptor found on metatype. Look in tp_dict of this
2068 * type and its bases */
2069 attribute = _PyType_Lookup(type, name);
2070 if (attribute != NULL) {
2071 /* Implement descriptor functionality, if any */
2072 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002073
2074 Py_XDECREF(meta_attribute);
2075
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002076 if (local_get != NULL) {
2077 /* NULL 2nd argument indicates the descriptor was
2078 * found on the target object itself (or a base) */
2079 return local_get(attribute, (PyObject *)NULL,
2080 (PyObject *)type);
2081 }
Tim Peters34592512002-07-11 06:23:50 +00002082
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002083 Py_INCREF(attribute);
2084 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002085 }
2086
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002087 /* No attribute found in local __dict__ (or bases): use the
2088 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002089 if (meta_get != NULL) {
2090 PyObject *res;
2091 res = meta_get(meta_attribute, (PyObject *)type,
2092 (PyObject *)metatype);
2093 Py_DECREF(meta_attribute);
2094 return res;
2095 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002096
2097 /* If an ordinary attribute was found on the metatype, return it now */
2098 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002099 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002100 }
2101
2102 /* Give up */
2103 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002104 "type object '%.50s' has no attribute '%.400s'",
2105 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002106 return NULL;
2107}
2108
2109static int
2110type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2111{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002112 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2113 PyErr_Format(
2114 PyExc_TypeError,
2115 "can't set attributes of built-in/extension type '%s'",
2116 type->tp_name);
2117 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002118 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002119 /* XXX Example of how I expect this to be used...
2120 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2121 return -1;
2122 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002123 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2124 return -1;
2125 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002126}
2127
2128static void
2129type_dealloc(PyTypeObject *type)
2130{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002131 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002132
2133 /* Assert this is a heap-allocated type object */
2134 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002135 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002136 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002137 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002138 Py_XDECREF(type->tp_base);
2139 Py_XDECREF(type->tp_dict);
2140 Py_XDECREF(type->tp_bases);
2141 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002142 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002143 Py_XDECREF(type->tp_subclasses);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002144 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2145 * of most other objects. It's okay to cast it to char *.
2146 */
2147 PyObject_Free((char *)type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002148 Py_XDECREF(et->name);
2149 Py_XDECREF(et->slots);
2150 type->ob_type->tp_free((PyObject *)type);
2151}
2152
Guido van Rossum1c450732001-10-08 15:18:27 +00002153static PyObject *
2154type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2155{
2156 PyObject *list, *raw, *ref;
2157 int i, n;
2158
2159 list = PyList_New(0);
2160 if (list == NULL)
2161 return NULL;
2162 raw = type->tp_subclasses;
2163 if (raw == NULL)
2164 return list;
2165 assert(PyList_Check(raw));
2166 n = PyList_GET_SIZE(raw);
2167 for (i = 0; i < n; i++) {
2168 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002169 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002170 ref = PyWeakref_GET_OBJECT(ref);
2171 if (ref != Py_None) {
2172 if (PyList_Append(list, ref) < 0) {
2173 Py_DECREF(list);
2174 return NULL;
2175 }
2176 }
2177 }
2178 return list;
2179}
2180
Tim Peters6d6c1a32001-08-02 04:15:00 +00002181static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002182 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002183 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002184 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002185 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002186 {0}
2187};
2188
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002189PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002190"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002191"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002192
Guido van Rossum048eb752001-10-02 21:24:57 +00002193static int
2194type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2195{
Guido van Rossum048eb752001-10-02 21:24:57 +00002196 int err;
2197
Guido van Rossuma3862092002-06-10 15:24:42 +00002198 /* Because of type_is_gc(), the collector only calls this
2199 for heaptypes. */
2200 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002201
2202#define VISIT(SLOT) \
2203 if (SLOT) { \
2204 err = visit((PyObject *)(SLOT), arg); \
2205 if (err) \
2206 return err; \
2207 }
2208
2209 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002210 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002211 VISIT(type->tp_mro);
2212 VISIT(type->tp_bases);
2213 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002214
2215 /* There's no need to visit type->tp_subclasses or
Guido van Rossume5c691a2003-03-07 15:13:17 +00002216 ((PyHeapTypeObject *)type)->slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002217 in cycles; tp_subclasses is a list of weak references,
2218 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002219
2220#undef VISIT
2221
2222 return 0;
2223}
2224
2225static int
2226type_clear(PyTypeObject *type)
2227{
Guido van Rossum048eb752001-10-02 21:24:57 +00002228 PyObject *tmp;
2229
Guido van Rossuma3862092002-06-10 15:24:42 +00002230 /* Because of type_is_gc(), the collector only calls this
2231 for heaptypes. */
2232 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002233
2234#define CLEAR(SLOT) \
2235 if (SLOT) { \
2236 tmp = (PyObject *)(SLOT); \
2237 SLOT = NULL; \
2238 Py_DECREF(tmp); \
2239 }
2240
Guido van Rossuma3862092002-06-10 15:24:42 +00002241 /* The only field we need to clear is tp_mro, which is part of a
2242 hard cycle (its first element is the class itself) that won't
2243 be broken otherwise (it's a tuple and tuples don't have a
2244 tp_clear handler). None of the other fields need to be
2245 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002246
Guido van Rossuma3862092002-06-10 15:24:42 +00002247 tp_dict:
2248 It is a dict, so the collector will call its tp_clear.
2249
2250 tp_cache:
2251 Not used; if it were, it would be a dict.
2252
2253 tp_bases, tp_base:
2254 If these are involved in a cycle, there must be at least
2255 one other, mutable object in the cycle, e.g. a base
2256 class's dict; the cycle will be broken that way.
2257
2258 tp_subclasses:
2259 A list of weak references can't be part of a cycle; and
2260 lists have their own tp_clear.
2261
Guido van Rossume5c691a2003-03-07 15:13:17 +00002262 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002263 A tuple of strings can't be part of a cycle.
2264 */
2265
2266 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002267
Guido van Rossum048eb752001-10-02 21:24:57 +00002268#undef CLEAR
2269
2270 return 0;
2271}
2272
2273static int
2274type_is_gc(PyTypeObject *type)
2275{
2276 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2277}
2278
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002279PyTypeObject PyType_Type = {
2280 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002281 0, /* ob_size */
2282 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002283 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002284 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002285 (destructor)type_dealloc, /* tp_dealloc */
2286 0, /* tp_print */
2287 0, /* tp_getattr */
2288 0, /* tp_setattr */
2289 type_compare, /* tp_compare */
2290 (reprfunc)type_repr, /* tp_repr */
2291 0, /* tp_as_number */
2292 0, /* tp_as_sequence */
2293 0, /* tp_as_mapping */
2294 (hashfunc)_Py_HashPointer, /* tp_hash */
2295 (ternaryfunc)type_call, /* tp_call */
2296 0, /* tp_str */
2297 (getattrofunc)type_getattro, /* tp_getattro */
2298 (setattrofunc)type_setattro, /* tp_setattro */
2299 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002300 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2301 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002302 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002303 (traverseproc)type_traverse, /* tp_traverse */
2304 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002305 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002306 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002307 0, /* tp_iter */
2308 0, /* tp_iternext */
2309 type_methods, /* tp_methods */
2310 type_members, /* tp_members */
2311 type_getsets, /* tp_getset */
2312 0, /* tp_base */
2313 0, /* tp_dict */
2314 0, /* tp_descr_get */
2315 0, /* tp_descr_set */
2316 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2317 0, /* tp_init */
2318 0, /* tp_alloc */
2319 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002320 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002321 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002322};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002323
2324
2325/* The base type of all types (eventually)... except itself. */
2326
2327static int
2328object_init(PyObject *self, PyObject *args, PyObject *kwds)
2329{
2330 return 0;
2331}
2332
Guido van Rossum298e4212003-02-13 16:30:16 +00002333/* If we don't have a tp_new for a new-style class, new will use this one.
2334 Therefore this should take no arguments/keywords. However, this new may
2335 also be inherited by objects that define a tp_init but no tp_new. These
2336 objects WILL pass argumets to tp_new, because it gets the same args as
2337 tp_init. So only allow arguments if we aren't using the default init, in
2338 which case we expect init to handle argument parsing. */
2339static PyObject *
2340object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2341{
2342 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2343 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2344 PyErr_SetString(PyExc_TypeError,
2345 "default __new__ takes no parameters");
2346 return NULL;
2347 }
2348 return type->tp_alloc(type, 0);
2349}
2350
Tim Peters6d6c1a32001-08-02 04:15:00 +00002351static void
2352object_dealloc(PyObject *self)
2353{
2354 self->ob_type->tp_free(self);
2355}
2356
Guido van Rossum8e248182001-08-12 05:17:56 +00002357static PyObject *
2358object_repr(PyObject *self)
2359{
Guido van Rossum76e69632001-08-16 18:52:43 +00002360 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002361 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002362
Guido van Rossum76e69632001-08-16 18:52:43 +00002363 type = self->ob_type;
2364 mod = type_module(type, NULL);
2365 if (mod == NULL)
2366 PyErr_Clear();
2367 else if (!PyString_Check(mod)) {
2368 Py_DECREF(mod);
2369 mod = NULL;
2370 }
2371 name = type_name(type, NULL);
2372 if (name == NULL)
2373 return NULL;
2374 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002375 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002376 PyString_AS_STRING(mod),
2377 PyString_AS_STRING(name),
2378 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002379 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002380 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002381 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002382 Py_XDECREF(mod);
2383 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002384 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002385}
2386
Guido van Rossumb8f63662001-08-15 23:57:02 +00002387static PyObject *
2388object_str(PyObject *self)
2389{
2390 unaryfunc f;
2391
2392 f = self->ob_type->tp_repr;
2393 if (f == NULL)
2394 f = object_repr;
2395 return f(self);
2396}
2397
Guido van Rossum8e248182001-08-12 05:17:56 +00002398static long
2399object_hash(PyObject *self)
2400{
2401 return _Py_HashPointer(self);
2402}
Guido van Rossum8e248182001-08-12 05:17:56 +00002403
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002404static PyObject *
2405object_get_class(PyObject *self, void *closure)
2406{
2407 Py_INCREF(self->ob_type);
2408 return (PyObject *)(self->ob_type);
2409}
2410
2411static int
2412equiv_structs(PyTypeObject *a, PyTypeObject *b)
2413{
2414 return a == b ||
2415 (a != NULL &&
2416 b != NULL &&
2417 a->tp_basicsize == b->tp_basicsize &&
2418 a->tp_itemsize == b->tp_itemsize &&
2419 a->tp_dictoffset == b->tp_dictoffset &&
2420 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2421 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2422 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2423}
2424
2425static int
2426same_slots_added(PyTypeObject *a, PyTypeObject *b)
2427{
2428 PyTypeObject *base = a->tp_base;
2429 int size;
2430
2431 if (base != b->tp_base)
2432 return 0;
2433 if (equiv_structs(a, base) && equiv_structs(b, base))
2434 return 1;
2435 size = base->tp_basicsize;
2436 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2437 size += sizeof(PyObject *);
2438 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2439 size += sizeof(PyObject *);
2440 return size == a->tp_basicsize && size == b->tp_basicsize;
2441}
2442
2443static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002444compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2445{
2446 PyTypeObject *newbase, *oldbase;
2447
2448 if (new->tp_dealloc != old->tp_dealloc ||
2449 new->tp_free != old->tp_free)
2450 {
2451 PyErr_Format(PyExc_TypeError,
2452 "%s assignment: "
2453 "'%s' deallocator differs from '%s'",
2454 attr,
2455 new->tp_name,
2456 old->tp_name);
2457 return 0;
2458 }
2459 newbase = new;
2460 oldbase = old;
2461 while (equiv_structs(newbase, newbase->tp_base))
2462 newbase = newbase->tp_base;
2463 while (equiv_structs(oldbase, oldbase->tp_base))
2464 oldbase = oldbase->tp_base;
2465 if (newbase != oldbase &&
2466 (newbase->tp_base != oldbase->tp_base ||
2467 !same_slots_added(newbase, oldbase))) {
2468 PyErr_Format(PyExc_TypeError,
2469 "%s assignment: "
2470 "'%s' object layout differs from '%s'",
2471 attr,
2472 new->tp_name,
2473 old->tp_name);
2474 return 0;
2475 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002476
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002477 return 1;
2478}
2479
2480static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002481object_set_class(PyObject *self, PyObject *value, void *closure)
2482{
2483 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002484 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002485
Guido van Rossumb6b89422002-04-15 01:03:30 +00002486 if (value == NULL) {
2487 PyErr_SetString(PyExc_TypeError,
2488 "can't delete __class__ attribute");
2489 return -1;
2490 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002491 if (!PyType_Check(value)) {
2492 PyErr_Format(PyExc_TypeError,
2493 "__class__ must be set to new-style class, not '%s' object",
2494 value->ob_type->tp_name);
2495 return -1;
2496 }
2497 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002498 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2499 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2500 {
2501 PyErr_Format(PyExc_TypeError,
2502 "__class__ assignment: only for heap types");
2503 return -1;
2504 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002505 if (compatible_for_assignment(new, old, "__class__")) {
2506 Py_INCREF(new);
2507 self->ob_type = new;
2508 Py_DECREF(old);
2509 return 0;
2510 }
2511 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002512 return -1;
2513 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002514}
2515
2516static PyGetSetDef object_getsets[] = {
2517 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002518 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002519 {0}
2520};
2521
Guido van Rossumc53f0092003-02-18 22:05:12 +00002522
Guido van Rossum036f9992003-02-21 22:02:54 +00002523/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2524 We fall back to helpers in copy_reg for:
2525 - pickle protocols < 2
2526 - calculating the list of slot names (done only once per class)
2527 - the __newobj__ function (which is used as a token but never called)
2528*/
2529
2530static PyObject *
2531import_copy_reg(void)
2532{
2533 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002534
2535 if (!copy_reg_str) {
2536 copy_reg_str = PyString_InternFromString("copy_reg");
2537 if (copy_reg_str == NULL)
2538 return NULL;
2539 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002540
2541 return PyImport_Import(copy_reg_str);
2542}
2543
2544static PyObject *
2545slotnames(PyObject *cls)
2546{
2547 PyObject *clsdict;
2548 PyObject *copy_reg;
2549 PyObject *slotnames;
2550
2551 if (!PyType_Check(cls)) {
2552 Py_INCREF(Py_None);
2553 return Py_None;
2554 }
2555
2556 clsdict = ((PyTypeObject *)cls)->tp_dict;
2557 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002558 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002559 Py_INCREF(slotnames);
2560 return slotnames;
2561 }
2562
2563 copy_reg = import_copy_reg();
2564 if (copy_reg == NULL)
2565 return NULL;
2566
2567 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2568 Py_DECREF(copy_reg);
2569 if (slotnames != NULL &&
2570 slotnames != Py_None &&
2571 !PyList_Check(slotnames))
2572 {
2573 PyErr_SetString(PyExc_TypeError,
2574 "copy_reg._slotnames didn't return a list or None");
2575 Py_DECREF(slotnames);
2576 slotnames = NULL;
2577 }
2578
2579 return slotnames;
2580}
2581
2582static PyObject *
2583reduce_2(PyObject *obj)
2584{
2585 PyObject *cls, *getnewargs;
2586 PyObject *args = NULL, *args2 = NULL;
2587 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2588 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2589 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
2590 int i, n;
2591
2592 cls = PyObject_GetAttrString(obj, "__class__");
2593 if (cls == NULL)
2594 return NULL;
2595
2596 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2597 if (getnewargs != NULL) {
2598 args = PyObject_CallObject(getnewargs, NULL);
2599 Py_DECREF(getnewargs);
2600 if (args != NULL && !PyTuple_Check(args)) {
2601 PyErr_SetString(PyExc_TypeError,
2602 "__getnewargs__ should return a tuple");
2603 goto end;
2604 }
2605 }
2606 else {
2607 PyErr_Clear();
2608 args = PyTuple_New(0);
2609 }
2610 if (args == NULL)
2611 goto end;
2612
2613 getstate = PyObject_GetAttrString(obj, "__getstate__");
2614 if (getstate != NULL) {
2615 state = PyObject_CallObject(getstate, NULL);
2616 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002617 if (state == NULL)
2618 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002619 }
2620 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002621 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002622 state = PyObject_GetAttrString(obj, "__dict__");
2623 if (state == NULL) {
2624 PyErr_Clear();
2625 state = Py_None;
2626 Py_INCREF(state);
2627 }
2628 names = slotnames(cls);
2629 if (names == NULL)
2630 goto end;
2631 if (names != Py_None) {
2632 assert(PyList_Check(names));
2633 slots = PyDict_New();
2634 if (slots == NULL)
2635 goto end;
2636 n = 0;
2637 /* Can't pre-compute the list size; the list
2638 is stored on the class so accessible to other
2639 threads, which may be run by DECREF */
2640 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2641 PyObject *name, *value;
2642 name = PyList_GET_ITEM(names, i);
2643 value = PyObject_GetAttr(obj, name);
2644 if (value == NULL)
2645 PyErr_Clear();
2646 else {
2647 int err = PyDict_SetItem(slots, name,
2648 value);
2649 Py_DECREF(value);
2650 if (err)
2651 goto end;
2652 n++;
2653 }
2654 }
2655 if (n) {
2656 state = Py_BuildValue("(NO)", state, slots);
2657 if (state == NULL)
2658 goto end;
2659 }
2660 }
2661 }
2662
2663 if (!PyList_Check(obj)) {
2664 listitems = Py_None;
2665 Py_INCREF(listitems);
2666 }
2667 else {
2668 listitems = PyObject_GetIter(obj);
2669 if (listitems == NULL)
2670 goto end;
2671 }
2672
2673 if (!PyDict_Check(obj)) {
2674 dictitems = Py_None;
2675 Py_INCREF(dictitems);
2676 }
2677 else {
2678 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2679 if (dictitems == NULL)
2680 goto end;
2681 }
2682
2683 copy_reg = import_copy_reg();
2684 if (copy_reg == NULL)
2685 goto end;
2686 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2687 if (newobj == NULL)
2688 goto end;
2689
2690 n = PyTuple_GET_SIZE(args);
2691 args2 = PyTuple_New(n+1);
2692 if (args2 == NULL)
2693 goto end;
2694 PyTuple_SET_ITEM(args2, 0, cls);
2695 cls = NULL;
2696 for (i = 0; i < n; i++) {
2697 PyObject *v = PyTuple_GET_ITEM(args, i);
2698 Py_INCREF(v);
2699 PyTuple_SET_ITEM(args2, i+1, v);
2700 }
2701
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002702 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002703
2704 end:
2705 Py_XDECREF(cls);
2706 Py_XDECREF(args);
2707 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002708 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002709 Py_XDECREF(state);
2710 Py_XDECREF(names);
2711 Py_XDECREF(listitems);
2712 Py_XDECREF(dictitems);
2713 Py_XDECREF(copy_reg);
2714 Py_XDECREF(newobj);
2715 return res;
2716}
2717
2718static PyObject *
2719object_reduce_ex(PyObject *self, PyObject *args)
2720{
2721 /* Call copy_reg._reduce_ex(self, proto) */
2722 PyObject *reduce, *copy_reg, *res;
2723 int proto = 0;
2724
2725 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2726 return NULL;
2727
2728 reduce = PyObject_GetAttrString(self, "__reduce__");
2729 if (reduce == NULL)
2730 PyErr_Clear();
2731 else {
2732 PyObject *cls, *clsreduce, *objreduce;
2733 int override;
2734 cls = PyObject_GetAttrString(self, "__class__");
2735 if (cls == NULL) {
2736 Py_DECREF(reduce);
2737 return NULL;
2738 }
2739 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2740 Py_DECREF(cls);
2741 if (clsreduce == NULL) {
2742 Py_DECREF(reduce);
2743 return NULL;
2744 }
2745 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2746 "__reduce__");
2747 override = (clsreduce != objreduce);
2748 Py_DECREF(clsreduce);
2749 if (override) {
2750 res = PyObject_CallObject(reduce, NULL);
2751 Py_DECREF(reduce);
2752 return res;
2753 }
2754 else
2755 Py_DECREF(reduce);
2756 }
2757
2758 if (proto >= 2)
2759 return reduce_2(self);
2760
2761 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002762 if (!copy_reg)
2763 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002764
Guido van Rossumc53f0092003-02-18 22:05:12 +00002765 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002766 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002767
Guido van Rossum3926a632001-09-25 16:25:58 +00002768 return res;
2769}
2770
2771static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002772 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2773 PyDoc_STR("helper for pickle")},
2774 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002775 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002776 {0}
2777};
2778
Guido van Rossum036f9992003-02-21 22:02:54 +00002779
Tim Peters6d6c1a32001-08-02 04:15:00 +00002780PyTypeObject PyBaseObject_Type = {
2781 PyObject_HEAD_INIT(&PyType_Type)
2782 0, /* ob_size */
2783 "object", /* tp_name */
2784 sizeof(PyObject), /* tp_basicsize */
2785 0, /* tp_itemsize */
2786 (destructor)object_dealloc, /* tp_dealloc */
2787 0, /* tp_print */
2788 0, /* tp_getattr */
2789 0, /* tp_setattr */
2790 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002791 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002792 0, /* tp_as_number */
2793 0, /* tp_as_sequence */
2794 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002795 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002796 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002797 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002798 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002799 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002800 0, /* tp_as_buffer */
2801 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002802 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002803 0, /* tp_traverse */
2804 0, /* tp_clear */
2805 0, /* tp_richcompare */
2806 0, /* tp_weaklistoffset */
2807 0, /* tp_iter */
2808 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002809 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002810 0, /* tp_members */
2811 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002812 0, /* tp_base */
2813 0, /* tp_dict */
2814 0, /* tp_descr_get */
2815 0, /* tp_descr_set */
2816 0, /* tp_dictoffset */
2817 object_init, /* tp_init */
2818 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002819 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002820 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002821};
2822
2823
2824/* Initialize the __dict__ in a type object */
2825
2826static int
2827add_methods(PyTypeObject *type, PyMethodDef *meth)
2828{
Guido van Rossum687ae002001-10-15 22:03:32 +00002829 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002830
2831 for (; meth->ml_name != NULL; meth++) {
2832 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002833 if (PyDict_GetItemString(dict, meth->ml_name) &&
2834 !(meth->ml_flags & METH_COEXIST))
2835 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002836 if (meth->ml_flags & METH_CLASS) {
2837 if (meth->ml_flags & METH_STATIC) {
2838 PyErr_SetString(PyExc_ValueError,
2839 "method cannot be both class and static");
2840 return -1;
2841 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002842 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002843 }
2844 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002845 PyObject *cfunc = PyCFunction_New(meth, NULL);
2846 if (cfunc == NULL)
2847 return -1;
2848 descr = PyStaticMethod_New(cfunc);
2849 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002850 }
2851 else {
2852 descr = PyDescr_NewMethod(type, meth);
2853 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002854 if (descr == NULL)
2855 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002856 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002857 return -1;
2858 Py_DECREF(descr);
2859 }
2860 return 0;
2861}
2862
2863static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002864add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002865{
Guido van Rossum687ae002001-10-15 22:03:32 +00002866 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002867
2868 for (; memb->name != NULL; memb++) {
2869 PyObject *descr;
2870 if (PyDict_GetItemString(dict, memb->name))
2871 continue;
2872 descr = PyDescr_NewMember(type, memb);
2873 if (descr == NULL)
2874 return -1;
2875 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2876 return -1;
2877 Py_DECREF(descr);
2878 }
2879 return 0;
2880}
2881
2882static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002883add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002884{
Guido van Rossum687ae002001-10-15 22:03:32 +00002885 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002886
2887 for (; gsp->name != NULL; gsp++) {
2888 PyObject *descr;
2889 if (PyDict_GetItemString(dict, gsp->name))
2890 continue;
2891 descr = PyDescr_NewGetSet(type, gsp);
2892
2893 if (descr == NULL)
2894 return -1;
2895 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2896 return -1;
2897 Py_DECREF(descr);
2898 }
2899 return 0;
2900}
2901
Guido van Rossum13d52f02001-08-10 21:24:08 +00002902static void
2903inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002904{
2905 int oldsize, newsize;
2906
Guido van Rossum13d52f02001-08-10 21:24:08 +00002907 /* Special flag magic */
2908 if (!type->tp_as_buffer && base->tp_as_buffer) {
2909 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2910 type->tp_flags |=
2911 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2912 }
2913 if (!type->tp_as_sequence && base->tp_as_sequence) {
2914 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2915 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2916 }
2917 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2918 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2919 if ((!type->tp_as_number && base->tp_as_number) ||
2920 (!type->tp_as_sequence && base->tp_as_sequence)) {
2921 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2922 if (!type->tp_as_number && !type->tp_as_sequence) {
2923 type->tp_flags |= base->tp_flags &
2924 Py_TPFLAGS_HAVE_INPLACEOPS;
2925 }
2926 }
2927 /* Wow */
2928 }
2929 if (!type->tp_as_number && base->tp_as_number) {
2930 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2931 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2932 }
2933
2934 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002935 oldsize = base->tp_basicsize;
2936 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2937 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2938 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002939 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2940 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002941 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002942 if (type->tp_traverse == NULL)
2943 type->tp_traverse = base->tp_traverse;
2944 if (type->tp_clear == NULL)
2945 type->tp_clear = base->tp_clear;
2946 }
2947 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002948 /* The condition below could use some explanation.
2949 It appears that tp_new is not inherited for static types
2950 whose base class is 'object'; this seems to be a precaution
2951 so that old extension types don't suddenly become
2952 callable (object.__new__ wouldn't insure the invariants
2953 that the extension type's own factory function ensures).
2954 Heap types, of course, are under our control, so they do
2955 inherit tp_new; static extension types that specify some
2956 other built-in type as the default are considered
2957 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002958 if (base != &PyBaseObject_Type ||
2959 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2960 if (type->tp_new == NULL)
2961 type->tp_new = base->tp_new;
2962 }
2963 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002964 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002965
2966 /* Copy other non-function slots */
2967
2968#undef COPYVAL
2969#define COPYVAL(SLOT) \
2970 if (type->SLOT == 0) type->SLOT = base->SLOT
2971
2972 COPYVAL(tp_itemsize);
2973 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2974 COPYVAL(tp_weaklistoffset);
2975 }
2976 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2977 COPYVAL(tp_dictoffset);
2978 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002979}
2980
2981static void
2982inherit_slots(PyTypeObject *type, PyTypeObject *base)
2983{
2984 PyTypeObject *basebase;
2985
2986#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002987#undef COPYSLOT
2988#undef COPYNUM
2989#undef COPYSEQ
2990#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002991#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002992
2993#define SLOTDEFINED(SLOT) \
2994 (base->SLOT != 0 && \
2995 (basebase == NULL || base->SLOT != basebase->SLOT))
2996
Tim Peters6d6c1a32001-08-02 04:15:00 +00002997#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002998 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002999
3000#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3001#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3002#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003003#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003004
Guido van Rossum13d52f02001-08-10 21:24:08 +00003005 /* This won't inherit indirect slots (from tp_as_number etc.)
3006 if type doesn't provide the space. */
3007
3008 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3009 basebase = base->tp_base;
3010 if (basebase->tp_as_number == NULL)
3011 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003012 COPYNUM(nb_add);
3013 COPYNUM(nb_subtract);
3014 COPYNUM(nb_multiply);
3015 COPYNUM(nb_divide);
3016 COPYNUM(nb_remainder);
3017 COPYNUM(nb_divmod);
3018 COPYNUM(nb_power);
3019 COPYNUM(nb_negative);
3020 COPYNUM(nb_positive);
3021 COPYNUM(nb_absolute);
3022 COPYNUM(nb_nonzero);
3023 COPYNUM(nb_invert);
3024 COPYNUM(nb_lshift);
3025 COPYNUM(nb_rshift);
3026 COPYNUM(nb_and);
3027 COPYNUM(nb_xor);
3028 COPYNUM(nb_or);
3029 COPYNUM(nb_coerce);
3030 COPYNUM(nb_int);
3031 COPYNUM(nb_long);
3032 COPYNUM(nb_float);
3033 COPYNUM(nb_oct);
3034 COPYNUM(nb_hex);
3035 COPYNUM(nb_inplace_add);
3036 COPYNUM(nb_inplace_subtract);
3037 COPYNUM(nb_inplace_multiply);
3038 COPYNUM(nb_inplace_divide);
3039 COPYNUM(nb_inplace_remainder);
3040 COPYNUM(nb_inplace_power);
3041 COPYNUM(nb_inplace_lshift);
3042 COPYNUM(nb_inplace_rshift);
3043 COPYNUM(nb_inplace_and);
3044 COPYNUM(nb_inplace_xor);
3045 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003046 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3047 COPYNUM(nb_true_divide);
3048 COPYNUM(nb_floor_divide);
3049 COPYNUM(nb_inplace_true_divide);
3050 COPYNUM(nb_inplace_floor_divide);
3051 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003052 }
3053
Guido van Rossum13d52f02001-08-10 21:24:08 +00003054 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3055 basebase = base->tp_base;
3056 if (basebase->tp_as_sequence == NULL)
3057 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003058 COPYSEQ(sq_length);
3059 COPYSEQ(sq_concat);
3060 COPYSEQ(sq_repeat);
3061 COPYSEQ(sq_item);
3062 COPYSEQ(sq_slice);
3063 COPYSEQ(sq_ass_item);
3064 COPYSEQ(sq_ass_slice);
3065 COPYSEQ(sq_contains);
3066 COPYSEQ(sq_inplace_concat);
3067 COPYSEQ(sq_inplace_repeat);
3068 }
3069
Guido van Rossum13d52f02001-08-10 21:24:08 +00003070 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3071 basebase = base->tp_base;
3072 if (basebase->tp_as_mapping == NULL)
3073 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003074 COPYMAP(mp_length);
3075 COPYMAP(mp_subscript);
3076 COPYMAP(mp_ass_subscript);
3077 }
3078
Tim Petersfc57ccb2001-10-12 02:38:24 +00003079 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3080 basebase = base->tp_base;
3081 if (basebase->tp_as_buffer == NULL)
3082 basebase = NULL;
3083 COPYBUF(bf_getreadbuffer);
3084 COPYBUF(bf_getwritebuffer);
3085 COPYBUF(bf_getsegcount);
3086 COPYBUF(bf_getcharbuffer);
3087 }
3088
Guido van Rossum13d52f02001-08-10 21:24:08 +00003089 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003090
Tim Peters6d6c1a32001-08-02 04:15:00 +00003091 COPYSLOT(tp_dealloc);
3092 COPYSLOT(tp_print);
3093 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3094 type->tp_getattr = base->tp_getattr;
3095 type->tp_getattro = base->tp_getattro;
3096 }
3097 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3098 type->tp_setattr = base->tp_setattr;
3099 type->tp_setattro = base->tp_setattro;
3100 }
3101 /* tp_compare see tp_richcompare */
3102 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003103 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003104 COPYSLOT(tp_call);
3105 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003106 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003107 if (type->tp_compare == NULL &&
3108 type->tp_richcompare == NULL &&
3109 type->tp_hash == NULL)
3110 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003111 type->tp_compare = base->tp_compare;
3112 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003113 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003114 }
3115 }
3116 else {
3117 COPYSLOT(tp_compare);
3118 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003119 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3120 COPYSLOT(tp_iter);
3121 COPYSLOT(tp_iternext);
3122 }
3123 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3124 COPYSLOT(tp_descr_get);
3125 COPYSLOT(tp_descr_set);
3126 COPYSLOT(tp_dictoffset);
3127 COPYSLOT(tp_init);
3128 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003129 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003130 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3131 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3132 /* They agree about gc. */
3133 COPYSLOT(tp_free);
3134 }
3135 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3136 type->tp_free == NULL &&
3137 base->tp_free == _PyObject_Del) {
3138 /* A bit of magic to plug in the correct default
3139 * tp_free function when a derived class adds gc,
3140 * didn't define tp_free, and the base uses the
3141 * default non-gc tp_free.
3142 */
3143 type->tp_free = PyObject_GC_Del;
3144 }
3145 /* else they didn't agree about gc, and there isn't something
3146 * obvious to be done -- the type is on its own.
3147 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003148 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003149}
3150
Jeremy Hylton938ace62002-07-17 16:30:39 +00003151static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003152
Tim Peters6d6c1a32001-08-02 04:15:00 +00003153int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003154PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003155{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003156 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003157 PyTypeObject *base;
3158 int i, n;
3159
Guido van Rossumcab05802002-06-10 15:29:03 +00003160 if (type->tp_flags & Py_TPFLAGS_READY) {
3161 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003162 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003163 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003164 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003165
3166 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003167
Tim Peters36eb4df2003-03-23 03:33:13 +00003168#ifdef Py_TRACE_REFS
3169 /* PyType_Ready is the closest thing we have to a choke point
3170 * for type objects, so is the best place I can think of to try
3171 * to get type objects into the doubly-linked list of all objects.
3172 * Still, not all type objects go thru PyType_Ready.
3173 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003174 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003175#endif
3176
Tim Peters6d6c1a32001-08-02 04:15:00 +00003177 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3178 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003179 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003180 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003181 Py_INCREF(base);
3182 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003183
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003184 /* Initialize the base class */
3185 if (base && base->tp_dict == NULL) {
3186 if (PyType_Ready(base) < 0)
3187 goto error;
3188 }
3189
Guido van Rossum0986d822002-04-08 01:38:42 +00003190 /* Initialize ob_type if NULL. This means extensions that want to be
3191 compilable separately on Windows can call PyType_Ready() instead of
3192 initializing the ob_type field of their type objects. */
3193 if (type->ob_type == NULL)
3194 type->ob_type = base->ob_type;
3195
Tim Peters6d6c1a32001-08-02 04:15:00 +00003196 /* Initialize tp_bases */
3197 bases = type->tp_bases;
3198 if (bases == NULL) {
3199 if (base == NULL)
3200 bases = PyTuple_New(0);
3201 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003202 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003203 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003204 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003205 type->tp_bases = bases;
3206 }
3207
Guido van Rossum687ae002001-10-15 22:03:32 +00003208 /* Initialize tp_dict */
3209 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003210 if (dict == NULL) {
3211 dict = PyDict_New();
3212 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003213 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003214 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003215 }
3216
Guido van Rossum687ae002001-10-15 22:03:32 +00003217 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003218 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003219 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003220 if (type->tp_methods != NULL) {
3221 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003222 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003223 }
3224 if (type->tp_members != NULL) {
3225 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003226 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003227 }
3228 if (type->tp_getset != NULL) {
3229 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003230 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003231 }
3232
Tim Peters6d6c1a32001-08-02 04:15:00 +00003233 /* Calculate method resolution order */
3234 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003235 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003236 }
3237
Guido van Rossum13d52f02001-08-10 21:24:08 +00003238 /* Inherit special flags from dominant base */
3239 if (type->tp_base != NULL)
3240 inherit_special(type, type->tp_base);
3241
Tim Peters6d6c1a32001-08-02 04:15:00 +00003242 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003243 bases = type->tp_mro;
3244 assert(bases != NULL);
3245 assert(PyTuple_Check(bases));
3246 n = PyTuple_GET_SIZE(bases);
3247 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003248 PyObject *b = PyTuple_GET_ITEM(bases, i);
3249 if (PyType_Check(b))
3250 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003251 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003252
Tim Peters3cfe7542003-05-21 21:29:48 +00003253 /* Sanity check for tp_free. */
3254 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3255 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3256 /* This base class needs to call tp_free, but doesn't have
3257 * one, or its tp_free is for non-gc'ed objects.
3258 */
3259 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3260 "gc and is a base type but has inappropriate "
3261 "tp_free slot",
3262 type->tp_name);
3263 goto error;
3264 }
3265
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003266 /* if the type dictionary doesn't contain a __doc__, set it from
3267 the tp_doc slot.
3268 */
3269 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3270 if (type->tp_doc != NULL) {
3271 PyObject *doc = PyString_FromString(type->tp_doc);
3272 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3273 Py_DECREF(doc);
3274 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003275 PyDict_SetItemString(type->tp_dict,
3276 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003277 }
3278 }
3279
Guido van Rossum13d52f02001-08-10 21:24:08 +00003280 /* Some more special stuff */
3281 base = type->tp_base;
3282 if (base != NULL) {
3283 if (type->tp_as_number == NULL)
3284 type->tp_as_number = base->tp_as_number;
3285 if (type->tp_as_sequence == NULL)
3286 type->tp_as_sequence = base->tp_as_sequence;
3287 if (type->tp_as_mapping == NULL)
3288 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003289 if (type->tp_as_buffer == NULL)
3290 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003291 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003292
Guido van Rossum1c450732001-10-08 15:18:27 +00003293 /* Link into each base class's list of subclasses */
3294 bases = type->tp_bases;
3295 n = PyTuple_GET_SIZE(bases);
3296 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003297 PyObject *b = PyTuple_GET_ITEM(bases, i);
3298 if (PyType_Check(b) &&
3299 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003300 goto error;
3301 }
3302
Guido van Rossum13d52f02001-08-10 21:24:08 +00003303 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003304 assert(type->tp_dict != NULL);
3305 type->tp_flags =
3306 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003307 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003308
3309 error:
3310 type->tp_flags &= ~Py_TPFLAGS_READYING;
3311 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003312}
3313
Guido van Rossum1c450732001-10-08 15:18:27 +00003314static int
3315add_subclass(PyTypeObject *base, PyTypeObject *type)
3316{
3317 int i;
3318 PyObject *list, *ref, *new;
3319
3320 list = base->tp_subclasses;
3321 if (list == NULL) {
3322 base->tp_subclasses = list = PyList_New(0);
3323 if (list == NULL)
3324 return -1;
3325 }
3326 assert(PyList_Check(list));
3327 new = PyWeakref_NewRef((PyObject *)type, NULL);
3328 i = PyList_GET_SIZE(list);
3329 while (--i >= 0) {
3330 ref = PyList_GET_ITEM(list, i);
3331 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003332 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3333 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003334 }
3335 i = PyList_Append(list, new);
3336 Py_DECREF(new);
3337 return i;
3338}
3339
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003340static void
3341remove_subclass(PyTypeObject *base, PyTypeObject *type)
3342{
3343 int i;
3344 PyObject *list, *ref;
3345
3346 list = base->tp_subclasses;
3347 if (list == NULL) {
3348 return;
3349 }
3350 assert(PyList_Check(list));
3351 i = PyList_GET_SIZE(list);
3352 while (--i >= 0) {
3353 ref = PyList_GET_ITEM(list, i);
3354 assert(PyWeakref_CheckRef(ref));
3355 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3356 /* this can't fail, right? */
3357 PySequence_DelItem(list, i);
3358 return;
3359 }
3360 }
3361}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003362
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003363static int
3364check_num_args(PyObject *ob, int n)
3365{
3366 if (!PyTuple_CheckExact(ob)) {
3367 PyErr_SetString(PyExc_SystemError,
3368 "PyArg_UnpackTuple() argument list is not a tuple");
3369 return 0;
3370 }
3371 if (n == PyTuple_GET_SIZE(ob))
3372 return 1;
3373 PyErr_Format(
3374 PyExc_TypeError,
3375 "expected %d arguments, got %d", n, PyTuple_GET_SIZE(ob));
3376 return 0;
3377}
3378
Tim Peters6d6c1a32001-08-02 04:15:00 +00003379/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3380
3381/* There's a wrapper *function* for each distinct function typedef used
3382 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3383 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3384 Most tables have only one entry; the tables for binary operators have two
3385 entries, one regular and one with reversed arguments. */
3386
3387static PyObject *
3388wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3389{
3390 inquiry func = (inquiry)wrapped;
3391 int res;
3392
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003393 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003394 return NULL;
3395 res = (*func)(self);
3396 if (res == -1 && PyErr_Occurred())
3397 return NULL;
3398 return PyInt_FromLong((long)res);
3399}
3400
Tim Peters6d6c1a32001-08-02 04:15:00 +00003401static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003402wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3403{
3404 inquiry func = (inquiry)wrapped;
3405 int res;
3406
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003407 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003408 return NULL;
3409 res = (*func)(self);
3410 if (res == -1 && PyErr_Occurred())
3411 return NULL;
3412 return PyBool_FromLong((long)res);
3413}
3414
3415static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003416wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3417{
3418 binaryfunc func = (binaryfunc)wrapped;
3419 PyObject *other;
3420
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003421 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003422 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003423 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003424 return (*func)(self, other);
3425}
3426
3427static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003428wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3429{
3430 binaryfunc func = (binaryfunc)wrapped;
3431 PyObject *other;
3432
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003433 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003434 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003435 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003436 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003437 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003438 Py_INCREF(Py_NotImplemented);
3439 return Py_NotImplemented;
3440 }
3441 return (*func)(self, other);
3442}
3443
3444static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003445wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3446{
3447 binaryfunc func = (binaryfunc)wrapped;
3448 PyObject *other;
3449
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003450 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003451 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003452 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003453 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003454 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003455 Py_INCREF(Py_NotImplemented);
3456 return Py_NotImplemented;
3457 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003458 return (*func)(other, self);
3459}
3460
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003461static PyObject *
3462wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3463{
3464 coercion func = (coercion)wrapped;
3465 PyObject *other, *res;
3466 int ok;
3467
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003468 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003469 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003470 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003471 ok = func(&self, &other);
3472 if (ok < 0)
3473 return NULL;
3474 if (ok > 0) {
3475 Py_INCREF(Py_NotImplemented);
3476 return Py_NotImplemented;
3477 }
3478 res = PyTuple_New(2);
3479 if (res == NULL) {
3480 Py_DECREF(self);
3481 Py_DECREF(other);
3482 return NULL;
3483 }
3484 PyTuple_SET_ITEM(res, 0, self);
3485 PyTuple_SET_ITEM(res, 1, other);
3486 return res;
3487}
3488
Tim Peters6d6c1a32001-08-02 04:15:00 +00003489static PyObject *
3490wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3491{
3492 ternaryfunc func = (ternaryfunc)wrapped;
3493 PyObject *other;
3494 PyObject *third = Py_None;
3495
3496 /* Note: This wrapper only works for __pow__() */
3497
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003498 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003499 return NULL;
3500 return (*func)(self, other, third);
3501}
3502
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003503static PyObject *
3504wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3505{
3506 ternaryfunc func = (ternaryfunc)wrapped;
3507 PyObject *other;
3508 PyObject *third = Py_None;
3509
3510 /* Note: This wrapper only works for __pow__() */
3511
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003512 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003513 return NULL;
3514 return (*func)(other, self, third);
3515}
3516
Tim Peters6d6c1a32001-08-02 04:15:00 +00003517static PyObject *
3518wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3519{
3520 unaryfunc func = (unaryfunc)wrapped;
3521
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003522 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003523 return NULL;
3524 return (*func)(self);
3525}
3526
Tim Peters6d6c1a32001-08-02 04:15:00 +00003527static PyObject *
3528wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3529{
3530 intargfunc func = (intargfunc)wrapped;
3531 int i;
3532
3533 if (!PyArg_ParseTuple(args, "i", &i))
3534 return NULL;
3535 return (*func)(self, i);
3536}
3537
Guido van Rossum5d815f32001-08-17 21:57:47 +00003538static int
3539getindex(PyObject *self, PyObject *arg)
3540{
3541 int i;
3542
3543 i = PyInt_AsLong(arg);
3544 if (i == -1 && PyErr_Occurred())
3545 return -1;
3546 if (i < 0) {
3547 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3548 if (sq && sq->sq_length) {
3549 int n = (*sq->sq_length)(self);
3550 if (n < 0)
3551 return -1;
3552 i += n;
3553 }
3554 }
3555 return i;
3556}
3557
3558static PyObject *
3559wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3560{
3561 intargfunc func = (intargfunc)wrapped;
3562 PyObject *arg;
3563 int i;
3564
Guido van Rossumf4593e02001-10-03 12:09:30 +00003565 if (PyTuple_GET_SIZE(args) == 1) {
3566 arg = PyTuple_GET_ITEM(args, 0);
3567 i = getindex(self, arg);
3568 if (i == -1 && PyErr_Occurred())
3569 return NULL;
3570 return (*func)(self, i);
3571 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003572 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003573 assert(PyErr_Occurred());
3574 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003575}
3576
Tim Peters6d6c1a32001-08-02 04:15:00 +00003577static PyObject *
3578wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3579{
3580 intintargfunc func = (intintargfunc)wrapped;
3581 int i, j;
3582
3583 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3584 return NULL;
3585 return (*func)(self, i, j);
3586}
3587
Tim Peters6d6c1a32001-08-02 04:15:00 +00003588static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003589wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003590{
3591 intobjargproc func = (intobjargproc)wrapped;
3592 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003593 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003594
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003595 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003596 return NULL;
3597 i = getindex(self, arg);
3598 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003599 return NULL;
3600 res = (*func)(self, i, value);
3601 if (res == -1 && PyErr_Occurred())
3602 return NULL;
3603 Py_INCREF(Py_None);
3604 return Py_None;
3605}
3606
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003607static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003608wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003609{
3610 intobjargproc func = (intobjargproc)wrapped;
3611 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003612 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003613
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003614 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003615 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003616 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003617 i = getindex(self, arg);
3618 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003619 return NULL;
3620 res = (*func)(self, i, NULL);
3621 if (res == -1 && PyErr_Occurred())
3622 return NULL;
3623 Py_INCREF(Py_None);
3624 return Py_None;
3625}
3626
Tim Peters6d6c1a32001-08-02 04:15:00 +00003627static PyObject *
3628wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3629{
3630 intintobjargproc func = (intintobjargproc)wrapped;
3631 int i, j, res;
3632 PyObject *value;
3633
3634 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3635 return NULL;
3636 res = (*func)(self, i, j, value);
3637 if (res == -1 && PyErr_Occurred())
3638 return NULL;
3639 Py_INCREF(Py_None);
3640 return Py_None;
3641}
3642
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003643static PyObject *
3644wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3645{
3646 intintobjargproc func = (intintobjargproc)wrapped;
3647 int i, j, res;
3648
3649 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3650 return NULL;
3651 res = (*func)(self, i, j, NULL);
3652 if (res == -1 && PyErr_Occurred())
3653 return NULL;
3654 Py_INCREF(Py_None);
3655 return Py_None;
3656}
3657
Tim Peters6d6c1a32001-08-02 04:15:00 +00003658/* XXX objobjproc is a misnomer; should be objargpred */
3659static PyObject *
3660wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3661{
3662 objobjproc func = (objobjproc)wrapped;
3663 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003664 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003665
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003666 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003667 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003668 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003669 res = (*func)(self, value);
3670 if (res == -1 && PyErr_Occurred())
3671 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003672 else
3673 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003674}
3675
Tim Peters6d6c1a32001-08-02 04:15:00 +00003676static PyObject *
3677wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3678{
3679 objobjargproc func = (objobjargproc)wrapped;
3680 int res;
3681 PyObject *key, *value;
3682
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003683 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003684 return NULL;
3685 res = (*func)(self, key, value);
3686 if (res == -1 && PyErr_Occurred())
3687 return NULL;
3688 Py_INCREF(Py_None);
3689 return Py_None;
3690}
3691
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003692static PyObject *
3693wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3694{
3695 objobjargproc func = (objobjargproc)wrapped;
3696 int res;
3697 PyObject *key;
3698
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003699 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003700 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003701 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003702 res = (*func)(self, key, NULL);
3703 if (res == -1 && PyErr_Occurred())
3704 return NULL;
3705 Py_INCREF(Py_None);
3706 return Py_None;
3707}
3708
Tim Peters6d6c1a32001-08-02 04:15:00 +00003709static PyObject *
3710wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3711{
3712 cmpfunc func = (cmpfunc)wrapped;
3713 int res;
3714 PyObject *other;
3715
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003716 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003717 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003718 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003719 if (other->ob_type->tp_compare != func &&
3720 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003721 PyErr_Format(
3722 PyExc_TypeError,
3723 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3724 self->ob_type->tp_name,
3725 self->ob_type->tp_name,
3726 other->ob_type->tp_name);
3727 return NULL;
3728 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003729 res = (*func)(self, other);
3730 if (PyErr_Occurred())
3731 return NULL;
3732 return PyInt_FromLong((long)res);
3733}
3734
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003735/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003736 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003737static int
3738hackcheck(PyObject *self, setattrofunc func, char *what)
3739{
3740 PyTypeObject *type = self->ob_type;
3741 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3742 type = type->tp_base;
3743 if (type->tp_setattro != func) {
3744 PyErr_Format(PyExc_TypeError,
3745 "can't apply this %s to %s object",
3746 what,
3747 type->tp_name);
3748 return 0;
3749 }
3750 return 1;
3751}
3752
Tim Peters6d6c1a32001-08-02 04:15:00 +00003753static PyObject *
3754wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3755{
3756 setattrofunc func = (setattrofunc)wrapped;
3757 int res;
3758 PyObject *name, *value;
3759
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003760 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003761 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003762 if (!hackcheck(self, func, "__setattr__"))
3763 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003764 res = (*func)(self, name, value);
3765 if (res < 0)
3766 return NULL;
3767 Py_INCREF(Py_None);
3768 return Py_None;
3769}
3770
3771static PyObject *
3772wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3773{
3774 setattrofunc func = (setattrofunc)wrapped;
3775 int res;
3776 PyObject *name;
3777
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003778 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003779 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003780 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003781 if (!hackcheck(self, func, "__delattr__"))
3782 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003783 res = (*func)(self, name, NULL);
3784 if (res < 0)
3785 return NULL;
3786 Py_INCREF(Py_None);
3787 return Py_None;
3788}
3789
Tim Peters6d6c1a32001-08-02 04:15:00 +00003790static PyObject *
3791wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3792{
3793 hashfunc func = (hashfunc)wrapped;
3794 long res;
3795
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003796 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003797 return NULL;
3798 res = (*func)(self);
3799 if (res == -1 && PyErr_Occurred())
3800 return NULL;
3801 return PyInt_FromLong(res);
3802}
3803
Tim Peters6d6c1a32001-08-02 04:15:00 +00003804static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003805wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003806{
3807 ternaryfunc func = (ternaryfunc)wrapped;
3808
Guido van Rossumc8e56452001-10-22 00:43:43 +00003809 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003810}
3811
Tim Peters6d6c1a32001-08-02 04:15:00 +00003812static PyObject *
3813wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3814{
3815 richcmpfunc func = (richcmpfunc)wrapped;
3816 PyObject *other;
3817
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003818 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003819 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003820 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003821 return (*func)(self, other, op);
3822}
3823
3824#undef RICHCMP_WRAPPER
3825#define RICHCMP_WRAPPER(NAME, OP) \
3826static PyObject * \
3827richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3828{ \
3829 return wrap_richcmpfunc(self, args, wrapped, OP); \
3830}
3831
Jack Jansen8e938b42001-08-08 15:29:49 +00003832RICHCMP_WRAPPER(lt, Py_LT)
3833RICHCMP_WRAPPER(le, Py_LE)
3834RICHCMP_WRAPPER(eq, Py_EQ)
3835RICHCMP_WRAPPER(ne, Py_NE)
3836RICHCMP_WRAPPER(gt, Py_GT)
3837RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003838
Tim Peters6d6c1a32001-08-02 04:15:00 +00003839static PyObject *
3840wrap_next(PyObject *self, PyObject *args, void *wrapped)
3841{
3842 unaryfunc func = (unaryfunc)wrapped;
3843 PyObject *res;
3844
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003845 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003846 return NULL;
3847 res = (*func)(self);
3848 if (res == NULL && !PyErr_Occurred())
3849 PyErr_SetNone(PyExc_StopIteration);
3850 return res;
3851}
3852
Tim Peters6d6c1a32001-08-02 04:15:00 +00003853static PyObject *
3854wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3855{
3856 descrgetfunc func = (descrgetfunc)wrapped;
3857 PyObject *obj;
3858 PyObject *type = NULL;
3859
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003860 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003861 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003862 if (obj == Py_None)
3863 obj = NULL;
3864 if (type == Py_None)
3865 type = NULL;
3866 if (type == NULL &&obj == NULL) {
3867 PyErr_SetString(PyExc_TypeError,
3868 "__get__(None, None) is invalid");
3869 return NULL;
3870 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003871 return (*func)(self, obj, type);
3872}
3873
Tim Peters6d6c1a32001-08-02 04:15:00 +00003874static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003875wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003876{
3877 descrsetfunc func = (descrsetfunc)wrapped;
3878 PyObject *obj, *value;
3879 int ret;
3880
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003881 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003882 return NULL;
3883 ret = (*func)(self, obj, value);
3884 if (ret < 0)
3885 return NULL;
3886 Py_INCREF(Py_None);
3887 return Py_None;
3888}
Guido van Rossum22b13872002-08-06 21:41:44 +00003889
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003890static PyObject *
3891wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3892{
3893 descrsetfunc func = (descrsetfunc)wrapped;
3894 PyObject *obj;
3895 int ret;
3896
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003897 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003898 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003899 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003900 ret = (*func)(self, obj, NULL);
3901 if (ret < 0)
3902 return NULL;
3903 Py_INCREF(Py_None);
3904 return Py_None;
3905}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003906
Tim Peters6d6c1a32001-08-02 04:15:00 +00003907static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003908wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003909{
3910 initproc func = (initproc)wrapped;
3911
Guido van Rossumc8e56452001-10-22 00:43:43 +00003912 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003913 return NULL;
3914 Py_INCREF(Py_None);
3915 return Py_None;
3916}
3917
Tim Peters6d6c1a32001-08-02 04:15:00 +00003918static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003919tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003920{
Barry Warsaw60f01882001-08-22 19:24:42 +00003921 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003922 PyObject *arg0, *res;
3923
3924 if (self == NULL || !PyType_Check(self))
3925 Py_FatalError("__new__() called with non-type 'self'");
3926 type = (PyTypeObject *)self;
3927 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003928 PyErr_Format(PyExc_TypeError,
3929 "%s.__new__(): not enough arguments",
3930 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003931 return NULL;
3932 }
3933 arg0 = PyTuple_GET_ITEM(args, 0);
3934 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003935 PyErr_Format(PyExc_TypeError,
3936 "%s.__new__(X): X is not a type object (%s)",
3937 type->tp_name,
3938 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003939 return NULL;
3940 }
3941 subtype = (PyTypeObject *)arg0;
3942 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003943 PyErr_Format(PyExc_TypeError,
3944 "%s.__new__(%s): %s is not a subtype of %s",
3945 type->tp_name,
3946 subtype->tp_name,
3947 subtype->tp_name,
3948 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003949 return NULL;
3950 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003951
3952 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003953 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003954 most derived base that's not a heap type is this type. */
3955 staticbase = subtype;
3956 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3957 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003958 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003959 PyErr_Format(PyExc_TypeError,
3960 "%s.__new__(%s) is not safe, use %s.__new__()",
3961 type->tp_name,
3962 subtype->tp_name,
3963 staticbase == NULL ? "?" : staticbase->tp_name);
3964 return NULL;
3965 }
3966
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003967 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3968 if (args == NULL)
3969 return NULL;
3970 res = type->tp_new(subtype, args, kwds);
3971 Py_DECREF(args);
3972 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003973}
3974
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003975static struct PyMethodDef tp_new_methoddef[] = {
3976 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003977 PyDoc_STR("T.__new__(S, ...) -> "
3978 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003979 {0}
3980};
3981
3982static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003983add_tp_new_wrapper(PyTypeObject *type)
3984{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003985 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003986
Guido van Rossum687ae002001-10-15 22:03:32 +00003987 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003988 return 0;
3989 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003990 if (func == NULL)
3991 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00003992 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00003993 Py_DECREF(func);
3994 return -1;
3995 }
3996 Py_DECREF(func);
3997 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003998}
3999
Guido van Rossumf040ede2001-08-07 16:40:56 +00004000/* Slot wrappers that call the corresponding __foo__ slot. See comments
4001 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004002
Guido van Rossumdc91b992001-08-08 22:26:22 +00004003#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004004static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004005FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004006{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004007 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004008 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004009}
4010
Guido van Rossumdc91b992001-08-08 22:26:22 +00004011#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004012static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004013FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004014{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004015 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004016 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004017}
4018
Guido van Rossumcd118802003-01-06 22:57:47 +00004019/* Boolean helper for SLOT1BINFULL().
4020 right.__class__ is a nontrivial subclass of left.__class__. */
4021static int
4022method_is_overloaded(PyObject *left, PyObject *right, char *name)
4023{
4024 PyObject *a, *b;
4025 int ok;
4026
4027 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
4028 if (b == NULL) {
4029 PyErr_Clear();
4030 /* If right doesn't have it, it's not overloaded */
4031 return 0;
4032 }
4033
4034 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
4035 if (a == NULL) {
4036 PyErr_Clear();
4037 Py_DECREF(b);
4038 /* If right has it but left doesn't, it's overloaded */
4039 return 1;
4040 }
4041
4042 ok = PyObject_RichCompareBool(a, b, Py_NE);
4043 Py_DECREF(a);
4044 Py_DECREF(b);
4045 if (ok < 0) {
4046 PyErr_Clear();
4047 return 0;
4048 }
4049
4050 return ok;
4051}
4052
Guido van Rossumdc91b992001-08-08 22:26:22 +00004053
4054#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004055static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004056FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004057{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004058 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004059 int do_other = self->ob_type != other->ob_type && \
4060 other->ob_type->tp_as_number != NULL && \
4061 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004062 if (self->ob_type->tp_as_number != NULL && \
4063 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
4064 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004065 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004066 PyType_IsSubtype(other->ob_type, self->ob_type) && \
4067 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004068 r = call_maybe( \
4069 other, ROPSTR, &rcache_str, "(O)", self); \
4070 if (r != Py_NotImplemented) \
4071 return r; \
4072 Py_DECREF(r); \
4073 do_other = 0; \
4074 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004075 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004076 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004077 if (r != Py_NotImplemented || \
4078 other->ob_type == self->ob_type) \
4079 return r; \
4080 Py_DECREF(r); \
4081 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004082 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004083 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004084 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004085 } \
4086 Py_INCREF(Py_NotImplemented); \
4087 return Py_NotImplemented; \
4088}
4089
4090#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4091 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4092
4093#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4094static PyObject * \
4095FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4096{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004097 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004098 return call_method(self, OPSTR, &cache_str, \
4099 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004100}
4101
4102static int
4103slot_sq_length(PyObject *self)
4104{
Guido van Rossum2730b132001-08-28 18:22:14 +00004105 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004106 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum630db602005-09-20 18:49:54 +00004107 long temp;
Guido van Rossum26111622001-10-01 16:42:49 +00004108 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004109
4110 if (res == NULL)
4111 return -1;
Guido van Rossum630db602005-09-20 18:49:54 +00004112 temp = PyInt_AsLong(res);
4113 len = (int)temp;
Guido van Rossum26111622001-10-01 16:42:49 +00004114 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00004115 if (len == -1 && PyErr_Occurred())
4116 return -1;
Guido van Rossum630db602005-09-20 18:49:54 +00004117#if SIZEOF_INT < SIZEOF_LONG
4118 /* Overflow check -- range of PyInt is more than C int */
4119 if (len != temp) {
4120 PyErr_SetString(PyExc_OverflowError,
4121 "__len__() should return 0 <= outcome < 2**31");
4122 return -1;
4123 }
4124#endif
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004125 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00004126 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004127 "__len__() should return >= 0");
4128 return -1;
4129 }
Guido van Rossum26111622001-10-01 16:42:49 +00004130 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004131}
4132
Guido van Rossumf4593e02001-10-03 12:09:30 +00004133/* Super-optimized version of slot_sq_item.
4134 Other slots could do the same... */
4135static PyObject *
4136slot_sq_item(PyObject *self, int i)
4137{
4138 static PyObject *getitem_str;
4139 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4140 descrgetfunc f;
4141
4142 if (getitem_str == NULL) {
4143 getitem_str = PyString_InternFromString("__getitem__");
4144 if (getitem_str == NULL)
4145 return NULL;
4146 }
4147 func = _PyType_Lookup(self->ob_type, getitem_str);
4148 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004149 if ((f = func->ob_type->tp_descr_get) == NULL)
4150 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004151 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004152 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004153 if (func == NULL) {
4154 return NULL;
4155 }
4156 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00004157 ival = PyInt_FromLong(i);
4158 if (ival != NULL) {
4159 args = PyTuple_New(1);
4160 if (args != NULL) {
4161 PyTuple_SET_ITEM(args, 0, ival);
4162 retval = PyObject_Call(func, args, NULL);
4163 Py_XDECREF(args);
4164 Py_XDECREF(func);
4165 return retval;
4166 }
4167 }
4168 }
4169 else {
4170 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4171 }
4172 Py_XDECREF(args);
4173 Py_XDECREF(ival);
4174 Py_XDECREF(func);
4175 return NULL;
4176}
4177
Guido van Rossumdc91b992001-08-08 22:26:22 +00004178SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004179
4180static int
4181slot_sq_ass_item(PyObject *self, int index, PyObject *value)
4182{
4183 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004184 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004185
4186 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004187 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004188 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004189 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004190 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004191 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004192 if (res == NULL)
4193 return -1;
4194 Py_DECREF(res);
4195 return 0;
4196}
4197
4198static int
4199slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
4200{
4201 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004202 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004203
4204 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004205 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004206 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004207 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004208 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004209 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004210 if (res == NULL)
4211 return -1;
4212 Py_DECREF(res);
4213 return 0;
4214}
4215
4216static int
4217slot_sq_contains(PyObject *self, PyObject *value)
4218{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004219 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004220 int result = -1;
4221
Guido van Rossum60718732001-08-28 17:47:51 +00004222 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004223
Guido van Rossum55f20992001-10-01 17:18:22 +00004224 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004225 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004226 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004227 if (args == NULL)
4228 res = NULL;
4229 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004230 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004231 Py_DECREF(args);
4232 }
4233 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004234 if (res != NULL) {
4235 result = PyObject_IsTrue(res);
4236 Py_DECREF(res);
4237 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004238 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004239 else if (! PyErr_Occurred()) {
4240 result = _PySequence_IterSearch(self, value,
4241 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004242 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004243 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004244}
4245
Tim Peters6d6c1a32001-08-02 04:15:00 +00004246#define slot_mp_length slot_sq_length
4247
Guido van Rossumdc91b992001-08-08 22:26:22 +00004248SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004249
4250static int
4251slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4252{
4253 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004254 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004255
4256 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004257 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004258 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004259 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004260 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004261 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004262 if (res == NULL)
4263 return -1;
4264 Py_DECREF(res);
4265 return 0;
4266}
4267
Guido van Rossumdc91b992001-08-08 22:26:22 +00004268SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4269SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4270SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4271SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4272SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4273SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4274
Jeremy Hylton938ace62002-07-17 16:30:39 +00004275static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004276
4277SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4278 nb_power, "__pow__", "__rpow__")
4279
4280static PyObject *
4281slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4282{
Guido van Rossum2730b132001-08-28 18:22:14 +00004283 static PyObject *pow_str;
4284
Guido van Rossumdc91b992001-08-08 22:26:22 +00004285 if (modulus == Py_None)
4286 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004287 /* Three-arg power doesn't use __rpow__. But ternary_op
4288 can call this when the second argument's type uses
4289 slot_nb_power, so check before calling self.__pow__. */
4290 if (self->ob_type->tp_as_number != NULL &&
4291 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4292 return call_method(self, "__pow__", &pow_str,
4293 "(OO)", other, modulus);
4294 }
4295 Py_INCREF(Py_NotImplemented);
4296 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004297}
4298
4299SLOT0(slot_nb_negative, "__neg__")
4300SLOT0(slot_nb_positive, "__pos__")
4301SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004302
4303static int
4304slot_nb_nonzero(PyObject *self)
4305{
Tim Petersea7f75d2002-12-07 21:39:16 +00004306 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004307 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004308 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004309
Guido van Rossum55f20992001-10-01 17:18:22 +00004310 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004311 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004312 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004313 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004314 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004315 if (func == NULL)
4316 return PyErr_Occurred() ? -1 : 1;
4317 }
4318 args = PyTuple_New(0);
4319 if (args != NULL) {
4320 PyObject *temp = PyObject_Call(func, args, NULL);
4321 Py_DECREF(args);
4322 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004323 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004324 result = PyObject_IsTrue(temp);
4325 else {
4326 PyErr_Format(PyExc_TypeError,
4327 "__nonzero__ should return "
4328 "bool or int, returned %s",
4329 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004330 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004331 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004332 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004333 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004334 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004335 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004336 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004337}
4338
Guido van Rossumdc91b992001-08-08 22:26:22 +00004339SLOT0(slot_nb_invert, "__invert__")
4340SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4341SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4342SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4343SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4344SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004345
4346static int
4347slot_nb_coerce(PyObject **a, PyObject **b)
4348{
4349 static PyObject *coerce_str;
4350 PyObject *self = *a, *other = *b;
4351
4352 if (self->ob_type->tp_as_number != NULL &&
4353 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4354 PyObject *r;
4355 r = call_maybe(
4356 self, "__coerce__", &coerce_str, "(O)", other);
4357 if (r == NULL)
4358 return -1;
4359 if (r == Py_NotImplemented) {
4360 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004361 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004362 else {
4363 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4364 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004365 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004366 Py_DECREF(r);
4367 return -1;
4368 }
4369 *a = PyTuple_GET_ITEM(r, 0);
4370 Py_INCREF(*a);
4371 *b = PyTuple_GET_ITEM(r, 1);
4372 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004373 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004374 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004375 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004376 }
4377 if (other->ob_type->tp_as_number != NULL &&
4378 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4379 PyObject *r;
4380 r = call_maybe(
4381 other, "__coerce__", &coerce_str, "(O)", self);
4382 if (r == NULL)
4383 return -1;
4384 if (r == Py_NotImplemented) {
4385 Py_DECREF(r);
4386 return 1;
4387 }
4388 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4389 PyErr_SetString(PyExc_TypeError,
4390 "__coerce__ didn't return a 2-tuple");
4391 Py_DECREF(r);
4392 return -1;
4393 }
4394 *a = PyTuple_GET_ITEM(r, 1);
4395 Py_INCREF(*a);
4396 *b = PyTuple_GET_ITEM(r, 0);
4397 Py_INCREF(*b);
4398 Py_DECREF(r);
4399 return 0;
4400 }
4401 return 1;
4402}
4403
Guido van Rossumdc91b992001-08-08 22:26:22 +00004404SLOT0(slot_nb_int, "__int__")
4405SLOT0(slot_nb_long, "__long__")
4406SLOT0(slot_nb_float, "__float__")
4407SLOT0(slot_nb_oct, "__oct__")
4408SLOT0(slot_nb_hex, "__hex__")
4409SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4410SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4411SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4412SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4413SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004414SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004415SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4416SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4417SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4418SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4419SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4420SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4421 "__floordiv__", "__rfloordiv__")
4422SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4423SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4424SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004425
4426static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004427half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004428{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004429 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004430 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004431 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004432
Guido van Rossum60718732001-08-28 17:47:51 +00004433 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004434 if (func == NULL) {
4435 PyErr_Clear();
4436 }
4437 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004438 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004439 if (args == NULL)
4440 res = NULL;
4441 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004442 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004443 Py_DECREF(args);
4444 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004445 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004446 if (res != Py_NotImplemented) {
4447 if (res == NULL)
4448 return -2;
4449 c = PyInt_AsLong(res);
4450 Py_DECREF(res);
4451 if (c == -1 && PyErr_Occurred())
4452 return -2;
4453 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4454 }
4455 Py_DECREF(res);
4456 }
4457 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004458}
4459
Guido van Rossumab3b0342001-09-18 20:38:53 +00004460/* This slot is published for the benefit of try_3way_compare in object.c */
4461int
4462_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004463{
4464 int c;
4465
Guido van Rossumab3b0342001-09-18 20:38:53 +00004466 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004467 c = half_compare(self, other);
4468 if (c <= 1)
4469 return c;
4470 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004471 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004472 c = half_compare(other, self);
4473 if (c < -1)
4474 return -2;
4475 if (c <= 1)
4476 return -c;
4477 }
4478 return (void *)self < (void *)other ? -1 :
4479 (void *)self > (void *)other ? 1 : 0;
4480}
4481
4482static PyObject *
4483slot_tp_repr(PyObject *self)
4484{
4485 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004486 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004487
Guido van Rossum60718732001-08-28 17:47:51 +00004488 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004489 if (func != NULL) {
4490 res = PyEval_CallObject(func, NULL);
4491 Py_DECREF(func);
4492 return res;
4493 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004494 PyErr_Clear();
4495 return PyString_FromFormat("<%s object at %p>",
4496 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004497}
4498
4499static PyObject *
4500slot_tp_str(PyObject *self)
4501{
4502 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004503 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004504
Guido van Rossum60718732001-08-28 17:47:51 +00004505 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004506 if (func != NULL) {
4507 res = PyEval_CallObject(func, NULL);
4508 Py_DECREF(func);
4509 return res;
4510 }
4511 else {
4512 PyErr_Clear();
4513 return slot_tp_repr(self);
4514 }
4515}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004516
4517static long
4518slot_tp_hash(PyObject *self)
4519{
Tim Peters61ce0a92002-12-06 23:38:02 +00004520 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004521 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004522 long h;
4523
Guido van Rossum60718732001-08-28 17:47:51 +00004524 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004525
4526 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004527 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004528 Py_DECREF(func);
4529 if (res == NULL)
4530 return -1;
4531 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004532 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004533 }
4534 else {
4535 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004536 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004537 if (func == NULL) {
4538 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004539 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004540 }
4541 if (func != NULL) {
4542 Py_DECREF(func);
4543 PyErr_SetString(PyExc_TypeError, "unhashable type");
4544 return -1;
4545 }
4546 PyErr_Clear();
4547 h = _Py_HashPointer((void *)self);
4548 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004549 if (h == -1 && !PyErr_Occurred())
4550 h = -2;
4551 return h;
4552}
4553
4554static PyObject *
4555slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4556{
Guido van Rossum60718732001-08-28 17:47:51 +00004557 static PyObject *call_str;
4558 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004559 PyObject *res;
4560
4561 if (meth == NULL)
4562 return NULL;
4563 res = PyObject_Call(meth, args, kwds);
4564 Py_DECREF(meth);
4565 return res;
4566}
4567
Guido van Rossum14a6f832001-10-17 13:59:09 +00004568/* There are two slot dispatch functions for tp_getattro.
4569
4570 - slot_tp_getattro() is used when __getattribute__ is overridden
4571 but no __getattr__ hook is present;
4572
4573 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4574
Guido van Rossumc334df52002-04-04 23:44:47 +00004575 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4576 detects the absence of __getattr__ and then installs the simpler slot if
4577 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004578
Tim Peters6d6c1a32001-08-02 04:15:00 +00004579static PyObject *
4580slot_tp_getattro(PyObject *self, PyObject *name)
4581{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004582 static PyObject *getattribute_str = NULL;
4583 return call_method(self, "__getattribute__", &getattribute_str,
4584 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004585}
4586
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004587static PyObject *
4588slot_tp_getattr_hook(PyObject *self, PyObject *name)
4589{
4590 PyTypeObject *tp = self->ob_type;
4591 PyObject *getattr, *getattribute, *res;
4592 static PyObject *getattribute_str = NULL;
4593 static PyObject *getattr_str = NULL;
4594
4595 if (getattr_str == NULL) {
4596 getattr_str = PyString_InternFromString("__getattr__");
4597 if (getattr_str == NULL)
4598 return NULL;
4599 }
4600 if (getattribute_str == NULL) {
4601 getattribute_str =
4602 PyString_InternFromString("__getattribute__");
4603 if (getattribute_str == NULL)
4604 return NULL;
4605 }
4606 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004607 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004608 /* No __getattr__ hook: use a simpler dispatcher */
4609 tp->tp_getattro = slot_tp_getattro;
4610 return slot_tp_getattro(self, name);
4611 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004612 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004613 if (getattribute == NULL ||
4614 (getattribute->ob_type == &PyWrapperDescr_Type &&
4615 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4616 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004617 res = PyObject_GenericGetAttr(self, name);
4618 else
4619 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004620 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004621 PyErr_Clear();
4622 res = PyObject_CallFunction(getattr, "OO", self, name);
4623 }
4624 return res;
4625}
4626
Tim Peters6d6c1a32001-08-02 04:15:00 +00004627static int
4628slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4629{
4630 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004631 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004632
4633 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004634 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004635 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004636 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004637 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004638 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004639 if (res == NULL)
4640 return -1;
4641 Py_DECREF(res);
4642 return 0;
4643}
4644
4645/* Map rich comparison operators to their __xx__ namesakes */
4646static char *name_op[] = {
4647 "__lt__",
4648 "__le__",
4649 "__eq__",
4650 "__ne__",
4651 "__gt__",
4652 "__ge__",
4653};
4654
4655static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004656half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004657{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004658 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004659 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004660
Guido van Rossum60718732001-08-28 17:47:51 +00004661 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004662 if (func == NULL) {
4663 PyErr_Clear();
4664 Py_INCREF(Py_NotImplemented);
4665 return Py_NotImplemented;
4666 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004667 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004668 if (args == NULL)
4669 res = NULL;
4670 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004671 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004672 Py_DECREF(args);
4673 }
4674 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004675 return res;
4676}
4677
Guido van Rossumb8f63662001-08-15 23:57:02 +00004678static PyObject *
4679slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4680{
4681 PyObject *res;
4682
4683 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4684 res = half_richcompare(self, other, op);
4685 if (res != Py_NotImplemented)
4686 return res;
4687 Py_DECREF(res);
4688 }
4689 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004690 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004691 if (res != Py_NotImplemented) {
4692 return res;
4693 }
4694 Py_DECREF(res);
4695 }
4696 Py_INCREF(Py_NotImplemented);
4697 return Py_NotImplemented;
4698}
4699
4700static PyObject *
4701slot_tp_iter(PyObject *self)
4702{
4703 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004704 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004705
Guido van Rossum60718732001-08-28 17:47:51 +00004706 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004707 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004708 PyObject *args;
4709 args = res = PyTuple_New(0);
4710 if (args != NULL) {
4711 res = PyObject_Call(func, args, NULL);
4712 Py_DECREF(args);
4713 }
4714 Py_DECREF(func);
4715 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004716 }
4717 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004718 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004719 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004720 PyErr_SetString(PyExc_TypeError,
4721 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004722 return NULL;
4723 }
4724 Py_DECREF(func);
4725 return PySeqIter_New(self);
4726}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004727
4728static PyObject *
4729slot_tp_iternext(PyObject *self)
4730{
Guido van Rossum2730b132001-08-28 18:22:14 +00004731 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004732 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004733}
4734
Guido van Rossum1a493502001-08-17 16:47:50 +00004735static PyObject *
4736slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4737{
4738 PyTypeObject *tp = self->ob_type;
4739 PyObject *get;
4740 static PyObject *get_str = NULL;
4741
4742 if (get_str == NULL) {
4743 get_str = PyString_InternFromString("__get__");
4744 if (get_str == NULL)
4745 return NULL;
4746 }
4747 get = _PyType_Lookup(tp, get_str);
4748 if (get == NULL) {
4749 /* Avoid further slowdowns */
4750 if (tp->tp_descr_get == slot_tp_descr_get)
4751 tp->tp_descr_get = NULL;
4752 Py_INCREF(self);
4753 return self;
4754 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004755 if (obj == NULL)
4756 obj = Py_None;
4757 if (type == NULL)
4758 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004759 return PyObject_CallFunction(get, "OOO", self, obj, type);
4760}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004761
4762static int
4763slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4764{
Guido van Rossum2c252392001-08-24 10:13:31 +00004765 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004766 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004767
4768 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004769 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004770 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004771 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004772 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004773 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004774 if (res == NULL)
4775 return -1;
4776 Py_DECREF(res);
4777 return 0;
4778}
4779
4780static int
4781slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4782{
Guido van Rossum60718732001-08-28 17:47:51 +00004783 static PyObject *init_str;
4784 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004785 PyObject *res;
4786
4787 if (meth == NULL)
4788 return -1;
4789 res = PyObject_Call(meth, args, kwds);
4790 Py_DECREF(meth);
4791 if (res == NULL)
4792 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004793 if (res != Py_None) {
4794 PyErr_SetString(PyExc_TypeError,
4795 "__init__() should return None");
4796 Py_DECREF(res);
4797 return -1;
4798 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004799 Py_DECREF(res);
4800 return 0;
4801}
4802
4803static PyObject *
4804slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4805{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004806 static PyObject *new_str;
4807 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004808 PyObject *newargs, *x;
4809 int i, n;
4810
Guido van Rossum7bed2132002-08-08 21:57:53 +00004811 if (new_str == NULL) {
4812 new_str = PyString_InternFromString("__new__");
4813 if (new_str == NULL)
4814 return NULL;
4815 }
4816 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004817 if (func == NULL)
4818 return NULL;
4819 assert(PyTuple_Check(args));
4820 n = PyTuple_GET_SIZE(args);
4821 newargs = PyTuple_New(n+1);
4822 if (newargs == NULL)
4823 return NULL;
4824 Py_INCREF(type);
4825 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4826 for (i = 0; i < n; i++) {
4827 x = PyTuple_GET_ITEM(args, i);
4828 Py_INCREF(x);
4829 PyTuple_SET_ITEM(newargs, i+1, x);
4830 }
4831 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004832 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004833 Py_DECREF(func);
4834 return x;
4835}
4836
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004837static void
4838slot_tp_del(PyObject *self)
4839{
4840 static PyObject *del_str = NULL;
4841 PyObject *del, *res;
4842 PyObject *error_type, *error_value, *error_traceback;
4843
4844 /* Temporarily resurrect the object. */
4845 assert(self->ob_refcnt == 0);
4846 self->ob_refcnt = 1;
4847
4848 /* Save the current exception, if any. */
4849 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4850
4851 /* Execute __del__ method, if any. */
4852 del = lookup_maybe(self, "__del__", &del_str);
4853 if (del != NULL) {
4854 res = PyEval_CallObject(del, NULL);
4855 if (res == NULL)
4856 PyErr_WriteUnraisable(del);
4857 else
4858 Py_DECREF(res);
4859 Py_DECREF(del);
4860 }
4861
4862 /* Restore the saved exception. */
4863 PyErr_Restore(error_type, error_value, error_traceback);
4864
4865 /* Undo the temporary resurrection; can't use DECREF here, it would
4866 * cause a recursive call.
4867 */
4868 assert(self->ob_refcnt > 0);
4869 if (--self->ob_refcnt == 0)
4870 return; /* this is the normal path out */
4871
4872 /* __del__ resurrected it! Make it look like the original Py_DECREF
4873 * never happened.
4874 */
4875 {
4876 int refcnt = self->ob_refcnt;
4877 _Py_NewReference(self);
4878 self->ob_refcnt = refcnt;
4879 }
4880 assert(!PyType_IS_GC(self->ob_type) ||
4881 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00004882 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
4883 * we need to undo that. */
4884 _Py_DEC_REFTOTAL;
4885 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4886 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004887 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4888 * _Py_NewReference bumped tp_allocs: both of those need to be
4889 * undone.
4890 */
4891#ifdef COUNT_ALLOCS
4892 --self->ob_type->tp_frees;
4893 --self->ob_type->tp_allocs;
4894#endif
4895}
4896
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004897
4898/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004899 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004900 structure, which incorporates the additional structures used for numbers,
4901 sequences and mappings.
4902 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004903 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004904 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4905 terminated with an all-zero entry. (This table is further initialized and
4906 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004907
Guido van Rossum6d204072001-10-21 00:44:31 +00004908typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004909
4910#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004911#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004912#undef ETSLOT
4913#undef SQSLOT
4914#undef MPSLOT
4915#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004916#undef UNSLOT
4917#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004918#undef BINSLOT
4919#undef RBINSLOT
4920
Guido van Rossum6d204072001-10-21 00:44:31 +00004921#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004922 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4923 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004924#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4925 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004926 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004927#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004928 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004929 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004930#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4931 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4932#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4933 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4934#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4935 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4936#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4937 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4938 "x." NAME "() <==> " DOC)
4939#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4940 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4941 "x." NAME "(y) <==> x" DOC "y")
4942#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4943 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4944 "x." NAME "(y) <==> x" DOC "y")
4945#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4946 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4947 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00004948#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
4949 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4950 "x." NAME "(y) <==> " DOC)
4951#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
4952 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4953 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004954
4955static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004956 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4957 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00004958 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
4959 The logic in abstract.c always falls back to nb_add/nb_multiply in
4960 this case. Defining both the nb_* and the sq_* slots to call the
4961 user-defined methods has unexpected side-effects, as shown by
4962 test_descr.notimplemented() */
4963 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
4964 "x.__add__(y) <==> x+y"),
4965 SQSLOT("__mul__", sq_repeat, NULL, wrap_intargfunc,
4966 "x.__mul__(n) <==> x*n"),
4967 SQSLOT("__rmul__", sq_repeat, NULL, wrap_intargfunc,
4968 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004969 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4970 "x.__getitem__(y) <==> x[y]"),
4971 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00004972 "x.__getslice__(i, j) <==> x[i:j]\n\
4973 \n\
4974 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004975 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004976 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004977 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004978 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004979 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004980 wrap_intintobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00004981 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
4982 \n\
4983 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004984 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00004985 "x.__delslice__(i, j) <==> del x[i:j]\n\
4986 \n\
4987 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004988 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4989 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00004990 SQSLOT("__iadd__", sq_inplace_concat, NULL,
4991 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
4992 SQSLOT("__imul__", sq_inplace_repeat, NULL,
4993 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004994
Guido van Rossum6d204072001-10-21 00:44:31 +00004995 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4996 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004997 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004998 wrap_binaryfunc,
4999 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005000 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005001 wrap_objobjargproc,
5002 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005003 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005004 wrap_delitem,
5005 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005006
Guido van Rossum6d204072001-10-21 00:44:31 +00005007 BINSLOT("__add__", nb_add, slot_nb_add,
5008 "+"),
5009 RBINSLOT("__radd__", nb_add, slot_nb_add,
5010 "+"),
5011 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5012 "-"),
5013 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5014 "-"),
5015 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5016 "*"),
5017 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5018 "*"),
5019 BINSLOT("__div__", nb_divide, slot_nb_divide,
5020 "/"),
5021 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5022 "/"),
5023 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5024 "%"),
5025 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5026 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005027 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005028 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005029 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005030 "divmod(y, x)"),
5031 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5032 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5033 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5034 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5035 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5036 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5037 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5038 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005039 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005040 "x != 0"),
5041 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5042 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5043 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5044 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5045 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5046 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5047 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5048 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5049 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5050 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5051 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5052 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5053 "x.__coerce__(y) <==> coerce(x, y)"),
5054 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5055 "int(x)"),
5056 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5057 "long(x)"),
5058 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5059 "float(x)"),
5060 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5061 "oct(x)"),
5062 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5063 "hex(x)"),
5064 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5065 wrap_binaryfunc, "+"),
5066 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5067 wrap_binaryfunc, "-"),
5068 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5069 wrap_binaryfunc, "*"),
5070 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5071 wrap_binaryfunc, "/"),
5072 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5073 wrap_binaryfunc, "%"),
5074 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005075 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005076 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5077 wrap_binaryfunc, "<<"),
5078 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5079 wrap_binaryfunc, ">>"),
5080 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5081 wrap_binaryfunc, "&"),
5082 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5083 wrap_binaryfunc, "^"),
5084 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5085 wrap_binaryfunc, "|"),
5086 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5087 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5088 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5089 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5090 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5091 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5092 IBSLOT("__itruediv__", nb_inplace_true_divide,
5093 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005094
Guido van Rossum6d204072001-10-21 00:44:31 +00005095 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5096 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005097 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005098 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5099 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005100 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005101 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5102 "x.__cmp__(y) <==> cmp(x,y)"),
5103 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5104 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005105 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5106 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005107 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005108 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5109 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5110 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5111 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5112 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5113 "x.__setattr__('name', value) <==> x.name = value"),
5114 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5115 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5116 "x.__delattr__('name') <==> del x.name"),
5117 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5118 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5119 "x.__lt__(y) <==> x<y"),
5120 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5121 "x.__le__(y) <==> x<=y"),
5122 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5123 "x.__eq__(y) <==> x==y"),
5124 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5125 "x.__ne__(y) <==> x!=y"),
5126 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5127 "x.__gt__(y) <==> x>y"),
5128 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5129 "x.__ge__(y) <==> x>=y"),
5130 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5131 "x.__iter__() <==> iter(x)"),
5132 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5133 "x.next() -> the next value, or raise StopIteration"),
5134 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5135 "descr.__get__(obj[, type]) -> value"),
5136 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5137 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005138 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5139 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005140 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005141 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005142 "see x.__class__.__doc__ for signature",
5143 PyWrapperFlag_KEYWORDS),
5144 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005145 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005146 {NULL}
5147};
5148
Guido van Rossumc334df52002-04-04 23:44:47 +00005149/* Given a type pointer and an offset gotten from a slotdef entry, return a
5150 pointer to the actual slot. This is not quite the same as simply adding
5151 the offset to the type pointer, since it takes care to indirect through the
5152 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5153 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005154static void **
5155slotptr(PyTypeObject *type, int offset)
5156{
5157 char *ptr;
5158
Guido van Rossume5c691a2003-03-07 15:13:17 +00005159 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005160 assert(offset >= 0);
Guido van Rossume5c691a2003-03-07 15:13:17 +00005161 assert(offset < offsetof(PyHeapTypeObject, as_buffer));
5162 if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005163 ptr = (void *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005164 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005165 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005166 else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Guido van Rossum09638c12002-06-13 19:17:46 +00005167 ptr = (void *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005168 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005169 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005170 else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005171 ptr = (void *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005172 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005173 }
5174 else {
5175 ptr = (void *)type;
5176 }
5177 if (ptr != NULL)
5178 ptr += offset;
5179 return (void **)ptr;
5180}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005181
Guido van Rossumc334df52002-04-04 23:44:47 +00005182/* Length of array of slotdef pointers used to store slots with the
5183 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5184 the same __name__, for any __name__. Since that's a static property, it is
5185 appropriate to declare fixed-size arrays for this. */
5186#define MAX_EQUIV 10
5187
5188/* Return a slot pointer for a given name, but ONLY if the attribute has
5189 exactly one slot function. The name must be an interned string. */
5190static void **
5191resolve_slotdups(PyTypeObject *type, PyObject *name)
5192{
5193 /* XXX Maybe this could be optimized more -- but is it worth it? */
5194
5195 /* pname and ptrs act as a little cache */
5196 static PyObject *pname;
5197 static slotdef *ptrs[MAX_EQUIV];
5198 slotdef *p, **pp;
5199 void **res, **ptr;
5200
5201 if (pname != name) {
5202 /* Collect all slotdefs that match name into ptrs. */
5203 pname = name;
5204 pp = ptrs;
5205 for (p = slotdefs; p->name_strobj; p++) {
5206 if (p->name_strobj == name)
5207 *pp++ = p;
5208 }
5209 *pp = NULL;
5210 }
5211
5212 /* Look in all matching slots of the type; if exactly one of these has
5213 a filled-in slot, return its value. Otherwise return NULL. */
5214 res = NULL;
5215 for (pp = ptrs; *pp; pp++) {
5216 ptr = slotptr(type, (*pp)->offset);
5217 if (ptr == NULL || *ptr == NULL)
5218 continue;
5219 if (res != NULL)
5220 return NULL;
5221 res = ptr;
5222 }
5223 return res;
5224}
5225
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005226/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005227 does some incredibly complex thinking and then sticks something into the
5228 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5229 interests, and then stores a generic wrapper or a specific function into
5230 the slot.) Return a pointer to the next slotdef with a different offset,
5231 because that's convenient for fixup_slot_dispatchers(). */
5232static slotdef *
5233update_one_slot(PyTypeObject *type, slotdef *p)
5234{
5235 PyObject *descr;
5236 PyWrapperDescrObject *d;
5237 void *generic = NULL, *specific = NULL;
5238 int use_generic = 0;
5239 int offset = p->offset;
5240 void **ptr = slotptr(type, offset);
5241
5242 if (ptr == NULL) {
5243 do {
5244 ++p;
5245 } while (p->offset == offset);
5246 return p;
5247 }
5248 do {
5249 descr = _PyType_Lookup(type, p->name_strobj);
5250 if (descr == NULL)
5251 continue;
5252 if (descr->ob_type == &PyWrapperDescr_Type) {
5253 void **tptr = resolve_slotdups(type, p->name_strobj);
5254 if (tptr == NULL || tptr == ptr)
5255 generic = p->function;
5256 d = (PyWrapperDescrObject *)descr;
5257 if (d->d_base->wrapper == p->wrapper &&
5258 PyType_IsSubtype(type, d->d_type))
5259 {
5260 if (specific == NULL ||
5261 specific == d->d_wrapped)
5262 specific = d->d_wrapped;
5263 else
5264 use_generic = 1;
5265 }
5266 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005267 else if (descr->ob_type == &PyCFunction_Type &&
5268 PyCFunction_GET_FUNCTION(descr) ==
5269 (PyCFunction)tp_new_wrapper &&
5270 strcmp(p->name, "__new__") == 0)
5271 {
5272 /* The __new__ wrapper is not a wrapper descriptor,
5273 so must be special-cased differently.
5274 If we don't do this, creating an instance will
5275 always use slot_tp_new which will look up
5276 __new__ in the MRO which will call tp_new_wrapper
5277 which will look through the base classes looking
5278 for a static base and call its tp_new (usually
5279 PyType_GenericNew), after performing various
5280 sanity checks and constructing a new argument
5281 list. Cut all that nonsense short -- this speeds
5282 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005283 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005284 /* XXX I'm not 100% sure that there isn't a hole
5285 in this reasoning that requires additional
5286 sanity checks. I'll buy the first person to
5287 point out a bug in this reasoning a beer. */
5288 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005289 else {
5290 use_generic = 1;
5291 generic = p->function;
5292 }
5293 } while ((++p)->offset == offset);
5294 if (specific && !use_generic)
5295 *ptr = specific;
5296 else
5297 *ptr = generic;
5298 return p;
5299}
5300
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005301/* In the type, update the slots whose slotdefs are gathered in the pp array.
5302 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005303static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005304update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005305{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005306 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005307
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005308 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005309 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005310 return 0;
5311}
5312
Guido van Rossumc334df52002-04-04 23:44:47 +00005313/* Comparison function for qsort() to compare slotdefs by their offset, and
5314 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005315static int
5316slotdef_cmp(const void *aa, const void *bb)
5317{
5318 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5319 int c = a->offset - b->offset;
5320 if (c != 0)
5321 return c;
5322 else
5323 return a - b;
5324}
5325
Guido van Rossumc334df52002-04-04 23:44:47 +00005326/* Initialize the slotdefs table by adding interned string objects for the
5327 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005328static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005329init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005330{
5331 slotdef *p;
5332 static int initialized = 0;
5333
5334 if (initialized)
5335 return;
5336 for (p = slotdefs; p->name; p++) {
5337 p->name_strobj = PyString_InternFromString(p->name);
5338 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005339 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005340 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005341 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5342 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005343 initialized = 1;
5344}
5345
Guido van Rossumc334df52002-04-04 23:44:47 +00005346/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005347static int
5348update_slot(PyTypeObject *type, PyObject *name)
5349{
Guido van Rossumc334df52002-04-04 23:44:47 +00005350 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005351 slotdef *p;
5352 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005353 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005354
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005355 init_slotdefs();
5356 pp = ptrs;
5357 for (p = slotdefs; p->name; p++) {
5358 /* XXX assume name is interned! */
5359 if (p->name_strobj == name)
5360 *pp++ = p;
5361 }
5362 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005363 for (pp = ptrs; *pp; pp++) {
5364 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005365 offset = p->offset;
5366 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005367 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005368 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005369 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005370 if (ptrs[0] == NULL)
5371 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005372 return update_subclasses(type, name,
5373 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005374}
5375
Guido van Rossumc334df52002-04-04 23:44:47 +00005376/* Store the proper functions in the slot dispatches at class (type)
5377 definition time, based upon which operations the class overrides in its
5378 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005379static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005380fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005381{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005382 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005383
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005384 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005385 for (p = slotdefs; p->name; )
5386 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005387}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005388
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005389static void
5390update_all_slots(PyTypeObject* type)
5391{
5392 slotdef *p;
5393
5394 init_slotdefs();
5395 for (p = slotdefs; p->name; p++) {
5396 /* update_slot returns int but can't actually fail */
5397 update_slot(type, p->name_strobj);
5398 }
5399}
5400
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005401/* recurse_down_subclasses() and update_subclasses() are mutually
5402 recursive functions to call a callback for all subclasses,
5403 but refraining from recursing into subclasses that define 'name'. */
5404
5405static int
5406update_subclasses(PyTypeObject *type, PyObject *name,
5407 update_callback callback, void *data)
5408{
5409 if (callback(type, data) < 0)
5410 return -1;
5411 return recurse_down_subclasses(type, name, callback, data);
5412}
5413
5414static int
5415recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5416 update_callback callback, void *data)
5417{
5418 PyTypeObject *subclass;
5419 PyObject *ref, *subclasses, *dict;
5420 int i, n;
5421
5422 subclasses = type->tp_subclasses;
5423 if (subclasses == NULL)
5424 return 0;
5425 assert(PyList_Check(subclasses));
5426 n = PyList_GET_SIZE(subclasses);
5427 for (i = 0; i < n; i++) {
5428 ref = PyList_GET_ITEM(subclasses, i);
5429 assert(PyWeakref_CheckRef(ref));
5430 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5431 assert(subclass != NULL);
5432 if ((PyObject *)subclass == Py_None)
5433 continue;
5434 assert(PyType_Check(subclass));
5435 /* Avoid recursing down into unaffected classes */
5436 dict = subclass->tp_dict;
5437 if (dict != NULL && PyDict_Check(dict) &&
5438 PyDict_GetItem(dict, name) != NULL)
5439 continue;
5440 if (update_subclasses(subclass, name, callback, data) < 0)
5441 return -1;
5442 }
5443 return 0;
5444}
5445
Guido van Rossum6d204072001-10-21 00:44:31 +00005446/* This function is called by PyType_Ready() to populate the type's
5447 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005448 function slot (like tp_repr) that's defined in the type, one or more
5449 corresponding descriptors are added in the type's tp_dict dictionary
5450 under the appropriate name (like __repr__). Some function slots
5451 cause more than one descriptor to be added (for example, the nb_add
5452 slot adds both __add__ and __radd__ descriptors) and some function
5453 slots compete for the same descriptor (for example both sq_item and
5454 mp_subscript generate a __getitem__ descriptor).
5455
5456 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005457 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005458 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005459 between competing slots: the members of PyHeapTypeObject are listed
5460 from most general to least general, so the most general slot is
5461 preferred. In particular, because as_mapping comes before as_sequence,
5462 for a type that defines both mp_subscript and sq_item, mp_subscript
5463 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005464
5465 This only adds new descriptors and doesn't overwrite entries in
5466 tp_dict that were previously defined. The descriptors contain a
5467 reference to the C function they must call, so that it's safe if they
5468 are copied into a subtype's __dict__ and the subtype has a different
5469 C function in its slot -- calling the method defined by the
5470 descriptor will call the C function that was used to create it,
5471 rather than the C function present in the slot when it is called.
5472 (This is important because a subtype may have a C function in the
5473 slot that calls the method from the dictionary, and we want to avoid
5474 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005475
5476static int
5477add_operators(PyTypeObject *type)
5478{
5479 PyObject *dict = type->tp_dict;
5480 slotdef *p;
5481 PyObject *descr;
5482 void **ptr;
5483
5484 init_slotdefs();
5485 for (p = slotdefs; p->name; p++) {
5486 if (p->wrapper == NULL)
5487 continue;
5488 ptr = slotptr(type, p->offset);
5489 if (!ptr || !*ptr)
5490 continue;
5491 if (PyDict_GetItem(dict, p->name_strobj))
5492 continue;
5493 descr = PyDescr_NewWrapper(type, p, *ptr);
5494 if (descr == NULL)
5495 return -1;
5496 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5497 return -1;
5498 Py_DECREF(descr);
5499 }
5500 if (type->tp_new != NULL) {
5501 if (add_tp_new_wrapper(type) < 0)
5502 return -1;
5503 }
5504 return 0;
5505}
5506
Guido van Rossum705f0f52001-08-24 16:47:00 +00005507
5508/* Cooperative 'super' */
5509
5510typedef struct {
5511 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005512 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005513 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005514 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005515} superobject;
5516
Guido van Rossum6f799372001-09-20 20:46:19 +00005517static PyMemberDef super_members[] = {
5518 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5519 "the class invoking super()"},
5520 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5521 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005522 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005523 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005524 {0}
5525};
5526
Guido van Rossum705f0f52001-08-24 16:47:00 +00005527static void
5528super_dealloc(PyObject *self)
5529{
5530 superobject *su = (superobject *)self;
5531
Guido van Rossum048eb752001-10-02 21:24:57 +00005532 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005533 Py_XDECREF(su->obj);
5534 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005535 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005536 self->ob_type->tp_free(self);
5537}
5538
5539static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005540super_repr(PyObject *self)
5541{
5542 superobject *su = (superobject *)self;
5543
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005544 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005545 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005546 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005547 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005548 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005549 else
5550 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005551 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005552 su->type ? su->type->tp_name : "NULL");
5553}
5554
5555static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005556super_getattro(PyObject *self, PyObject *name)
5557{
5558 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005559 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005560
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005561 if (!skip) {
5562 /* We want __class__ to return the class of the super object
5563 (i.e. super, or a subclass), not the class of su->obj. */
5564 skip = (PyString_Check(name) &&
5565 PyString_GET_SIZE(name) == 9 &&
5566 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5567 }
5568
5569 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005570 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005571 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005572 descrgetfunc f;
5573 int i, n;
5574
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005575 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005576 mro = starttype->tp_mro;
5577
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005578 if (mro == NULL)
5579 n = 0;
5580 else {
5581 assert(PyTuple_Check(mro));
5582 n = PyTuple_GET_SIZE(mro);
5583 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005584 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005585 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005586 break;
5587 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005588 i++;
5589 res = NULL;
5590 for (; i < n; i++) {
5591 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005592 if (PyType_Check(tmp))
5593 dict = ((PyTypeObject *)tmp)->tp_dict;
5594 else if (PyClass_Check(tmp))
5595 dict = ((PyClassObject *)tmp)->cl_dict;
5596 else
5597 continue;
5598 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005599 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005600 Py_INCREF(res);
5601 f = res->ob_type->tp_descr_get;
5602 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005603 tmp = f(res,
5604 /* Only pass 'obj' param if
5605 this is instance-mode super
5606 (See SF ID #743627)
5607 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005608 (su->obj == (PyObject *)
5609 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005610 ? (PyObject *)NULL
5611 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005612 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005613 Py_DECREF(res);
5614 res = tmp;
5615 }
5616 return res;
5617 }
5618 }
5619 }
5620 return PyObject_GenericGetAttr(self, name);
5621}
5622
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005623static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005624supercheck(PyTypeObject *type, PyObject *obj)
5625{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005626 /* Check that a super() call makes sense. Return a type object.
5627
5628 obj can be a new-style class, or an instance of one:
5629
5630 - If it is a class, it must be a subclass of 'type'. This case is
5631 used for class methods; the return value is obj.
5632
5633 - If it is an instance, it must be an instance of 'type'. This is
5634 the normal case; the return value is obj.__class__.
5635
5636 But... when obj is an instance, we want to allow for the case where
5637 obj->ob_type is not a subclass of type, but obj.__class__ is!
5638 This will allow using super() with a proxy for obj.
5639 */
5640
Guido van Rossum8e80a722003-02-18 19:22:22 +00005641 /* Check for first bullet above (special case) */
5642 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5643 Py_INCREF(obj);
5644 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005645 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005646
5647 /* Normal case */
5648 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005649 Py_INCREF(obj->ob_type);
5650 return obj->ob_type;
5651 }
5652 else {
5653 /* Try the slow way */
5654 static PyObject *class_str = NULL;
5655 PyObject *class_attr;
5656
5657 if (class_str == NULL) {
5658 class_str = PyString_FromString("__class__");
5659 if (class_str == NULL)
5660 return NULL;
5661 }
5662
5663 class_attr = PyObject_GetAttr(obj, class_str);
5664
5665 if (class_attr != NULL &&
5666 PyType_Check(class_attr) &&
5667 (PyTypeObject *)class_attr != obj->ob_type)
5668 {
5669 int ok = PyType_IsSubtype(
5670 (PyTypeObject *)class_attr, type);
5671 if (ok)
5672 return (PyTypeObject *)class_attr;
5673 }
5674
5675 if (class_attr == NULL)
5676 PyErr_Clear();
5677 else
5678 Py_DECREF(class_attr);
5679 }
5680
Tim Peters97e5ff52003-02-18 19:32:50 +00005681 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005682 "super(type, obj): "
5683 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005684 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005685}
5686
Guido van Rossum705f0f52001-08-24 16:47:00 +00005687static PyObject *
5688super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5689{
5690 superobject *su = (superobject *)self;
5691 superobject *new;
5692
5693 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5694 /* Not binding to an object, or already bound */
5695 Py_INCREF(self);
5696 return self;
5697 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005698 if (su->ob_type != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005699 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005700 call its type */
5701 return PyObject_CallFunction((PyObject *)su->ob_type,
5702 "OO", su->type, obj);
5703 else {
5704 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005705 PyTypeObject *obj_type = supercheck(su->type, obj);
5706 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005707 return NULL;
5708 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5709 NULL, NULL);
5710 if (new == NULL)
5711 return NULL;
5712 Py_INCREF(su->type);
5713 Py_INCREF(obj);
5714 new->type = su->type;
5715 new->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005716 new->obj_type = obj_type;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005717 return (PyObject *)new;
5718 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005719}
5720
5721static int
5722super_init(PyObject *self, PyObject *args, PyObject *kwds)
5723{
5724 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005725 PyTypeObject *type;
5726 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005727 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005728
5729 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5730 return -1;
5731 if (obj == Py_None)
5732 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005733 if (obj != NULL) {
5734 obj_type = supercheck(type, obj);
5735 if (obj_type == NULL)
5736 return -1;
5737 Py_INCREF(obj);
5738 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005739 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005740 su->type = type;
5741 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005742 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005743 return 0;
5744}
5745
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005746PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005747"super(type) -> unbound super object\n"
5748"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005749"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005750"Typical use to call a cooperative superclass method:\n"
5751"class C(B):\n"
5752" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005753" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005754
Guido van Rossum048eb752001-10-02 21:24:57 +00005755static int
5756super_traverse(PyObject *self, visitproc visit, void *arg)
5757{
5758 superobject *su = (superobject *)self;
5759 int err;
5760
5761#define VISIT(SLOT) \
5762 if (SLOT) { \
5763 err = visit((PyObject *)(SLOT), arg); \
5764 if (err) \
5765 return err; \
5766 }
5767
5768 VISIT(su->obj);
5769 VISIT(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005770 VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005771
5772#undef VISIT
5773
5774 return 0;
5775}
5776
Guido van Rossum705f0f52001-08-24 16:47:00 +00005777PyTypeObject PySuper_Type = {
5778 PyObject_HEAD_INIT(&PyType_Type)
5779 0, /* ob_size */
5780 "super", /* tp_name */
5781 sizeof(superobject), /* tp_basicsize */
5782 0, /* tp_itemsize */
5783 /* methods */
5784 super_dealloc, /* tp_dealloc */
5785 0, /* tp_print */
5786 0, /* tp_getattr */
5787 0, /* tp_setattr */
5788 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005789 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005790 0, /* tp_as_number */
5791 0, /* tp_as_sequence */
5792 0, /* tp_as_mapping */
5793 0, /* tp_hash */
5794 0, /* tp_call */
5795 0, /* tp_str */
5796 super_getattro, /* tp_getattro */
5797 0, /* tp_setattro */
5798 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005799 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5800 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005801 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005802 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005803 0, /* tp_clear */
5804 0, /* tp_richcompare */
5805 0, /* tp_weaklistoffset */
5806 0, /* tp_iter */
5807 0, /* tp_iternext */
5808 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005809 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005810 0, /* tp_getset */
5811 0, /* tp_base */
5812 0, /* tp_dict */
5813 super_descr_get, /* tp_descr_get */
5814 0, /* tp_descr_set */
5815 0, /* tp_dictoffset */
5816 super_init, /* tp_init */
5817 PyType_GenericAlloc, /* tp_alloc */
5818 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005819 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005820};