blob: 7c36ba4f402a72f666d48b348dac5d9b0b870b55 [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;
1291
1292 if (type->ob_type == &PyType_Type) {
1293 result = mro_implementation(type);
1294 }
1295 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001296 static PyObject *mro_str;
1297 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001298 if (mro == NULL)
1299 return -1;
1300 result = PyObject_CallObject(mro, NULL);
1301 Py_DECREF(mro);
1302 }
1303 if (result == NULL)
1304 return -1;
1305 tuple = PySequence_Tuple(result);
1306 Py_DECREF(result);
1307 type->tp_mro = tuple;
1308 return 0;
1309}
1310
1311
1312/* Calculate the best base amongst multiple base classes.
1313 This is the first one that's on the path to the "solid base". */
1314
1315static PyTypeObject *
1316best_base(PyObject *bases)
1317{
1318 int i, n;
1319 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001320 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001321
1322 assert(PyTuple_Check(bases));
1323 n = PyTuple_GET_SIZE(bases);
1324 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001325 base = NULL;
1326 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001327 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001328 base_proto = PyTuple_GET_ITEM(bases, i);
1329 if (PyClass_Check(base_proto))
1330 continue;
1331 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001332 PyErr_SetString(
1333 PyExc_TypeError,
1334 "bases must be types");
1335 return NULL;
1336 }
Tim Petersa91e9642001-11-14 23:32:33 +00001337 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001338 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001339 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001340 return NULL;
1341 }
1342 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001343 if (winner == NULL) {
1344 winner = candidate;
1345 base = base_i;
1346 }
1347 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001348 ;
1349 else if (PyType_IsSubtype(candidate, winner)) {
1350 winner = candidate;
1351 base = base_i;
1352 }
1353 else {
1354 PyErr_SetString(
1355 PyExc_TypeError,
1356 "multiple bases have "
1357 "instance lay-out conflict");
1358 return NULL;
1359 }
1360 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001361 if (base == NULL)
1362 PyErr_SetString(PyExc_TypeError,
1363 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001364 return base;
1365}
1366
1367static int
1368extra_ivars(PyTypeObject *type, PyTypeObject *base)
1369{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001370 size_t t_size = type->tp_basicsize;
1371 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001372
Guido van Rossum9676b222001-08-17 20:32:36 +00001373 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001374 if (type->tp_itemsize || base->tp_itemsize) {
1375 /* If itemsize is involved, stricter rules */
1376 return t_size != b_size ||
1377 type->tp_itemsize != base->tp_itemsize;
1378 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001379 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1380 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1381 t_size -= sizeof(PyObject *);
1382 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1383 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1384 t_size -= sizeof(PyObject *);
1385
1386 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001387}
1388
1389static PyTypeObject *
1390solid_base(PyTypeObject *type)
1391{
1392 PyTypeObject *base;
1393
1394 if (type->tp_base)
1395 base = solid_base(type->tp_base);
1396 else
1397 base = &PyBaseObject_Type;
1398 if (extra_ivars(type, base))
1399 return type;
1400 else
1401 return base;
1402}
1403
Jeremy Hylton938ace62002-07-17 16:30:39 +00001404static void object_dealloc(PyObject *);
1405static int object_init(PyObject *, PyObject *, PyObject *);
1406static int update_slot(PyTypeObject *, PyObject *);
1407static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001408
1409static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001410subtype_dict(PyObject *obj, void *context)
1411{
1412 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1413 PyObject *dict;
1414
1415 if (dictptr == NULL) {
1416 PyErr_SetString(PyExc_AttributeError,
1417 "This object has no __dict__");
1418 return NULL;
1419 }
1420 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001421 if (dict == NULL)
1422 *dictptr = dict = PyDict_New();
1423 Py_XINCREF(dict);
1424 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001425}
1426
Guido van Rossum6661be32001-10-26 04:26:12 +00001427static int
1428subtype_setdict(PyObject *obj, PyObject *value, void *context)
1429{
1430 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1431 PyObject *dict;
1432
1433 if (dictptr == NULL) {
1434 PyErr_SetString(PyExc_AttributeError,
1435 "This object has no __dict__");
1436 return -1;
1437 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001438 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001439 PyErr_SetString(PyExc_TypeError,
1440 "__dict__ must be set to a dictionary");
1441 return -1;
1442 }
1443 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001444 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001445 *dictptr = value;
1446 Py_XDECREF(dict);
1447 return 0;
1448}
1449
Guido van Rossumad47da02002-08-12 19:05:44 +00001450static PyObject *
1451subtype_getweakref(PyObject *obj, void *context)
1452{
1453 PyObject **weaklistptr;
1454 PyObject *result;
1455
1456 if (obj->ob_type->tp_weaklistoffset == 0) {
1457 PyErr_SetString(PyExc_AttributeError,
1458 "This object has no __weaklist__");
1459 return NULL;
1460 }
1461 assert(obj->ob_type->tp_weaklistoffset > 0);
1462 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001463 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001464 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001465 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001466 if (*weaklistptr == NULL)
1467 result = Py_None;
1468 else
1469 result = *weaklistptr;
1470 Py_INCREF(result);
1471 return result;
1472}
1473
Guido van Rossum373c7412003-01-07 13:41:37 +00001474/* Three variants on the subtype_getsets list. */
1475
1476static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001477 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001478 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001479 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001480 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001481 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001482};
1483
Guido van Rossum373c7412003-01-07 13:41:37 +00001484static PyGetSetDef subtype_getsets_dict_only[] = {
1485 {"__dict__", subtype_dict, subtype_setdict,
1486 PyDoc_STR("dictionary for instance variables (if defined)")},
1487 {0}
1488};
1489
1490static PyGetSetDef subtype_getsets_weakref_only[] = {
1491 {"__weakref__", subtype_getweakref, NULL,
1492 PyDoc_STR("list of weak references to the object (if defined)")},
1493 {0}
1494};
1495
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001496static int
1497valid_identifier(PyObject *s)
1498{
Guido van Rossum03013a02002-07-16 14:30:28 +00001499 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001500 int i, n;
1501
1502 if (!PyString_Check(s)) {
1503 PyErr_SetString(PyExc_TypeError,
1504 "__slots__ must be strings");
1505 return 0;
1506 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001507 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001508 n = PyString_GET_SIZE(s);
1509 /* We must reject an empty name. As a hack, we bump the
1510 length to 1 so that the loop will balk on the trailing \0. */
1511 if (n == 0)
1512 n = 1;
1513 for (i = 0; i < n; i++, p++) {
1514 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1515 PyErr_SetString(PyExc_TypeError,
1516 "__slots__ must be identifiers");
1517 return 0;
1518 }
1519 }
1520 return 1;
1521}
1522
Martin v. Löwisd919a592002-10-14 21:07:28 +00001523#ifdef Py_USING_UNICODE
1524/* Replace Unicode objects in slots. */
1525
1526static PyObject *
1527_unicode_to_string(PyObject *slots, int nslots)
1528{
1529 PyObject *tmp = slots;
1530 PyObject *o, *o1;
1531 int i;
1532 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1533 for (i = 0; i < nslots; i++) {
1534 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1535 if (tmp == slots) {
1536 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1537 if (tmp == NULL)
1538 return NULL;
1539 }
1540 o1 = _PyUnicode_AsDefaultEncodedString
1541 (o, NULL);
1542 if (o1 == NULL) {
1543 Py_DECREF(tmp);
1544 return 0;
1545 }
1546 Py_INCREF(o1);
1547 Py_DECREF(o);
1548 PyTuple_SET_ITEM(tmp, i, o1);
1549 }
1550 }
1551 return tmp;
1552}
1553#endif
1554
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001555static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001556type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1557{
1558 PyObject *name, *bases, *dict;
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001559 static const char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001560 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001561 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001562 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001563 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001564 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001565 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001566
Tim Peters3abca122001-10-27 19:37:48 +00001567 assert(args != NULL && PyTuple_Check(args));
1568 assert(kwds == NULL || PyDict_Check(kwds));
1569
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001570 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001571 {
1572 const int nargs = PyTuple_GET_SIZE(args);
1573 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1574
1575 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1576 PyObject *x = PyTuple_GET_ITEM(args, 0);
1577 Py_INCREF(x->ob_type);
1578 return (PyObject *) x->ob_type;
1579 }
1580
1581 /* SF bug 475327 -- if that didn't trigger, we need 3
1582 arguments. but PyArg_ParseTupleAndKeywords below may give
1583 a msg saying type() needs exactly 3. */
1584 if (nargs + nkwds != 3) {
1585 PyErr_SetString(PyExc_TypeError,
1586 "type() takes 1 or 3 arguments");
1587 return NULL;
1588 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001589 }
1590
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001591 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001592 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1593 &name,
1594 &PyTuple_Type, &bases,
1595 &PyDict_Type, &dict))
1596 return NULL;
1597
1598 /* Determine the proper metatype to deal with this,
1599 and check for metatype conflicts while we're at it.
1600 Note that if some other metatype wins to contract,
1601 it's possible that its instances are not types. */
1602 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001603 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001604 for (i = 0; i < nbases; i++) {
1605 tmp = PyTuple_GET_ITEM(bases, i);
1606 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001607 if (tmptype == &PyClass_Type)
1608 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001609 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001610 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001611 if (PyType_IsSubtype(tmptype, winner)) {
1612 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001613 continue;
1614 }
1615 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001616 "metaclass conflict: "
1617 "the metaclass of a derived class "
1618 "must be a (non-strict) subclass "
1619 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001620 return NULL;
1621 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001622 if (winner != metatype) {
1623 if (winner->tp_new != type_new) /* Pass it to the winner */
1624 return winner->tp_new(winner, args, kwds);
1625 metatype = winner;
1626 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001627
1628 /* Adjust for empty tuple bases */
1629 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001630 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001631 if (bases == NULL)
1632 return NULL;
1633 nbases = 1;
1634 }
1635 else
1636 Py_INCREF(bases);
1637
1638 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1639
1640 /* Calculate best base, and check that all bases are type objects */
1641 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001642 if (base == NULL) {
1643 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001644 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001645 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001646 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1647 PyErr_Format(PyExc_TypeError,
1648 "type '%.100s' is not an acceptable base type",
1649 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001650 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001651 return NULL;
1652 }
1653
Tim Peters6d6c1a32001-08-02 04:15:00 +00001654 /* Check for a __slots__ sequence variable in dict, and count it */
1655 slots = PyDict_GetItemString(dict, "__slots__");
1656 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001657 add_dict = 0;
1658 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001659 may_add_dict = base->tp_dictoffset == 0;
1660 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1661 if (slots == NULL) {
1662 if (may_add_dict) {
1663 add_dict++;
1664 }
1665 if (may_add_weak) {
1666 add_weak++;
1667 }
1668 }
1669 else {
1670 /* Have slots */
1671
Tim Peters6d6c1a32001-08-02 04:15:00 +00001672 /* Make it into a tuple */
1673 if (PyString_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001674 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001675 else
1676 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001677 if (slots == NULL) {
1678 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001679 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001680 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001681 assert(PyTuple_Check(slots));
1682
1683 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001684 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001685 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001686 PyErr_Format(PyExc_TypeError,
1687 "nonempty __slots__ "
1688 "not supported for subtype of '%s'",
1689 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001690 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001691 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001692 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001693 return NULL;
1694 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001695
Martin v. Löwisd919a592002-10-14 21:07:28 +00001696#ifdef Py_USING_UNICODE
1697 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001698 if (tmp != slots) {
1699 Py_DECREF(slots);
1700 slots = tmp;
1701 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001702 if (!tmp)
1703 return NULL;
1704#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001705 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001706 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001707 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1708 char *s;
1709 if (!valid_identifier(tmp))
1710 goto bad_slots;
1711 assert(PyString_Check(tmp));
1712 s = PyString_AS_STRING(tmp);
1713 if (strcmp(s, "__dict__") == 0) {
1714 if (!may_add_dict || add_dict) {
1715 PyErr_SetString(PyExc_TypeError,
1716 "__dict__ slot disallowed: "
1717 "we already got one");
1718 goto bad_slots;
1719 }
1720 add_dict++;
1721 }
1722 if (strcmp(s, "__weakref__") == 0) {
1723 if (!may_add_weak || add_weak) {
1724 PyErr_SetString(PyExc_TypeError,
1725 "__weakref__ slot disallowed: "
1726 "either we already got one, "
1727 "or __itemsize__ != 0");
1728 goto bad_slots;
1729 }
1730 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001731 }
1732 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001733
Guido van Rossumad47da02002-08-12 19:05:44 +00001734 /* Copy slots into yet another tuple, demangling names */
1735 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001736 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001737 goto bad_slots;
1738 for (i = j = 0; i < nslots; i++) {
1739 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001740 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001741 s = PyString_AS_STRING(tmp);
1742 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1743 (add_weak && strcmp(s, "__weakref__") == 0))
1744 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001745 tmp =_Py_Mangle(name, tmp);
1746 if (!tmp)
1747 goto bad_slots;
Guido van Rossumad47da02002-08-12 19:05:44 +00001748 PyTuple_SET_ITEM(newslots, j, tmp);
1749 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001750 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001751 assert(j == nslots - add_dict - add_weak);
1752 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001753 Py_DECREF(slots);
1754 slots = newslots;
1755
Guido van Rossumad47da02002-08-12 19:05:44 +00001756 /* Secondary bases may provide weakrefs or dict */
1757 if (nbases > 1 &&
1758 ((may_add_dict && !add_dict) ||
1759 (may_add_weak && !add_weak))) {
1760 for (i = 0; i < nbases; i++) {
1761 tmp = PyTuple_GET_ITEM(bases, i);
1762 if (tmp == (PyObject *)base)
1763 continue; /* Skip primary base */
1764 if (PyClass_Check(tmp)) {
1765 /* Classic base class provides both */
1766 if (may_add_dict && !add_dict)
1767 add_dict++;
1768 if (may_add_weak && !add_weak)
1769 add_weak++;
1770 break;
1771 }
1772 assert(PyType_Check(tmp));
1773 tmptype = (PyTypeObject *)tmp;
1774 if (may_add_dict && !add_dict &&
1775 tmptype->tp_dictoffset != 0)
1776 add_dict++;
1777 if (may_add_weak && !add_weak &&
1778 tmptype->tp_weaklistoffset != 0)
1779 add_weak++;
1780 if (may_add_dict && !add_dict)
1781 continue;
1782 if (may_add_weak && !add_weak)
1783 continue;
1784 /* Nothing more to check */
1785 break;
1786 }
1787 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001788 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001789
1790 /* XXX From here until type is safely allocated,
1791 "return NULL" may leak slots! */
1792
1793 /* Allocate the type object */
1794 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001795 if (type == NULL) {
1796 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001797 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001798 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001799 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001800
1801 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001802 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001803 Py_INCREF(name);
1804 et->name = name;
1805 et->slots = slots;
1806
Guido van Rossumdc91b992001-08-08 22:26:22 +00001807 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001808 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1809 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001810 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1811 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001812
1813 /* It's a new-style number unless it specifically inherits any
1814 old-style numeric behavior */
1815 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1816 (base->tp_as_number == NULL))
1817 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1818
1819 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001820 type->tp_as_number = &et->as_number;
1821 type->tp_as_sequence = &et->as_sequence;
1822 type->tp_as_mapping = &et->as_mapping;
1823 type->tp_as_buffer = &et->as_buffer;
1824 type->tp_name = PyString_AS_STRING(name);
1825
1826 /* Set tp_base and tp_bases */
1827 type->tp_bases = bases;
1828 Py_INCREF(base);
1829 type->tp_base = base;
1830
Guido van Rossum687ae002001-10-15 22:03:32 +00001831 /* Initialize tp_dict from passed-in dict */
1832 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001833 if (dict == NULL) {
1834 Py_DECREF(type);
1835 return NULL;
1836 }
1837
Guido van Rossumc3542212001-08-16 09:18:56 +00001838 /* Set __module__ in the dict */
1839 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1840 tmp = PyEval_GetGlobals();
1841 if (tmp != NULL) {
1842 tmp = PyDict_GetItemString(tmp, "__name__");
1843 if (tmp != NULL) {
1844 if (PyDict_SetItemString(dict, "__module__",
1845 tmp) < 0)
1846 return NULL;
1847 }
1848 }
1849 }
1850
Tim Peters2f93e282001-10-04 05:27:00 +00001851 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001852 and is a string. The __doc__ accessor will first look for tp_doc;
1853 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001854 */
1855 {
1856 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1857 if (doc != NULL && PyString_Check(doc)) {
1858 const size_t n = (size_t)PyString_GET_SIZE(doc);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001859 char *tp_doc = PyObject_MALLOC(n+1);
1860 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00001861 Py_DECREF(type);
1862 return NULL;
1863 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001864 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
1865 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00001866 }
1867 }
1868
Tim Peters6d6c1a32001-08-02 04:15:00 +00001869 /* Special-case __new__: if it's a plain function,
1870 make it a static function */
1871 tmp = PyDict_GetItemString(dict, "__new__");
1872 if (tmp != NULL && PyFunction_Check(tmp)) {
1873 tmp = PyStaticMethod_New(tmp);
1874 if (tmp == NULL) {
1875 Py_DECREF(type);
1876 return NULL;
1877 }
1878 PyDict_SetItemString(dict, "__new__", tmp);
1879 Py_DECREF(tmp);
1880 }
1881
1882 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001883 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001884 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001885 if (slots != NULL) {
1886 for (i = 0; i < nslots; i++, mp++) {
1887 mp->name = PyString_AS_STRING(
1888 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001889 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001890 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001891 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001892 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001893 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001894 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001895 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001896 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001897 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001898 slotoffset += sizeof(PyObject *);
1899 }
1900 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001901 if (add_dict) {
1902 if (base->tp_itemsize)
1903 type->tp_dictoffset = -(long)sizeof(PyObject *);
1904 else
1905 type->tp_dictoffset = slotoffset;
1906 slotoffset += sizeof(PyObject *);
1907 }
1908 if (add_weak) {
1909 assert(!base->tp_itemsize);
1910 type->tp_weaklistoffset = slotoffset;
1911 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001912 }
1913 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001914 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001915 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001916
1917 if (type->tp_weaklistoffset && type->tp_dictoffset)
1918 type->tp_getset = subtype_getsets_full;
1919 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1920 type->tp_getset = subtype_getsets_weakref_only;
1921 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1922 type->tp_getset = subtype_getsets_dict_only;
1923 else
1924 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001925
1926 /* Special case some slots */
1927 if (type->tp_dictoffset != 0 || nslots > 0) {
1928 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1929 type->tp_getattro = PyObject_GenericGetAttr;
1930 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1931 type->tp_setattro = PyObject_GenericSetAttr;
1932 }
1933 type->tp_dealloc = subtype_dealloc;
1934
Guido van Rossum9475a232001-10-05 20:51:39 +00001935 /* Enable GC unless there are really no instance variables possible */
1936 if (!(type->tp_basicsize == sizeof(PyObject) &&
1937 type->tp_itemsize == 0))
1938 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1939
Tim Peters6d6c1a32001-08-02 04:15:00 +00001940 /* Always override allocation strategy to use regular heap */
1941 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001942 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001943 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001944 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001945 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001946 }
1947 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001948 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001949
1950 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001951 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001952 Py_DECREF(type);
1953 return NULL;
1954 }
1955
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001956 /* Put the proper slots in place */
1957 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001958
Tim Peters6d6c1a32001-08-02 04:15:00 +00001959 return (PyObject *)type;
1960}
1961
1962/* Internal API to look for a name through the MRO.
1963 This returns a borrowed reference, and doesn't set an exception! */
1964PyObject *
1965_PyType_Lookup(PyTypeObject *type, PyObject *name)
1966{
1967 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001968 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001969
Guido van Rossum687ae002001-10-15 22:03:32 +00001970 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001971 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001972
1973 /* If mro is NULL, the type is either not yet initialized
1974 by PyType_Ready(), or already cleared by type_clear().
1975 Either way the safest thing to do is to return NULL. */
1976 if (mro == NULL)
1977 return NULL;
1978
Tim Peters6d6c1a32001-08-02 04:15:00 +00001979 assert(PyTuple_Check(mro));
1980 n = PyTuple_GET_SIZE(mro);
1981 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001982 base = PyTuple_GET_ITEM(mro, i);
1983 if (PyClass_Check(base))
1984 dict = ((PyClassObject *)base)->cl_dict;
1985 else {
1986 assert(PyType_Check(base));
1987 dict = ((PyTypeObject *)base)->tp_dict;
1988 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001989 assert(dict && PyDict_Check(dict));
1990 res = PyDict_GetItem(dict, name);
1991 if (res != NULL)
1992 return res;
1993 }
1994 return NULL;
1995}
1996
1997/* This is similar to PyObject_GenericGetAttr(),
1998 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1999static PyObject *
2000type_getattro(PyTypeObject *type, PyObject *name)
2001{
2002 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002003 PyObject *meta_attribute, *attribute;
2004 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002005
2006 /* Initialize this type (we'll assume the metatype is initialized) */
2007 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002008 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002009 return NULL;
2010 }
2011
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002012 /* No readable descriptor found yet */
2013 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002014
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002015 /* Look for the attribute in the metatype */
2016 meta_attribute = _PyType_Lookup(metatype, name);
2017
2018 if (meta_attribute != NULL) {
2019 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002020
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002021 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2022 /* Data descriptors implement tp_descr_set to intercept
2023 * writes. Assume the attribute is not overridden in
2024 * type's tp_dict (and bases): call the descriptor now.
2025 */
2026 return meta_get(meta_attribute, (PyObject *)type,
2027 (PyObject *)metatype);
2028 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002029 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002030 }
2031
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002032 /* No data descriptor found on metatype. Look in tp_dict of this
2033 * type and its bases */
2034 attribute = _PyType_Lookup(type, name);
2035 if (attribute != NULL) {
2036 /* Implement descriptor functionality, if any */
2037 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002038
2039 Py_XDECREF(meta_attribute);
2040
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002041 if (local_get != NULL) {
2042 /* NULL 2nd argument indicates the descriptor was
2043 * found on the target object itself (or a base) */
2044 return local_get(attribute, (PyObject *)NULL,
2045 (PyObject *)type);
2046 }
Tim Peters34592512002-07-11 06:23:50 +00002047
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002048 Py_INCREF(attribute);
2049 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002050 }
2051
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002052 /* No attribute found in local __dict__ (or bases): use the
2053 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002054 if (meta_get != NULL) {
2055 PyObject *res;
2056 res = meta_get(meta_attribute, (PyObject *)type,
2057 (PyObject *)metatype);
2058 Py_DECREF(meta_attribute);
2059 return res;
2060 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002061
2062 /* If an ordinary attribute was found on the metatype, return it now */
2063 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002064 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002065 }
2066
2067 /* Give up */
2068 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002069 "type object '%.50s' has no attribute '%.400s'",
2070 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002071 return NULL;
2072}
2073
2074static int
2075type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2076{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002077 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2078 PyErr_Format(
2079 PyExc_TypeError,
2080 "can't set attributes of built-in/extension type '%s'",
2081 type->tp_name);
2082 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002083 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002084 /* XXX Example of how I expect this to be used...
2085 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2086 return -1;
2087 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002088 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2089 return -1;
2090 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002091}
2092
2093static void
2094type_dealloc(PyTypeObject *type)
2095{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002096 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002097
2098 /* Assert this is a heap-allocated type object */
2099 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002100 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002101 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002102 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002103 Py_XDECREF(type->tp_base);
2104 Py_XDECREF(type->tp_dict);
2105 Py_XDECREF(type->tp_bases);
2106 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002107 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002108 Py_XDECREF(type->tp_subclasses);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002109 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2110 * of most other objects. It's okay to cast it to char *.
2111 */
2112 PyObject_Free((char *)type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002113 Py_XDECREF(et->name);
2114 Py_XDECREF(et->slots);
2115 type->ob_type->tp_free((PyObject *)type);
2116}
2117
Guido van Rossum1c450732001-10-08 15:18:27 +00002118static PyObject *
2119type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2120{
2121 PyObject *list, *raw, *ref;
2122 int i, n;
2123
2124 list = PyList_New(0);
2125 if (list == NULL)
2126 return NULL;
2127 raw = type->tp_subclasses;
2128 if (raw == NULL)
2129 return list;
2130 assert(PyList_Check(raw));
2131 n = PyList_GET_SIZE(raw);
2132 for (i = 0; i < n; i++) {
2133 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002134 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002135 ref = PyWeakref_GET_OBJECT(ref);
2136 if (ref != Py_None) {
2137 if (PyList_Append(list, ref) < 0) {
2138 Py_DECREF(list);
2139 return NULL;
2140 }
2141 }
2142 }
2143 return list;
2144}
2145
Tim Peters6d6c1a32001-08-02 04:15:00 +00002146static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002147 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002148 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002149 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002150 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002151 {0}
2152};
2153
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002154PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002155"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002156"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002157
Guido van Rossum048eb752001-10-02 21:24:57 +00002158static int
2159type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2160{
Guido van Rossum048eb752001-10-02 21:24:57 +00002161 int err;
2162
Guido van Rossuma3862092002-06-10 15:24:42 +00002163 /* Because of type_is_gc(), the collector only calls this
2164 for heaptypes. */
2165 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002166
2167#define VISIT(SLOT) \
2168 if (SLOT) { \
2169 err = visit((PyObject *)(SLOT), arg); \
2170 if (err) \
2171 return err; \
2172 }
2173
2174 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002175 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002176 VISIT(type->tp_mro);
2177 VISIT(type->tp_bases);
2178 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002179
2180 /* There's no need to visit type->tp_subclasses or
Guido van Rossume5c691a2003-03-07 15:13:17 +00002181 ((PyHeapTypeObject *)type)->slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002182 in cycles; tp_subclasses is a list of weak references,
2183 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002184
2185#undef VISIT
2186
2187 return 0;
2188}
2189
2190static int
2191type_clear(PyTypeObject *type)
2192{
Guido van Rossum048eb752001-10-02 21:24:57 +00002193 PyObject *tmp;
2194
Guido van Rossuma3862092002-06-10 15:24:42 +00002195 /* Because of type_is_gc(), the collector only calls this
2196 for heaptypes. */
2197 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002198
2199#define CLEAR(SLOT) \
2200 if (SLOT) { \
2201 tmp = (PyObject *)(SLOT); \
2202 SLOT = NULL; \
2203 Py_DECREF(tmp); \
2204 }
2205
Guido van Rossuma3862092002-06-10 15:24:42 +00002206 /* The only field we need to clear is tp_mro, which is part of a
2207 hard cycle (its first element is the class itself) that won't
2208 be broken otherwise (it's a tuple and tuples don't have a
2209 tp_clear handler). None of the other fields need to be
2210 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002211
Guido van Rossuma3862092002-06-10 15:24:42 +00002212 tp_dict:
2213 It is a dict, so the collector will call its tp_clear.
2214
2215 tp_cache:
2216 Not used; if it were, it would be a dict.
2217
2218 tp_bases, tp_base:
2219 If these are involved in a cycle, there must be at least
2220 one other, mutable object in the cycle, e.g. a base
2221 class's dict; the cycle will be broken that way.
2222
2223 tp_subclasses:
2224 A list of weak references can't be part of a cycle; and
2225 lists have their own tp_clear.
2226
Guido van Rossume5c691a2003-03-07 15:13:17 +00002227 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002228 A tuple of strings can't be part of a cycle.
2229 */
2230
2231 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002232
Guido van Rossum048eb752001-10-02 21:24:57 +00002233#undef CLEAR
2234
2235 return 0;
2236}
2237
2238static int
2239type_is_gc(PyTypeObject *type)
2240{
2241 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2242}
2243
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002244PyTypeObject PyType_Type = {
2245 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002246 0, /* ob_size */
2247 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002248 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002249 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002250 (destructor)type_dealloc, /* tp_dealloc */
2251 0, /* tp_print */
2252 0, /* tp_getattr */
2253 0, /* tp_setattr */
2254 type_compare, /* tp_compare */
2255 (reprfunc)type_repr, /* tp_repr */
2256 0, /* tp_as_number */
2257 0, /* tp_as_sequence */
2258 0, /* tp_as_mapping */
2259 (hashfunc)_Py_HashPointer, /* tp_hash */
2260 (ternaryfunc)type_call, /* tp_call */
2261 0, /* tp_str */
2262 (getattrofunc)type_getattro, /* tp_getattro */
2263 (setattrofunc)type_setattro, /* tp_setattro */
2264 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002265 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2266 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002267 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002268 (traverseproc)type_traverse, /* tp_traverse */
2269 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002270 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002271 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002272 0, /* tp_iter */
2273 0, /* tp_iternext */
2274 type_methods, /* tp_methods */
2275 type_members, /* tp_members */
2276 type_getsets, /* tp_getset */
2277 0, /* tp_base */
2278 0, /* tp_dict */
2279 0, /* tp_descr_get */
2280 0, /* tp_descr_set */
2281 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2282 0, /* tp_init */
2283 0, /* tp_alloc */
2284 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002285 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002286 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002287};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002288
2289
2290/* The base type of all types (eventually)... except itself. */
2291
2292static int
2293object_init(PyObject *self, PyObject *args, PyObject *kwds)
2294{
2295 return 0;
2296}
2297
Guido van Rossum298e4212003-02-13 16:30:16 +00002298/* If we don't have a tp_new for a new-style class, new will use this one.
2299 Therefore this should take no arguments/keywords. However, this new may
2300 also be inherited by objects that define a tp_init but no tp_new. These
2301 objects WILL pass argumets to tp_new, because it gets the same args as
2302 tp_init. So only allow arguments if we aren't using the default init, in
2303 which case we expect init to handle argument parsing. */
2304static PyObject *
2305object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2306{
2307 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2308 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2309 PyErr_SetString(PyExc_TypeError,
2310 "default __new__ takes no parameters");
2311 return NULL;
2312 }
2313 return type->tp_alloc(type, 0);
2314}
2315
Tim Peters6d6c1a32001-08-02 04:15:00 +00002316static void
2317object_dealloc(PyObject *self)
2318{
2319 self->ob_type->tp_free(self);
2320}
2321
Guido van Rossum8e248182001-08-12 05:17:56 +00002322static PyObject *
2323object_repr(PyObject *self)
2324{
Guido van Rossum76e69632001-08-16 18:52:43 +00002325 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002326 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002327
Guido van Rossum76e69632001-08-16 18:52:43 +00002328 type = self->ob_type;
2329 mod = type_module(type, NULL);
2330 if (mod == NULL)
2331 PyErr_Clear();
2332 else if (!PyString_Check(mod)) {
2333 Py_DECREF(mod);
2334 mod = NULL;
2335 }
2336 name = type_name(type, NULL);
2337 if (name == NULL)
2338 return NULL;
2339 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002340 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002341 PyString_AS_STRING(mod),
2342 PyString_AS_STRING(name),
2343 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002344 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002345 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002346 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002347 Py_XDECREF(mod);
2348 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002349 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002350}
2351
Guido van Rossumb8f63662001-08-15 23:57:02 +00002352static PyObject *
2353object_str(PyObject *self)
2354{
2355 unaryfunc f;
2356
2357 f = self->ob_type->tp_repr;
2358 if (f == NULL)
2359 f = object_repr;
2360 return f(self);
2361}
2362
Guido van Rossum8e248182001-08-12 05:17:56 +00002363static long
2364object_hash(PyObject *self)
2365{
2366 return _Py_HashPointer(self);
2367}
Guido van Rossum8e248182001-08-12 05:17:56 +00002368
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002369static PyObject *
2370object_get_class(PyObject *self, void *closure)
2371{
2372 Py_INCREF(self->ob_type);
2373 return (PyObject *)(self->ob_type);
2374}
2375
2376static int
2377equiv_structs(PyTypeObject *a, PyTypeObject *b)
2378{
2379 return a == b ||
2380 (a != NULL &&
2381 b != NULL &&
2382 a->tp_basicsize == b->tp_basicsize &&
2383 a->tp_itemsize == b->tp_itemsize &&
2384 a->tp_dictoffset == b->tp_dictoffset &&
2385 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2386 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2387 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2388}
2389
2390static int
2391same_slots_added(PyTypeObject *a, PyTypeObject *b)
2392{
2393 PyTypeObject *base = a->tp_base;
2394 int size;
2395
2396 if (base != b->tp_base)
2397 return 0;
2398 if (equiv_structs(a, base) && equiv_structs(b, base))
2399 return 1;
2400 size = base->tp_basicsize;
2401 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2402 size += sizeof(PyObject *);
2403 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2404 size += sizeof(PyObject *);
2405 return size == a->tp_basicsize && size == b->tp_basicsize;
2406}
2407
2408static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002409compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2410{
2411 PyTypeObject *newbase, *oldbase;
2412
2413 if (new->tp_dealloc != old->tp_dealloc ||
2414 new->tp_free != old->tp_free)
2415 {
2416 PyErr_Format(PyExc_TypeError,
2417 "%s assignment: "
2418 "'%s' deallocator differs from '%s'",
2419 attr,
2420 new->tp_name,
2421 old->tp_name);
2422 return 0;
2423 }
2424 newbase = new;
2425 oldbase = old;
2426 while (equiv_structs(newbase, newbase->tp_base))
2427 newbase = newbase->tp_base;
2428 while (equiv_structs(oldbase, oldbase->tp_base))
2429 oldbase = oldbase->tp_base;
2430 if (newbase != oldbase &&
2431 (newbase->tp_base != oldbase->tp_base ||
2432 !same_slots_added(newbase, oldbase))) {
2433 PyErr_Format(PyExc_TypeError,
2434 "%s assignment: "
2435 "'%s' object layout differs from '%s'",
2436 attr,
2437 new->tp_name,
2438 old->tp_name);
2439 return 0;
2440 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002441
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002442 return 1;
2443}
2444
2445static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002446object_set_class(PyObject *self, PyObject *value, void *closure)
2447{
2448 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002449 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002450
Guido van Rossumb6b89422002-04-15 01:03:30 +00002451 if (value == NULL) {
2452 PyErr_SetString(PyExc_TypeError,
2453 "can't delete __class__ attribute");
2454 return -1;
2455 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002456 if (!PyType_Check(value)) {
2457 PyErr_Format(PyExc_TypeError,
2458 "__class__ must be set to new-style class, not '%s' object",
2459 value->ob_type->tp_name);
2460 return -1;
2461 }
2462 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002463 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2464 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2465 {
2466 PyErr_Format(PyExc_TypeError,
2467 "__class__ assignment: only for heap types");
2468 return -1;
2469 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002470 if (compatible_for_assignment(new, old, "__class__")) {
2471 Py_INCREF(new);
2472 self->ob_type = new;
2473 Py_DECREF(old);
2474 return 0;
2475 }
2476 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002477 return -1;
2478 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002479}
2480
2481static PyGetSetDef object_getsets[] = {
2482 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002483 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002484 {0}
2485};
2486
Guido van Rossumc53f0092003-02-18 22:05:12 +00002487
Guido van Rossum036f9992003-02-21 22:02:54 +00002488/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2489 We fall back to helpers in copy_reg for:
2490 - pickle protocols < 2
2491 - calculating the list of slot names (done only once per class)
2492 - the __newobj__ function (which is used as a token but never called)
2493*/
2494
2495static PyObject *
2496import_copy_reg(void)
2497{
2498 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002499
2500 if (!copy_reg_str) {
2501 copy_reg_str = PyString_InternFromString("copy_reg");
2502 if (copy_reg_str == NULL)
2503 return NULL;
2504 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002505
2506 return PyImport_Import(copy_reg_str);
2507}
2508
2509static PyObject *
2510slotnames(PyObject *cls)
2511{
2512 PyObject *clsdict;
2513 PyObject *copy_reg;
2514 PyObject *slotnames;
2515
2516 if (!PyType_Check(cls)) {
2517 Py_INCREF(Py_None);
2518 return Py_None;
2519 }
2520
2521 clsdict = ((PyTypeObject *)cls)->tp_dict;
2522 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002523 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002524 Py_INCREF(slotnames);
2525 return slotnames;
2526 }
2527
2528 copy_reg = import_copy_reg();
2529 if (copy_reg == NULL)
2530 return NULL;
2531
2532 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2533 Py_DECREF(copy_reg);
2534 if (slotnames != NULL &&
2535 slotnames != Py_None &&
2536 !PyList_Check(slotnames))
2537 {
2538 PyErr_SetString(PyExc_TypeError,
2539 "copy_reg._slotnames didn't return a list or None");
2540 Py_DECREF(slotnames);
2541 slotnames = NULL;
2542 }
2543
2544 return slotnames;
2545}
2546
2547static PyObject *
2548reduce_2(PyObject *obj)
2549{
2550 PyObject *cls, *getnewargs;
2551 PyObject *args = NULL, *args2 = NULL;
2552 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2553 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2554 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
2555 int i, n;
2556
2557 cls = PyObject_GetAttrString(obj, "__class__");
2558 if (cls == NULL)
2559 return NULL;
2560
2561 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2562 if (getnewargs != NULL) {
2563 args = PyObject_CallObject(getnewargs, NULL);
2564 Py_DECREF(getnewargs);
2565 if (args != NULL && !PyTuple_Check(args)) {
2566 PyErr_SetString(PyExc_TypeError,
2567 "__getnewargs__ should return a tuple");
2568 goto end;
2569 }
2570 }
2571 else {
2572 PyErr_Clear();
2573 args = PyTuple_New(0);
2574 }
2575 if (args == NULL)
2576 goto end;
2577
2578 getstate = PyObject_GetAttrString(obj, "__getstate__");
2579 if (getstate != NULL) {
2580 state = PyObject_CallObject(getstate, NULL);
2581 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002582 if (state == NULL)
2583 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002584 }
2585 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002586 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002587 state = PyObject_GetAttrString(obj, "__dict__");
2588 if (state == NULL) {
2589 PyErr_Clear();
2590 state = Py_None;
2591 Py_INCREF(state);
2592 }
2593 names = slotnames(cls);
2594 if (names == NULL)
2595 goto end;
2596 if (names != Py_None) {
2597 assert(PyList_Check(names));
2598 slots = PyDict_New();
2599 if (slots == NULL)
2600 goto end;
2601 n = 0;
2602 /* Can't pre-compute the list size; the list
2603 is stored on the class so accessible to other
2604 threads, which may be run by DECREF */
2605 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2606 PyObject *name, *value;
2607 name = PyList_GET_ITEM(names, i);
2608 value = PyObject_GetAttr(obj, name);
2609 if (value == NULL)
2610 PyErr_Clear();
2611 else {
2612 int err = PyDict_SetItem(slots, name,
2613 value);
2614 Py_DECREF(value);
2615 if (err)
2616 goto end;
2617 n++;
2618 }
2619 }
2620 if (n) {
2621 state = Py_BuildValue("(NO)", state, slots);
2622 if (state == NULL)
2623 goto end;
2624 }
2625 }
2626 }
2627
2628 if (!PyList_Check(obj)) {
2629 listitems = Py_None;
2630 Py_INCREF(listitems);
2631 }
2632 else {
2633 listitems = PyObject_GetIter(obj);
2634 if (listitems == NULL)
2635 goto end;
2636 }
2637
2638 if (!PyDict_Check(obj)) {
2639 dictitems = Py_None;
2640 Py_INCREF(dictitems);
2641 }
2642 else {
2643 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2644 if (dictitems == NULL)
2645 goto end;
2646 }
2647
2648 copy_reg = import_copy_reg();
2649 if (copy_reg == NULL)
2650 goto end;
2651 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2652 if (newobj == NULL)
2653 goto end;
2654
2655 n = PyTuple_GET_SIZE(args);
2656 args2 = PyTuple_New(n+1);
2657 if (args2 == NULL)
2658 goto end;
2659 PyTuple_SET_ITEM(args2, 0, cls);
2660 cls = NULL;
2661 for (i = 0; i < n; i++) {
2662 PyObject *v = PyTuple_GET_ITEM(args, i);
2663 Py_INCREF(v);
2664 PyTuple_SET_ITEM(args2, i+1, v);
2665 }
2666
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002667 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002668
2669 end:
2670 Py_XDECREF(cls);
2671 Py_XDECREF(args);
2672 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002673 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002674 Py_XDECREF(state);
2675 Py_XDECREF(names);
2676 Py_XDECREF(listitems);
2677 Py_XDECREF(dictitems);
2678 Py_XDECREF(copy_reg);
2679 Py_XDECREF(newobj);
2680 return res;
2681}
2682
2683static PyObject *
2684object_reduce_ex(PyObject *self, PyObject *args)
2685{
2686 /* Call copy_reg._reduce_ex(self, proto) */
2687 PyObject *reduce, *copy_reg, *res;
2688 int proto = 0;
2689
2690 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2691 return NULL;
2692
2693 reduce = PyObject_GetAttrString(self, "__reduce__");
2694 if (reduce == NULL)
2695 PyErr_Clear();
2696 else {
2697 PyObject *cls, *clsreduce, *objreduce;
2698 int override;
2699 cls = PyObject_GetAttrString(self, "__class__");
2700 if (cls == NULL) {
2701 Py_DECREF(reduce);
2702 return NULL;
2703 }
2704 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2705 Py_DECREF(cls);
2706 if (clsreduce == NULL) {
2707 Py_DECREF(reduce);
2708 return NULL;
2709 }
2710 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2711 "__reduce__");
2712 override = (clsreduce != objreduce);
2713 Py_DECREF(clsreduce);
2714 if (override) {
2715 res = PyObject_CallObject(reduce, NULL);
2716 Py_DECREF(reduce);
2717 return res;
2718 }
2719 else
2720 Py_DECREF(reduce);
2721 }
2722
2723 if (proto >= 2)
2724 return reduce_2(self);
2725
2726 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002727 if (!copy_reg)
2728 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002729
Guido van Rossumc53f0092003-02-18 22:05:12 +00002730 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002731 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002732
Guido van Rossum3926a632001-09-25 16:25:58 +00002733 return res;
2734}
2735
2736static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002737 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2738 PyDoc_STR("helper for pickle")},
2739 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002740 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002741 {0}
2742};
2743
Guido van Rossum036f9992003-02-21 22:02:54 +00002744
Tim Peters6d6c1a32001-08-02 04:15:00 +00002745PyTypeObject PyBaseObject_Type = {
2746 PyObject_HEAD_INIT(&PyType_Type)
2747 0, /* ob_size */
2748 "object", /* tp_name */
2749 sizeof(PyObject), /* tp_basicsize */
2750 0, /* tp_itemsize */
2751 (destructor)object_dealloc, /* tp_dealloc */
2752 0, /* tp_print */
2753 0, /* tp_getattr */
2754 0, /* tp_setattr */
2755 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002756 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002757 0, /* tp_as_number */
2758 0, /* tp_as_sequence */
2759 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002760 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002761 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002762 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002763 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002764 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002765 0, /* tp_as_buffer */
2766 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002767 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002768 0, /* tp_traverse */
2769 0, /* tp_clear */
2770 0, /* tp_richcompare */
2771 0, /* tp_weaklistoffset */
2772 0, /* tp_iter */
2773 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002774 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002775 0, /* tp_members */
2776 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002777 0, /* tp_base */
2778 0, /* tp_dict */
2779 0, /* tp_descr_get */
2780 0, /* tp_descr_set */
2781 0, /* tp_dictoffset */
2782 object_init, /* tp_init */
2783 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002784 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002785 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002786};
2787
2788
2789/* Initialize the __dict__ in a type object */
2790
2791static int
2792add_methods(PyTypeObject *type, PyMethodDef *meth)
2793{
Guido van Rossum687ae002001-10-15 22:03:32 +00002794 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002795
2796 for (; meth->ml_name != NULL; meth++) {
2797 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002798 if (PyDict_GetItemString(dict, meth->ml_name) &&
2799 !(meth->ml_flags & METH_COEXIST))
2800 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002801 if (meth->ml_flags & METH_CLASS) {
2802 if (meth->ml_flags & METH_STATIC) {
2803 PyErr_SetString(PyExc_ValueError,
2804 "method cannot be both class and static");
2805 return -1;
2806 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002807 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002808 }
2809 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002810 PyObject *cfunc = PyCFunction_New(meth, NULL);
2811 if (cfunc == NULL)
2812 return -1;
2813 descr = PyStaticMethod_New(cfunc);
2814 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002815 }
2816 else {
2817 descr = PyDescr_NewMethod(type, meth);
2818 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002819 if (descr == NULL)
2820 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002821 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002822 return -1;
2823 Py_DECREF(descr);
2824 }
2825 return 0;
2826}
2827
2828static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002829add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002830{
Guido van Rossum687ae002001-10-15 22:03:32 +00002831 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002832
2833 for (; memb->name != NULL; memb++) {
2834 PyObject *descr;
2835 if (PyDict_GetItemString(dict, memb->name))
2836 continue;
2837 descr = PyDescr_NewMember(type, memb);
2838 if (descr == NULL)
2839 return -1;
2840 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2841 return -1;
2842 Py_DECREF(descr);
2843 }
2844 return 0;
2845}
2846
2847static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002848add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002849{
Guido van Rossum687ae002001-10-15 22:03:32 +00002850 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002851
2852 for (; gsp->name != NULL; gsp++) {
2853 PyObject *descr;
2854 if (PyDict_GetItemString(dict, gsp->name))
2855 continue;
2856 descr = PyDescr_NewGetSet(type, gsp);
2857
2858 if (descr == NULL)
2859 return -1;
2860 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2861 return -1;
2862 Py_DECREF(descr);
2863 }
2864 return 0;
2865}
2866
Guido van Rossum13d52f02001-08-10 21:24:08 +00002867static void
2868inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002869{
2870 int oldsize, newsize;
2871
Guido van Rossum13d52f02001-08-10 21:24:08 +00002872 /* Special flag magic */
2873 if (!type->tp_as_buffer && base->tp_as_buffer) {
2874 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2875 type->tp_flags |=
2876 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2877 }
2878 if (!type->tp_as_sequence && base->tp_as_sequence) {
2879 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2880 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2881 }
2882 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2883 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2884 if ((!type->tp_as_number && base->tp_as_number) ||
2885 (!type->tp_as_sequence && base->tp_as_sequence)) {
2886 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2887 if (!type->tp_as_number && !type->tp_as_sequence) {
2888 type->tp_flags |= base->tp_flags &
2889 Py_TPFLAGS_HAVE_INPLACEOPS;
2890 }
2891 }
2892 /* Wow */
2893 }
2894 if (!type->tp_as_number && base->tp_as_number) {
2895 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2896 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2897 }
2898
2899 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002900 oldsize = base->tp_basicsize;
2901 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2902 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2903 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002904 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2905 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002906 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002907 if (type->tp_traverse == NULL)
2908 type->tp_traverse = base->tp_traverse;
2909 if (type->tp_clear == NULL)
2910 type->tp_clear = base->tp_clear;
2911 }
2912 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002913 /* The condition below could use some explanation.
2914 It appears that tp_new is not inherited for static types
2915 whose base class is 'object'; this seems to be a precaution
2916 so that old extension types don't suddenly become
2917 callable (object.__new__ wouldn't insure the invariants
2918 that the extension type's own factory function ensures).
2919 Heap types, of course, are under our control, so they do
2920 inherit tp_new; static extension types that specify some
2921 other built-in type as the default are considered
2922 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002923 if (base != &PyBaseObject_Type ||
2924 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2925 if (type->tp_new == NULL)
2926 type->tp_new = base->tp_new;
2927 }
2928 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002929 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002930
2931 /* Copy other non-function slots */
2932
2933#undef COPYVAL
2934#define COPYVAL(SLOT) \
2935 if (type->SLOT == 0) type->SLOT = base->SLOT
2936
2937 COPYVAL(tp_itemsize);
2938 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2939 COPYVAL(tp_weaklistoffset);
2940 }
2941 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2942 COPYVAL(tp_dictoffset);
2943 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002944}
2945
2946static void
2947inherit_slots(PyTypeObject *type, PyTypeObject *base)
2948{
2949 PyTypeObject *basebase;
2950
2951#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002952#undef COPYSLOT
2953#undef COPYNUM
2954#undef COPYSEQ
2955#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002956#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002957
2958#define SLOTDEFINED(SLOT) \
2959 (base->SLOT != 0 && \
2960 (basebase == NULL || base->SLOT != basebase->SLOT))
2961
Tim Peters6d6c1a32001-08-02 04:15:00 +00002962#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002963 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002964
2965#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2966#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2967#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002968#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002969
Guido van Rossum13d52f02001-08-10 21:24:08 +00002970 /* This won't inherit indirect slots (from tp_as_number etc.)
2971 if type doesn't provide the space. */
2972
2973 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2974 basebase = base->tp_base;
2975 if (basebase->tp_as_number == NULL)
2976 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002977 COPYNUM(nb_add);
2978 COPYNUM(nb_subtract);
2979 COPYNUM(nb_multiply);
2980 COPYNUM(nb_divide);
2981 COPYNUM(nb_remainder);
2982 COPYNUM(nb_divmod);
2983 COPYNUM(nb_power);
2984 COPYNUM(nb_negative);
2985 COPYNUM(nb_positive);
2986 COPYNUM(nb_absolute);
2987 COPYNUM(nb_nonzero);
2988 COPYNUM(nb_invert);
2989 COPYNUM(nb_lshift);
2990 COPYNUM(nb_rshift);
2991 COPYNUM(nb_and);
2992 COPYNUM(nb_xor);
2993 COPYNUM(nb_or);
2994 COPYNUM(nb_coerce);
2995 COPYNUM(nb_int);
2996 COPYNUM(nb_long);
2997 COPYNUM(nb_float);
2998 COPYNUM(nb_oct);
2999 COPYNUM(nb_hex);
3000 COPYNUM(nb_inplace_add);
3001 COPYNUM(nb_inplace_subtract);
3002 COPYNUM(nb_inplace_multiply);
3003 COPYNUM(nb_inplace_divide);
3004 COPYNUM(nb_inplace_remainder);
3005 COPYNUM(nb_inplace_power);
3006 COPYNUM(nb_inplace_lshift);
3007 COPYNUM(nb_inplace_rshift);
3008 COPYNUM(nb_inplace_and);
3009 COPYNUM(nb_inplace_xor);
3010 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003011 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3012 COPYNUM(nb_true_divide);
3013 COPYNUM(nb_floor_divide);
3014 COPYNUM(nb_inplace_true_divide);
3015 COPYNUM(nb_inplace_floor_divide);
3016 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003017 }
3018
Guido van Rossum13d52f02001-08-10 21:24:08 +00003019 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3020 basebase = base->tp_base;
3021 if (basebase->tp_as_sequence == NULL)
3022 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003023 COPYSEQ(sq_length);
3024 COPYSEQ(sq_concat);
3025 COPYSEQ(sq_repeat);
3026 COPYSEQ(sq_item);
3027 COPYSEQ(sq_slice);
3028 COPYSEQ(sq_ass_item);
3029 COPYSEQ(sq_ass_slice);
3030 COPYSEQ(sq_contains);
3031 COPYSEQ(sq_inplace_concat);
3032 COPYSEQ(sq_inplace_repeat);
3033 }
3034
Guido van Rossum13d52f02001-08-10 21:24:08 +00003035 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3036 basebase = base->tp_base;
3037 if (basebase->tp_as_mapping == NULL)
3038 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003039 COPYMAP(mp_length);
3040 COPYMAP(mp_subscript);
3041 COPYMAP(mp_ass_subscript);
3042 }
3043
Tim Petersfc57ccb2001-10-12 02:38:24 +00003044 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3045 basebase = base->tp_base;
3046 if (basebase->tp_as_buffer == NULL)
3047 basebase = NULL;
3048 COPYBUF(bf_getreadbuffer);
3049 COPYBUF(bf_getwritebuffer);
3050 COPYBUF(bf_getsegcount);
3051 COPYBUF(bf_getcharbuffer);
3052 }
3053
Guido van Rossum13d52f02001-08-10 21:24:08 +00003054 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003055
Tim Peters6d6c1a32001-08-02 04:15:00 +00003056 COPYSLOT(tp_dealloc);
3057 COPYSLOT(tp_print);
3058 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3059 type->tp_getattr = base->tp_getattr;
3060 type->tp_getattro = base->tp_getattro;
3061 }
3062 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3063 type->tp_setattr = base->tp_setattr;
3064 type->tp_setattro = base->tp_setattro;
3065 }
3066 /* tp_compare see tp_richcompare */
3067 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003068 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003069 COPYSLOT(tp_call);
3070 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003071 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003072 if (type->tp_compare == NULL &&
3073 type->tp_richcompare == NULL &&
3074 type->tp_hash == NULL)
3075 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003076 type->tp_compare = base->tp_compare;
3077 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003078 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003079 }
3080 }
3081 else {
3082 COPYSLOT(tp_compare);
3083 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003084 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3085 COPYSLOT(tp_iter);
3086 COPYSLOT(tp_iternext);
3087 }
3088 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3089 COPYSLOT(tp_descr_get);
3090 COPYSLOT(tp_descr_set);
3091 COPYSLOT(tp_dictoffset);
3092 COPYSLOT(tp_init);
3093 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003094 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003095 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3096 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3097 /* They agree about gc. */
3098 COPYSLOT(tp_free);
3099 }
3100 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3101 type->tp_free == NULL &&
3102 base->tp_free == _PyObject_Del) {
3103 /* A bit of magic to plug in the correct default
3104 * tp_free function when a derived class adds gc,
3105 * didn't define tp_free, and the base uses the
3106 * default non-gc tp_free.
3107 */
3108 type->tp_free = PyObject_GC_Del;
3109 }
3110 /* else they didn't agree about gc, and there isn't something
3111 * obvious to be done -- the type is on its own.
3112 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003113 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003114}
3115
Jeremy Hylton938ace62002-07-17 16:30:39 +00003116static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003117
Tim Peters6d6c1a32001-08-02 04:15:00 +00003118int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003119PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003120{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003121 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003122 PyTypeObject *base;
3123 int i, n;
3124
Guido van Rossumcab05802002-06-10 15:29:03 +00003125 if (type->tp_flags & Py_TPFLAGS_READY) {
3126 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003127 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003128 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003129 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003130
3131 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003132
Tim Peters36eb4df2003-03-23 03:33:13 +00003133#ifdef Py_TRACE_REFS
3134 /* PyType_Ready is the closest thing we have to a choke point
3135 * for type objects, so is the best place I can think of to try
3136 * to get type objects into the doubly-linked list of all objects.
3137 * Still, not all type objects go thru PyType_Ready.
3138 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003139 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003140#endif
3141
Tim Peters6d6c1a32001-08-02 04:15:00 +00003142 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3143 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003144 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003145 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003146 Py_INCREF(base);
3147 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003148
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003149 /* Initialize the base class */
3150 if (base && base->tp_dict == NULL) {
3151 if (PyType_Ready(base) < 0)
3152 goto error;
3153 }
3154
Guido van Rossum0986d822002-04-08 01:38:42 +00003155 /* Initialize ob_type if NULL. This means extensions that want to be
3156 compilable separately on Windows can call PyType_Ready() instead of
3157 initializing the ob_type field of their type objects. */
3158 if (type->ob_type == NULL)
3159 type->ob_type = base->ob_type;
3160
Tim Peters6d6c1a32001-08-02 04:15:00 +00003161 /* Initialize tp_bases */
3162 bases = type->tp_bases;
3163 if (bases == NULL) {
3164 if (base == NULL)
3165 bases = PyTuple_New(0);
3166 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003167 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003168 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003169 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003170 type->tp_bases = bases;
3171 }
3172
Guido van Rossum687ae002001-10-15 22:03:32 +00003173 /* Initialize tp_dict */
3174 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003175 if (dict == NULL) {
3176 dict = PyDict_New();
3177 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003178 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003179 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003180 }
3181
Guido van Rossum687ae002001-10-15 22:03:32 +00003182 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003183 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003184 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003185 if (type->tp_methods != NULL) {
3186 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003187 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003188 }
3189 if (type->tp_members != NULL) {
3190 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003191 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003192 }
3193 if (type->tp_getset != NULL) {
3194 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003195 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003196 }
3197
Tim Peters6d6c1a32001-08-02 04:15:00 +00003198 /* Calculate method resolution order */
3199 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003200 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003201 }
3202
Guido van Rossum13d52f02001-08-10 21:24:08 +00003203 /* Inherit special flags from dominant base */
3204 if (type->tp_base != NULL)
3205 inherit_special(type, type->tp_base);
3206
Tim Peters6d6c1a32001-08-02 04:15:00 +00003207 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003208 bases = type->tp_mro;
3209 assert(bases != NULL);
3210 assert(PyTuple_Check(bases));
3211 n = PyTuple_GET_SIZE(bases);
3212 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003213 PyObject *b = PyTuple_GET_ITEM(bases, i);
3214 if (PyType_Check(b))
3215 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003216 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003217
Tim Peters3cfe7542003-05-21 21:29:48 +00003218 /* Sanity check for tp_free. */
3219 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3220 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3221 /* This base class needs to call tp_free, but doesn't have
3222 * one, or its tp_free is for non-gc'ed objects.
3223 */
3224 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3225 "gc and is a base type but has inappropriate "
3226 "tp_free slot",
3227 type->tp_name);
3228 goto error;
3229 }
3230
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003231 /* if the type dictionary doesn't contain a __doc__, set it from
3232 the tp_doc slot.
3233 */
3234 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3235 if (type->tp_doc != NULL) {
3236 PyObject *doc = PyString_FromString(type->tp_doc);
3237 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3238 Py_DECREF(doc);
3239 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003240 PyDict_SetItemString(type->tp_dict,
3241 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003242 }
3243 }
3244
Guido van Rossum13d52f02001-08-10 21:24:08 +00003245 /* Some more special stuff */
3246 base = type->tp_base;
3247 if (base != NULL) {
3248 if (type->tp_as_number == NULL)
3249 type->tp_as_number = base->tp_as_number;
3250 if (type->tp_as_sequence == NULL)
3251 type->tp_as_sequence = base->tp_as_sequence;
3252 if (type->tp_as_mapping == NULL)
3253 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003254 if (type->tp_as_buffer == NULL)
3255 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003256 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003257
Guido van Rossum1c450732001-10-08 15:18:27 +00003258 /* Link into each base class's list of subclasses */
3259 bases = type->tp_bases;
3260 n = PyTuple_GET_SIZE(bases);
3261 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003262 PyObject *b = PyTuple_GET_ITEM(bases, i);
3263 if (PyType_Check(b) &&
3264 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003265 goto error;
3266 }
3267
Guido van Rossum13d52f02001-08-10 21:24:08 +00003268 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003269 assert(type->tp_dict != NULL);
3270 type->tp_flags =
3271 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003272 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003273
3274 error:
3275 type->tp_flags &= ~Py_TPFLAGS_READYING;
3276 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003277}
3278
Guido van Rossum1c450732001-10-08 15:18:27 +00003279static int
3280add_subclass(PyTypeObject *base, PyTypeObject *type)
3281{
3282 int i;
3283 PyObject *list, *ref, *new;
3284
3285 list = base->tp_subclasses;
3286 if (list == NULL) {
3287 base->tp_subclasses = list = PyList_New(0);
3288 if (list == NULL)
3289 return -1;
3290 }
3291 assert(PyList_Check(list));
3292 new = PyWeakref_NewRef((PyObject *)type, NULL);
3293 i = PyList_GET_SIZE(list);
3294 while (--i >= 0) {
3295 ref = PyList_GET_ITEM(list, i);
3296 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003297 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3298 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003299 }
3300 i = PyList_Append(list, new);
3301 Py_DECREF(new);
3302 return i;
3303}
3304
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003305static void
3306remove_subclass(PyTypeObject *base, PyTypeObject *type)
3307{
3308 int i;
3309 PyObject *list, *ref;
3310
3311 list = base->tp_subclasses;
3312 if (list == NULL) {
3313 return;
3314 }
3315 assert(PyList_Check(list));
3316 i = PyList_GET_SIZE(list);
3317 while (--i >= 0) {
3318 ref = PyList_GET_ITEM(list, i);
3319 assert(PyWeakref_CheckRef(ref));
3320 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3321 /* this can't fail, right? */
3322 PySequence_DelItem(list, i);
3323 return;
3324 }
3325 }
3326}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003327
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003328static int
3329check_num_args(PyObject *ob, int n)
3330{
3331 if (!PyTuple_CheckExact(ob)) {
3332 PyErr_SetString(PyExc_SystemError,
3333 "PyArg_UnpackTuple() argument list is not a tuple");
3334 return 0;
3335 }
3336 if (n == PyTuple_GET_SIZE(ob))
3337 return 1;
3338 PyErr_Format(
3339 PyExc_TypeError,
3340 "expected %d arguments, got %d", n, PyTuple_GET_SIZE(ob));
3341 return 0;
3342}
3343
Tim Peters6d6c1a32001-08-02 04:15:00 +00003344/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3345
3346/* There's a wrapper *function* for each distinct function typedef used
3347 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3348 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3349 Most tables have only one entry; the tables for binary operators have two
3350 entries, one regular and one with reversed arguments. */
3351
3352static PyObject *
3353wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3354{
3355 inquiry func = (inquiry)wrapped;
3356 int res;
3357
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003358 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003359 return NULL;
3360 res = (*func)(self);
3361 if (res == -1 && PyErr_Occurred())
3362 return NULL;
3363 return PyInt_FromLong((long)res);
3364}
3365
Tim Peters6d6c1a32001-08-02 04:15:00 +00003366static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003367wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3368{
3369 inquiry func = (inquiry)wrapped;
3370 int res;
3371
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003372 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003373 return NULL;
3374 res = (*func)(self);
3375 if (res == -1 && PyErr_Occurred())
3376 return NULL;
3377 return PyBool_FromLong((long)res);
3378}
3379
3380static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003381wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3382{
3383 binaryfunc func = (binaryfunc)wrapped;
3384 PyObject *other;
3385
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003386 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003387 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003388 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003389 return (*func)(self, other);
3390}
3391
3392static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003393wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3394{
3395 binaryfunc func = (binaryfunc)wrapped;
3396 PyObject *other;
3397
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003398 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003399 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003400 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003401 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003402 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003403 Py_INCREF(Py_NotImplemented);
3404 return Py_NotImplemented;
3405 }
3406 return (*func)(self, other);
3407}
3408
3409static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003410wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3411{
3412 binaryfunc func = (binaryfunc)wrapped;
3413 PyObject *other;
3414
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003415 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003416 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003417 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003418 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003419 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003420 Py_INCREF(Py_NotImplemented);
3421 return Py_NotImplemented;
3422 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003423 return (*func)(other, self);
3424}
3425
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003426static PyObject *
3427wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3428{
3429 coercion func = (coercion)wrapped;
3430 PyObject *other, *res;
3431 int ok;
3432
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003433 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003434 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003435 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003436 ok = func(&self, &other);
3437 if (ok < 0)
3438 return NULL;
3439 if (ok > 0) {
3440 Py_INCREF(Py_NotImplemented);
3441 return Py_NotImplemented;
3442 }
3443 res = PyTuple_New(2);
3444 if (res == NULL) {
3445 Py_DECREF(self);
3446 Py_DECREF(other);
3447 return NULL;
3448 }
3449 PyTuple_SET_ITEM(res, 0, self);
3450 PyTuple_SET_ITEM(res, 1, other);
3451 return res;
3452}
3453
Tim Peters6d6c1a32001-08-02 04:15:00 +00003454static PyObject *
3455wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3456{
3457 ternaryfunc func = (ternaryfunc)wrapped;
3458 PyObject *other;
3459 PyObject *third = Py_None;
3460
3461 /* Note: This wrapper only works for __pow__() */
3462
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003463 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003464 return NULL;
3465 return (*func)(self, other, third);
3466}
3467
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003468static PyObject *
3469wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3470{
3471 ternaryfunc func = (ternaryfunc)wrapped;
3472 PyObject *other;
3473 PyObject *third = Py_None;
3474
3475 /* Note: This wrapper only works for __pow__() */
3476
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003477 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003478 return NULL;
3479 return (*func)(other, self, third);
3480}
3481
Tim Peters6d6c1a32001-08-02 04:15:00 +00003482static PyObject *
3483wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3484{
3485 unaryfunc func = (unaryfunc)wrapped;
3486
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003487 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003488 return NULL;
3489 return (*func)(self);
3490}
3491
Tim Peters6d6c1a32001-08-02 04:15:00 +00003492static PyObject *
3493wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3494{
3495 intargfunc func = (intargfunc)wrapped;
3496 int i;
3497
3498 if (!PyArg_ParseTuple(args, "i", &i))
3499 return NULL;
3500 return (*func)(self, i);
3501}
3502
Guido van Rossum5d815f32001-08-17 21:57:47 +00003503static int
3504getindex(PyObject *self, PyObject *arg)
3505{
3506 int i;
3507
3508 i = PyInt_AsLong(arg);
3509 if (i == -1 && PyErr_Occurred())
3510 return -1;
3511 if (i < 0) {
3512 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3513 if (sq && sq->sq_length) {
3514 int n = (*sq->sq_length)(self);
3515 if (n < 0)
3516 return -1;
3517 i += n;
3518 }
3519 }
3520 return i;
3521}
3522
3523static PyObject *
3524wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3525{
3526 intargfunc func = (intargfunc)wrapped;
3527 PyObject *arg;
3528 int i;
3529
Guido van Rossumf4593e02001-10-03 12:09:30 +00003530 if (PyTuple_GET_SIZE(args) == 1) {
3531 arg = PyTuple_GET_ITEM(args, 0);
3532 i = getindex(self, arg);
3533 if (i == -1 && PyErr_Occurred())
3534 return NULL;
3535 return (*func)(self, i);
3536 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003537 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003538 assert(PyErr_Occurred());
3539 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003540}
3541
Tim Peters6d6c1a32001-08-02 04:15:00 +00003542static PyObject *
3543wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3544{
3545 intintargfunc func = (intintargfunc)wrapped;
3546 int i, j;
3547
3548 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3549 return NULL;
3550 return (*func)(self, i, j);
3551}
3552
Tim Peters6d6c1a32001-08-02 04:15:00 +00003553static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003554wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003555{
3556 intobjargproc func = (intobjargproc)wrapped;
3557 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003558 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003559
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003560 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003561 return NULL;
3562 i = getindex(self, arg);
3563 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003564 return NULL;
3565 res = (*func)(self, i, value);
3566 if (res == -1 && PyErr_Occurred())
3567 return NULL;
3568 Py_INCREF(Py_None);
3569 return Py_None;
3570}
3571
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003572static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003573wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003574{
3575 intobjargproc func = (intobjargproc)wrapped;
3576 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003577 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003578
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003579 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003580 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003581 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003582 i = getindex(self, arg);
3583 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003584 return NULL;
3585 res = (*func)(self, i, NULL);
3586 if (res == -1 && PyErr_Occurred())
3587 return NULL;
3588 Py_INCREF(Py_None);
3589 return Py_None;
3590}
3591
Tim Peters6d6c1a32001-08-02 04:15:00 +00003592static PyObject *
3593wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3594{
3595 intintobjargproc func = (intintobjargproc)wrapped;
3596 int i, j, res;
3597 PyObject *value;
3598
3599 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3600 return NULL;
3601 res = (*func)(self, i, j, value);
3602 if (res == -1 && PyErr_Occurred())
3603 return NULL;
3604 Py_INCREF(Py_None);
3605 return Py_None;
3606}
3607
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003608static PyObject *
3609wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3610{
3611 intintobjargproc func = (intintobjargproc)wrapped;
3612 int i, j, res;
3613
3614 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3615 return NULL;
3616 res = (*func)(self, i, j, NULL);
3617 if (res == -1 && PyErr_Occurred())
3618 return NULL;
3619 Py_INCREF(Py_None);
3620 return Py_None;
3621}
3622
Tim Peters6d6c1a32001-08-02 04:15:00 +00003623/* XXX objobjproc is a misnomer; should be objargpred */
3624static PyObject *
3625wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3626{
3627 objobjproc func = (objobjproc)wrapped;
3628 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003629 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003630
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003631 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003632 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003633 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003634 res = (*func)(self, value);
3635 if (res == -1 && PyErr_Occurred())
3636 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003637 else
3638 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003639}
3640
Tim Peters6d6c1a32001-08-02 04:15:00 +00003641static PyObject *
3642wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3643{
3644 objobjargproc func = (objobjargproc)wrapped;
3645 int res;
3646 PyObject *key, *value;
3647
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003648 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003649 return NULL;
3650 res = (*func)(self, key, value);
3651 if (res == -1 && PyErr_Occurred())
3652 return NULL;
3653 Py_INCREF(Py_None);
3654 return Py_None;
3655}
3656
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003657static PyObject *
3658wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3659{
3660 objobjargproc func = (objobjargproc)wrapped;
3661 int res;
3662 PyObject *key;
3663
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003664 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003665 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003666 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003667 res = (*func)(self, key, NULL);
3668 if (res == -1 && PyErr_Occurred())
3669 return NULL;
3670 Py_INCREF(Py_None);
3671 return Py_None;
3672}
3673
Tim Peters6d6c1a32001-08-02 04:15:00 +00003674static PyObject *
3675wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3676{
3677 cmpfunc func = (cmpfunc)wrapped;
3678 int res;
3679 PyObject *other;
3680
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003681 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003682 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003683 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003684 if (other->ob_type->tp_compare != func &&
3685 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003686 PyErr_Format(
3687 PyExc_TypeError,
3688 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3689 self->ob_type->tp_name,
3690 self->ob_type->tp_name,
3691 other->ob_type->tp_name);
3692 return NULL;
3693 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003694 res = (*func)(self, other);
3695 if (PyErr_Occurred())
3696 return NULL;
3697 return PyInt_FromLong((long)res);
3698}
3699
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003700/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003701 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003702static int
3703hackcheck(PyObject *self, setattrofunc func, char *what)
3704{
3705 PyTypeObject *type = self->ob_type;
3706 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3707 type = type->tp_base;
3708 if (type->tp_setattro != func) {
3709 PyErr_Format(PyExc_TypeError,
3710 "can't apply this %s to %s object",
3711 what,
3712 type->tp_name);
3713 return 0;
3714 }
3715 return 1;
3716}
3717
Tim Peters6d6c1a32001-08-02 04:15:00 +00003718static PyObject *
3719wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3720{
3721 setattrofunc func = (setattrofunc)wrapped;
3722 int res;
3723 PyObject *name, *value;
3724
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003725 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003726 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003727 if (!hackcheck(self, func, "__setattr__"))
3728 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003729 res = (*func)(self, name, value);
3730 if (res < 0)
3731 return NULL;
3732 Py_INCREF(Py_None);
3733 return Py_None;
3734}
3735
3736static PyObject *
3737wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3738{
3739 setattrofunc func = (setattrofunc)wrapped;
3740 int res;
3741 PyObject *name;
3742
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003743 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003744 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003745 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003746 if (!hackcheck(self, func, "__delattr__"))
3747 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003748 res = (*func)(self, name, NULL);
3749 if (res < 0)
3750 return NULL;
3751 Py_INCREF(Py_None);
3752 return Py_None;
3753}
3754
Tim Peters6d6c1a32001-08-02 04:15:00 +00003755static PyObject *
3756wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3757{
3758 hashfunc func = (hashfunc)wrapped;
3759 long res;
3760
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003761 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003762 return NULL;
3763 res = (*func)(self);
3764 if (res == -1 && PyErr_Occurred())
3765 return NULL;
3766 return PyInt_FromLong(res);
3767}
3768
Tim Peters6d6c1a32001-08-02 04:15:00 +00003769static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003770wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003771{
3772 ternaryfunc func = (ternaryfunc)wrapped;
3773
Guido van Rossumc8e56452001-10-22 00:43:43 +00003774 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003775}
3776
Tim Peters6d6c1a32001-08-02 04:15:00 +00003777static PyObject *
3778wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3779{
3780 richcmpfunc func = (richcmpfunc)wrapped;
3781 PyObject *other;
3782
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003783 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003784 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003785 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003786 return (*func)(self, other, op);
3787}
3788
3789#undef RICHCMP_WRAPPER
3790#define RICHCMP_WRAPPER(NAME, OP) \
3791static PyObject * \
3792richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3793{ \
3794 return wrap_richcmpfunc(self, args, wrapped, OP); \
3795}
3796
Jack Jansen8e938b42001-08-08 15:29:49 +00003797RICHCMP_WRAPPER(lt, Py_LT)
3798RICHCMP_WRAPPER(le, Py_LE)
3799RICHCMP_WRAPPER(eq, Py_EQ)
3800RICHCMP_WRAPPER(ne, Py_NE)
3801RICHCMP_WRAPPER(gt, Py_GT)
3802RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003803
Tim Peters6d6c1a32001-08-02 04:15:00 +00003804static PyObject *
3805wrap_next(PyObject *self, PyObject *args, void *wrapped)
3806{
3807 unaryfunc func = (unaryfunc)wrapped;
3808 PyObject *res;
3809
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003810 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003811 return NULL;
3812 res = (*func)(self);
3813 if (res == NULL && !PyErr_Occurred())
3814 PyErr_SetNone(PyExc_StopIteration);
3815 return res;
3816}
3817
Tim Peters6d6c1a32001-08-02 04:15:00 +00003818static PyObject *
3819wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3820{
3821 descrgetfunc func = (descrgetfunc)wrapped;
3822 PyObject *obj;
3823 PyObject *type = NULL;
3824
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003825 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003826 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003827 if (obj == Py_None)
3828 obj = NULL;
3829 if (type == Py_None)
3830 type = NULL;
3831 if (type == NULL &&obj == NULL) {
3832 PyErr_SetString(PyExc_TypeError,
3833 "__get__(None, None) is invalid");
3834 return NULL;
3835 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003836 return (*func)(self, obj, type);
3837}
3838
Tim Peters6d6c1a32001-08-02 04:15:00 +00003839static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003840wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003841{
3842 descrsetfunc func = (descrsetfunc)wrapped;
3843 PyObject *obj, *value;
3844 int ret;
3845
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003846 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003847 return NULL;
3848 ret = (*func)(self, obj, value);
3849 if (ret < 0)
3850 return NULL;
3851 Py_INCREF(Py_None);
3852 return Py_None;
3853}
Guido van Rossum22b13872002-08-06 21:41:44 +00003854
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003855static PyObject *
3856wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3857{
3858 descrsetfunc func = (descrsetfunc)wrapped;
3859 PyObject *obj;
3860 int ret;
3861
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003862 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003863 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003864 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003865 ret = (*func)(self, obj, NULL);
3866 if (ret < 0)
3867 return NULL;
3868 Py_INCREF(Py_None);
3869 return Py_None;
3870}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003871
Tim Peters6d6c1a32001-08-02 04:15:00 +00003872static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003873wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003874{
3875 initproc func = (initproc)wrapped;
3876
Guido van Rossumc8e56452001-10-22 00:43:43 +00003877 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003878 return NULL;
3879 Py_INCREF(Py_None);
3880 return Py_None;
3881}
3882
Tim Peters6d6c1a32001-08-02 04:15:00 +00003883static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003884tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003885{
Barry Warsaw60f01882001-08-22 19:24:42 +00003886 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003887 PyObject *arg0, *res;
3888
3889 if (self == NULL || !PyType_Check(self))
3890 Py_FatalError("__new__() called with non-type 'self'");
3891 type = (PyTypeObject *)self;
3892 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003893 PyErr_Format(PyExc_TypeError,
3894 "%s.__new__(): not enough arguments",
3895 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003896 return NULL;
3897 }
3898 arg0 = PyTuple_GET_ITEM(args, 0);
3899 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003900 PyErr_Format(PyExc_TypeError,
3901 "%s.__new__(X): X is not a type object (%s)",
3902 type->tp_name,
3903 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003904 return NULL;
3905 }
3906 subtype = (PyTypeObject *)arg0;
3907 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003908 PyErr_Format(PyExc_TypeError,
3909 "%s.__new__(%s): %s is not a subtype of %s",
3910 type->tp_name,
3911 subtype->tp_name,
3912 subtype->tp_name,
3913 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003914 return NULL;
3915 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003916
3917 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003918 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003919 most derived base that's not a heap type is this type. */
3920 staticbase = subtype;
3921 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3922 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003923 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003924 PyErr_Format(PyExc_TypeError,
3925 "%s.__new__(%s) is not safe, use %s.__new__()",
3926 type->tp_name,
3927 subtype->tp_name,
3928 staticbase == NULL ? "?" : staticbase->tp_name);
3929 return NULL;
3930 }
3931
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003932 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3933 if (args == NULL)
3934 return NULL;
3935 res = type->tp_new(subtype, args, kwds);
3936 Py_DECREF(args);
3937 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003938}
3939
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003940static struct PyMethodDef tp_new_methoddef[] = {
3941 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003942 PyDoc_STR("T.__new__(S, ...) -> "
3943 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003944 {0}
3945};
3946
3947static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003948add_tp_new_wrapper(PyTypeObject *type)
3949{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003950 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003951
Guido van Rossum687ae002001-10-15 22:03:32 +00003952 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003953 return 0;
3954 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003955 if (func == NULL)
3956 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00003957 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00003958 Py_DECREF(func);
3959 return -1;
3960 }
3961 Py_DECREF(func);
3962 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003963}
3964
Guido van Rossumf040ede2001-08-07 16:40:56 +00003965/* Slot wrappers that call the corresponding __foo__ slot. See comments
3966 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003967
Guido van Rossumdc91b992001-08-08 22:26:22 +00003968#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003969static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003970FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003971{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003972 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003973 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003974}
3975
Guido van Rossumdc91b992001-08-08 22:26:22 +00003976#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003977static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003978FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003979{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003980 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003981 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003982}
3983
Guido van Rossumcd118802003-01-06 22:57:47 +00003984/* Boolean helper for SLOT1BINFULL().
3985 right.__class__ is a nontrivial subclass of left.__class__. */
3986static int
3987method_is_overloaded(PyObject *left, PyObject *right, char *name)
3988{
3989 PyObject *a, *b;
3990 int ok;
3991
3992 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3993 if (b == NULL) {
3994 PyErr_Clear();
3995 /* If right doesn't have it, it's not overloaded */
3996 return 0;
3997 }
3998
3999 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
4000 if (a == NULL) {
4001 PyErr_Clear();
4002 Py_DECREF(b);
4003 /* If right has it but left doesn't, it's overloaded */
4004 return 1;
4005 }
4006
4007 ok = PyObject_RichCompareBool(a, b, Py_NE);
4008 Py_DECREF(a);
4009 Py_DECREF(b);
4010 if (ok < 0) {
4011 PyErr_Clear();
4012 return 0;
4013 }
4014
4015 return ok;
4016}
4017
Guido van Rossumdc91b992001-08-08 22:26:22 +00004018
4019#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004020static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004021FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004022{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004023 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004024 int do_other = self->ob_type != other->ob_type && \
4025 other->ob_type->tp_as_number != NULL && \
4026 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004027 if (self->ob_type->tp_as_number != NULL && \
4028 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
4029 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004030 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004031 PyType_IsSubtype(other->ob_type, self->ob_type) && \
4032 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004033 r = call_maybe( \
4034 other, ROPSTR, &rcache_str, "(O)", self); \
4035 if (r != Py_NotImplemented) \
4036 return r; \
4037 Py_DECREF(r); \
4038 do_other = 0; \
4039 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004040 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004041 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004042 if (r != Py_NotImplemented || \
4043 other->ob_type == self->ob_type) \
4044 return r; \
4045 Py_DECREF(r); \
4046 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004047 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004048 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004049 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004050 } \
4051 Py_INCREF(Py_NotImplemented); \
4052 return Py_NotImplemented; \
4053}
4054
4055#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4056 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4057
4058#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4059static PyObject * \
4060FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4061{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004062 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004063 return call_method(self, OPSTR, &cache_str, \
4064 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004065}
4066
4067static int
4068slot_sq_length(PyObject *self)
4069{
Guido van Rossum2730b132001-08-28 18:22:14 +00004070 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004071 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum630db602005-09-20 18:49:54 +00004072 long temp;
Guido van Rossum26111622001-10-01 16:42:49 +00004073 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004074
4075 if (res == NULL)
4076 return -1;
Guido van Rossum630db602005-09-20 18:49:54 +00004077 temp = PyInt_AsLong(res);
4078 len = (int)temp;
Guido van Rossum26111622001-10-01 16:42:49 +00004079 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00004080 if (len == -1 && PyErr_Occurred())
4081 return -1;
Guido van Rossum630db602005-09-20 18:49:54 +00004082#if SIZEOF_INT < SIZEOF_LONG
4083 /* Overflow check -- range of PyInt is more than C int */
4084 if (len != temp) {
4085 PyErr_SetString(PyExc_OverflowError,
4086 "__len__() should return 0 <= outcome < 2**31");
4087 return -1;
4088 }
4089#endif
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004090 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00004091 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004092 "__len__() should return >= 0");
4093 return -1;
4094 }
Guido van Rossum26111622001-10-01 16:42:49 +00004095 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004096}
4097
Guido van Rossumdc91b992001-08-08 22:26:22 +00004098SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
4099SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00004100
4101/* Super-optimized version of slot_sq_item.
4102 Other slots could do the same... */
4103static PyObject *
4104slot_sq_item(PyObject *self, int i)
4105{
4106 static PyObject *getitem_str;
4107 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4108 descrgetfunc f;
4109
4110 if (getitem_str == NULL) {
4111 getitem_str = PyString_InternFromString("__getitem__");
4112 if (getitem_str == NULL)
4113 return NULL;
4114 }
4115 func = _PyType_Lookup(self->ob_type, getitem_str);
4116 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004117 if ((f = func->ob_type->tp_descr_get) == NULL)
4118 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004119 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004120 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004121 if (func == NULL) {
4122 return NULL;
4123 }
4124 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00004125 ival = PyInt_FromLong(i);
4126 if (ival != NULL) {
4127 args = PyTuple_New(1);
4128 if (args != NULL) {
4129 PyTuple_SET_ITEM(args, 0, ival);
4130 retval = PyObject_Call(func, args, NULL);
4131 Py_XDECREF(args);
4132 Py_XDECREF(func);
4133 return retval;
4134 }
4135 }
4136 }
4137 else {
4138 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4139 }
4140 Py_XDECREF(args);
4141 Py_XDECREF(ival);
4142 Py_XDECREF(func);
4143 return NULL;
4144}
4145
Guido van Rossumdc91b992001-08-08 22:26:22 +00004146SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004147
4148static int
4149slot_sq_ass_item(PyObject *self, int index, PyObject *value)
4150{
4151 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004152 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004153
4154 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004155 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004156 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004157 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004158 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004159 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004160 if (res == NULL)
4161 return -1;
4162 Py_DECREF(res);
4163 return 0;
4164}
4165
4166static int
4167slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
4168{
4169 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004170 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004171
4172 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004173 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004174 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004175 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004176 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004177 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004178 if (res == NULL)
4179 return -1;
4180 Py_DECREF(res);
4181 return 0;
4182}
4183
4184static int
4185slot_sq_contains(PyObject *self, PyObject *value)
4186{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004187 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004188 int result = -1;
4189
Guido van Rossum60718732001-08-28 17:47:51 +00004190 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004191
Guido van Rossum55f20992001-10-01 17:18:22 +00004192 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004193 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004194 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004195 if (args == NULL)
4196 res = NULL;
4197 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004198 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004199 Py_DECREF(args);
4200 }
4201 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004202 if (res != NULL) {
4203 result = PyObject_IsTrue(res);
4204 Py_DECREF(res);
4205 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004206 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004207 else if (! PyErr_Occurred()) {
4208 result = _PySequence_IterSearch(self, value,
4209 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004210 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004211 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004212}
4213
Guido van Rossumdc91b992001-08-08 22:26:22 +00004214SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
4215SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004216
4217#define slot_mp_length slot_sq_length
4218
Guido van Rossumdc91b992001-08-08 22:26:22 +00004219SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004220
4221static int
4222slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4223{
4224 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004225 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004226
4227 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004228 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004229 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004230 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004231 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004232 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004233 if (res == NULL)
4234 return -1;
4235 Py_DECREF(res);
4236 return 0;
4237}
4238
Guido van Rossumdc91b992001-08-08 22:26:22 +00004239SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4240SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4241SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4242SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4243SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4244SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4245
Jeremy Hylton938ace62002-07-17 16:30:39 +00004246static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004247
4248SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4249 nb_power, "__pow__", "__rpow__")
4250
4251static PyObject *
4252slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4253{
Guido van Rossum2730b132001-08-28 18:22:14 +00004254 static PyObject *pow_str;
4255
Guido van Rossumdc91b992001-08-08 22:26:22 +00004256 if (modulus == Py_None)
4257 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004258 /* Three-arg power doesn't use __rpow__. But ternary_op
4259 can call this when the second argument's type uses
4260 slot_nb_power, so check before calling self.__pow__. */
4261 if (self->ob_type->tp_as_number != NULL &&
4262 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4263 return call_method(self, "__pow__", &pow_str,
4264 "(OO)", other, modulus);
4265 }
4266 Py_INCREF(Py_NotImplemented);
4267 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004268}
4269
4270SLOT0(slot_nb_negative, "__neg__")
4271SLOT0(slot_nb_positive, "__pos__")
4272SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004273
4274static int
4275slot_nb_nonzero(PyObject *self)
4276{
Tim Petersea7f75d2002-12-07 21:39:16 +00004277 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004278 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004279 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004280
Guido van Rossum55f20992001-10-01 17:18:22 +00004281 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004282 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004283 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004284 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004285 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004286 if (func == NULL)
4287 return PyErr_Occurred() ? -1 : 1;
4288 }
4289 args = PyTuple_New(0);
4290 if (args != NULL) {
4291 PyObject *temp = PyObject_Call(func, args, NULL);
4292 Py_DECREF(args);
4293 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004294 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004295 result = PyObject_IsTrue(temp);
4296 else {
4297 PyErr_Format(PyExc_TypeError,
4298 "__nonzero__ should return "
4299 "bool or int, returned %s",
4300 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004301 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004302 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004303 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004304 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004305 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004306 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004307 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004308}
4309
Guido van Rossumdc91b992001-08-08 22:26:22 +00004310SLOT0(slot_nb_invert, "__invert__")
4311SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4312SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4313SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4314SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4315SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004316
4317static int
4318slot_nb_coerce(PyObject **a, PyObject **b)
4319{
4320 static PyObject *coerce_str;
4321 PyObject *self = *a, *other = *b;
4322
4323 if (self->ob_type->tp_as_number != NULL &&
4324 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4325 PyObject *r;
4326 r = call_maybe(
4327 self, "__coerce__", &coerce_str, "(O)", other);
4328 if (r == NULL)
4329 return -1;
4330 if (r == Py_NotImplemented) {
4331 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004332 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004333 else {
4334 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4335 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004336 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004337 Py_DECREF(r);
4338 return -1;
4339 }
4340 *a = PyTuple_GET_ITEM(r, 0);
4341 Py_INCREF(*a);
4342 *b = PyTuple_GET_ITEM(r, 1);
4343 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004344 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004345 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004346 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004347 }
4348 if (other->ob_type->tp_as_number != NULL &&
4349 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4350 PyObject *r;
4351 r = call_maybe(
4352 other, "__coerce__", &coerce_str, "(O)", self);
4353 if (r == NULL)
4354 return -1;
4355 if (r == Py_NotImplemented) {
4356 Py_DECREF(r);
4357 return 1;
4358 }
4359 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4360 PyErr_SetString(PyExc_TypeError,
4361 "__coerce__ didn't return a 2-tuple");
4362 Py_DECREF(r);
4363 return -1;
4364 }
4365 *a = PyTuple_GET_ITEM(r, 1);
4366 Py_INCREF(*a);
4367 *b = PyTuple_GET_ITEM(r, 0);
4368 Py_INCREF(*b);
4369 Py_DECREF(r);
4370 return 0;
4371 }
4372 return 1;
4373}
4374
Guido van Rossumdc91b992001-08-08 22:26:22 +00004375SLOT0(slot_nb_int, "__int__")
4376SLOT0(slot_nb_long, "__long__")
4377SLOT0(slot_nb_float, "__float__")
4378SLOT0(slot_nb_oct, "__oct__")
4379SLOT0(slot_nb_hex, "__hex__")
4380SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4381SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4382SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4383SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4384SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004385SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004386SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4387SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4388SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4389SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4390SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4391SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4392 "__floordiv__", "__rfloordiv__")
4393SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4394SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4395SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004396
4397static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004398half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004399{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004400 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004401 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004402 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004403
Guido van Rossum60718732001-08-28 17:47:51 +00004404 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004405 if (func == NULL) {
4406 PyErr_Clear();
4407 }
4408 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004409 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004410 if (args == NULL)
4411 res = NULL;
4412 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004413 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004414 Py_DECREF(args);
4415 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004416 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004417 if (res != Py_NotImplemented) {
4418 if (res == NULL)
4419 return -2;
4420 c = PyInt_AsLong(res);
4421 Py_DECREF(res);
4422 if (c == -1 && PyErr_Occurred())
4423 return -2;
4424 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4425 }
4426 Py_DECREF(res);
4427 }
4428 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004429}
4430
Guido van Rossumab3b0342001-09-18 20:38:53 +00004431/* This slot is published for the benefit of try_3way_compare in object.c */
4432int
4433_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004434{
4435 int c;
4436
Guido van Rossumab3b0342001-09-18 20:38:53 +00004437 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004438 c = half_compare(self, other);
4439 if (c <= 1)
4440 return c;
4441 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004442 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004443 c = half_compare(other, self);
4444 if (c < -1)
4445 return -2;
4446 if (c <= 1)
4447 return -c;
4448 }
4449 return (void *)self < (void *)other ? -1 :
4450 (void *)self > (void *)other ? 1 : 0;
4451}
4452
4453static PyObject *
4454slot_tp_repr(PyObject *self)
4455{
4456 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004457 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004458
Guido van Rossum60718732001-08-28 17:47:51 +00004459 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004460 if (func != NULL) {
4461 res = PyEval_CallObject(func, NULL);
4462 Py_DECREF(func);
4463 return res;
4464 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004465 PyErr_Clear();
4466 return PyString_FromFormat("<%s object at %p>",
4467 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004468}
4469
4470static PyObject *
4471slot_tp_str(PyObject *self)
4472{
4473 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004474 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004475
Guido van Rossum60718732001-08-28 17:47:51 +00004476 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004477 if (func != NULL) {
4478 res = PyEval_CallObject(func, NULL);
4479 Py_DECREF(func);
4480 return res;
4481 }
4482 else {
4483 PyErr_Clear();
4484 return slot_tp_repr(self);
4485 }
4486}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004487
4488static long
4489slot_tp_hash(PyObject *self)
4490{
Tim Peters61ce0a92002-12-06 23:38:02 +00004491 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004492 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004493 long h;
4494
Guido van Rossum60718732001-08-28 17:47:51 +00004495 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004496
4497 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004498 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004499 Py_DECREF(func);
4500 if (res == NULL)
4501 return -1;
4502 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004503 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004504 }
4505 else {
4506 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004507 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004508 if (func == NULL) {
4509 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004510 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004511 }
4512 if (func != NULL) {
4513 Py_DECREF(func);
4514 PyErr_SetString(PyExc_TypeError, "unhashable type");
4515 return -1;
4516 }
4517 PyErr_Clear();
4518 h = _Py_HashPointer((void *)self);
4519 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004520 if (h == -1 && !PyErr_Occurred())
4521 h = -2;
4522 return h;
4523}
4524
4525static PyObject *
4526slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4527{
Guido van Rossum60718732001-08-28 17:47:51 +00004528 static PyObject *call_str;
4529 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004530 PyObject *res;
4531
4532 if (meth == NULL)
4533 return NULL;
4534 res = PyObject_Call(meth, args, kwds);
4535 Py_DECREF(meth);
4536 return res;
4537}
4538
Guido van Rossum14a6f832001-10-17 13:59:09 +00004539/* There are two slot dispatch functions for tp_getattro.
4540
4541 - slot_tp_getattro() is used when __getattribute__ is overridden
4542 but no __getattr__ hook is present;
4543
4544 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4545
Guido van Rossumc334df52002-04-04 23:44:47 +00004546 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4547 detects the absence of __getattr__ and then installs the simpler slot if
4548 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004549
Tim Peters6d6c1a32001-08-02 04:15:00 +00004550static PyObject *
4551slot_tp_getattro(PyObject *self, PyObject *name)
4552{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004553 static PyObject *getattribute_str = NULL;
4554 return call_method(self, "__getattribute__", &getattribute_str,
4555 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004556}
4557
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004558static PyObject *
4559slot_tp_getattr_hook(PyObject *self, PyObject *name)
4560{
4561 PyTypeObject *tp = self->ob_type;
4562 PyObject *getattr, *getattribute, *res;
4563 static PyObject *getattribute_str = NULL;
4564 static PyObject *getattr_str = NULL;
4565
4566 if (getattr_str == NULL) {
4567 getattr_str = PyString_InternFromString("__getattr__");
4568 if (getattr_str == NULL)
4569 return NULL;
4570 }
4571 if (getattribute_str == NULL) {
4572 getattribute_str =
4573 PyString_InternFromString("__getattribute__");
4574 if (getattribute_str == NULL)
4575 return NULL;
4576 }
4577 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004578 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004579 /* No __getattr__ hook: use a simpler dispatcher */
4580 tp->tp_getattro = slot_tp_getattro;
4581 return slot_tp_getattro(self, name);
4582 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004583 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004584 if (getattribute == NULL ||
4585 (getattribute->ob_type == &PyWrapperDescr_Type &&
4586 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4587 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004588 res = PyObject_GenericGetAttr(self, name);
4589 else
4590 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004591 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004592 PyErr_Clear();
4593 res = PyObject_CallFunction(getattr, "OO", self, name);
4594 }
4595 return res;
4596}
4597
Tim Peters6d6c1a32001-08-02 04:15:00 +00004598static int
4599slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4600{
4601 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004602 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004603
4604 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004605 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004606 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004607 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004608 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004609 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004610 if (res == NULL)
4611 return -1;
4612 Py_DECREF(res);
4613 return 0;
4614}
4615
4616/* Map rich comparison operators to their __xx__ namesakes */
4617static char *name_op[] = {
4618 "__lt__",
4619 "__le__",
4620 "__eq__",
4621 "__ne__",
4622 "__gt__",
4623 "__ge__",
4624};
4625
4626static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004627half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004628{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004629 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004630 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004631
Guido van Rossum60718732001-08-28 17:47:51 +00004632 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004633 if (func == NULL) {
4634 PyErr_Clear();
4635 Py_INCREF(Py_NotImplemented);
4636 return Py_NotImplemented;
4637 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004638 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004639 if (args == NULL)
4640 res = NULL;
4641 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004642 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004643 Py_DECREF(args);
4644 }
4645 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004646 return res;
4647}
4648
Guido van Rossumb8f63662001-08-15 23:57:02 +00004649static PyObject *
4650slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4651{
4652 PyObject *res;
4653
4654 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4655 res = half_richcompare(self, other, op);
4656 if (res != Py_NotImplemented)
4657 return res;
4658 Py_DECREF(res);
4659 }
4660 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004661 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004662 if (res != Py_NotImplemented) {
4663 return res;
4664 }
4665 Py_DECREF(res);
4666 }
4667 Py_INCREF(Py_NotImplemented);
4668 return Py_NotImplemented;
4669}
4670
4671static PyObject *
4672slot_tp_iter(PyObject *self)
4673{
4674 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004675 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004676
Guido van Rossum60718732001-08-28 17:47:51 +00004677 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004678 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004679 PyObject *args;
4680 args = res = PyTuple_New(0);
4681 if (args != NULL) {
4682 res = PyObject_Call(func, args, NULL);
4683 Py_DECREF(args);
4684 }
4685 Py_DECREF(func);
4686 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004687 }
4688 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004689 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004690 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004691 PyErr_SetString(PyExc_TypeError,
4692 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004693 return NULL;
4694 }
4695 Py_DECREF(func);
4696 return PySeqIter_New(self);
4697}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004698
4699static PyObject *
4700slot_tp_iternext(PyObject *self)
4701{
Guido van Rossum2730b132001-08-28 18:22:14 +00004702 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004703 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004704}
4705
Guido van Rossum1a493502001-08-17 16:47:50 +00004706static PyObject *
4707slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4708{
4709 PyTypeObject *tp = self->ob_type;
4710 PyObject *get;
4711 static PyObject *get_str = NULL;
4712
4713 if (get_str == NULL) {
4714 get_str = PyString_InternFromString("__get__");
4715 if (get_str == NULL)
4716 return NULL;
4717 }
4718 get = _PyType_Lookup(tp, get_str);
4719 if (get == NULL) {
4720 /* Avoid further slowdowns */
4721 if (tp->tp_descr_get == slot_tp_descr_get)
4722 tp->tp_descr_get = NULL;
4723 Py_INCREF(self);
4724 return self;
4725 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004726 if (obj == NULL)
4727 obj = Py_None;
4728 if (type == NULL)
4729 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004730 return PyObject_CallFunction(get, "OOO", self, obj, type);
4731}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004732
4733static int
4734slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4735{
Guido van Rossum2c252392001-08-24 10:13:31 +00004736 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004737 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004738
4739 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004740 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004741 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004742 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004743 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004744 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004745 if (res == NULL)
4746 return -1;
4747 Py_DECREF(res);
4748 return 0;
4749}
4750
4751static int
4752slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4753{
Guido van Rossum60718732001-08-28 17:47:51 +00004754 static PyObject *init_str;
4755 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004756 PyObject *res;
4757
4758 if (meth == NULL)
4759 return -1;
4760 res = PyObject_Call(meth, args, kwds);
4761 Py_DECREF(meth);
4762 if (res == NULL)
4763 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004764 if (res != Py_None) {
4765 PyErr_SetString(PyExc_TypeError,
4766 "__init__() should return None");
4767 Py_DECREF(res);
4768 return -1;
4769 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004770 Py_DECREF(res);
4771 return 0;
4772}
4773
4774static PyObject *
4775slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4776{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004777 static PyObject *new_str;
4778 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004779 PyObject *newargs, *x;
4780 int i, n;
4781
Guido van Rossum7bed2132002-08-08 21:57:53 +00004782 if (new_str == NULL) {
4783 new_str = PyString_InternFromString("__new__");
4784 if (new_str == NULL)
4785 return NULL;
4786 }
4787 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004788 if (func == NULL)
4789 return NULL;
4790 assert(PyTuple_Check(args));
4791 n = PyTuple_GET_SIZE(args);
4792 newargs = PyTuple_New(n+1);
4793 if (newargs == NULL)
4794 return NULL;
4795 Py_INCREF(type);
4796 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4797 for (i = 0; i < n; i++) {
4798 x = PyTuple_GET_ITEM(args, i);
4799 Py_INCREF(x);
4800 PyTuple_SET_ITEM(newargs, i+1, x);
4801 }
4802 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004803 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004804 Py_DECREF(func);
4805 return x;
4806}
4807
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004808static void
4809slot_tp_del(PyObject *self)
4810{
4811 static PyObject *del_str = NULL;
4812 PyObject *del, *res;
4813 PyObject *error_type, *error_value, *error_traceback;
4814
4815 /* Temporarily resurrect the object. */
4816 assert(self->ob_refcnt == 0);
4817 self->ob_refcnt = 1;
4818
4819 /* Save the current exception, if any. */
4820 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4821
4822 /* Execute __del__ method, if any. */
4823 del = lookup_maybe(self, "__del__", &del_str);
4824 if (del != NULL) {
4825 res = PyEval_CallObject(del, NULL);
4826 if (res == NULL)
4827 PyErr_WriteUnraisable(del);
4828 else
4829 Py_DECREF(res);
4830 Py_DECREF(del);
4831 }
4832
4833 /* Restore the saved exception. */
4834 PyErr_Restore(error_type, error_value, error_traceback);
4835
4836 /* Undo the temporary resurrection; can't use DECREF here, it would
4837 * cause a recursive call.
4838 */
4839 assert(self->ob_refcnt > 0);
4840 if (--self->ob_refcnt == 0)
4841 return; /* this is the normal path out */
4842
4843 /* __del__ resurrected it! Make it look like the original Py_DECREF
4844 * never happened.
4845 */
4846 {
4847 int refcnt = self->ob_refcnt;
4848 _Py_NewReference(self);
4849 self->ob_refcnt = refcnt;
4850 }
4851 assert(!PyType_IS_GC(self->ob_type) ||
4852 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00004853 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
4854 * we need to undo that. */
4855 _Py_DEC_REFTOTAL;
4856 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4857 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004858 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4859 * _Py_NewReference bumped tp_allocs: both of those need to be
4860 * undone.
4861 */
4862#ifdef COUNT_ALLOCS
4863 --self->ob_type->tp_frees;
4864 --self->ob_type->tp_allocs;
4865#endif
4866}
4867
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004868
4869/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004870 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004871 structure, which incorporates the additional structures used for numbers,
4872 sequences and mappings.
4873 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004874 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004875 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4876 terminated with an all-zero entry. (This table is further initialized and
4877 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004878
Guido van Rossum6d204072001-10-21 00:44:31 +00004879typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004880
4881#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004882#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004883#undef ETSLOT
4884#undef SQSLOT
4885#undef MPSLOT
4886#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004887#undef UNSLOT
4888#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004889#undef BINSLOT
4890#undef RBINSLOT
4891
Guido van Rossum6d204072001-10-21 00:44:31 +00004892#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004893 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4894 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004895#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4896 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004897 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004898#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004899 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004900 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004901#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4902 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4903#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4904 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4905#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4906 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4907#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4908 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4909 "x." NAME "() <==> " DOC)
4910#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4911 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4912 "x." NAME "(y) <==> x" DOC "y")
4913#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4914 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4915 "x." NAME "(y) <==> x" DOC "y")
4916#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4917 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4918 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00004919#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
4920 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4921 "x." NAME "(y) <==> " DOC)
4922#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
4923 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4924 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004925
4926static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004927 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4928 "x.__len__() <==> len(x)"),
4929 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4930 "x.__add__(y) <==> x+y"),
4931 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4932 "x.__mul__(n) <==> x*n"),
4933 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4934 "x.__rmul__(n) <==> n*x"),
4935 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4936 "x.__getitem__(y) <==> x[y]"),
4937 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00004938 "x.__getslice__(i, j) <==> x[i:j]\n\
4939 \n\
4940 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004941 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004942 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004943 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004944 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004945 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004946 wrap_intintobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00004947 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
4948 \n\
4949 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004950 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00004951 "x.__delslice__(i, j) <==> del x[i:j]\n\
4952 \n\
4953 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004954 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4955 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004956 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004957 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004958 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004959 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004960
Guido van Rossum6d204072001-10-21 00:44:31 +00004961 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4962 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004963 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004964 wrap_binaryfunc,
4965 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004966 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004967 wrap_objobjargproc,
4968 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004969 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004970 wrap_delitem,
4971 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004972
Guido van Rossum6d204072001-10-21 00:44:31 +00004973 BINSLOT("__add__", nb_add, slot_nb_add,
4974 "+"),
4975 RBINSLOT("__radd__", nb_add, slot_nb_add,
4976 "+"),
4977 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4978 "-"),
4979 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4980 "-"),
4981 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4982 "*"),
4983 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4984 "*"),
4985 BINSLOT("__div__", nb_divide, slot_nb_divide,
4986 "/"),
4987 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4988 "/"),
4989 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4990 "%"),
4991 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4992 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00004993 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00004994 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00004995 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00004996 "divmod(y, x)"),
4997 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4998 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4999 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5000 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5001 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5002 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5003 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5004 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005005 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005006 "x != 0"),
5007 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5008 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5009 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5010 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5011 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5012 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5013 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5014 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5015 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5016 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5017 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5018 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5019 "x.__coerce__(y) <==> coerce(x, y)"),
5020 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5021 "int(x)"),
5022 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5023 "long(x)"),
5024 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5025 "float(x)"),
5026 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5027 "oct(x)"),
5028 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5029 "hex(x)"),
5030 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5031 wrap_binaryfunc, "+"),
5032 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5033 wrap_binaryfunc, "-"),
5034 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5035 wrap_binaryfunc, "*"),
5036 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5037 wrap_binaryfunc, "/"),
5038 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5039 wrap_binaryfunc, "%"),
5040 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005041 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005042 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5043 wrap_binaryfunc, "<<"),
5044 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5045 wrap_binaryfunc, ">>"),
5046 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5047 wrap_binaryfunc, "&"),
5048 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5049 wrap_binaryfunc, "^"),
5050 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5051 wrap_binaryfunc, "|"),
5052 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5053 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5054 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5055 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5056 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5057 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5058 IBSLOT("__itruediv__", nb_inplace_true_divide,
5059 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005060
Guido van Rossum6d204072001-10-21 00:44:31 +00005061 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5062 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005063 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005064 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5065 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005066 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005067 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5068 "x.__cmp__(y) <==> cmp(x,y)"),
5069 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5070 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005071 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5072 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005073 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005074 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5075 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5076 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5077 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5078 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5079 "x.__setattr__('name', value) <==> x.name = value"),
5080 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5081 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5082 "x.__delattr__('name') <==> del x.name"),
5083 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5084 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5085 "x.__lt__(y) <==> x<y"),
5086 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5087 "x.__le__(y) <==> x<=y"),
5088 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5089 "x.__eq__(y) <==> x==y"),
5090 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5091 "x.__ne__(y) <==> x!=y"),
5092 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5093 "x.__gt__(y) <==> x>y"),
5094 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5095 "x.__ge__(y) <==> x>=y"),
5096 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5097 "x.__iter__() <==> iter(x)"),
5098 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5099 "x.next() -> the next value, or raise StopIteration"),
5100 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5101 "descr.__get__(obj[, type]) -> value"),
5102 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5103 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005104 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5105 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005106 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005107 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005108 "see x.__class__.__doc__ for signature",
5109 PyWrapperFlag_KEYWORDS),
5110 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005111 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005112 {NULL}
5113};
5114
Guido van Rossumc334df52002-04-04 23:44:47 +00005115/* Given a type pointer and an offset gotten from a slotdef entry, return a
5116 pointer to the actual slot. This is not quite the same as simply adding
5117 the offset to the type pointer, since it takes care to indirect through the
5118 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5119 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005120static void **
5121slotptr(PyTypeObject *type, int offset)
5122{
5123 char *ptr;
5124
Guido van Rossume5c691a2003-03-07 15:13:17 +00005125 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005126 assert(offset >= 0);
Guido van Rossume5c691a2003-03-07 15:13:17 +00005127 assert(offset < offsetof(PyHeapTypeObject, as_buffer));
5128 if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005129 ptr = (void *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005130 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005131 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005132 else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Guido van Rossum09638c12002-06-13 19:17:46 +00005133 ptr = (void *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005134 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005135 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005136 else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005137 ptr = (void *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005138 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005139 }
5140 else {
5141 ptr = (void *)type;
5142 }
5143 if (ptr != NULL)
5144 ptr += offset;
5145 return (void **)ptr;
5146}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005147
Guido van Rossumc334df52002-04-04 23:44:47 +00005148/* Length of array of slotdef pointers used to store slots with the
5149 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5150 the same __name__, for any __name__. Since that's a static property, it is
5151 appropriate to declare fixed-size arrays for this. */
5152#define MAX_EQUIV 10
5153
5154/* Return a slot pointer for a given name, but ONLY if the attribute has
5155 exactly one slot function. The name must be an interned string. */
5156static void **
5157resolve_slotdups(PyTypeObject *type, PyObject *name)
5158{
5159 /* XXX Maybe this could be optimized more -- but is it worth it? */
5160
5161 /* pname and ptrs act as a little cache */
5162 static PyObject *pname;
5163 static slotdef *ptrs[MAX_EQUIV];
5164 slotdef *p, **pp;
5165 void **res, **ptr;
5166
5167 if (pname != name) {
5168 /* Collect all slotdefs that match name into ptrs. */
5169 pname = name;
5170 pp = ptrs;
5171 for (p = slotdefs; p->name_strobj; p++) {
5172 if (p->name_strobj == name)
5173 *pp++ = p;
5174 }
5175 *pp = NULL;
5176 }
5177
5178 /* Look in all matching slots of the type; if exactly one of these has
5179 a filled-in slot, return its value. Otherwise return NULL. */
5180 res = NULL;
5181 for (pp = ptrs; *pp; pp++) {
5182 ptr = slotptr(type, (*pp)->offset);
5183 if (ptr == NULL || *ptr == NULL)
5184 continue;
5185 if (res != NULL)
5186 return NULL;
5187 res = ptr;
5188 }
5189 return res;
5190}
5191
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005192/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005193 does some incredibly complex thinking and then sticks something into the
5194 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5195 interests, and then stores a generic wrapper or a specific function into
5196 the slot.) Return a pointer to the next slotdef with a different offset,
5197 because that's convenient for fixup_slot_dispatchers(). */
5198static slotdef *
5199update_one_slot(PyTypeObject *type, slotdef *p)
5200{
5201 PyObject *descr;
5202 PyWrapperDescrObject *d;
5203 void *generic = NULL, *specific = NULL;
5204 int use_generic = 0;
5205 int offset = p->offset;
5206 void **ptr = slotptr(type, offset);
5207
5208 if (ptr == NULL) {
5209 do {
5210 ++p;
5211 } while (p->offset == offset);
5212 return p;
5213 }
5214 do {
5215 descr = _PyType_Lookup(type, p->name_strobj);
5216 if (descr == NULL)
5217 continue;
5218 if (descr->ob_type == &PyWrapperDescr_Type) {
5219 void **tptr = resolve_slotdups(type, p->name_strobj);
5220 if (tptr == NULL || tptr == ptr)
5221 generic = p->function;
5222 d = (PyWrapperDescrObject *)descr;
5223 if (d->d_base->wrapper == p->wrapper &&
5224 PyType_IsSubtype(type, d->d_type))
5225 {
5226 if (specific == NULL ||
5227 specific == d->d_wrapped)
5228 specific = d->d_wrapped;
5229 else
5230 use_generic = 1;
5231 }
5232 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005233 else if (descr->ob_type == &PyCFunction_Type &&
5234 PyCFunction_GET_FUNCTION(descr) ==
5235 (PyCFunction)tp_new_wrapper &&
5236 strcmp(p->name, "__new__") == 0)
5237 {
5238 /* The __new__ wrapper is not a wrapper descriptor,
5239 so must be special-cased differently.
5240 If we don't do this, creating an instance will
5241 always use slot_tp_new which will look up
5242 __new__ in the MRO which will call tp_new_wrapper
5243 which will look through the base classes looking
5244 for a static base and call its tp_new (usually
5245 PyType_GenericNew), after performing various
5246 sanity checks and constructing a new argument
5247 list. Cut all that nonsense short -- this speeds
5248 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005249 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005250 /* XXX I'm not 100% sure that there isn't a hole
5251 in this reasoning that requires additional
5252 sanity checks. I'll buy the first person to
5253 point out a bug in this reasoning a beer. */
5254 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005255 else {
5256 use_generic = 1;
5257 generic = p->function;
5258 }
5259 } while ((++p)->offset == offset);
5260 if (specific && !use_generic)
5261 *ptr = specific;
5262 else
5263 *ptr = generic;
5264 return p;
5265}
5266
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005267/* In the type, update the slots whose slotdefs are gathered in the pp array.
5268 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005269static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005270update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005271{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005272 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005273
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005274 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005275 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005276 return 0;
5277}
5278
Guido van Rossumc334df52002-04-04 23:44:47 +00005279/* Comparison function for qsort() to compare slotdefs by their offset, and
5280 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005281static int
5282slotdef_cmp(const void *aa, const void *bb)
5283{
5284 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5285 int c = a->offset - b->offset;
5286 if (c != 0)
5287 return c;
5288 else
5289 return a - b;
5290}
5291
Guido van Rossumc334df52002-04-04 23:44:47 +00005292/* Initialize the slotdefs table by adding interned string objects for the
5293 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005294static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005295init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005296{
5297 slotdef *p;
5298 static int initialized = 0;
5299
5300 if (initialized)
5301 return;
5302 for (p = slotdefs; p->name; p++) {
5303 p->name_strobj = PyString_InternFromString(p->name);
5304 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005305 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005306 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005307 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5308 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005309 initialized = 1;
5310}
5311
Guido van Rossumc334df52002-04-04 23:44:47 +00005312/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005313static int
5314update_slot(PyTypeObject *type, PyObject *name)
5315{
Guido van Rossumc334df52002-04-04 23:44:47 +00005316 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005317 slotdef *p;
5318 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005319 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005320
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005321 init_slotdefs();
5322 pp = ptrs;
5323 for (p = slotdefs; p->name; p++) {
5324 /* XXX assume name is interned! */
5325 if (p->name_strobj == name)
5326 *pp++ = p;
5327 }
5328 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005329 for (pp = ptrs; *pp; pp++) {
5330 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005331 offset = p->offset;
5332 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005333 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005334 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005335 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005336 if (ptrs[0] == NULL)
5337 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005338 return update_subclasses(type, name,
5339 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005340}
5341
Guido van Rossumc334df52002-04-04 23:44:47 +00005342/* Store the proper functions in the slot dispatches at class (type)
5343 definition time, based upon which operations the class overrides in its
5344 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005345static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005346fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005347{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005348 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005349
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005350 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005351 for (p = slotdefs; p->name; )
5352 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005353}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005354
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005355static void
5356update_all_slots(PyTypeObject* type)
5357{
5358 slotdef *p;
5359
5360 init_slotdefs();
5361 for (p = slotdefs; p->name; p++) {
5362 /* update_slot returns int but can't actually fail */
5363 update_slot(type, p->name_strobj);
5364 }
5365}
5366
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005367/* recurse_down_subclasses() and update_subclasses() are mutually
5368 recursive functions to call a callback for all subclasses,
5369 but refraining from recursing into subclasses that define 'name'. */
5370
5371static int
5372update_subclasses(PyTypeObject *type, PyObject *name,
5373 update_callback callback, void *data)
5374{
5375 if (callback(type, data) < 0)
5376 return -1;
5377 return recurse_down_subclasses(type, name, callback, data);
5378}
5379
5380static int
5381recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5382 update_callback callback, void *data)
5383{
5384 PyTypeObject *subclass;
5385 PyObject *ref, *subclasses, *dict;
5386 int i, n;
5387
5388 subclasses = type->tp_subclasses;
5389 if (subclasses == NULL)
5390 return 0;
5391 assert(PyList_Check(subclasses));
5392 n = PyList_GET_SIZE(subclasses);
5393 for (i = 0; i < n; i++) {
5394 ref = PyList_GET_ITEM(subclasses, i);
5395 assert(PyWeakref_CheckRef(ref));
5396 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5397 assert(subclass != NULL);
5398 if ((PyObject *)subclass == Py_None)
5399 continue;
5400 assert(PyType_Check(subclass));
5401 /* Avoid recursing down into unaffected classes */
5402 dict = subclass->tp_dict;
5403 if (dict != NULL && PyDict_Check(dict) &&
5404 PyDict_GetItem(dict, name) != NULL)
5405 continue;
5406 if (update_subclasses(subclass, name, callback, data) < 0)
5407 return -1;
5408 }
5409 return 0;
5410}
5411
Guido van Rossum6d204072001-10-21 00:44:31 +00005412/* This function is called by PyType_Ready() to populate the type's
5413 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005414 function slot (like tp_repr) that's defined in the type, one or more
5415 corresponding descriptors are added in the type's tp_dict dictionary
5416 under the appropriate name (like __repr__). Some function slots
5417 cause more than one descriptor to be added (for example, the nb_add
5418 slot adds both __add__ and __radd__ descriptors) and some function
5419 slots compete for the same descriptor (for example both sq_item and
5420 mp_subscript generate a __getitem__ descriptor).
5421
5422 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005423 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005424 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005425 between competing slots: the members of PyHeapTypeObject are listed
5426 from most general to least general, so the most general slot is
5427 preferred. In particular, because as_mapping comes before as_sequence,
5428 for a type that defines both mp_subscript and sq_item, mp_subscript
5429 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005430
5431 This only adds new descriptors and doesn't overwrite entries in
5432 tp_dict that were previously defined. The descriptors contain a
5433 reference to the C function they must call, so that it's safe if they
5434 are copied into a subtype's __dict__ and the subtype has a different
5435 C function in its slot -- calling the method defined by the
5436 descriptor will call the C function that was used to create it,
5437 rather than the C function present in the slot when it is called.
5438 (This is important because a subtype may have a C function in the
5439 slot that calls the method from the dictionary, and we want to avoid
5440 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005441
5442static int
5443add_operators(PyTypeObject *type)
5444{
5445 PyObject *dict = type->tp_dict;
5446 slotdef *p;
5447 PyObject *descr;
5448 void **ptr;
5449
5450 init_slotdefs();
5451 for (p = slotdefs; p->name; p++) {
5452 if (p->wrapper == NULL)
5453 continue;
5454 ptr = slotptr(type, p->offset);
5455 if (!ptr || !*ptr)
5456 continue;
5457 if (PyDict_GetItem(dict, p->name_strobj))
5458 continue;
5459 descr = PyDescr_NewWrapper(type, p, *ptr);
5460 if (descr == NULL)
5461 return -1;
5462 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5463 return -1;
5464 Py_DECREF(descr);
5465 }
5466 if (type->tp_new != NULL) {
5467 if (add_tp_new_wrapper(type) < 0)
5468 return -1;
5469 }
5470 return 0;
5471}
5472
Guido van Rossum705f0f52001-08-24 16:47:00 +00005473
5474/* Cooperative 'super' */
5475
5476typedef struct {
5477 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005478 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005479 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005480 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005481} superobject;
5482
Guido van Rossum6f799372001-09-20 20:46:19 +00005483static PyMemberDef super_members[] = {
5484 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5485 "the class invoking super()"},
5486 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5487 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005488 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005489 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005490 {0}
5491};
5492
Guido van Rossum705f0f52001-08-24 16:47:00 +00005493static void
5494super_dealloc(PyObject *self)
5495{
5496 superobject *su = (superobject *)self;
5497
Guido van Rossum048eb752001-10-02 21:24:57 +00005498 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005499 Py_XDECREF(su->obj);
5500 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005501 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005502 self->ob_type->tp_free(self);
5503}
5504
5505static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005506super_repr(PyObject *self)
5507{
5508 superobject *su = (superobject *)self;
5509
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005510 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005511 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005512 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005513 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005514 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005515 else
5516 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005517 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005518 su->type ? su->type->tp_name : "NULL");
5519}
5520
5521static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005522super_getattro(PyObject *self, PyObject *name)
5523{
5524 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005525 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005526
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005527 if (!skip) {
5528 /* We want __class__ to return the class of the super object
5529 (i.e. super, or a subclass), not the class of su->obj. */
5530 skip = (PyString_Check(name) &&
5531 PyString_GET_SIZE(name) == 9 &&
5532 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5533 }
5534
5535 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005536 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005537 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005538 descrgetfunc f;
5539 int i, n;
5540
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005541 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005542 mro = starttype->tp_mro;
5543
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005544 if (mro == NULL)
5545 n = 0;
5546 else {
5547 assert(PyTuple_Check(mro));
5548 n = PyTuple_GET_SIZE(mro);
5549 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005550 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005551 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005552 break;
5553 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005554 i++;
5555 res = NULL;
5556 for (; i < n; i++) {
5557 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005558 if (PyType_Check(tmp))
5559 dict = ((PyTypeObject *)tmp)->tp_dict;
5560 else if (PyClass_Check(tmp))
5561 dict = ((PyClassObject *)tmp)->cl_dict;
5562 else
5563 continue;
5564 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005565 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005566 Py_INCREF(res);
5567 f = res->ob_type->tp_descr_get;
5568 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005569 tmp = f(res,
5570 /* Only pass 'obj' param if
5571 this is instance-mode super
5572 (See SF ID #743627)
5573 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005574 (su->obj == (PyObject *)
5575 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005576 ? (PyObject *)NULL
5577 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005578 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005579 Py_DECREF(res);
5580 res = tmp;
5581 }
5582 return res;
5583 }
5584 }
5585 }
5586 return PyObject_GenericGetAttr(self, name);
5587}
5588
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005589static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005590supercheck(PyTypeObject *type, PyObject *obj)
5591{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005592 /* Check that a super() call makes sense. Return a type object.
5593
5594 obj can be a new-style class, or an instance of one:
5595
5596 - If it is a class, it must be a subclass of 'type'. This case is
5597 used for class methods; the return value is obj.
5598
5599 - If it is an instance, it must be an instance of 'type'. This is
5600 the normal case; the return value is obj.__class__.
5601
5602 But... when obj is an instance, we want to allow for the case where
5603 obj->ob_type is not a subclass of type, but obj.__class__ is!
5604 This will allow using super() with a proxy for obj.
5605 */
5606
Guido van Rossum8e80a722003-02-18 19:22:22 +00005607 /* Check for first bullet above (special case) */
5608 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5609 Py_INCREF(obj);
5610 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005611 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005612
5613 /* Normal case */
5614 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005615 Py_INCREF(obj->ob_type);
5616 return obj->ob_type;
5617 }
5618 else {
5619 /* Try the slow way */
5620 static PyObject *class_str = NULL;
5621 PyObject *class_attr;
5622
5623 if (class_str == NULL) {
5624 class_str = PyString_FromString("__class__");
5625 if (class_str == NULL)
5626 return NULL;
5627 }
5628
5629 class_attr = PyObject_GetAttr(obj, class_str);
5630
5631 if (class_attr != NULL &&
5632 PyType_Check(class_attr) &&
5633 (PyTypeObject *)class_attr != obj->ob_type)
5634 {
5635 int ok = PyType_IsSubtype(
5636 (PyTypeObject *)class_attr, type);
5637 if (ok)
5638 return (PyTypeObject *)class_attr;
5639 }
5640
5641 if (class_attr == NULL)
5642 PyErr_Clear();
5643 else
5644 Py_DECREF(class_attr);
5645 }
5646
Tim Peters97e5ff52003-02-18 19:32:50 +00005647 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005648 "super(type, obj): "
5649 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005650 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005651}
5652
Guido van Rossum705f0f52001-08-24 16:47:00 +00005653static PyObject *
5654super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5655{
5656 superobject *su = (superobject *)self;
5657 superobject *new;
5658
5659 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5660 /* Not binding to an object, or already bound */
5661 Py_INCREF(self);
5662 return self;
5663 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005664 if (su->ob_type != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005665 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005666 call its type */
5667 return PyObject_CallFunction((PyObject *)su->ob_type,
5668 "OO", su->type, obj);
5669 else {
5670 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005671 PyTypeObject *obj_type = supercheck(su->type, obj);
5672 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005673 return NULL;
5674 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5675 NULL, NULL);
5676 if (new == NULL)
5677 return NULL;
5678 Py_INCREF(su->type);
5679 Py_INCREF(obj);
5680 new->type = su->type;
5681 new->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005682 new->obj_type = obj_type;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005683 return (PyObject *)new;
5684 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005685}
5686
5687static int
5688super_init(PyObject *self, PyObject *args, PyObject *kwds)
5689{
5690 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005691 PyTypeObject *type;
5692 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005693 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005694
5695 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5696 return -1;
5697 if (obj == Py_None)
5698 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005699 if (obj != NULL) {
5700 obj_type = supercheck(type, obj);
5701 if (obj_type == NULL)
5702 return -1;
5703 Py_INCREF(obj);
5704 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005705 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005706 su->type = type;
5707 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005708 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005709 return 0;
5710}
5711
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005712PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005713"super(type) -> unbound super object\n"
5714"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005715"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005716"Typical use to call a cooperative superclass method:\n"
5717"class C(B):\n"
5718" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005719" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005720
Guido van Rossum048eb752001-10-02 21:24:57 +00005721static int
5722super_traverse(PyObject *self, visitproc visit, void *arg)
5723{
5724 superobject *su = (superobject *)self;
5725 int err;
5726
5727#define VISIT(SLOT) \
5728 if (SLOT) { \
5729 err = visit((PyObject *)(SLOT), arg); \
5730 if (err) \
5731 return err; \
5732 }
5733
5734 VISIT(su->obj);
5735 VISIT(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005736 VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005737
5738#undef VISIT
5739
5740 return 0;
5741}
5742
Guido van Rossum705f0f52001-08-24 16:47:00 +00005743PyTypeObject PySuper_Type = {
5744 PyObject_HEAD_INIT(&PyType_Type)
5745 0, /* ob_size */
5746 "super", /* tp_name */
5747 sizeof(superobject), /* tp_basicsize */
5748 0, /* tp_itemsize */
5749 /* methods */
5750 super_dealloc, /* tp_dealloc */
5751 0, /* tp_print */
5752 0, /* tp_getattr */
5753 0, /* tp_setattr */
5754 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005755 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005756 0, /* tp_as_number */
5757 0, /* tp_as_sequence */
5758 0, /* tp_as_mapping */
5759 0, /* tp_hash */
5760 0, /* tp_call */
5761 0, /* tp_str */
5762 super_getattro, /* tp_getattro */
5763 0, /* tp_setattro */
5764 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005765 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5766 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005767 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005768 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005769 0, /* tp_clear */
5770 0, /* tp_richcompare */
5771 0, /* tp_weaklistoffset */
5772 0, /* tp_iter */
5773 0, /* tp_iternext */
5774 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005775 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005776 0, /* tp_getset */
5777 0, /* tp_base */
5778 0, /* tp_dict */
5779 super_descr_get, /* tp_descr_get */
5780 0, /* tp_descr_set */
5781 0, /* tp_dictoffset */
5782 super_init, /* tp_init */
5783 PyType_GenericAlloc, /* tp_alloc */
5784 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005785 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005786};