blob: b403f646c434946e93c71bf840e68febc670bdcd [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
Guido van Rossum6f799372001-09-20 20:46:19 +00008static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00009 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
10 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
11 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000017 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
18 {0}
19};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000020
Guido van Rossumc0b618a1997-05-02 03:12:38 +000021static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000022type_name(PyTypeObject *type, void *context)
23{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +000024 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +000025
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000026 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +000027 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +000028
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000029 Py_INCREF(et->name);
30 return et->name;
31 }
32 else {
33 s = strrchr(type->tp_name, '.');
34 if (s == NULL)
35 s = type->tp_name;
36 else
37 s++;
38 return PyString_FromString(s);
39 }
Guido van Rossumc3542212001-08-16 09:18:56 +000040}
41
Michael W. Hudson98bbc492002-11-26 14:47:27 +000042static int
43type_set_name(PyTypeObject *type, PyObject *value, void *context)
44{
Guido van Rossume5c691a2003-03-07 15:13:17 +000045 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000046
47 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
48 PyErr_Format(PyExc_TypeError,
49 "can't set %s.__name__", type->tp_name);
50 return -1;
51 }
52 if (!value) {
53 PyErr_Format(PyExc_TypeError,
54 "can't delete %s.__name__", type->tp_name);
55 return -1;
56 }
57 if (!PyString_Check(value)) {
58 PyErr_Format(PyExc_TypeError,
59 "can only assign string to %s.__name__, not '%s'",
60 type->tp_name, value->ob_type->tp_name);
61 return -1;
62 }
Tim Petersea7f75d2002-12-07 21:39:16 +000063 if (strlen(PyString_AS_STRING(value))
Michael W. Hudson98bbc492002-11-26 14:47:27 +000064 != (size_t)PyString_GET_SIZE(value)) {
65 PyErr_Format(PyExc_ValueError,
66 "__name__ must not contain null bytes");
67 return -1;
68 }
69
Guido van Rossume5c691a2003-03-07 15:13:17 +000070 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000071
72 Py_INCREF(value);
73
74 Py_DECREF(et->name);
75 et->name = value;
76
77 type->tp_name = PyString_AS_STRING(value);
78
79 return 0;
80}
81
Guido van Rossumc3542212001-08-16 09:18:56 +000082static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000083type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000084{
Guido van Rossumc3542212001-08-16 09:18:56 +000085 PyObject *mod;
86 char *s;
87
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000088 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
89 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Anthony Baxter3ecdb252004-06-11 14:41:18 +000090 if (!mod) {
91 PyErr_Format(PyExc_AttributeError, "__module__");
92 return 0;
93 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000094 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +000095 return mod;
96 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000097 else {
98 s = strrchr(type->tp_name, '.');
99 if (s != NULL)
100 return PyString_FromStringAndSize(
101 type->tp_name, (int)(s - type->tp_name));
102 return PyString_FromString("__builtin__");
103 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000104}
105
Guido van Rossum3926a632001-09-25 16:25:58 +0000106static int
107type_set_module(PyTypeObject *type, PyObject *value, void *context)
108{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000109 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000110 PyErr_Format(PyExc_TypeError,
111 "can't set %s.__module__", type->tp_name);
112 return -1;
113 }
114 if (!value) {
115 PyErr_Format(PyExc_TypeError,
116 "can't delete %s.__module__", type->tp_name);
117 return -1;
118 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000119
Guido van Rossum3926a632001-09-25 16:25:58 +0000120 return PyDict_SetItemString(type->tp_dict, "__module__", value);
121}
122
Tim Peters6d6c1a32001-08-02 04:15:00 +0000123static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000124type_get_bases(PyTypeObject *type, void *context)
125{
126 Py_INCREF(type->tp_bases);
127 return type->tp_bases;
128}
129
130static PyTypeObject *best_base(PyObject *);
131static int mro_internal(PyTypeObject *);
132static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
133static int add_subclass(PyTypeObject*, PyTypeObject*);
134static void remove_subclass(PyTypeObject *, PyTypeObject *);
135static void update_all_slots(PyTypeObject *);
136
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000137typedef int (*update_callback)(PyTypeObject *, void *);
138static int update_subclasses(PyTypeObject *type, PyObject *name,
139 update_callback callback, void *data);
140static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
141 update_callback callback, void *data);
142
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000143static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000144mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000145{
146 PyTypeObject *subclass;
147 PyObject *ref, *subclasses, *old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000148 int i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000149
150 subclasses = type->tp_subclasses;
151 if (subclasses == NULL)
152 return 0;
153 assert(PyList_Check(subclasses));
154 n = PyList_GET_SIZE(subclasses);
155 for (i = 0; i < n; i++) {
156 ref = PyList_GET_ITEM(subclasses, i);
157 assert(PyWeakref_CheckRef(ref));
158 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
159 assert(subclass != NULL);
160 if ((PyObject *)subclass == Py_None)
161 continue;
162 assert(PyType_Check(subclass));
163 old_mro = subclass->tp_mro;
164 if (mro_internal(subclass) < 0) {
165 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000166 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000167 }
168 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000169 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000170 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000171 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000172 if (!tuple)
173 return -1;
174 if (PyList_Append(temp, tuple) < 0)
175 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000176 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000177 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000178 if (mro_subclasses(subclass, temp) < 0)
179 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000180 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000181 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000182}
183
184static int
185type_set_bases(PyTypeObject *type, PyObject *value, void *context)
186{
187 int i, r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000188 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000189 PyTypeObject *new_base, *old_base;
190 PyObject *old_bases, *old_mro;
191
192 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
193 PyErr_Format(PyExc_TypeError,
194 "can't set %s.__bases__", type->tp_name);
195 return -1;
196 }
197 if (!value) {
198 PyErr_Format(PyExc_TypeError,
199 "can't delete %s.__bases__", type->tp_name);
200 return -1;
201 }
202 if (!PyTuple_Check(value)) {
203 PyErr_Format(PyExc_TypeError,
204 "can only assign tuple to %s.__bases__, not %s",
205 type->tp_name, value->ob_type->tp_name);
206 return -1;
207 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000208 if (PyTuple_GET_SIZE(value) == 0) {
209 PyErr_Format(PyExc_TypeError,
210 "can only assign non-empty tuple to %s.__bases__, not ()",
211 type->tp_name);
212 return -1;
213 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000214 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
215 ob = PyTuple_GET_ITEM(value, i);
216 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
217 PyErr_Format(
218 PyExc_TypeError,
219 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
220 type->tp_name, ob->ob_type->tp_name);
221 return -1;
222 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000223 if (PyType_Check(ob)) {
224 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
225 PyErr_SetString(PyExc_TypeError,
226 "a __bases__ item causes an inheritance cycle");
227 return -1;
228 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000229 }
230 }
231
232 new_base = best_base(value);
233
234 if (!new_base) {
235 return -1;
236 }
237
238 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
239 return -1;
240
241 Py_INCREF(new_base);
242 Py_INCREF(value);
243
244 old_bases = type->tp_bases;
245 old_base = type->tp_base;
246 old_mro = type->tp_mro;
247
248 type->tp_bases = value;
249 type->tp_base = new_base;
250
251 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000252 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000253 }
254
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000255 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000256 if (!temp)
257 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000258
259 r = mro_subclasses(type, temp);
260
261 if (r < 0) {
262 for (i = 0; i < PyList_Size(temp); i++) {
263 PyTypeObject* cls;
264 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000265 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
266 "", 2, 2, &cls, &mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000267 Py_DECREF(cls->tp_mro);
268 cls->tp_mro = mro;
269 Py_INCREF(cls->tp_mro);
270 }
271 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000272 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000273 }
274
275 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000276
277 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000278 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000279 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000280 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000281
282 /* for now, sod that: just remove from all old_bases,
283 add to all new_bases */
284
285 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
286 ob = PyTuple_GET_ITEM(old_bases, i);
287 if (PyType_Check(ob)) {
288 remove_subclass(
289 (PyTypeObject*)ob, type);
290 }
291 }
292
293 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
294 ob = PyTuple_GET_ITEM(value, i);
295 if (PyType_Check(ob)) {
296 if (add_subclass((PyTypeObject*)ob, type) < 0)
297 r = -1;
298 }
299 }
300
301 update_all_slots(type);
302
303 Py_DECREF(old_bases);
304 Py_DECREF(old_base);
305 Py_DECREF(old_mro);
306
307 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000308
309 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000310 Py_DECREF(type->tp_bases);
311 Py_DECREF(type->tp_base);
312 if (type->tp_mro != old_mro) {
313 Py_DECREF(type->tp_mro);
314 }
315
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000316 type->tp_bases = old_bases;
317 type->tp_base = old_base;
318 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000319
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000320 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000321}
322
323static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000324type_dict(PyTypeObject *type, void *context)
325{
326 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000327 Py_INCREF(Py_None);
328 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000329 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000330 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000331}
332
Tim Peters24008312002-03-17 18:56:20 +0000333static PyObject *
334type_get_doc(PyTypeObject *type, void *context)
335{
336 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000337 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000338 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000339 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000340 if (result == NULL) {
341 result = Py_None;
342 Py_INCREF(result);
343 }
344 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000345 result = result->ob_type->tp_descr_get(result, NULL,
346 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000347 }
348 else {
349 Py_INCREF(result);
350 }
Tim Peters24008312002-03-17 18:56:20 +0000351 return result;
352}
353
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000354static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000355 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
356 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000357 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000358 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000359 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000360 {0}
361};
362
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000363static int
364type_compare(PyObject *v, PyObject *w)
365{
366 /* This is called with type objects only. So we
367 can just compare the addresses. */
368 Py_uintptr_t vv = (Py_uintptr_t)v;
369 Py_uintptr_t ww = (Py_uintptr_t)w;
370 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
371}
372
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000373static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000374type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000375{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000376 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000377 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000378
379 mod = type_module(type, NULL);
380 if (mod == NULL)
381 PyErr_Clear();
382 else if (!PyString_Check(mod)) {
383 Py_DECREF(mod);
384 mod = NULL;
385 }
386 name = type_name(type, NULL);
387 if (name == NULL)
388 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000389
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000390 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
391 kind = "class";
392 else
393 kind = "type";
394
Barry Warsaw7ce36942001-08-24 18:34:26 +0000395 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000396 rtn = PyString_FromFormat("<%s '%s.%s'>",
397 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000398 PyString_AS_STRING(mod),
399 PyString_AS_STRING(name));
400 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000401 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000402 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000403
Guido van Rossumc3542212001-08-16 09:18:56 +0000404 Py_XDECREF(mod);
405 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000406 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000407}
408
Tim Peters6d6c1a32001-08-02 04:15:00 +0000409static PyObject *
410type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
411{
412 PyObject *obj;
413
414 if (type->tp_new == NULL) {
415 PyErr_Format(PyExc_TypeError,
416 "cannot create '%.100s' instances",
417 type->tp_name);
418 return NULL;
419 }
420
Tim Peters3f996e72001-09-13 19:18:27 +0000421 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000422 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000423 /* Ugly exception: when the call was type(something),
424 don't call tp_init on the result. */
425 if (type == &PyType_Type &&
426 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
427 (kwds == NULL ||
428 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
429 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000430 /* If the returned object is not an instance of type,
431 it won't be initialized. */
432 if (!PyType_IsSubtype(obj->ob_type, type))
433 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000434 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000435 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
436 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000437 type->tp_init(obj, args, kwds) < 0) {
438 Py_DECREF(obj);
439 obj = NULL;
440 }
441 }
442 return obj;
443}
444
445PyObject *
446PyType_GenericAlloc(PyTypeObject *type, int nitems)
447{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000448 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000449 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
450 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000451
452 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000453 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000454 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000455 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000456
Neil Schemenauerc806c882001-08-29 23:54:54 +0000457 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000458 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000459
Neil Schemenauerc806c882001-08-29 23:54:54 +0000460 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000461
Tim Peters6d6c1a32001-08-02 04:15:00 +0000462 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
463 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000464
Tim Peters6d6c1a32001-08-02 04:15:00 +0000465 if (type->tp_itemsize == 0)
466 PyObject_INIT(obj, type);
467 else
468 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000469
Tim Peters6d6c1a32001-08-02 04:15:00 +0000470 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000471 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000472 return obj;
473}
474
475PyObject *
476PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
477{
478 return type->tp_alloc(type, 0);
479}
480
Guido van Rossum9475a232001-10-05 20:51:39 +0000481/* Helpers for subtyping */
482
483static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000484traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
485{
486 int i, n;
487 PyMemberDef *mp;
488
489 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000490 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000491 for (i = 0; i < n; i++, mp++) {
492 if (mp->type == T_OBJECT_EX) {
493 char *addr = (char *)self + mp->offset;
494 PyObject *obj = *(PyObject **)addr;
495 if (obj != NULL) {
496 int err = visit(obj, arg);
497 if (err)
498 return err;
499 }
500 }
501 }
502 return 0;
503}
504
505static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000506subtype_traverse(PyObject *self, visitproc visit, void *arg)
507{
508 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000509 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000510
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000511 /* Find the nearest base with a different tp_traverse,
512 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000513 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000514 base = type;
515 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
516 if (base->ob_size) {
517 int err = traverse_slots(base, self, visit, arg);
518 if (err)
519 return err;
520 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000521 base = base->tp_base;
522 assert(base);
523 }
524
525 if (type->tp_dictoffset != base->tp_dictoffset) {
526 PyObject **dictptr = _PyObject_GetDictPtr(self);
527 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000528 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000529 if (err)
530 return err;
531 }
532 }
533
Guido van Rossuma3862092002-06-10 15:24:42 +0000534 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
535 /* For a heaptype, the instances count as references
536 to the type. Traverse the type so the collector
537 can find cycles involving this link. */
538 int err = visit((PyObject *)type, arg);
539 if (err)
540 return err;
541 }
542
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000543 if (basetraverse)
544 return basetraverse(self, visit, arg);
545 return 0;
546}
547
548static void
549clear_slots(PyTypeObject *type, PyObject *self)
550{
551 int i, n;
552 PyMemberDef *mp;
553
554 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000555 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000556 for (i = 0; i < n; i++, mp++) {
557 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
558 char *addr = (char *)self + mp->offset;
559 PyObject *obj = *(PyObject **)addr;
560 if (obj != NULL) {
561 Py_DECREF(obj);
562 *(PyObject **)addr = NULL;
563 }
564 }
565 }
566}
567
568static int
569subtype_clear(PyObject *self)
570{
571 PyTypeObject *type, *base;
572 inquiry baseclear;
573
574 /* Find the nearest base with a different tp_clear
575 and clear slots while we're at it */
576 type = self->ob_type;
577 base = type;
578 while ((baseclear = base->tp_clear) == subtype_clear) {
579 if (base->ob_size)
580 clear_slots(base, self);
581 base = base->tp_base;
582 assert(base);
583 }
584
Guido van Rossuma3862092002-06-10 15:24:42 +0000585 /* There's no need to clear the instance dict (if any);
586 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000587
588 if (baseclear)
589 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000590 return 0;
591}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000592
593static void
594subtype_dealloc(PyObject *self)
595{
Guido van Rossum14227b42001-12-06 02:35:58 +0000596 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000597 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000598
Guido van Rossum22b13872002-08-06 21:41:44 +0000599 /* Extract the type; we expect it to be a heap type */
600 type = self->ob_type;
601 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000602
Guido van Rossum22b13872002-08-06 21:41:44 +0000603 /* Test whether the type has GC exactly once */
604
605 if (!PyType_IS_GC(type)) {
606 /* It's really rare to find a dynamic type that doesn't have
607 GC; it can only happen when deriving from 'object' and not
608 adding any slots or instance variables. This allows
609 certain simplifications: there's no need to call
610 clear_slots(), or DECREF the dict, or clear weakrefs. */
611
612 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000613 if (type->tp_del) {
614 type->tp_del(self);
615 if (self->ob_refcnt > 0)
616 return;
617 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000618
619 /* Find the nearest base with a different tp_dealloc */
620 base = type;
621 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
622 assert(base->ob_size == 0);
623 base = base->tp_base;
624 assert(base);
625 }
626
627 /* Call the base tp_dealloc() */
628 assert(basedealloc);
629 basedealloc(self);
630
631 /* Can't reference self beyond this point */
632 Py_DECREF(type);
633
634 /* Done */
635 return;
636 }
637
638 /* We get here only if the type has GC */
639
640 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000641 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000642 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000643 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000644 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000645 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000646 /* DO NOT restore GC tracking at this point. weakref callbacks
647 * (if any, and whether directly here or indirectly in something we
648 * call) may trigger GC, and if self is tracked at that point, it
649 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000650 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000651
Guido van Rossum59195fd2003-06-13 20:54:40 +0000652 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000653 base = type;
654 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000655 base = base->tp_base;
656 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000657 }
658
Guido van Rossum1987c662003-05-29 14:29:23 +0000659 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000660 the finalizer (__del__), clearing slots, or clearing the instance
661 dict. */
662
Guido van Rossum1987c662003-05-29 14:29:23 +0000663 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
664 PyObject_ClearWeakRefs(self);
665
666 /* Maybe call finalizer; exit early if resurrected */
667 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000668 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000669 type->tp_del(self);
670 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000671 goto endlabel; /* resurrected */
672 else
673 _PyObject_GC_UNTRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000674 }
675
Guido van Rossum59195fd2003-06-13 20:54:40 +0000676 /* Clear slots up to the nearest base with a different tp_dealloc */
677 base = type;
678 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
679 if (base->ob_size)
680 clear_slots(base, self);
681 base = base->tp_base;
682 assert(base);
683 }
684
Tim Peters6d6c1a32001-08-02 04:15:00 +0000685 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000686 if (type->tp_dictoffset && !base->tp_dictoffset) {
687 PyObject **dictptr = _PyObject_GetDictPtr(self);
688 if (dictptr != NULL) {
689 PyObject *dict = *dictptr;
690 if (dict != NULL) {
691 Py_DECREF(dict);
692 *dictptr = NULL;
693 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000694 }
695 }
696
Tim Peters0bd743c2003-11-13 22:50:00 +0000697 /* Call the base tp_dealloc(); first retrack self if
698 * basedealloc knows about gc.
699 */
700 if (PyType_IS_GC(base))
701 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000702 assert(basedealloc);
703 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000704
705 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000706 Py_DECREF(type);
707
Guido van Rossum0906e072002-08-07 20:42:09 +0000708 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000709 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000710 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000711 --_PyTrash_delete_nesting;
712
713 /* Explanation of the weirdness around the trashcan macros:
714
715 Q. What do the trashcan macros do?
716
717 A. Read the comment titled "Trashcan mechanism" in object.h.
718 For one, this explains why there must be a call to GC-untrack
719 before the trashcan begin macro. Without understanding the
720 trashcan code, the answers to the following questions don't make
721 sense.
722
723 Q. Why do we GC-untrack before the trashcan and then immediately
724 GC-track again afterward?
725
726 A. In the case that the base class is GC-aware, the base class
727 probably GC-untracks the object. If it does that using the
728 UNTRACK macro, this will crash when the object is already
729 untracked. Because we don't know what the base class does, the
730 only safe thing is to make sure the object is tracked when we
731 call the base class dealloc. But... The trashcan begin macro
732 requires that the object is *untracked* before it is called. So
733 the dance becomes:
734
735 GC untrack
736 trashcan begin
737 GC track
738
Tim Petersf7f9e992003-11-13 21:59:32 +0000739 Q. Why did the last question say "immediately GC-track again"?
740 It's nowhere near immediately.
741
742 A. Because the code *used* to re-track immediately. Bad Idea.
743 self has a refcount of 0, and if gc ever gets its hands on it
744 (which can happen if any weakref callback gets invoked), it
745 looks like trash to gc too, and gc also tries to delete self
746 then. But we're already deleting self. Double dealloction is
747 a subtle disaster.
748
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000749 Q. Why the bizarre (net-zero) manipulation of
750 _PyTrash_delete_nesting around the trashcan macros?
751
752 A. Some base classes (e.g. list) also use the trashcan mechanism.
753 The following scenario used to be possible:
754
755 - suppose the trashcan level is one below the trashcan limit
756
757 - subtype_dealloc() is called
758
759 - the trashcan limit is not yet reached, so the trashcan level
760 is incremented and the code between trashcan begin and end is
761 executed
762
763 - this destroys much of the object's contents, including its
764 slots and __dict__
765
766 - basedealloc() is called; this is really list_dealloc(), or
767 some other type which also uses the trashcan macros
768
769 - the trashcan limit is now reached, so the object is put on the
770 trashcan's to-be-deleted-later list
771
772 - basedealloc() returns
773
774 - subtype_dealloc() decrefs the object's type
775
776 - subtype_dealloc() returns
777
778 - later, the trashcan code starts deleting the objects from its
779 to-be-deleted-later list
780
781 - subtype_dealloc() is called *AGAIN* for the same object
782
783 - at the very least (if the destroyed slots and __dict__ don't
784 cause problems) the object's type gets decref'ed a second
785 time, which is *BAD*!!!
786
787 The remedy is to make sure that if the code between trashcan
788 begin and end in subtype_dealloc() is called, the code between
789 trashcan begin and end in basedealloc() will also be called.
790 This is done by decrementing the level after passing into the
791 trashcan block, and incrementing it just before leaving the
792 block.
793
794 But now it's possible that a chain of objects consisting solely
795 of objects whose deallocator is subtype_dealloc() will defeat
796 the trashcan mechanism completely: the decremented level means
797 that the effective level never reaches the limit. Therefore, we
798 *increment* the level *before* entering the trashcan block, and
799 matchingly decrement it after leaving. This means the trashcan
800 code will trigger a little early, but that's no big deal.
801
802 Q. Are there any live examples of code in need of all this
803 complexity?
804
805 A. Yes. See SF bug 668433 for code that crashed (when Python was
806 compiled in debug mode) before the trashcan level manipulations
807 were added. For more discussion, see SF patches 581742, 575073
808 and bug 574207.
809 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000810}
811
Jeremy Hylton938ace62002-07-17 16:30:39 +0000812static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000813
Tim Peters6d6c1a32001-08-02 04:15:00 +0000814/* type test with subclassing support */
815
816int
817PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
818{
819 PyObject *mro;
820
Guido van Rossum9478d072001-09-07 18:52:13 +0000821 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
822 return b == a || b == &PyBaseObject_Type;
823
Tim Peters6d6c1a32001-08-02 04:15:00 +0000824 mro = a->tp_mro;
825 if (mro != NULL) {
826 /* Deal with multiple inheritance without recursion
827 by walking the MRO tuple */
828 int i, n;
829 assert(PyTuple_Check(mro));
830 n = PyTuple_GET_SIZE(mro);
831 for (i = 0; i < n; i++) {
832 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
833 return 1;
834 }
835 return 0;
836 }
837 else {
838 /* a is not completely initilized yet; follow tp_base */
839 do {
840 if (a == b)
841 return 1;
842 a = a->tp_base;
843 } while (a != NULL);
844 return b == &PyBaseObject_Type;
845 }
846}
847
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000848/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000849 without looking in the instance dictionary
850 (so we can't use PyObject_GetAttr) but still binding
851 it to the instance. The arguments are the object,
852 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000853 static variable used to cache the interned Python string.
854
855 Two variants:
856
857 - lookup_maybe() returns NULL without raising an exception
858 when the _PyType_Lookup() call fails;
859
860 - lookup_method() always raises an exception upon errors.
861*/
Guido van Rossum60718732001-08-28 17:47:51 +0000862
863static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000864lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000865{
866 PyObject *res;
867
868 if (*attrobj == NULL) {
869 *attrobj = PyString_InternFromString(attrstr);
870 if (*attrobj == NULL)
871 return NULL;
872 }
873 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000874 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000875 descrgetfunc f;
876 if ((f = res->ob_type->tp_descr_get) == NULL)
877 Py_INCREF(res);
878 else
879 res = f(res, self, (PyObject *)(self->ob_type));
880 }
881 return res;
882}
883
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000884static PyObject *
885lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
886{
887 PyObject *res = lookup_maybe(self, attrstr, attrobj);
888 if (res == NULL && !PyErr_Occurred())
889 PyErr_SetObject(PyExc_AttributeError, *attrobj);
890 return res;
891}
892
Guido van Rossum2730b132001-08-28 18:22:14 +0000893/* A variation of PyObject_CallMethod that uses lookup_method()
894 instead of PyObject_GetAttrString(). This uses the same convention
895 as lookup_method to cache the interned name string object. */
896
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000897static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000898call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
899{
900 va_list va;
901 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000902 va_start(va, format);
903
Guido van Rossumda21c012001-10-03 00:50:18 +0000904 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000905 if (func == NULL) {
906 va_end(va);
907 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000908 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000909 return NULL;
910 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000911
912 if (format && *format)
913 args = Py_VaBuildValue(format, va);
914 else
915 args = PyTuple_New(0);
916
917 va_end(va);
918
919 if (args == NULL)
920 return NULL;
921
922 assert(PyTuple_Check(args));
923 retval = PyObject_Call(func, args, NULL);
924
925 Py_DECREF(args);
926 Py_DECREF(func);
927
928 return retval;
929}
930
931/* Clone of call_method() that returns NotImplemented when the lookup fails. */
932
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000933static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000934call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
935{
936 va_list va;
937 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000938 va_start(va, format);
939
Guido van Rossumda21c012001-10-03 00:50:18 +0000940 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000941 if (func == NULL) {
942 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000943 if (!PyErr_Occurred()) {
944 Py_INCREF(Py_NotImplemented);
945 return Py_NotImplemented;
946 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000947 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000948 }
949
950 if (format && *format)
951 args = Py_VaBuildValue(format, va);
952 else
953 args = PyTuple_New(0);
954
955 va_end(va);
956
Guido van Rossum717ce002001-09-14 16:58:08 +0000957 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000958 return NULL;
959
Guido van Rossum717ce002001-09-14 16:58:08 +0000960 assert(PyTuple_Check(args));
961 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000962
963 Py_DECREF(args);
964 Py_DECREF(func);
965
966 return retval;
967}
968
Tim Petersa91e9642001-11-14 23:32:33 +0000969static int
970fill_classic_mro(PyObject *mro, PyObject *cls)
971{
972 PyObject *bases, *base;
973 int i, n;
974
975 assert(PyList_Check(mro));
976 assert(PyClass_Check(cls));
977 i = PySequence_Contains(mro, cls);
978 if (i < 0)
979 return -1;
980 if (!i) {
981 if (PyList_Append(mro, cls) < 0)
982 return -1;
983 }
984 bases = ((PyClassObject *)cls)->cl_bases;
985 assert(bases && PyTuple_Check(bases));
986 n = PyTuple_GET_SIZE(bases);
987 for (i = 0; i < n; i++) {
988 base = PyTuple_GET_ITEM(bases, i);
989 if (fill_classic_mro(mro, base) < 0)
990 return -1;
991 }
992 return 0;
993}
994
995static PyObject *
996classic_mro(PyObject *cls)
997{
998 PyObject *mro;
999
1000 assert(PyClass_Check(cls));
1001 mro = PyList_New(0);
1002 if (mro != NULL) {
1003 if (fill_classic_mro(mro, cls) == 0)
1004 return mro;
1005 Py_DECREF(mro);
1006 }
1007 return NULL;
1008}
1009
Tim Petersea7f75d2002-12-07 21:39:16 +00001010/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001011 Method resolution order algorithm C3 described in
1012 "A Monotonic Superclass Linearization for Dylan",
1013 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001014 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001015 (OOPSLA 1996)
1016
Guido van Rossum98f33732002-11-25 21:36:54 +00001017 Some notes about the rules implied by C3:
1018
Tim Petersea7f75d2002-12-07 21:39:16 +00001019 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001020 It isn't legal to repeat a class in a list of base classes.
1021
1022 The next three properties are the 3 constraints in "C3".
1023
Tim Petersea7f75d2002-12-07 21:39:16 +00001024 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001025 If A precedes B in C's MRO, then A will precede B in the MRO of all
1026 subclasses of C.
1027
1028 Monotonicity.
1029 The MRO of a class must be an extension without reordering of the
1030 MRO of each of its superclasses.
1031
1032 Extended Precedence Graph (EPG).
1033 Linearization is consistent if there is a path in the EPG from
1034 each class to all its successors in the linearization. See
1035 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001036 */
1037
Tim Petersea7f75d2002-12-07 21:39:16 +00001038static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001039tail_contains(PyObject *list, int whence, PyObject *o) {
1040 int j, size;
1041 size = PyList_GET_SIZE(list);
1042
1043 for (j = whence+1; j < size; j++) {
1044 if (PyList_GET_ITEM(list, j) == o)
1045 return 1;
1046 }
1047 return 0;
1048}
1049
Guido van Rossum98f33732002-11-25 21:36:54 +00001050static PyObject *
1051class_name(PyObject *cls)
1052{
1053 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1054 if (name == NULL) {
1055 PyErr_Clear();
1056 Py_XDECREF(name);
1057 name = PyObject_Repr(cls);
1058 }
1059 if (name == NULL)
1060 return NULL;
1061 if (!PyString_Check(name)) {
1062 Py_DECREF(name);
1063 return NULL;
1064 }
1065 return name;
1066}
1067
1068static int
1069check_duplicates(PyObject *list)
1070{
1071 int i, j, n;
1072 /* Let's use a quadratic time algorithm,
1073 assuming that the bases lists is short.
1074 */
1075 n = PyList_GET_SIZE(list);
1076 for (i = 0; i < n; i++) {
1077 PyObject *o = PyList_GET_ITEM(list, i);
1078 for (j = i + 1; j < n; j++) {
1079 if (PyList_GET_ITEM(list, j) == o) {
1080 o = class_name(o);
1081 PyErr_Format(PyExc_TypeError,
1082 "duplicate base class %s",
1083 o ? PyString_AS_STRING(o) : "?");
1084 Py_XDECREF(o);
1085 return -1;
1086 }
1087 }
1088 }
1089 return 0;
1090}
1091
1092/* Raise a TypeError for an MRO order disagreement.
1093
1094 It's hard to produce a good error message. In the absence of better
1095 insight into error reporting, report the classes that were candidates
1096 to be put next into the MRO. There is some conflict between the
1097 order in which they should be put in the MRO, but it's hard to
1098 diagnose what constraint can't be satisfied.
1099*/
1100
1101static void
1102set_mro_error(PyObject *to_merge, int *remain)
1103{
1104 int i, n, off, to_merge_size;
1105 char buf[1000];
1106 PyObject *k, *v;
1107 PyObject *set = PyDict_New();
1108
1109 to_merge_size = PyList_GET_SIZE(to_merge);
1110 for (i = 0; i < to_merge_size; i++) {
1111 PyObject *L = PyList_GET_ITEM(to_merge, i);
1112 if (remain[i] < PyList_GET_SIZE(L)) {
1113 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1114 if (PyDict_SetItem(set, c, Py_None) < 0)
1115 return;
1116 }
1117 }
1118 n = PyDict_Size(set);
1119
Raymond Hettingerf394df42003-04-06 19:13:41 +00001120 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1121consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001122 i = 0;
1123 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1124 PyObject *name = class_name(k);
1125 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1126 name ? PyString_AS_STRING(name) : "?");
1127 Py_XDECREF(name);
1128 if (--n && off+1 < sizeof(buf)) {
1129 buf[off++] = ',';
1130 buf[off] = '\0';
1131 }
1132 }
1133 PyErr_SetString(PyExc_TypeError, buf);
1134 Py_DECREF(set);
1135}
1136
Tim Petersea7f75d2002-12-07 21:39:16 +00001137static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001138pmerge(PyObject *acc, PyObject* to_merge) {
1139 int i, j, to_merge_size;
1140 int *remain;
1141 int ok, empty_cnt;
Tim Petersea7f75d2002-12-07 21:39:16 +00001142
Guido van Rossum1f121312002-11-14 19:49:16 +00001143 to_merge_size = PyList_GET_SIZE(to_merge);
1144
Guido van Rossum98f33732002-11-25 21:36:54 +00001145 /* remain stores an index into each sublist of to_merge.
1146 remain[i] is the index of the next base in to_merge[i]
1147 that is not included in acc.
1148 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001149 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1150 if (remain == NULL)
1151 return -1;
1152 for (i = 0; i < to_merge_size; i++)
1153 remain[i] = 0;
1154
1155 again:
1156 empty_cnt = 0;
1157 for (i = 0; i < to_merge_size; i++) {
1158 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001159
Guido van Rossum1f121312002-11-14 19:49:16 +00001160 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1161
1162 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1163 empty_cnt++;
1164 continue;
1165 }
1166
Guido van Rossum98f33732002-11-25 21:36:54 +00001167 /* Choose next candidate for MRO.
1168
1169 The input sequences alone can determine the choice.
1170 If not, choose the class which appears in the MRO
1171 of the earliest direct superclass of the new class.
1172 */
1173
Guido van Rossum1f121312002-11-14 19:49:16 +00001174 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1175 for (j = 0; j < to_merge_size; j++) {
1176 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001177 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001178 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001179 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001180 }
1181 ok = PyList_Append(acc, candidate);
1182 if (ok < 0) {
1183 PyMem_Free(remain);
1184 return -1;
1185 }
1186 for (j = 0; j < to_merge_size; j++) {
1187 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001188 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1189 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001190 remain[j]++;
1191 }
1192 }
1193 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001194 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001195 }
1196
Guido van Rossum98f33732002-11-25 21:36:54 +00001197 if (empty_cnt == to_merge_size) {
1198 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001199 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001200 }
1201 set_mro_error(to_merge, remain);
1202 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001203 return -1;
1204}
1205
Tim Peters6d6c1a32001-08-02 04:15:00 +00001206static PyObject *
1207mro_implementation(PyTypeObject *type)
1208{
1209 int i, n, ok;
1210 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001211 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001212
Guido van Rossum63517572002-06-18 16:44:57 +00001213 if(type->tp_dict == NULL) {
1214 if(PyType_Ready(type) < 0)
1215 return NULL;
1216 }
1217
Guido van Rossum98f33732002-11-25 21:36:54 +00001218 /* Find a superclass linearization that honors the constraints
1219 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001220 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001221
1222 to_merge is a list of lists, where each list is a superclass
1223 linearization implied by a base class. The last element of
1224 to_merge is the declared list of bases.
1225 */
1226
Tim Peters6d6c1a32001-08-02 04:15:00 +00001227 bases = type->tp_bases;
1228 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001229
1230 to_merge = PyList_New(n+1);
1231 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001232 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001233
Tim Peters6d6c1a32001-08-02 04:15:00 +00001234 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001235 PyObject *base = PyTuple_GET_ITEM(bases, i);
1236 PyObject *parentMRO;
1237 if (PyType_Check(base))
1238 parentMRO = PySequence_List(
1239 ((PyTypeObject*)base)->tp_mro);
1240 else
1241 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001242 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001243 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001244 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001245 }
1246
1247 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001248 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001249
1250 bases_aslist = PySequence_List(bases);
1251 if (bases_aslist == NULL) {
1252 Py_DECREF(to_merge);
1253 return NULL;
1254 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001255 /* This is just a basic sanity check. */
1256 if (check_duplicates(bases_aslist) < 0) {
1257 Py_DECREF(to_merge);
1258 Py_DECREF(bases_aslist);
1259 return NULL;
1260 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001261 PyList_SET_ITEM(to_merge, n, bases_aslist);
1262
1263 result = Py_BuildValue("[O]", (PyObject *)type);
1264 if (result == NULL) {
1265 Py_DECREF(to_merge);
1266 return NULL;
1267 }
1268
1269 ok = pmerge(result, to_merge);
1270 Py_DECREF(to_merge);
1271 if (ok < 0) {
1272 Py_DECREF(result);
1273 return NULL;
1274 }
1275
Tim Peters6d6c1a32001-08-02 04:15:00 +00001276 return result;
1277}
1278
1279static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001280mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001281{
1282 PyTypeObject *type = (PyTypeObject *)self;
1283
Tim Peters6d6c1a32001-08-02 04:15:00 +00001284 return mro_implementation(type);
1285}
1286
1287static int
1288mro_internal(PyTypeObject *type)
1289{
1290 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001291 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001292
1293 if (type->ob_type == &PyType_Type) {
1294 result = mro_implementation(type);
1295 }
1296 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001297 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001298 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001299 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001300 if (mro == NULL)
1301 return -1;
1302 result = PyObject_CallObject(mro, NULL);
1303 Py_DECREF(mro);
1304 }
1305 if (result == NULL)
1306 return -1;
1307 tuple = PySequence_Tuple(result);
1308 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001309 if (tuple == NULL)
1310 return -1;
1311 if (checkit) {
1312 int i, len;
1313 PyObject *cls;
1314 PyTypeObject *solid;
1315
1316 solid = solid_base(type);
1317
1318 len = PyTuple_GET_SIZE(tuple);
1319
1320 for (i = 0; i < len; i++) {
1321 PyTypeObject *t;
1322 cls = PyTuple_GET_ITEM(tuple, i);
1323 if (PyClass_Check(cls))
1324 continue;
1325 else if (!PyType_Check(cls)) {
1326 PyErr_Format(PyExc_TypeError,
1327 "mro() returned a non-class ('%.500s')",
1328 cls->ob_type->tp_name);
1329 return -1;
1330 }
1331 t = (PyTypeObject*)cls;
1332 if (!PyType_IsSubtype(solid, solid_base(t))) {
1333 PyErr_Format(PyExc_TypeError,
1334 "mro() returned base with unsuitable layout ('%.500s')",
1335 t->tp_name);
1336 return -1;
1337 }
1338 }
1339 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001340 type->tp_mro = tuple;
1341 return 0;
1342}
1343
1344
1345/* Calculate the best base amongst multiple base classes.
1346 This is the first one that's on the path to the "solid base". */
1347
1348static PyTypeObject *
1349best_base(PyObject *bases)
1350{
1351 int i, n;
1352 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001353 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001354
1355 assert(PyTuple_Check(bases));
1356 n = PyTuple_GET_SIZE(bases);
1357 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001358 base = NULL;
1359 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001360 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001361 base_proto = PyTuple_GET_ITEM(bases, i);
1362 if (PyClass_Check(base_proto))
1363 continue;
1364 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001365 PyErr_SetString(
1366 PyExc_TypeError,
1367 "bases must be types");
1368 return NULL;
1369 }
Tim Petersa91e9642001-11-14 23:32:33 +00001370 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001371 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001372 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001373 return NULL;
1374 }
1375 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001376 if (winner == NULL) {
1377 winner = candidate;
1378 base = base_i;
1379 }
1380 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001381 ;
1382 else if (PyType_IsSubtype(candidate, winner)) {
1383 winner = candidate;
1384 base = base_i;
1385 }
1386 else {
1387 PyErr_SetString(
1388 PyExc_TypeError,
1389 "multiple bases have "
1390 "instance lay-out conflict");
1391 return NULL;
1392 }
1393 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001394 if (base == NULL)
1395 PyErr_SetString(PyExc_TypeError,
1396 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001397 return base;
1398}
1399
1400static int
1401extra_ivars(PyTypeObject *type, PyTypeObject *base)
1402{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001403 size_t t_size = type->tp_basicsize;
1404 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001405
Guido van Rossum9676b222001-08-17 20:32:36 +00001406 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001407 if (type->tp_itemsize || base->tp_itemsize) {
1408 /* If itemsize is involved, stricter rules */
1409 return t_size != b_size ||
1410 type->tp_itemsize != base->tp_itemsize;
1411 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001412 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1413 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1414 t_size -= sizeof(PyObject *);
1415 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1416 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1417 t_size -= sizeof(PyObject *);
1418
1419 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001420}
1421
1422static PyTypeObject *
1423solid_base(PyTypeObject *type)
1424{
1425 PyTypeObject *base;
1426
1427 if (type->tp_base)
1428 base = solid_base(type->tp_base);
1429 else
1430 base = &PyBaseObject_Type;
1431 if (extra_ivars(type, base))
1432 return type;
1433 else
1434 return base;
1435}
1436
Jeremy Hylton938ace62002-07-17 16:30:39 +00001437static void object_dealloc(PyObject *);
1438static int object_init(PyObject *, PyObject *, PyObject *);
1439static int update_slot(PyTypeObject *, PyObject *);
1440static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001441
1442static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001443subtype_dict(PyObject *obj, void *context)
1444{
1445 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1446 PyObject *dict;
1447
1448 if (dictptr == NULL) {
1449 PyErr_SetString(PyExc_AttributeError,
1450 "This object has no __dict__");
1451 return NULL;
1452 }
1453 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001454 if (dict == NULL)
1455 *dictptr = dict = PyDict_New();
1456 Py_XINCREF(dict);
1457 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001458}
1459
Guido van Rossum6661be32001-10-26 04:26:12 +00001460static int
1461subtype_setdict(PyObject *obj, PyObject *value, void *context)
1462{
1463 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1464 PyObject *dict;
1465
1466 if (dictptr == NULL) {
1467 PyErr_SetString(PyExc_AttributeError,
1468 "This object has no __dict__");
1469 return -1;
1470 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001471 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001472 PyErr_SetString(PyExc_TypeError,
1473 "__dict__ must be set to a dictionary");
1474 return -1;
1475 }
1476 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001477 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001478 *dictptr = value;
1479 Py_XDECREF(dict);
1480 return 0;
1481}
1482
Guido van Rossumad47da02002-08-12 19:05:44 +00001483static PyObject *
1484subtype_getweakref(PyObject *obj, void *context)
1485{
1486 PyObject **weaklistptr;
1487 PyObject *result;
1488
1489 if (obj->ob_type->tp_weaklistoffset == 0) {
1490 PyErr_SetString(PyExc_AttributeError,
1491 "This object has no __weaklist__");
1492 return NULL;
1493 }
1494 assert(obj->ob_type->tp_weaklistoffset > 0);
1495 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001496 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001497 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001498 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001499 if (*weaklistptr == NULL)
1500 result = Py_None;
1501 else
1502 result = *weaklistptr;
1503 Py_INCREF(result);
1504 return result;
1505}
1506
Guido van Rossum373c7412003-01-07 13:41:37 +00001507/* Three variants on the subtype_getsets list. */
1508
1509static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001510 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001511 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001512 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001513 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001514 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001515};
1516
Guido van Rossum373c7412003-01-07 13:41:37 +00001517static PyGetSetDef subtype_getsets_dict_only[] = {
1518 {"__dict__", subtype_dict, subtype_setdict,
1519 PyDoc_STR("dictionary for instance variables (if defined)")},
1520 {0}
1521};
1522
1523static PyGetSetDef subtype_getsets_weakref_only[] = {
1524 {"__weakref__", subtype_getweakref, NULL,
1525 PyDoc_STR("list of weak references to the object (if defined)")},
1526 {0}
1527};
1528
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001529static int
1530valid_identifier(PyObject *s)
1531{
Guido van Rossum03013a02002-07-16 14:30:28 +00001532 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001533 int i, n;
1534
1535 if (!PyString_Check(s)) {
1536 PyErr_SetString(PyExc_TypeError,
1537 "__slots__ must be strings");
1538 return 0;
1539 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001540 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001541 n = PyString_GET_SIZE(s);
1542 /* We must reject an empty name. As a hack, we bump the
1543 length to 1 so that the loop will balk on the trailing \0. */
1544 if (n == 0)
1545 n = 1;
1546 for (i = 0; i < n; i++, p++) {
1547 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1548 PyErr_SetString(PyExc_TypeError,
1549 "__slots__ must be identifiers");
1550 return 0;
1551 }
1552 }
1553 return 1;
1554}
1555
Martin v. Löwisd919a592002-10-14 21:07:28 +00001556#ifdef Py_USING_UNICODE
1557/* Replace Unicode objects in slots. */
1558
1559static PyObject *
1560_unicode_to_string(PyObject *slots, int nslots)
1561{
1562 PyObject *tmp = slots;
1563 PyObject *o, *o1;
1564 int i;
1565 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1566 for (i = 0; i < nslots; i++) {
1567 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1568 if (tmp == slots) {
1569 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1570 if (tmp == NULL)
1571 return NULL;
1572 }
1573 o1 = _PyUnicode_AsDefaultEncodedString
1574 (o, NULL);
1575 if (o1 == NULL) {
1576 Py_DECREF(tmp);
1577 return 0;
1578 }
1579 Py_INCREF(o1);
1580 Py_DECREF(o);
1581 PyTuple_SET_ITEM(tmp, i, o1);
1582 }
1583 }
1584 return tmp;
1585}
1586#endif
1587
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001588static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001589type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1590{
1591 PyObject *name, *bases, *dict;
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001592 static const char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001593 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001594 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001595 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001596 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001597 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001598 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001599
Tim Peters3abca122001-10-27 19:37:48 +00001600 assert(args != NULL && PyTuple_Check(args));
1601 assert(kwds == NULL || PyDict_Check(kwds));
1602
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001603 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001604 {
1605 const int nargs = PyTuple_GET_SIZE(args);
1606 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1607
1608 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1609 PyObject *x = PyTuple_GET_ITEM(args, 0);
1610 Py_INCREF(x->ob_type);
1611 return (PyObject *) x->ob_type;
1612 }
1613
1614 /* SF bug 475327 -- if that didn't trigger, we need 3
1615 arguments. but PyArg_ParseTupleAndKeywords below may give
1616 a msg saying type() needs exactly 3. */
1617 if (nargs + nkwds != 3) {
1618 PyErr_SetString(PyExc_TypeError,
1619 "type() takes 1 or 3 arguments");
1620 return NULL;
1621 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001622 }
1623
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001624 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001625 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1626 &name,
1627 &PyTuple_Type, &bases,
1628 &PyDict_Type, &dict))
1629 return NULL;
1630
1631 /* Determine the proper metatype to deal with this,
1632 and check for metatype conflicts while we're at it.
1633 Note that if some other metatype wins to contract,
1634 it's possible that its instances are not types. */
1635 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001636 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001637 for (i = 0; i < nbases; i++) {
1638 tmp = PyTuple_GET_ITEM(bases, i);
1639 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001640 if (tmptype == &PyClass_Type)
1641 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001642 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001643 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001644 if (PyType_IsSubtype(tmptype, winner)) {
1645 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001646 continue;
1647 }
1648 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001649 "metaclass conflict: "
1650 "the metaclass of a derived class "
1651 "must be a (non-strict) subclass "
1652 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001653 return NULL;
1654 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001655 if (winner != metatype) {
1656 if (winner->tp_new != type_new) /* Pass it to the winner */
1657 return winner->tp_new(winner, args, kwds);
1658 metatype = winner;
1659 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001660
1661 /* Adjust for empty tuple bases */
1662 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001663 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001664 if (bases == NULL)
1665 return NULL;
1666 nbases = 1;
1667 }
1668 else
1669 Py_INCREF(bases);
1670
1671 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1672
1673 /* Calculate best base, and check that all bases are type objects */
1674 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001675 if (base == NULL) {
1676 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001677 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001678 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001679 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1680 PyErr_Format(PyExc_TypeError,
1681 "type '%.100s' is not an acceptable base type",
1682 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001683 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001684 return NULL;
1685 }
1686
Tim Peters6d6c1a32001-08-02 04:15:00 +00001687 /* Check for a __slots__ sequence variable in dict, and count it */
1688 slots = PyDict_GetItemString(dict, "__slots__");
1689 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001690 add_dict = 0;
1691 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001692 may_add_dict = base->tp_dictoffset == 0;
1693 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1694 if (slots == NULL) {
1695 if (may_add_dict) {
1696 add_dict++;
1697 }
1698 if (may_add_weak) {
1699 add_weak++;
1700 }
1701 }
1702 else {
1703 /* Have slots */
1704
Tim Peters6d6c1a32001-08-02 04:15:00 +00001705 /* Make it into a tuple */
1706 if (PyString_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001707 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001708 else
1709 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001710 if (slots == NULL) {
1711 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001712 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001713 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001714 assert(PyTuple_Check(slots));
1715
1716 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001717 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001718 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001719 PyErr_Format(PyExc_TypeError,
1720 "nonempty __slots__ "
1721 "not supported for subtype of '%s'",
1722 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001723 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001724 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001725 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001726 return NULL;
1727 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001728
Martin v. Löwisd919a592002-10-14 21:07:28 +00001729#ifdef Py_USING_UNICODE
1730 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001731 if (tmp != slots) {
1732 Py_DECREF(slots);
1733 slots = tmp;
1734 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001735 if (!tmp)
1736 return NULL;
1737#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001738 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001739 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001740 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1741 char *s;
1742 if (!valid_identifier(tmp))
1743 goto bad_slots;
1744 assert(PyString_Check(tmp));
1745 s = PyString_AS_STRING(tmp);
1746 if (strcmp(s, "__dict__") == 0) {
1747 if (!may_add_dict || add_dict) {
1748 PyErr_SetString(PyExc_TypeError,
1749 "__dict__ slot disallowed: "
1750 "we already got one");
1751 goto bad_slots;
1752 }
1753 add_dict++;
1754 }
1755 if (strcmp(s, "__weakref__") == 0) {
1756 if (!may_add_weak || add_weak) {
1757 PyErr_SetString(PyExc_TypeError,
1758 "__weakref__ slot disallowed: "
1759 "either we already got one, "
1760 "or __itemsize__ != 0");
1761 goto bad_slots;
1762 }
1763 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001764 }
1765 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001766
Guido van Rossumad47da02002-08-12 19:05:44 +00001767 /* Copy slots into yet another tuple, demangling names */
1768 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001769 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001770 goto bad_slots;
1771 for (i = j = 0; i < nslots; i++) {
1772 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001773 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001774 s = PyString_AS_STRING(tmp);
1775 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1776 (add_weak && strcmp(s, "__weakref__") == 0))
1777 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001778 tmp =_Py_Mangle(name, tmp);
1779 if (!tmp)
1780 goto bad_slots;
Guido van Rossumad47da02002-08-12 19:05:44 +00001781 PyTuple_SET_ITEM(newslots, j, tmp);
1782 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001783 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001784 assert(j == nslots - add_dict - add_weak);
1785 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001786 Py_DECREF(slots);
1787 slots = newslots;
1788
Guido van Rossumad47da02002-08-12 19:05:44 +00001789 /* Secondary bases may provide weakrefs or dict */
1790 if (nbases > 1 &&
1791 ((may_add_dict && !add_dict) ||
1792 (may_add_weak && !add_weak))) {
1793 for (i = 0; i < nbases; i++) {
1794 tmp = PyTuple_GET_ITEM(bases, i);
1795 if (tmp == (PyObject *)base)
1796 continue; /* Skip primary base */
1797 if (PyClass_Check(tmp)) {
1798 /* Classic base class provides both */
1799 if (may_add_dict && !add_dict)
1800 add_dict++;
1801 if (may_add_weak && !add_weak)
1802 add_weak++;
1803 break;
1804 }
1805 assert(PyType_Check(tmp));
1806 tmptype = (PyTypeObject *)tmp;
1807 if (may_add_dict && !add_dict &&
1808 tmptype->tp_dictoffset != 0)
1809 add_dict++;
1810 if (may_add_weak && !add_weak &&
1811 tmptype->tp_weaklistoffset != 0)
1812 add_weak++;
1813 if (may_add_dict && !add_dict)
1814 continue;
1815 if (may_add_weak && !add_weak)
1816 continue;
1817 /* Nothing more to check */
1818 break;
1819 }
1820 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001821 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001822
1823 /* XXX From here until type is safely allocated,
1824 "return NULL" may leak slots! */
1825
1826 /* Allocate the type object */
1827 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001828 if (type == NULL) {
1829 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001830 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001831 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001832 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001833
1834 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001835 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001836 Py_INCREF(name);
1837 et->name = name;
1838 et->slots = slots;
1839
Guido van Rossumdc91b992001-08-08 22:26:22 +00001840 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001841 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1842 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001843 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1844 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001845
1846 /* It's a new-style number unless it specifically inherits any
1847 old-style numeric behavior */
1848 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1849 (base->tp_as_number == NULL))
1850 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1851
1852 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001853 type->tp_as_number = &et->as_number;
1854 type->tp_as_sequence = &et->as_sequence;
1855 type->tp_as_mapping = &et->as_mapping;
1856 type->tp_as_buffer = &et->as_buffer;
1857 type->tp_name = PyString_AS_STRING(name);
1858
1859 /* Set tp_base and tp_bases */
1860 type->tp_bases = bases;
1861 Py_INCREF(base);
1862 type->tp_base = base;
1863
Guido van Rossum687ae002001-10-15 22:03:32 +00001864 /* Initialize tp_dict from passed-in dict */
1865 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001866 if (dict == NULL) {
1867 Py_DECREF(type);
1868 return NULL;
1869 }
1870
Guido van Rossumc3542212001-08-16 09:18:56 +00001871 /* Set __module__ in the dict */
1872 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1873 tmp = PyEval_GetGlobals();
1874 if (tmp != NULL) {
1875 tmp = PyDict_GetItemString(tmp, "__name__");
1876 if (tmp != NULL) {
1877 if (PyDict_SetItemString(dict, "__module__",
1878 tmp) < 0)
1879 return NULL;
1880 }
1881 }
1882 }
1883
Tim Peters2f93e282001-10-04 05:27:00 +00001884 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001885 and is a string. The __doc__ accessor will first look for tp_doc;
1886 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001887 */
1888 {
1889 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1890 if (doc != NULL && PyString_Check(doc)) {
1891 const size_t n = (size_t)PyString_GET_SIZE(doc);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001892 char *tp_doc = PyObject_MALLOC(n+1);
1893 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00001894 Py_DECREF(type);
1895 return NULL;
1896 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001897 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
1898 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00001899 }
1900 }
1901
Tim Peters6d6c1a32001-08-02 04:15:00 +00001902 /* Special-case __new__: if it's a plain function,
1903 make it a static function */
1904 tmp = PyDict_GetItemString(dict, "__new__");
1905 if (tmp != NULL && PyFunction_Check(tmp)) {
1906 tmp = PyStaticMethod_New(tmp);
1907 if (tmp == NULL) {
1908 Py_DECREF(type);
1909 return NULL;
1910 }
1911 PyDict_SetItemString(dict, "__new__", tmp);
1912 Py_DECREF(tmp);
1913 }
1914
1915 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001916 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001917 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001918 if (slots != NULL) {
1919 for (i = 0; i < nslots; i++, mp++) {
1920 mp->name = PyString_AS_STRING(
1921 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001922 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001923 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001924 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001925 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001926 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001927 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001928 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001929 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001930 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001931 slotoffset += sizeof(PyObject *);
1932 }
1933 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001934 if (add_dict) {
1935 if (base->tp_itemsize)
1936 type->tp_dictoffset = -(long)sizeof(PyObject *);
1937 else
1938 type->tp_dictoffset = slotoffset;
1939 slotoffset += sizeof(PyObject *);
1940 }
1941 if (add_weak) {
1942 assert(!base->tp_itemsize);
1943 type->tp_weaklistoffset = slotoffset;
1944 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001945 }
1946 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001947 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001948 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001949
1950 if (type->tp_weaklistoffset && type->tp_dictoffset)
1951 type->tp_getset = subtype_getsets_full;
1952 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1953 type->tp_getset = subtype_getsets_weakref_only;
1954 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1955 type->tp_getset = subtype_getsets_dict_only;
1956 else
1957 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001958
1959 /* Special case some slots */
1960 if (type->tp_dictoffset != 0 || nslots > 0) {
1961 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1962 type->tp_getattro = PyObject_GenericGetAttr;
1963 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1964 type->tp_setattro = PyObject_GenericSetAttr;
1965 }
1966 type->tp_dealloc = subtype_dealloc;
1967
Guido van Rossum9475a232001-10-05 20:51:39 +00001968 /* Enable GC unless there are really no instance variables possible */
1969 if (!(type->tp_basicsize == sizeof(PyObject) &&
1970 type->tp_itemsize == 0))
1971 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1972
Tim Peters6d6c1a32001-08-02 04:15:00 +00001973 /* Always override allocation strategy to use regular heap */
1974 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001975 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001976 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001977 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001978 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001979 }
1980 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001981 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001982
1983 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001984 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001985 Py_DECREF(type);
1986 return NULL;
1987 }
1988
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001989 /* Put the proper slots in place */
1990 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001991
Tim Peters6d6c1a32001-08-02 04:15:00 +00001992 return (PyObject *)type;
1993}
1994
1995/* Internal API to look for a name through the MRO.
1996 This returns a borrowed reference, and doesn't set an exception! */
1997PyObject *
1998_PyType_Lookup(PyTypeObject *type, PyObject *name)
1999{
2000 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002001 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002002
Guido van Rossum687ae002001-10-15 22:03:32 +00002003 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002004 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002005
2006 /* If mro is NULL, the type is either not yet initialized
2007 by PyType_Ready(), or already cleared by type_clear().
2008 Either way the safest thing to do is to return NULL. */
2009 if (mro == NULL)
2010 return NULL;
2011
Tim Peters6d6c1a32001-08-02 04:15:00 +00002012 assert(PyTuple_Check(mro));
2013 n = PyTuple_GET_SIZE(mro);
2014 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002015 base = PyTuple_GET_ITEM(mro, i);
2016 if (PyClass_Check(base))
2017 dict = ((PyClassObject *)base)->cl_dict;
2018 else {
2019 assert(PyType_Check(base));
2020 dict = ((PyTypeObject *)base)->tp_dict;
2021 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002022 assert(dict && PyDict_Check(dict));
2023 res = PyDict_GetItem(dict, name);
2024 if (res != NULL)
2025 return res;
2026 }
2027 return NULL;
2028}
2029
2030/* This is similar to PyObject_GenericGetAttr(),
2031 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2032static PyObject *
2033type_getattro(PyTypeObject *type, PyObject *name)
2034{
2035 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002036 PyObject *meta_attribute, *attribute;
2037 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002038
2039 /* Initialize this type (we'll assume the metatype is initialized) */
2040 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002041 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002042 return NULL;
2043 }
2044
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002045 /* No readable descriptor found yet */
2046 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002047
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002048 /* Look for the attribute in the metatype */
2049 meta_attribute = _PyType_Lookup(metatype, name);
2050
2051 if (meta_attribute != NULL) {
2052 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002053
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002054 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2055 /* Data descriptors implement tp_descr_set to intercept
2056 * writes. Assume the attribute is not overridden in
2057 * type's tp_dict (and bases): call the descriptor now.
2058 */
2059 return meta_get(meta_attribute, (PyObject *)type,
2060 (PyObject *)metatype);
2061 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002062 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002063 }
2064
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002065 /* No data descriptor found on metatype. Look in tp_dict of this
2066 * type and its bases */
2067 attribute = _PyType_Lookup(type, name);
2068 if (attribute != NULL) {
2069 /* Implement descriptor functionality, if any */
2070 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002071
2072 Py_XDECREF(meta_attribute);
2073
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002074 if (local_get != NULL) {
2075 /* NULL 2nd argument indicates the descriptor was
2076 * found on the target object itself (or a base) */
2077 return local_get(attribute, (PyObject *)NULL,
2078 (PyObject *)type);
2079 }
Tim Peters34592512002-07-11 06:23:50 +00002080
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002081 Py_INCREF(attribute);
2082 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002083 }
2084
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002085 /* No attribute found in local __dict__ (or bases): use the
2086 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002087 if (meta_get != NULL) {
2088 PyObject *res;
2089 res = meta_get(meta_attribute, (PyObject *)type,
2090 (PyObject *)metatype);
2091 Py_DECREF(meta_attribute);
2092 return res;
2093 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002094
2095 /* If an ordinary attribute was found on the metatype, return it now */
2096 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002097 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002098 }
2099
2100 /* Give up */
2101 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002102 "type object '%.50s' has no attribute '%.400s'",
2103 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002104 return NULL;
2105}
2106
2107static int
2108type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2109{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002110 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2111 PyErr_Format(
2112 PyExc_TypeError,
2113 "can't set attributes of built-in/extension type '%s'",
2114 type->tp_name);
2115 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002116 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002117 /* XXX Example of how I expect this to be used...
2118 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2119 return -1;
2120 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002121 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2122 return -1;
2123 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002124}
2125
2126static void
2127type_dealloc(PyTypeObject *type)
2128{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002129 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002130
2131 /* Assert this is a heap-allocated type object */
2132 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002133 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002134 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002135 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002136 Py_XDECREF(type->tp_base);
2137 Py_XDECREF(type->tp_dict);
2138 Py_XDECREF(type->tp_bases);
2139 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002140 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002141 Py_XDECREF(type->tp_subclasses);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002142 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2143 * of most other objects. It's okay to cast it to char *.
2144 */
2145 PyObject_Free((char *)type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002146 Py_XDECREF(et->name);
2147 Py_XDECREF(et->slots);
2148 type->ob_type->tp_free((PyObject *)type);
2149}
2150
Guido van Rossum1c450732001-10-08 15:18:27 +00002151static PyObject *
2152type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2153{
2154 PyObject *list, *raw, *ref;
2155 int i, n;
2156
2157 list = PyList_New(0);
2158 if (list == NULL)
2159 return NULL;
2160 raw = type->tp_subclasses;
2161 if (raw == NULL)
2162 return list;
2163 assert(PyList_Check(raw));
2164 n = PyList_GET_SIZE(raw);
2165 for (i = 0; i < n; i++) {
2166 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002167 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002168 ref = PyWeakref_GET_OBJECT(ref);
2169 if (ref != Py_None) {
2170 if (PyList_Append(list, ref) < 0) {
2171 Py_DECREF(list);
2172 return NULL;
2173 }
2174 }
2175 }
2176 return list;
2177}
2178
Tim Peters6d6c1a32001-08-02 04:15:00 +00002179static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002180 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002181 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002182 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002183 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002184 {0}
2185};
2186
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002187PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002188"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002189"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002190
Guido van Rossum048eb752001-10-02 21:24:57 +00002191static int
2192type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2193{
Guido van Rossum048eb752001-10-02 21:24:57 +00002194 int err;
2195
Guido van Rossuma3862092002-06-10 15:24:42 +00002196 /* Because of type_is_gc(), the collector only calls this
2197 for heaptypes. */
2198 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002199
2200#define VISIT(SLOT) \
2201 if (SLOT) { \
2202 err = visit((PyObject *)(SLOT), arg); \
2203 if (err) \
2204 return err; \
2205 }
2206
2207 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002208 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002209 VISIT(type->tp_mro);
2210 VISIT(type->tp_bases);
2211 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002212
2213 /* There's no need to visit type->tp_subclasses or
Guido van Rossume5c691a2003-03-07 15:13:17 +00002214 ((PyHeapTypeObject *)type)->slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002215 in cycles; tp_subclasses is a list of weak references,
2216 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002217
2218#undef VISIT
2219
2220 return 0;
2221}
2222
2223static int
2224type_clear(PyTypeObject *type)
2225{
Guido van Rossum048eb752001-10-02 21:24:57 +00002226 PyObject *tmp;
2227
Guido van Rossuma3862092002-06-10 15:24:42 +00002228 /* Because of type_is_gc(), the collector only calls this
2229 for heaptypes. */
2230 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002231
2232#define CLEAR(SLOT) \
2233 if (SLOT) { \
2234 tmp = (PyObject *)(SLOT); \
2235 SLOT = NULL; \
2236 Py_DECREF(tmp); \
2237 }
2238
Guido van Rossuma3862092002-06-10 15:24:42 +00002239 /* The only field we need to clear is tp_mro, which is part of a
2240 hard cycle (its first element is the class itself) that won't
2241 be broken otherwise (it's a tuple and tuples don't have a
2242 tp_clear handler). None of the other fields need to be
2243 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002244
Guido van Rossuma3862092002-06-10 15:24:42 +00002245 tp_dict:
2246 It is a dict, so the collector will call its tp_clear.
2247
2248 tp_cache:
2249 Not used; if it were, it would be a dict.
2250
2251 tp_bases, tp_base:
2252 If these are involved in a cycle, there must be at least
2253 one other, mutable object in the cycle, e.g. a base
2254 class's dict; the cycle will be broken that way.
2255
2256 tp_subclasses:
2257 A list of weak references can't be part of a cycle; and
2258 lists have their own tp_clear.
2259
Guido van Rossume5c691a2003-03-07 15:13:17 +00002260 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002261 A tuple of strings can't be part of a cycle.
2262 */
2263
2264 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002265
Guido van Rossum048eb752001-10-02 21:24:57 +00002266#undef CLEAR
2267
2268 return 0;
2269}
2270
2271static int
2272type_is_gc(PyTypeObject *type)
2273{
2274 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2275}
2276
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002277PyTypeObject PyType_Type = {
2278 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002279 0, /* ob_size */
2280 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002281 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002282 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002283 (destructor)type_dealloc, /* tp_dealloc */
2284 0, /* tp_print */
2285 0, /* tp_getattr */
2286 0, /* tp_setattr */
2287 type_compare, /* tp_compare */
2288 (reprfunc)type_repr, /* tp_repr */
2289 0, /* tp_as_number */
2290 0, /* tp_as_sequence */
2291 0, /* tp_as_mapping */
2292 (hashfunc)_Py_HashPointer, /* tp_hash */
2293 (ternaryfunc)type_call, /* tp_call */
2294 0, /* tp_str */
2295 (getattrofunc)type_getattro, /* tp_getattro */
2296 (setattrofunc)type_setattro, /* tp_setattro */
2297 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002298 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2299 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002300 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002301 (traverseproc)type_traverse, /* tp_traverse */
2302 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002303 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002304 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002305 0, /* tp_iter */
2306 0, /* tp_iternext */
2307 type_methods, /* tp_methods */
2308 type_members, /* tp_members */
2309 type_getsets, /* tp_getset */
2310 0, /* tp_base */
2311 0, /* tp_dict */
2312 0, /* tp_descr_get */
2313 0, /* tp_descr_set */
2314 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2315 0, /* tp_init */
2316 0, /* tp_alloc */
2317 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002318 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002319 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002320};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002321
2322
2323/* The base type of all types (eventually)... except itself. */
2324
2325static int
2326object_init(PyObject *self, PyObject *args, PyObject *kwds)
2327{
2328 return 0;
2329}
2330
Guido van Rossum298e4212003-02-13 16:30:16 +00002331/* If we don't have a tp_new for a new-style class, new will use this one.
2332 Therefore this should take no arguments/keywords. However, this new may
2333 also be inherited by objects that define a tp_init but no tp_new. These
2334 objects WILL pass argumets to tp_new, because it gets the same args as
2335 tp_init. So only allow arguments if we aren't using the default init, in
2336 which case we expect init to handle argument parsing. */
2337static PyObject *
2338object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2339{
2340 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2341 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2342 PyErr_SetString(PyExc_TypeError,
2343 "default __new__ takes no parameters");
2344 return NULL;
2345 }
2346 return type->tp_alloc(type, 0);
2347}
2348
Tim Peters6d6c1a32001-08-02 04:15:00 +00002349static void
2350object_dealloc(PyObject *self)
2351{
2352 self->ob_type->tp_free(self);
2353}
2354
Guido van Rossum8e248182001-08-12 05:17:56 +00002355static PyObject *
2356object_repr(PyObject *self)
2357{
Guido van Rossum76e69632001-08-16 18:52:43 +00002358 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002359 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002360
Guido van Rossum76e69632001-08-16 18:52:43 +00002361 type = self->ob_type;
2362 mod = type_module(type, NULL);
2363 if (mod == NULL)
2364 PyErr_Clear();
2365 else if (!PyString_Check(mod)) {
2366 Py_DECREF(mod);
2367 mod = NULL;
2368 }
2369 name = type_name(type, NULL);
2370 if (name == NULL)
2371 return NULL;
2372 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002373 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002374 PyString_AS_STRING(mod),
2375 PyString_AS_STRING(name),
2376 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002377 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002378 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002379 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002380 Py_XDECREF(mod);
2381 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002382 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002383}
2384
Guido van Rossumb8f63662001-08-15 23:57:02 +00002385static PyObject *
2386object_str(PyObject *self)
2387{
2388 unaryfunc f;
2389
2390 f = self->ob_type->tp_repr;
2391 if (f == NULL)
2392 f = object_repr;
2393 return f(self);
2394}
2395
Guido van Rossum8e248182001-08-12 05:17:56 +00002396static long
2397object_hash(PyObject *self)
2398{
2399 return _Py_HashPointer(self);
2400}
Guido van Rossum8e248182001-08-12 05:17:56 +00002401
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002402static PyObject *
2403object_get_class(PyObject *self, void *closure)
2404{
2405 Py_INCREF(self->ob_type);
2406 return (PyObject *)(self->ob_type);
2407}
2408
2409static int
2410equiv_structs(PyTypeObject *a, PyTypeObject *b)
2411{
2412 return a == b ||
2413 (a != NULL &&
2414 b != NULL &&
2415 a->tp_basicsize == b->tp_basicsize &&
2416 a->tp_itemsize == b->tp_itemsize &&
2417 a->tp_dictoffset == b->tp_dictoffset &&
2418 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2419 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2420 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2421}
2422
2423static int
2424same_slots_added(PyTypeObject *a, PyTypeObject *b)
2425{
2426 PyTypeObject *base = a->tp_base;
2427 int size;
2428
2429 if (base != b->tp_base)
2430 return 0;
2431 if (equiv_structs(a, base) && equiv_structs(b, base))
2432 return 1;
2433 size = base->tp_basicsize;
2434 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2435 size += sizeof(PyObject *);
2436 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2437 size += sizeof(PyObject *);
2438 return size == a->tp_basicsize && size == b->tp_basicsize;
2439}
2440
2441static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002442compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2443{
2444 PyTypeObject *newbase, *oldbase;
2445
2446 if (new->tp_dealloc != old->tp_dealloc ||
2447 new->tp_free != old->tp_free)
2448 {
2449 PyErr_Format(PyExc_TypeError,
2450 "%s assignment: "
2451 "'%s' deallocator differs from '%s'",
2452 attr,
2453 new->tp_name,
2454 old->tp_name);
2455 return 0;
2456 }
2457 newbase = new;
2458 oldbase = old;
2459 while (equiv_structs(newbase, newbase->tp_base))
2460 newbase = newbase->tp_base;
2461 while (equiv_structs(oldbase, oldbase->tp_base))
2462 oldbase = oldbase->tp_base;
2463 if (newbase != oldbase &&
2464 (newbase->tp_base != oldbase->tp_base ||
2465 !same_slots_added(newbase, oldbase))) {
2466 PyErr_Format(PyExc_TypeError,
2467 "%s assignment: "
2468 "'%s' object layout differs from '%s'",
2469 attr,
2470 new->tp_name,
2471 old->tp_name);
2472 return 0;
2473 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002474
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002475 return 1;
2476}
2477
2478static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002479object_set_class(PyObject *self, PyObject *value, void *closure)
2480{
2481 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002482 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002483
Guido van Rossumb6b89422002-04-15 01:03:30 +00002484 if (value == NULL) {
2485 PyErr_SetString(PyExc_TypeError,
2486 "can't delete __class__ attribute");
2487 return -1;
2488 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002489 if (!PyType_Check(value)) {
2490 PyErr_Format(PyExc_TypeError,
2491 "__class__ must be set to new-style class, not '%s' object",
2492 value->ob_type->tp_name);
2493 return -1;
2494 }
2495 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002496 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2497 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2498 {
2499 PyErr_Format(PyExc_TypeError,
2500 "__class__ assignment: only for heap types");
2501 return -1;
2502 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002503 if (compatible_for_assignment(new, old, "__class__")) {
2504 Py_INCREF(new);
2505 self->ob_type = new;
2506 Py_DECREF(old);
2507 return 0;
2508 }
2509 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002510 return -1;
2511 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002512}
2513
2514static PyGetSetDef object_getsets[] = {
2515 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002516 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002517 {0}
2518};
2519
Guido van Rossumc53f0092003-02-18 22:05:12 +00002520
Guido van Rossum036f9992003-02-21 22:02:54 +00002521/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2522 We fall back to helpers in copy_reg for:
2523 - pickle protocols < 2
2524 - calculating the list of slot names (done only once per class)
2525 - the __newobj__ function (which is used as a token but never called)
2526*/
2527
2528static PyObject *
2529import_copy_reg(void)
2530{
2531 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002532
2533 if (!copy_reg_str) {
2534 copy_reg_str = PyString_InternFromString("copy_reg");
2535 if (copy_reg_str == NULL)
2536 return NULL;
2537 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002538
2539 return PyImport_Import(copy_reg_str);
2540}
2541
2542static PyObject *
2543slotnames(PyObject *cls)
2544{
2545 PyObject *clsdict;
2546 PyObject *copy_reg;
2547 PyObject *slotnames;
2548
2549 if (!PyType_Check(cls)) {
2550 Py_INCREF(Py_None);
2551 return Py_None;
2552 }
2553
2554 clsdict = ((PyTypeObject *)cls)->tp_dict;
2555 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002556 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002557 Py_INCREF(slotnames);
2558 return slotnames;
2559 }
2560
2561 copy_reg = import_copy_reg();
2562 if (copy_reg == NULL)
2563 return NULL;
2564
2565 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2566 Py_DECREF(copy_reg);
2567 if (slotnames != NULL &&
2568 slotnames != Py_None &&
2569 !PyList_Check(slotnames))
2570 {
2571 PyErr_SetString(PyExc_TypeError,
2572 "copy_reg._slotnames didn't return a list or None");
2573 Py_DECREF(slotnames);
2574 slotnames = NULL;
2575 }
2576
2577 return slotnames;
2578}
2579
2580static PyObject *
2581reduce_2(PyObject *obj)
2582{
2583 PyObject *cls, *getnewargs;
2584 PyObject *args = NULL, *args2 = NULL;
2585 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2586 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2587 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
2588 int i, n;
2589
2590 cls = PyObject_GetAttrString(obj, "__class__");
2591 if (cls == NULL)
2592 return NULL;
2593
2594 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2595 if (getnewargs != NULL) {
2596 args = PyObject_CallObject(getnewargs, NULL);
2597 Py_DECREF(getnewargs);
2598 if (args != NULL && !PyTuple_Check(args)) {
2599 PyErr_SetString(PyExc_TypeError,
2600 "__getnewargs__ should return a tuple");
2601 goto end;
2602 }
2603 }
2604 else {
2605 PyErr_Clear();
2606 args = PyTuple_New(0);
2607 }
2608 if (args == NULL)
2609 goto end;
2610
2611 getstate = PyObject_GetAttrString(obj, "__getstate__");
2612 if (getstate != NULL) {
2613 state = PyObject_CallObject(getstate, NULL);
2614 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002615 if (state == NULL)
2616 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002617 }
2618 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002619 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002620 state = PyObject_GetAttrString(obj, "__dict__");
2621 if (state == NULL) {
2622 PyErr_Clear();
2623 state = Py_None;
2624 Py_INCREF(state);
2625 }
2626 names = slotnames(cls);
2627 if (names == NULL)
2628 goto end;
2629 if (names != Py_None) {
2630 assert(PyList_Check(names));
2631 slots = PyDict_New();
2632 if (slots == NULL)
2633 goto end;
2634 n = 0;
2635 /* Can't pre-compute the list size; the list
2636 is stored on the class so accessible to other
2637 threads, which may be run by DECREF */
2638 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2639 PyObject *name, *value;
2640 name = PyList_GET_ITEM(names, i);
2641 value = PyObject_GetAttr(obj, name);
2642 if (value == NULL)
2643 PyErr_Clear();
2644 else {
2645 int err = PyDict_SetItem(slots, name,
2646 value);
2647 Py_DECREF(value);
2648 if (err)
2649 goto end;
2650 n++;
2651 }
2652 }
2653 if (n) {
2654 state = Py_BuildValue("(NO)", state, slots);
2655 if (state == NULL)
2656 goto end;
2657 }
2658 }
2659 }
2660
2661 if (!PyList_Check(obj)) {
2662 listitems = Py_None;
2663 Py_INCREF(listitems);
2664 }
2665 else {
2666 listitems = PyObject_GetIter(obj);
2667 if (listitems == NULL)
2668 goto end;
2669 }
2670
2671 if (!PyDict_Check(obj)) {
2672 dictitems = Py_None;
2673 Py_INCREF(dictitems);
2674 }
2675 else {
2676 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2677 if (dictitems == NULL)
2678 goto end;
2679 }
2680
2681 copy_reg = import_copy_reg();
2682 if (copy_reg == NULL)
2683 goto end;
2684 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2685 if (newobj == NULL)
2686 goto end;
2687
2688 n = PyTuple_GET_SIZE(args);
2689 args2 = PyTuple_New(n+1);
2690 if (args2 == NULL)
2691 goto end;
2692 PyTuple_SET_ITEM(args2, 0, cls);
2693 cls = NULL;
2694 for (i = 0; i < n; i++) {
2695 PyObject *v = PyTuple_GET_ITEM(args, i);
2696 Py_INCREF(v);
2697 PyTuple_SET_ITEM(args2, i+1, v);
2698 }
2699
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002700 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002701
2702 end:
2703 Py_XDECREF(cls);
2704 Py_XDECREF(args);
2705 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002706 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002707 Py_XDECREF(state);
2708 Py_XDECREF(names);
2709 Py_XDECREF(listitems);
2710 Py_XDECREF(dictitems);
2711 Py_XDECREF(copy_reg);
2712 Py_XDECREF(newobj);
2713 return res;
2714}
2715
2716static PyObject *
2717object_reduce_ex(PyObject *self, PyObject *args)
2718{
2719 /* Call copy_reg._reduce_ex(self, proto) */
2720 PyObject *reduce, *copy_reg, *res;
2721 int proto = 0;
2722
2723 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2724 return NULL;
2725
2726 reduce = PyObject_GetAttrString(self, "__reduce__");
2727 if (reduce == NULL)
2728 PyErr_Clear();
2729 else {
2730 PyObject *cls, *clsreduce, *objreduce;
2731 int override;
2732 cls = PyObject_GetAttrString(self, "__class__");
2733 if (cls == NULL) {
2734 Py_DECREF(reduce);
2735 return NULL;
2736 }
2737 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2738 Py_DECREF(cls);
2739 if (clsreduce == NULL) {
2740 Py_DECREF(reduce);
2741 return NULL;
2742 }
2743 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2744 "__reduce__");
2745 override = (clsreduce != objreduce);
2746 Py_DECREF(clsreduce);
2747 if (override) {
2748 res = PyObject_CallObject(reduce, NULL);
2749 Py_DECREF(reduce);
2750 return res;
2751 }
2752 else
2753 Py_DECREF(reduce);
2754 }
2755
2756 if (proto >= 2)
2757 return reduce_2(self);
2758
2759 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002760 if (!copy_reg)
2761 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002762
Guido van Rossumc53f0092003-02-18 22:05:12 +00002763 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002764 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002765
Guido van Rossum3926a632001-09-25 16:25:58 +00002766 return res;
2767}
2768
2769static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002770 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2771 PyDoc_STR("helper for pickle")},
2772 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002773 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002774 {0}
2775};
2776
Guido van Rossum036f9992003-02-21 22:02:54 +00002777
Tim Peters6d6c1a32001-08-02 04:15:00 +00002778PyTypeObject PyBaseObject_Type = {
2779 PyObject_HEAD_INIT(&PyType_Type)
2780 0, /* ob_size */
2781 "object", /* tp_name */
2782 sizeof(PyObject), /* tp_basicsize */
2783 0, /* tp_itemsize */
2784 (destructor)object_dealloc, /* tp_dealloc */
2785 0, /* tp_print */
2786 0, /* tp_getattr */
2787 0, /* tp_setattr */
2788 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002789 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002790 0, /* tp_as_number */
2791 0, /* tp_as_sequence */
2792 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002793 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002794 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002795 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002796 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002797 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002798 0, /* tp_as_buffer */
2799 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002800 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002801 0, /* tp_traverse */
2802 0, /* tp_clear */
2803 0, /* tp_richcompare */
2804 0, /* tp_weaklistoffset */
2805 0, /* tp_iter */
2806 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002807 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002808 0, /* tp_members */
2809 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002810 0, /* tp_base */
2811 0, /* tp_dict */
2812 0, /* tp_descr_get */
2813 0, /* tp_descr_set */
2814 0, /* tp_dictoffset */
2815 object_init, /* tp_init */
2816 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002817 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002818 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002819};
2820
2821
2822/* Initialize the __dict__ in a type object */
2823
2824static int
2825add_methods(PyTypeObject *type, PyMethodDef *meth)
2826{
Guido van Rossum687ae002001-10-15 22:03:32 +00002827 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002828
2829 for (; meth->ml_name != NULL; meth++) {
2830 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002831 if (PyDict_GetItemString(dict, meth->ml_name) &&
2832 !(meth->ml_flags & METH_COEXIST))
2833 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002834 if (meth->ml_flags & METH_CLASS) {
2835 if (meth->ml_flags & METH_STATIC) {
2836 PyErr_SetString(PyExc_ValueError,
2837 "method cannot be both class and static");
2838 return -1;
2839 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002840 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002841 }
2842 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002843 PyObject *cfunc = PyCFunction_New(meth, NULL);
2844 if (cfunc == NULL)
2845 return -1;
2846 descr = PyStaticMethod_New(cfunc);
2847 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002848 }
2849 else {
2850 descr = PyDescr_NewMethod(type, meth);
2851 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002852 if (descr == NULL)
2853 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002854 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002855 return -1;
2856 Py_DECREF(descr);
2857 }
2858 return 0;
2859}
2860
2861static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002862add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002863{
Guido van Rossum687ae002001-10-15 22:03:32 +00002864 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002865
2866 for (; memb->name != NULL; memb++) {
2867 PyObject *descr;
2868 if (PyDict_GetItemString(dict, memb->name))
2869 continue;
2870 descr = PyDescr_NewMember(type, memb);
2871 if (descr == NULL)
2872 return -1;
2873 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2874 return -1;
2875 Py_DECREF(descr);
2876 }
2877 return 0;
2878}
2879
2880static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002881add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002882{
Guido van Rossum687ae002001-10-15 22:03:32 +00002883 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002884
2885 for (; gsp->name != NULL; gsp++) {
2886 PyObject *descr;
2887 if (PyDict_GetItemString(dict, gsp->name))
2888 continue;
2889 descr = PyDescr_NewGetSet(type, gsp);
2890
2891 if (descr == NULL)
2892 return -1;
2893 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2894 return -1;
2895 Py_DECREF(descr);
2896 }
2897 return 0;
2898}
2899
Guido van Rossum13d52f02001-08-10 21:24:08 +00002900static void
2901inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002902{
2903 int oldsize, newsize;
2904
Guido van Rossum13d52f02001-08-10 21:24:08 +00002905 /* Special flag magic */
2906 if (!type->tp_as_buffer && base->tp_as_buffer) {
2907 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2908 type->tp_flags |=
2909 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2910 }
2911 if (!type->tp_as_sequence && base->tp_as_sequence) {
2912 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2913 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2914 }
2915 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2916 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2917 if ((!type->tp_as_number && base->tp_as_number) ||
2918 (!type->tp_as_sequence && base->tp_as_sequence)) {
2919 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2920 if (!type->tp_as_number && !type->tp_as_sequence) {
2921 type->tp_flags |= base->tp_flags &
2922 Py_TPFLAGS_HAVE_INPLACEOPS;
2923 }
2924 }
2925 /* Wow */
2926 }
2927 if (!type->tp_as_number && base->tp_as_number) {
2928 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2929 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2930 }
2931
2932 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002933 oldsize = base->tp_basicsize;
2934 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2935 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2936 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002937 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2938 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002939 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002940 if (type->tp_traverse == NULL)
2941 type->tp_traverse = base->tp_traverse;
2942 if (type->tp_clear == NULL)
2943 type->tp_clear = base->tp_clear;
2944 }
2945 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002946 /* The condition below could use some explanation.
2947 It appears that tp_new is not inherited for static types
2948 whose base class is 'object'; this seems to be a precaution
2949 so that old extension types don't suddenly become
2950 callable (object.__new__ wouldn't insure the invariants
2951 that the extension type's own factory function ensures).
2952 Heap types, of course, are under our control, so they do
2953 inherit tp_new; static extension types that specify some
2954 other built-in type as the default are considered
2955 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002956 if (base != &PyBaseObject_Type ||
2957 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2958 if (type->tp_new == NULL)
2959 type->tp_new = base->tp_new;
2960 }
2961 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002962 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002963
2964 /* Copy other non-function slots */
2965
2966#undef COPYVAL
2967#define COPYVAL(SLOT) \
2968 if (type->SLOT == 0) type->SLOT = base->SLOT
2969
2970 COPYVAL(tp_itemsize);
2971 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2972 COPYVAL(tp_weaklistoffset);
2973 }
2974 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2975 COPYVAL(tp_dictoffset);
2976 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002977}
2978
2979static void
2980inherit_slots(PyTypeObject *type, PyTypeObject *base)
2981{
2982 PyTypeObject *basebase;
2983
2984#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002985#undef COPYSLOT
2986#undef COPYNUM
2987#undef COPYSEQ
2988#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002989#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002990
2991#define SLOTDEFINED(SLOT) \
2992 (base->SLOT != 0 && \
2993 (basebase == NULL || base->SLOT != basebase->SLOT))
2994
Tim Peters6d6c1a32001-08-02 04:15:00 +00002995#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002996 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002997
2998#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2999#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3000#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003001#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003002
Guido van Rossum13d52f02001-08-10 21:24:08 +00003003 /* This won't inherit indirect slots (from tp_as_number etc.)
3004 if type doesn't provide the space. */
3005
3006 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3007 basebase = base->tp_base;
3008 if (basebase->tp_as_number == NULL)
3009 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003010 COPYNUM(nb_add);
3011 COPYNUM(nb_subtract);
3012 COPYNUM(nb_multiply);
3013 COPYNUM(nb_divide);
3014 COPYNUM(nb_remainder);
3015 COPYNUM(nb_divmod);
3016 COPYNUM(nb_power);
3017 COPYNUM(nb_negative);
3018 COPYNUM(nb_positive);
3019 COPYNUM(nb_absolute);
3020 COPYNUM(nb_nonzero);
3021 COPYNUM(nb_invert);
3022 COPYNUM(nb_lshift);
3023 COPYNUM(nb_rshift);
3024 COPYNUM(nb_and);
3025 COPYNUM(nb_xor);
3026 COPYNUM(nb_or);
3027 COPYNUM(nb_coerce);
3028 COPYNUM(nb_int);
3029 COPYNUM(nb_long);
3030 COPYNUM(nb_float);
3031 COPYNUM(nb_oct);
3032 COPYNUM(nb_hex);
3033 COPYNUM(nb_inplace_add);
3034 COPYNUM(nb_inplace_subtract);
3035 COPYNUM(nb_inplace_multiply);
3036 COPYNUM(nb_inplace_divide);
3037 COPYNUM(nb_inplace_remainder);
3038 COPYNUM(nb_inplace_power);
3039 COPYNUM(nb_inplace_lshift);
3040 COPYNUM(nb_inplace_rshift);
3041 COPYNUM(nb_inplace_and);
3042 COPYNUM(nb_inplace_xor);
3043 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003044 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3045 COPYNUM(nb_true_divide);
3046 COPYNUM(nb_floor_divide);
3047 COPYNUM(nb_inplace_true_divide);
3048 COPYNUM(nb_inplace_floor_divide);
3049 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003050 }
3051
Guido van Rossum13d52f02001-08-10 21:24:08 +00003052 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3053 basebase = base->tp_base;
3054 if (basebase->tp_as_sequence == NULL)
3055 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003056 COPYSEQ(sq_length);
3057 COPYSEQ(sq_concat);
3058 COPYSEQ(sq_repeat);
3059 COPYSEQ(sq_item);
3060 COPYSEQ(sq_slice);
3061 COPYSEQ(sq_ass_item);
3062 COPYSEQ(sq_ass_slice);
3063 COPYSEQ(sq_contains);
3064 COPYSEQ(sq_inplace_concat);
3065 COPYSEQ(sq_inplace_repeat);
3066 }
3067
Guido van Rossum13d52f02001-08-10 21:24:08 +00003068 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3069 basebase = base->tp_base;
3070 if (basebase->tp_as_mapping == NULL)
3071 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003072 COPYMAP(mp_length);
3073 COPYMAP(mp_subscript);
3074 COPYMAP(mp_ass_subscript);
3075 }
3076
Tim Petersfc57ccb2001-10-12 02:38:24 +00003077 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3078 basebase = base->tp_base;
3079 if (basebase->tp_as_buffer == NULL)
3080 basebase = NULL;
3081 COPYBUF(bf_getreadbuffer);
3082 COPYBUF(bf_getwritebuffer);
3083 COPYBUF(bf_getsegcount);
3084 COPYBUF(bf_getcharbuffer);
3085 }
3086
Guido van Rossum13d52f02001-08-10 21:24:08 +00003087 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003088
Tim Peters6d6c1a32001-08-02 04:15:00 +00003089 COPYSLOT(tp_dealloc);
3090 COPYSLOT(tp_print);
3091 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3092 type->tp_getattr = base->tp_getattr;
3093 type->tp_getattro = base->tp_getattro;
3094 }
3095 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3096 type->tp_setattr = base->tp_setattr;
3097 type->tp_setattro = base->tp_setattro;
3098 }
3099 /* tp_compare see tp_richcompare */
3100 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003101 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003102 COPYSLOT(tp_call);
3103 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003104 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003105 if (type->tp_compare == NULL &&
3106 type->tp_richcompare == NULL &&
3107 type->tp_hash == NULL)
3108 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003109 type->tp_compare = base->tp_compare;
3110 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003111 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003112 }
3113 }
3114 else {
3115 COPYSLOT(tp_compare);
3116 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003117 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3118 COPYSLOT(tp_iter);
3119 COPYSLOT(tp_iternext);
3120 }
3121 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3122 COPYSLOT(tp_descr_get);
3123 COPYSLOT(tp_descr_set);
3124 COPYSLOT(tp_dictoffset);
3125 COPYSLOT(tp_init);
3126 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003127 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003128 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3129 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3130 /* They agree about gc. */
3131 COPYSLOT(tp_free);
3132 }
3133 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3134 type->tp_free == NULL &&
3135 base->tp_free == _PyObject_Del) {
3136 /* A bit of magic to plug in the correct default
3137 * tp_free function when a derived class adds gc,
3138 * didn't define tp_free, and the base uses the
3139 * default non-gc tp_free.
3140 */
3141 type->tp_free = PyObject_GC_Del;
3142 }
3143 /* else they didn't agree about gc, and there isn't something
3144 * obvious to be done -- the type is on its own.
3145 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003146 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003147}
3148
Jeremy Hylton938ace62002-07-17 16:30:39 +00003149static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003150
Tim Peters6d6c1a32001-08-02 04:15:00 +00003151int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003152PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003153{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003154 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003155 PyTypeObject *base;
3156 int i, n;
3157
Guido van Rossumcab05802002-06-10 15:29:03 +00003158 if (type->tp_flags & Py_TPFLAGS_READY) {
3159 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003160 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003161 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003162 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003163
3164 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003165
Tim Peters36eb4df2003-03-23 03:33:13 +00003166#ifdef Py_TRACE_REFS
3167 /* PyType_Ready is the closest thing we have to a choke point
3168 * for type objects, so is the best place I can think of to try
3169 * to get type objects into the doubly-linked list of all objects.
3170 * Still, not all type objects go thru PyType_Ready.
3171 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003172 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003173#endif
3174
Tim Peters6d6c1a32001-08-02 04:15:00 +00003175 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3176 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003177 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003178 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003179 Py_INCREF(base);
3180 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003181
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003182 /* Initialize the base class */
3183 if (base && base->tp_dict == NULL) {
3184 if (PyType_Ready(base) < 0)
3185 goto error;
3186 }
3187
Guido van Rossum0986d822002-04-08 01:38:42 +00003188 /* Initialize ob_type if NULL. This means extensions that want to be
3189 compilable separately on Windows can call PyType_Ready() instead of
3190 initializing the ob_type field of their type objects. */
3191 if (type->ob_type == NULL)
3192 type->ob_type = base->ob_type;
3193
Tim Peters6d6c1a32001-08-02 04:15:00 +00003194 /* Initialize tp_bases */
3195 bases = type->tp_bases;
3196 if (bases == NULL) {
3197 if (base == NULL)
3198 bases = PyTuple_New(0);
3199 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003200 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003201 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003202 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003203 type->tp_bases = bases;
3204 }
3205
Guido van Rossum687ae002001-10-15 22:03:32 +00003206 /* Initialize tp_dict */
3207 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003208 if (dict == NULL) {
3209 dict = PyDict_New();
3210 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003211 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003212 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003213 }
3214
Guido van Rossum687ae002001-10-15 22:03:32 +00003215 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003216 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003217 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003218 if (type->tp_methods != NULL) {
3219 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003220 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003221 }
3222 if (type->tp_members != NULL) {
3223 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003224 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003225 }
3226 if (type->tp_getset != NULL) {
3227 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003228 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003229 }
3230
Tim Peters6d6c1a32001-08-02 04:15:00 +00003231 /* Calculate method resolution order */
3232 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003233 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003234 }
3235
Guido van Rossum13d52f02001-08-10 21:24:08 +00003236 /* Inherit special flags from dominant base */
3237 if (type->tp_base != NULL)
3238 inherit_special(type, type->tp_base);
3239
Tim Peters6d6c1a32001-08-02 04:15:00 +00003240 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003241 bases = type->tp_mro;
3242 assert(bases != NULL);
3243 assert(PyTuple_Check(bases));
3244 n = PyTuple_GET_SIZE(bases);
3245 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003246 PyObject *b = PyTuple_GET_ITEM(bases, i);
3247 if (PyType_Check(b))
3248 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003249 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003250
Tim Peters3cfe7542003-05-21 21:29:48 +00003251 /* Sanity check for tp_free. */
3252 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3253 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3254 /* This base class needs to call tp_free, but doesn't have
3255 * one, or its tp_free is for non-gc'ed objects.
3256 */
3257 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3258 "gc and is a base type but has inappropriate "
3259 "tp_free slot",
3260 type->tp_name);
3261 goto error;
3262 }
3263
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003264 /* if the type dictionary doesn't contain a __doc__, set it from
3265 the tp_doc slot.
3266 */
3267 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3268 if (type->tp_doc != NULL) {
3269 PyObject *doc = PyString_FromString(type->tp_doc);
3270 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3271 Py_DECREF(doc);
3272 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003273 PyDict_SetItemString(type->tp_dict,
3274 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003275 }
3276 }
3277
Guido van Rossum13d52f02001-08-10 21:24:08 +00003278 /* Some more special stuff */
3279 base = type->tp_base;
3280 if (base != NULL) {
3281 if (type->tp_as_number == NULL)
3282 type->tp_as_number = base->tp_as_number;
3283 if (type->tp_as_sequence == NULL)
3284 type->tp_as_sequence = base->tp_as_sequence;
3285 if (type->tp_as_mapping == NULL)
3286 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003287 if (type->tp_as_buffer == NULL)
3288 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003289 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003290
Guido van Rossum1c450732001-10-08 15:18:27 +00003291 /* Link into each base class's list of subclasses */
3292 bases = type->tp_bases;
3293 n = PyTuple_GET_SIZE(bases);
3294 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003295 PyObject *b = PyTuple_GET_ITEM(bases, i);
3296 if (PyType_Check(b) &&
3297 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003298 goto error;
3299 }
3300
Guido van Rossum13d52f02001-08-10 21:24:08 +00003301 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003302 assert(type->tp_dict != NULL);
3303 type->tp_flags =
3304 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003305 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003306
3307 error:
3308 type->tp_flags &= ~Py_TPFLAGS_READYING;
3309 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003310}
3311
Guido van Rossum1c450732001-10-08 15:18:27 +00003312static int
3313add_subclass(PyTypeObject *base, PyTypeObject *type)
3314{
3315 int i;
3316 PyObject *list, *ref, *new;
3317
3318 list = base->tp_subclasses;
3319 if (list == NULL) {
3320 base->tp_subclasses = list = PyList_New(0);
3321 if (list == NULL)
3322 return -1;
3323 }
3324 assert(PyList_Check(list));
3325 new = PyWeakref_NewRef((PyObject *)type, NULL);
3326 i = PyList_GET_SIZE(list);
3327 while (--i >= 0) {
3328 ref = PyList_GET_ITEM(list, i);
3329 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003330 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3331 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003332 }
3333 i = PyList_Append(list, new);
3334 Py_DECREF(new);
3335 return i;
3336}
3337
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003338static void
3339remove_subclass(PyTypeObject *base, PyTypeObject *type)
3340{
3341 int i;
3342 PyObject *list, *ref;
3343
3344 list = base->tp_subclasses;
3345 if (list == NULL) {
3346 return;
3347 }
3348 assert(PyList_Check(list));
3349 i = PyList_GET_SIZE(list);
3350 while (--i >= 0) {
3351 ref = PyList_GET_ITEM(list, i);
3352 assert(PyWeakref_CheckRef(ref));
3353 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3354 /* this can't fail, right? */
3355 PySequence_DelItem(list, i);
3356 return;
3357 }
3358 }
3359}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003360
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003361static int
3362check_num_args(PyObject *ob, int n)
3363{
3364 if (!PyTuple_CheckExact(ob)) {
3365 PyErr_SetString(PyExc_SystemError,
3366 "PyArg_UnpackTuple() argument list is not a tuple");
3367 return 0;
3368 }
3369 if (n == PyTuple_GET_SIZE(ob))
3370 return 1;
3371 PyErr_Format(
3372 PyExc_TypeError,
3373 "expected %d arguments, got %d", n, PyTuple_GET_SIZE(ob));
3374 return 0;
3375}
3376
Tim Peters6d6c1a32001-08-02 04:15:00 +00003377/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3378
3379/* There's a wrapper *function* for each distinct function typedef used
3380 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3381 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3382 Most tables have only one entry; the tables for binary operators have two
3383 entries, one regular and one with reversed arguments. */
3384
3385static PyObject *
3386wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3387{
3388 inquiry func = (inquiry)wrapped;
3389 int res;
3390
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003391 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003392 return NULL;
3393 res = (*func)(self);
3394 if (res == -1 && PyErr_Occurred())
3395 return NULL;
3396 return PyInt_FromLong((long)res);
3397}
3398
Tim Peters6d6c1a32001-08-02 04:15:00 +00003399static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003400wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3401{
3402 inquiry func = (inquiry)wrapped;
3403 int res;
3404
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003405 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003406 return NULL;
3407 res = (*func)(self);
3408 if (res == -1 && PyErr_Occurred())
3409 return NULL;
3410 return PyBool_FromLong((long)res);
3411}
3412
3413static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003414wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3415{
3416 binaryfunc func = (binaryfunc)wrapped;
3417 PyObject *other;
3418
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003419 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003420 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003421 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003422 return (*func)(self, other);
3423}
3424
3425static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003426wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3427{
3428 binaryfunc func = (binaryfunc)wrapped;
3429 PyObject *other;
3430
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003431 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003432 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003433 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003434 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003435 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003436 Py_INCREF(Py_NotImplemented);
3437 return Py_NotImplemented;
3438 }
3439 return (*func)(self, other);
3440}
3441
3442static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003443wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3444{
3445 binaryfunc func = (binaryfunc)wrapped;
3446 PyObject *other;
3447
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003448 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003449 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003450 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003451 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003452 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003453 Py_INCREF(Py_NotImplemented);
3454 return Py_NotImplemented;
3455 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003456 return (*func)(other, self);
3457}
3458
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003459static PyObject *
3460wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3461{
3462 coercion func = (coercion)wrapped;
3463 PyObject *other, *res;
3464 int ok;
3465
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003466 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003467 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003468 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003469 ok = func(&self, &other);
3470 if (ok < 0)
3471 return NULL;
3472 if (ok > 0) {
3473 Py_INCREF(Py_NotImplemented);
3474 return Py_NotImplemented;
3475 }
3476 res = PyTuple_New(2);
3477 if (res == NULL) {
3478 Py_DECREF(self);
3479 Py_DECREF(other);
3480 return NULL;
3481 }
3482 PyTuple_SET_ITEM(res, 0, self);
3483 PyTuple_SET_ITEM(res, 1, other);
3484 return res;
3485}
3486
Tim Peters6d6c1a32001-08-02 04:15:00 +00003487static PyObject *
3488wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3489{
3490 ternaryfunc func = (ternaryfunc)wrapped;
3491 PyObject *other;
3492 PyObject *third = Py_None;
3493
3494 /* Note: This wrapper only works for __pow__() */
3495
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003496 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003497 return NULL;
3498 return (*func)(self, other, third);
3499}
3500
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003501static PyObject *
3502wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3503{
3504 ternaryfunc func = (ternaryfunc)wrapped;
3505 PyObject *other;
3506 PyObject *third = Py_None;
3507
3508 /* Note: This wrapper only works for __pow__() */
3509
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003510 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003511 return NULL;
3512 return (*func)(other, self, third);
3513}
3514
Tim Peters6d6c1a32001-08-02 04:15:00 +00003515static PyObject *
3516wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3517{
3518 unaryfunc func = (unaryfunc)wrapped;
3519
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003520 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003521 return NULL;
3522 return (*func)(self);
3523}
3524
Tim Peters6d6c1a32001-08-02 04:15:00 +00003525static PyObject *
3526wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3527{
3528 intargfunc func = (intargfunc)wrapped;
3529 int i;
3530
3531 if (!PyArg_ParseTuple(args, "i", &i))
3532 return NULL;
3533 return (*func)(self, i);
3534}
3535
Guido van Rossum5d815f32001-08-17 21:57:47 +00003536static int
3537getindex(PyObject *self, PyObject *arg)
3538{
3539 int i;
3540
3541 i = PyInt_AsLong(arg);
3542 if (i == -1 && PyErr_Occurred())
3543 return -1;
3544 if (i < 0) {
3545 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3546 if (sq && sq->sq_length) {
3547 int n = (*sq->sq_length)(self);
3548 if (n < 0)
3549 return -1;
3550 i += n;
3551 }
3552 }
3553 return i;
3554}
3555
3556static PyObject *
3557wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3558{
3559 intargfunc func = (intargfunc)wrapped;
3560 PyObject *arg;
3561 int i;
3562
Guido van Rossumf4593e02001-10-03 12:09:30 +00003563 if (PyTuple_GET_SIZE(args) == 1) {
3564 arg = PyTuple_GET_ITEM(args, 0);
3565 i = getindex(self, arg);
3566 if (i == -1 && PyErr_Occurred())
3567 return NULL;
3568 return (*func)(self, i);
3569 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003570 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003571 assert(PyErr_Occurred());
3572 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003573}
3574
Tim Peters6d6c1a32001-08-02 04:15:00 +00003575static PyObject *
3576wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3577{
3578 intintargfunc func = (intintargfunc)wrapped;
3579 int i, j;
3580
3581 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3582 return NULL;
3583 return (*func)(self, i, j);
3584}
3585
Tim Peters6d6c1a32001-08-02 04:15:00 +00003586static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003587wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003588{
3589 intobjargproc func = (intobjargproc)wrapped;
3590 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003591 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003592
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003593 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003594 return NULL;
3595 i = getindex(self, arg);
3596 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003597 return NULL;
3598 res = (*func)(self, i, value);
3599 if (res == -1 && PyErr_Occurred())
3600 return NULL;
3601 Py_INCREF(Py_None);
3602 return Py_None;
3603}
3604
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003605static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003606wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003607{
3608 intobjargproc func = (intobjargproc)wrapped;
3609 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003610 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003611
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003612 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003613 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003614 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003615 i = getindex(self, arg);
3616 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003617 return NULL;
3618 res = (*func)(self, i, NULL);
3619 if (res == -1 && PyErr_Occurred())
3620 return NULL;
3621 Py_INCREF(Py_None);
3622 return Py_None;
3623}
3624
Tim Peters6d6c1a32001-08-02 04:15:00 +00003625static PyObject *
3626wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3627{
3628 intintobjargproc func = (intintobjargproc)wrapped;
3629 int i, j, res;
3630 PyObject *value;
3631
3632 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3633 return NULL;
3634 res = (*func)(self, i, j, value);
3635 if (res == -1 && PyErr_Occurred())
3636 return NULL;
3637 Py_INCREF(Py_None);
3638 return Py_None;
3639}
3640
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003641static PyObject *
3642wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3643{
3644 intintobjargproc func = (intintobjargproc)wrapped;
3645 int i, j, res;
3646
3647 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3648 return NULL;
3649 res = (*func)(self, i, j, NULL);
3650 if (res == -1 && PyErr_Occurred())
3651 return NULL;
3652 Py_INCREF(Py_None);
3653 return Py_None;
3654}
3655
Tim Peters6d6c1a32001-08-02 04:15:00 +00003656/* XXX objobjproc is a misnomer; should be objargpred */
3657static PyObject *
3658wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3659{
3660 objobjproc func = (objobjproc)wrapped;
3661 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003662 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003663
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003664 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003665 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003666 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003667 res = (*func)(self, value);
3668 if (res == -1 && PyErr_Occurred())
3669 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003670 else
3671 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003672}
3673
Tim Peters6d6c1a32001-08-02 04:15:00 +00003674static PyObject *
3675wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3676{
3677 objobjargproc func = (objobjargproc)wrapped;
3678 int res;
3679 PyObject *key, *value;
3680
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003681 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003682 return NULL;
3683 res = (*func)(self, key, value);
3684 if (res == -1 && PyErr_Occurred())
3685 return NULL;
3686 Py_INCREF(Py_None);
3687 return Py_None;
3688}
3689
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003690static PyObject *
3691wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3692{
3693 objobjargproc func = (objobjargproc)wrapped;
3694 int res;
3695 PyObject *key;
3696
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003697 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003698 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003699 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003700 res = (*func)(self, key, NULL);
3701 if (res == -1 && PyErr_Occurred())
3702 return NULL;
3703 Py_INCREF(Py_None);
3704 return Py_None;
3705}
3706
Tim Peters6d6c1a32001-08-02 04:15:00 +00003707static PyObject *
3708wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3709{
3710 cmpfunc func = (cmpfunc)wrapped;
3711 int res;
3712 PyObject *other;
3713
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003714 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003715 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003716 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003717 if (other->ob_type->tp_compare != func &&
3718 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003719 PyErr_Format(
3720 PyExc_TypeError,
3721 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3722 self->ob_type->tp_name,
3723 self->ob_type->tp_name,
3724 other->ob_type->tp_name);
3725 return NULL;
3726 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003727 res = (*func)(self, other);
3728 if (PyErr_Occurred())
3729 return NULL;
3730 return PyInt_FromLong((long)res);
3731}
3732
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003733/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003734 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003735static int
3736hackcheck(PyObject *self, setattrofunc func, char *what)
3737{
3738 PyTypeObject *type = self->ob_type;
3739 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3740 type = type->tp_base;
3741 if (type->tp_setattro != func) {
3742 PyErr_Format(PyExc_TypeError,
3743 "can't apply this %s to %s object",
3744 what,
3745 type->tp_name);
3746 return 0;
3747 }
3748 return 1;
3749}
3750
Tim Peters6d6c1a32001-08-02 04:15:00 +00003751static PyObject *
3752wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3753{
3754 setattrofunc func = (setattrofunc)wrapped;
3755 int res;
3756 PyObject *name, *value;
3757
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003758 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003759 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003760 if (!hackcheck(self, func, "__setattr__"))
3761 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003762 res = (*func)(self, name, value);
3763 if (res < 0)
3764 return NULL;
3765 Py_INCREF(Py_None);
3766 return Py_None;
3767}
3768
3769static PyObject *
3770wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3771{
3772 setattrofunc func = (setattrofunc)wrapped;
3773 int res;
3774 PyObject *name;
3775
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003776 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003777 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003778 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003779 if (!hackcheck(self, func, "__delattr__"))
3780 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003781 res = (*func)(self, name, NULL);
3782 if (res < 0)
3783 return NULL;
3784 Py_INCREF(Py_None);
3785 return Py_None;
3786}
3787
Tim Peters6d6c1a32001-08-02 04:15:00 +00003788static PyObject *
3789wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3790{
3791 hashfunc func = (hashfunc)wrapped;
3792 long res;
3793
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003794 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003795 return NULL;
3796 res = (*func)(self);
3797 if (res == -1 && PyErr_Occurred())
3798 return NULL;
3799 return PyInt_FromLong(res);
3800}
3801
Tim Peters6d6c1a32001-08-02 04:15:00 +00003802static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003803wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003804{
3805 ternaryfunc func = (ternaryfunc)wrapped;
3806
Guido van Rossumc8e56452001-10-22 00:43:43 +00003807 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003808}
3809
Tim Peters6d6c1a32001-08-02 04:15:00 +00003810static PyObject *
3811wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3812{
3813 richcmpfunc func = (richcmpfunc)wrapped;
3814 PyObject *other;
3815
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003816 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003817 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003818 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003819 return (*func)(self, other, op);
3820}
3821
3822#undef RICHCMP_WRAPPER
3823#define RICHCMP_WRAPPER(NAME, OP) \
3824static PyObject * \
3825richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3826{ \
3827 return wrap_richcmpfunc(self, args, wrapped, OP); \
3828}
3829
Jack Jansen8e938b42001-08-08 15:29:49 +00003830RICHCMP_WRAPPER(lt, Py_LT)
3831RICHCMP_WRAPPER(le, Py_LE)
3832RICHCMP_WRAPPER(eq, Py_EQ)
3833RICHCMP_WRAPPER(ne, Py_NE)
3834RICHCMP_WRAPPER(gt, Py_GT)
3835RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003836
Tim Peters6d6c1a32001-08-02 04:15:00 +00003837static PyObject *
3838wrap_next(PyObject *self, PyObject *args, void *wrapped)
3839{
3840 unaryfunc func = (unaryfunc)wrapped;
3841 PyObject *res;
3842
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003843 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003844 return NULL;
3845 res = (*func)(self);
3846 if (res == NULL && !PyErr_Occurred())
3847 PyErr_SetNone(PyExc_StopIteration);
3848 return res;
3849}
3850
Tim Peters6d6c1a32001-08-02 04:15:00 +00003851static PyObject *
3852wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3853{
3854 descrgetfunc func = (descrgetfunc)wrapped;
3855 PyObject *obj;
3856 PyObject *type = NULL;
3857
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003858 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003859 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003860 if (obj == Py_None)
3861 obj = NULL;
3862 if (type == Py_None)
3863 type = NULL;
3864 if (type == NULL &&obj == NULL) {
3865 PyErr_SetString(PyExc_TypeError,
3866 "__get__(None, None) is invalid");
3867 return NULL;
3868 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003869 return (*func)(self, obj, type);
3870}
3871
Tim Peters6d6c1a32001-08-02 04:15:00 +00003872static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003873wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003874{
3875 descrsetfunc func = (descrsetfunc)wrapped;
3876 PyObject *obj, *value;
3877 int ret;
3878
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003879 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003880 return NULL;
3881 ret = (*func)(self, obj, value);
3882 if (ret < 0)
3883 return NULL;
3884 Py_INCREF(Py_None);
3885 return Py_None;
3886}
Guido van Rossum22b13872002-08-06 21:41:44 +00003887
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003888static PyObject *
3889wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3890{
3891 descrsetfunc func = (descrsetfunc)wrapped;
3892 PyObject *obj;
3893 int ret;
3894
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003895 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003896 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003897 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003898 ret = (*func)(self, obj, NULL);
3899 if (ret < 0)
3900 return NULL;
3901 Py_INCREF(Py_None);
3902 return Py_None;
3903}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003904
Tim Peters6d6c1a32001-08-02 04:15:00 +00003905static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003906wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003907{
3908 initproc func = (initproc)wrapped;
3909
Guido van Rossumc8e56452001-10-22 00:43:43 +00003910 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003911 return NULL;
3912 Py_INCREF(Py_None);
3913 return Py_None;
3914}
3915
Tim Peters6d6c1a32001-08-02 04:15:00 +00003916static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003917tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003918{
Barry Warsaw60f01882001-08-22 19:24:42 +00003919 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003920 PyObject *arg0, *res;
3921
3922 if (self == NULL || !PyType_Check(self))
3923 Py_FatalError("__new__() called with non-type 'self'");
3924 type = (PyTypeObject *)self;
3925 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003926 PyErr_Format(PyExc_TypeError,
3927 "%s.__new__(): not enough arguments",
3928 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003929 return NULL;
3930 }
3931 arg0 = PyTuple_GET_ITEM(args, 0);
3932 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003933 PyErr_Format(PyExc_TypeError,
3934 "%s.__new__(X): X is not a type object (%s)",
3935 type->tp_name,
3936 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003937 return NULL;
3938 }
3939 subtype = (PyTypeObject *)arg0;
3940 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003941 PyErr_Format(PyExc_TypeError,
3942 "%s.__new__(%s): %s is not a subtype of %s",
3943 type->tp_name,
3944 subtype->tp_name,
3945 subtype->tp_name,
3946 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003947 return NULL;
3948 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003949
3950 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003951 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003952 most derived base that's not a heap type is this type. */
3953 staticbase = subtype;
3954 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3955 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003956 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003957 PyErr_Format(PyExc_TypeError,
3958 "%s.__new__(%s) is not safe, use %s.__new__()",
3959 type->tp_name,
3960 subtype->tp_name,
3961 staticbase == NULL ? "?" : staticbase->tp_name);
3962 return NULL;
3963 }
3964
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003965 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3966 if (args == NULL)
3967 return NULL;
3968 res = type->tp_new(subtype, args, kwds);
3969 Py_DECREF(args);
3970 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003971}
3972
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003973static struct PyMethodDef tp_new_methoddef[] = {
3974 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003975 PyDoc_STR("T.__new__(S, ...) -> "
3976 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003977 {0}
3978};
3979
3980static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003981add_tp_new_wrapper(PyTypeObject *type)
3982{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003983 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003984
Guido van Rossum687ae002001-10-15 22:03:32 +00003985 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003986 return 0;
3987 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003988 if (func == NULL)
3989 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00003990 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00003991 Py_DECREF(func);
3992 return -1;
3993 }
3994 Py_DECREF(func);
3995 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003996}
3997
Guido van Rossumf040ede2001-08-07 16:40:56 +00003998/* Slot wrappers that call the corresponding __foo__ slot. See comments
3999 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004000
Guido van Rossumdc91b992001-08-08 22:26:22 +00004001#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004002static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004003FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004004{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004005 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004006 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004007}
4008
Guido van Rossumdc91b992001-08-08 22:26:22 +00004009#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004010static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004011FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004012{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004013 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004014 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004015}
4016
Guido van Rossumcd118802003-01-06 22:57:47 +00004017/* Boolean helper for SLOT1BINFULL().
4018 right.__class__ is a nontrivial subclass of left.__class__. */
4019static int
4020method_is_overloaded(PyObject *left, PyObject *right, char *name)
4021{
4022 PyObject *a, *b;
4023 int ok;
4024
4025 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
4026 if (b == NULL) {
4027 PyErr_Clear();
4028 /* If right doesn't have it, it's not overloaded */
4029 return 0;
4030 }
4031
4032 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
4033 if (a == NULL) {
4034 PyErr_Clear();
4035 Py_DECREF(b);
4036 /* If right has it but left doesn't, it's overloaded */
4037 return 1;
4038 }
4039
4040 ok = PyObject_RichCompareBool(a, b, Py_NE);
4041 Py_DECREF(a);
4042 Py_DECREF(b);
4043 if (ok < 0) {
4044 PyErr_Clear();
4045 return 0;
4046 }
4047
4048 return ok;
4049}
4050
Guido van Rossumdc91b992001-08-08 22:26:22 +00004051
4052#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004053static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004054FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004055{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004056 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004057 int do_other = self->ob_type != other->ob_type && \
4058 other->ob_type->tp_as_number != NULL && \
4059 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004060 if (self->ob_type->tp_as_number != NULL && \
4061 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
4062 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004063 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004064 PyType_IsSubtype(other->ob_type, self->ob_type) && \
4065 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004066 r = call_maybe( \
4067 other, ROPSTR, &rcache_str, "(O)", self); \
4068 if (r != Py_NotImplemented) \
4069 return r; \
4070 Py_DECREF(r); \
4071 do_other = 0; \
4072 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004073 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004074 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004075 if (r != Py_NotImplemented || \
4076 other->ob_type == self->ob_type) \
4077 return r; \
4078 Py_DECREF(r); \
4079 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004080 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004081 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004082 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004083 } \
4084 Py_INCREF(Py_NotImplemented); \
4085 return Py_NotImplemented; \
4086}
4087
4088#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4089 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4090
4091#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4092static PyObject * \
4093FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4094{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004095 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004096 return call_method(self, OPSTR, &cache_str, \
4097 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004098}
4099
4100static int
4101slot_sq_length(PyObject *self)
4102{
Guido van Rossum2730b132001-08-28 18:22:14 +00004103 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004104 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum630db602005-09-20 18:49:54 +00004105 long temp;
Guido van Rossum26111622001-10-01 16:42:49 +00004106 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004107
4108 if (res == NULL)
4109 return -1;
Guido van Rossum630db602005-09-20 18:49:54 +00004110 temp = PyInt_AsLong(res);
4111 len = (int)temp;
Guido van Rossum26111622001-10-01 16:42:49 +00004112 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00004113 if (len == -1 && PyErr_Occurred())
4114 return -1;
Guido van Rossum630db602005-09-20 18:49:54 +00004115#if SIZEOF_INT < SIZEOF_LONG
4116 /* Overflow check -- range of PyInt is more than C int */
4117 if (len != temp) {
4118 PyErr_SetString(PyExc_OverflowError,
4119 "__len__() should return 0 <= outcome < 2**31");
4120 return -1;
4121 }
4122#endif
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004123 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00004124 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004125 "__len__() should return >= 0");
4126 return -1;
4127 }
Guido van Rossum26111622001-10-01 16:42:49 +00004128 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004129}
4130
Guido van Rossumf4593e02001-10-03 12:09:30 +00004131/* Super-optimized version of slot_sq_item.
4132 Other slots could do the same... */
4133static PyObject *
4134slot_sq_item(PyObject *self, int i)
4135{
4136 static PyObject *getitem_str;
4137 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4138 descrgetfunc f;
4139
4140 if (getitem_str == NULL) {
4141 getitem_str = PyString_InternFromString("__getitem__");
4142 if (getitem_str == NULL)
4143 return NULL;
4144 }
4145 func = _PyType_Lookup(self->ob_type, getitem_str);
4146 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004147 if ((f = func->ob_type->tp_descr_get) == NULL)
4148 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004149 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004150 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004151 if (func == NULL) {
4152 return NULL;
4153 }
4154 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00004155 ival = PyInt_FromLong(i);
4156 if (ival != NULL) {
4157 args = PyTuple_New(1);
4158 if (args != NULL) {
4159 PyTuple_SET_ITEM(args, 0, ival);
4160 retval = PyObject_Call(func, args, NULL);
4161 Py_XDECREF(args);
4162 Py_XDECREF(func);
4163 return retval;
4164 }
4165 }
4166 }
4167 else {
4168 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4169 }
4170 Py_XDECREF(args);
4171 Py_XDECREF(ival);
4172 Py_XDECREF(func);
4173 return NULL;
4174}
4175
Guido van Rossumdc91b992001-08-08 22:26:22 +00004176SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004177
4178static int
4179slot_sq_ass_item(PyObject *self, int index, PyObject *value)
4180{
4181 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004182 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004183
4184 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004185 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004186 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004187 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004188 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004189 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004190 if (res == NULL)
4191 return -1;
4192 Py_DECREF(res);
4193 return 0;
4194}
4195
4196static int
4197slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
4198{
4199 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004200 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004201
4202 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004203 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004204 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004205 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004206 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004207 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004208 if (res == NULL)
4209 return -1;
4210 Py_DECREF(res);
4211 return 0;
4212}
4213
4214static int
4215slot_sq_contains(PyObject *self, PyObject *value)
4216{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004217 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004218 int result = -1;
4219
Guido van Rossum60718732001-08-28 17:47:51 +00004220 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004221
Guido van Rossum55f20992001-10-01 17:18:22 +00004222 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004223 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004224 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004225 if (args == NULL)
4226 res = NULL;
4227 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004228 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004229 Py_DECREF(args);
4230 }
4231 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004232 if (res != NULL) {
4233 result = PyObject_IsTrue(res);
4234 Py_DECREF(res);
4235 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004236 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004237 else if (! PyErr_Occurred()) {
4238 result = _PySequence_IterSearch(self, value,
4239 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004240 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004241 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004242}
4243
Tim Peters6d6c1a32001-08-02 04:15:00 +00004244#define slot_mp_length slot_sq_length
4245
Guido van Rossumdc91b992001-08-08 22:26:22 +00004246SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004247
4248static int
4249slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4250{
4251 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004252 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004253
4254 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004255 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004256 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004257 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004258 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004259 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004260 if (res == NULL)
4261 return -1;
4262 Py_DECREF(res);
4263 return 0;
4264}
4265
Guido van Rossumdc91b992001-08-08 22:26:22 +00004266SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4267SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4268SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4269SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4270SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4271SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4272
Jeremy Hylton938ace62002-07-17 16:30:39 +00004273static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004274
4275SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4276 nb_power, "__pow__", "__rpow__")
4277
4278static PyObject *
4279slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4280{
Guido van Rossum2730b132001-08-28 18:22:14 +00004281 static PyObject *pow_str;
4282
Guido van Rossumdc91b992001-08-08 22:26:22 +00004283 if (modulus == Py_None)
4284 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004285 /* Three-arg power doesn't use __rpow__. But ternary_op
4286 can call this when the second argument's type uses
4287 slot_nb_power, so check before calling self.__pow__. */
4288 if (self->ob_type->tp_as_number != NULL &&
4289 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4290 return call_method(self, "__pow__", &pow_str,
4291 "(OO)", other, modulus);
4292 }
4293 Py_INCREF(Py_NotImplemented);
4294 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004295}
4296
4297SLOT0(slot_nb_negative, "__neg__")
4298SLOT0(slot_nb_positive, "__pos__")
4299SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004300
4301static int
4302slot_nb_nonzero(PyObject *self)
4303{
Tim Petersea7f75d2002-12-07 21:39:16 +00004304 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004305 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004306 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004307
Guido van Rossum55f20992001-10-01 17:18:22 +00004308 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004309 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004310 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004311 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004312 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004313 if (func == NULL)
4314 return PyErr_Occurred() ? -1 : 1;
4315 }
4316 args = PyTuple_New(0);
4317 if (args != NULL) {
4318 PyObject *temp = PyObject_Call(func, args, NULL);
4319 Py_DECREF(args);
4320 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004321 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004322 result = PyObject_IsTrue(temp);
4323 else {
4324 PyErr_Format(PyExc_TypeError,
4325 "__nonzero__ should return "
4326 "bool or int, returned %s",
4327 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004328 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004329 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004330 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004331 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004332 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004333 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004334 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004335}
4336
Guido van Rossumdc91b992001-08-08 22:26:22 +00004337SLOT0(slot_nb_invert, "__invert__")
4338SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4339SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4340SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4341SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4342SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004343
4344static int
4345slot_nb_coerce(PyObject **a, PyObject **b)
4346{
4347 static PyObject *coerce_str;
4348 PyObject *self = *a, *other = *b;
4349
4350 if (self->ob_type->tp_as_number != NULL &&
4351 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4352 PyObject *r;
4353 r = call_maybe(
4354 self, "__coerce__", &coerce_str, "(O)", other);
4355 if (r == NULL)
4356 return -1;
4357 if (r == Py_NotImplemented) {
4358 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004359 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004360 else {
4361 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4362 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004363 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004364 Py_DECREF(r);
4365 return -1;
4366 }
4367 *a = PyTuple_GET_ITEM(r, 0);
4368 Py_INCREF(*a);
4369 *b = PyTuple_GET_ITEM(r, 1);
4370 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004371 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004372 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004373 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004374 }
4375 if (other->ob_type->tp_as_number != NULL &&
4376 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4377 PyObject *r;
4378 r = call_maybe(
4379 other, "__coerce__", &coerce_str, "(O)", self);
4380 if (r == NULL)
4381 return -1;
4382 if (r == Py_NotImplemented) {
4383 Py_DECREF(r);
4384 return 1;
4385 }
4386 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4387 PyErr_SetString(PyExc_TypeError,
4388 "__coerce__ didn't return a 2-tuple");
4389 Py_DECREF(r);
4390 return -1;
4391 }
4392 *a = PyTuple_GET_ITEM(r, 1);
4393 Py_INCREF(*a);
4394 *b = PyTuple_GET_ITEM(r, 0);
4395 Py_INCREF(*b);
4396 Py_DECREF(r);
4397 return 0;
4398 }
4399 return 1;
4400}
4401
Guido van Rossumdc91b992001-08-08 22:26:22 +00004402SLOT0(slot_nb_int, "__int__")
4403SLOT0(slot_nb_long, "__long__")
4404SLOT0(slot_nb_float, "__float__")
4405SLOT0(slot_nb_oct, "__oct__")
4406SLOT0(slot_nb_hex, "__hex__")
4407SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4408SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4409SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4410SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4411SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004412SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004413SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4414SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4415SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4416SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4417SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4418SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4419 "__floordiv__", "__rfloordiv__")
4420SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4421SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4422SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004423
4424static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004425half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004426{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004427 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004428 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004429 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004430
Guido van Rossum60718732001-08-28 17:47:51 +00004431 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004432 if (func == NULL) {
4433 PyErr_Clear();
4434 }
4435 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004436 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004437 if (args == NULL)
4438 res = NULL;
4439 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004440 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004441 Py_DECREF(args);
4442 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004443 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004444 if (res != Py_NotImplemented) {
4445 if (res == NULL)
4446 return -2;
4447 c = PyInt_AsLong(res);
4448 Py_DECREF(res);
4449 if (c == -1 && PyErr_Occurred())
4450 return -2;
4451 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4452 }
4453 Py_DECREF(res);
4454 }
4455 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004456}
4457
Guido van Rossumab3b0342001-09-18 20:38:53 +00004458/* This slot is published for the benefit of try_3way_compare in object.c */
4459int
4460_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004461{
4462 int c;
4463
Guido van Rossumab3b0342001-09-18 20:38:53 +00004464 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004465 c = half_compare(self, other);
4466 if (c <= 1)
4467 return c;
4468 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004469 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004470 c = half_compare(other, self);
4471 if (c < -1)
4472 return -2;
4473 if (c <= 1)
4474 return -c;
4475 }
4476 return (void *)self < (void *)other ? -1 :
4477 (void *)self > (void *)other ? 1 : 0;
4478}
4479
4480static PyObject *
4481slot_tp_repr(PyObject *self)
4482{
4483 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004484 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004485
Guido van Rossum60718732001-08-28 17:47:51 +00004486 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004487 if (func != NULL) {
4488 res = PyEval_CallObject(func, NULL);
4489 Py_DECREF(func);
4490 return res;
4491 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004492 PyErr_Clear();
4493 return PyString_FromFormat("<%s object at %p>",
4494 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004495}
4496
4497static PyObject *
4498slot_tp_str(PyObject *self)
4499{
4500 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004501 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004502
Guido van Rossum60718732001-08-28 17:47:51 +00004503 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004504 if (func != NULL) {
4505 res = PyEval_CallObject(func, NULL);
4506 Py_DECREF(func);
4507 return res;
4508 }
4509 else {
4510 PyErr_Clear();
4511 return slot_tp_repr(self);
4512 }
4513}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004514
4515static long
4516slot_tp_hash(PyObject *self)
4517{
Tim Peters61ce0a92002-12-06 23:38:02 +00004518 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004519 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004520 long h;
4521
Guido van Rossum60718732001-08-28 17:47:51 +00004522 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004523
4524 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004525 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004526 Py_DECREF(func);
4527 if (res == NULL)
4528 return -1;
4529 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004530 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004531 }
4532 else {
4533 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004534 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004535 if (func == NULL) {
4536 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004537 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004538 }
4539 if (func != NULL) {
4540 Py_DECREF(func);
4541 PyErr_SetString(PyExc_TypeError, "unhashable type");
4542 return -1;
4543 }
4544 PyErr_Clear();
4545 h = _Py_HashPointer((void *)self);
4546 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004547 if (h == -1 && !PyErr_Occurred())
4548 h = -2;
4549 return h;
4550}
4551
4552static PyObject *
4553slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4554{
Guido van Rossum60718732001-08-28 17:47:51 +00004555 static PyObject *call_str;
4556 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004557 PyObject *res;
4558
4559 if (meth == NULL)
4560 return NULL;
4561 res = PyObject_Call(meth, args, kwds);
4562 Py_DECREF(meth);
4563 return res;
4564}
4565
Guido van Rossum14a6f832001-10-17 13:59:09 +00004566/* There are two slot dispatch functions for tp_getattro.
4567
4568 - slot_tp_getattro() is used when __getattribute__ is overridden
4569 but no __getattr__ hook is present;
4570
4571 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4572
Guido van Rossumc334df52002-04-04 23:44:47 +00004573 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4574 detects the absence of __getattr__ and then installs the simpler slot if
4575 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004576
Tim Peters6d6c1a32001-08-02 04:15:00 +00004577static PyObject *
4578slot_tp_getattro(PyObject *self, PyObject *name)
4579{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004580 static PyObject *getattribute_str = NULL;
4581 return call_method(self, "__getattribute__", &getattribute_str,
4582 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004583}
4584
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004585static PyObject *
4586slot_tp_getattr_hook(PyObject *self, PyObject *name)
4587{
4588 PyTypeObject *tp = self->ob_type;
4589 PyObject *getattr, *getattribute, *res;
4590 static PyObject *getattribute_str = NULL;
4591 static PyObject *getattr_str = NULL;
4592
4593 if (getattr_str == NULL) {
4594 getattr_str = PyString_InternFromString("__getattr__");
4595 if (getattr_str == NULL)
4596 return NULL;
4597 }
4598 if (getattribute_str == NULL) {
4599 getattribute_str =
4600 PyString_InternFromString("__getattribute__");
4601 if (getattribute_str == NULL)
4602 return NULL;
4603 }
4604 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004605 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004606 /* No __getattr__ hook: use a simpler dispatcher */
4607 tp->tp_getattro = slot_tp_getattro;
4608 return slot_tp_getattro(self, name);
4609 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004610 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004611 if (getattribute == NULL ||
4612 (getattribute->ob_type == &PyWrapperDescr_Type &&
4613 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4614 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004615 res = PyObject_GenericGetAttr(self, name);
4616 else
4617 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004618 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004619 PyErr_Clear();
4620 res = PyObject_CallFunction(getattr, "OO", self, name);
4621 }
4622 return res;
4623}
4624
Tim Peters6d6c1a32001-08-02 04:15:00 +00004625static int
4626slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4627{
4628 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004629 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004630
4631 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004632 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004633 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004634 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004635 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004636 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004637 if (res == NULL)
4638 return -1;
4639 Py_DECREF(res);
4640 return 0;
4641}
4642
4643/* Map rich comparison operators to their __xx__ namesakes */
4644static char *name_op[] = {
4645 "__lt__",
4646 "__le__",
4647 "__eq__",
4648 "__ne__",
4649 "__gt__",
4650 "__ge__",
4651};
4652
4653static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004654half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004655{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004656 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004657 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004658
Guido van Rossum60718732001-08-28 17:47:51 +00004659 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004660 if (func == NULL) {
4661 PyErr_Clear();
4662 Py_INCREF(Py_NotImplemented);
4663 return Py_NotImplemented;
4664 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004665 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004666 if (args == NULL)
4667 res = NULL;
4668 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004669 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004670 Py_DECREF(args);
4671 }
4672 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004673 return res;
4674}
4675
Guido van Rossumb8f63662001-08-15 23:57:02 +00004676static PyObject *
4677slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4678{
4679 PyObject *res;
4680
4681 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4682 res = half_richcompare(self, other, op);
4683 if (res != Py_NotImplemented)
4684 return res;
4685 Py_DECREF(res);
4686 }
4687 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004688 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004689 if (res != Py_NotImplemented) {
4690 return res;
4691 }
4692 Py_DECREF(res);
4693 }
4694 Py_INCREF(Py_NotImplemented);
4695 return Py_NotImplemented;
4696}
4697
4698static PyObject *
4699slot_tp_iter(PyObject *self)
4700{
4701 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004702 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004703
Guido van Rossum60718732001-08-28 17:47:51 +00004704 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004705 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004706 PyObject *args;
4707 args = res = PyTuple_New(0);
4708 if (args != NULL) {
4709 res = PyObject_Call(func, args, NULL);
4710 Py_DECREF(args);
4711 }
4712 Py_DECREF(func);
4713 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004714 }
4715 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004716 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004717 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004718 PyErr_SetString(PyExc_TypeError,
4719 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004720 return NULL;
4721 }
4722 Py_DECREF(func);
4723 return PySeqIter_New(self);
4724}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004725
4726static PyObject *
4727slot_tp_iternext(PyObject *self)
4728{
Guido van Rossum2730b132001-08-28 18:22:14 +00004729 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004730 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004731}
4732
Guido van Rossum1a493502001-08-17 16:47:50 +00004733static PyObject *
4734slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4735{
4736 PyTypeObject *tp = self->ob_type;
4737 PyObject *get;
4738 static PyObject *get_str = NULL;
4739
4740 if (get_str == NULL) {
4741 get_str = PyString_InternFromString("__get__");
4742 if (get_str == NULL)
4743 return NULL;
4744 }
4745 get = _PyType_Lookup(tp, get_str);
4746 if (get == NULL) {
4747 /* Avoid further slowdowns */
4748 if (tp->tp_descr_get == slot_tp_descr_get)
4749 tp->tp_descr_get = NULL;
4750 Py_INCREF(self);
4751 return self;
4752 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004753 if (obj == NULL)
4754 obj = Py_None;
4755 if (type == NULL)
4756 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004757 return PyObject_CallFunction(get, "OOO", self, obj, type);
4758}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004759
4760static int
4761slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4762{
Guido van Rossum2c252392001-08-24 10:13:31 +00004763 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004764 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004765
4766 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004767 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004768 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004769 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004770 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004771 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004772 if (res == NULL)
4773 return -1;
4774 Py_DECREF(res);
4775 return 0;
4776}
4777
4778static int
4779slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4780{
Guido van Rossum60718732001-08-28 17:47:51 +00004781 static PyObject *init_str;
4782 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004783 PyObject *res;
4784
4785 if (meth == NULL)
4786 return -1;
4787 res = PyObject_Call(meth, args, kwds);
4788 Py_DECREF(meth);
4789 if (res == NULL)
4790 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004791 if (res != Py_None) {
4792 PyErr_SetString(PyExc_TypeError,
4793 "__init__() should return None");
4794 Py_DECREF(res);
4795 return -1;
4796 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004797 Py_DECREF(res);
4798 return 0;
4799}
4800
4801static PyObject *
4802slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4803{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004804 static PyObject *new_str;
4805 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004806 PyObject *newargs, *x;
4807 int i, n;
4808
Guido van Rossum7bed2132002-08-08 21:57:53 +00004809 if (new_str == NULL) {
4810 new_str = PyString_InternFromString("__new__");
4811 if (new_str == NULL)
4812 return NULL;
4813 }
4814 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004815 if (func == NULL)
4816 return NULL;
4817 assert(PyTuple_Check(args));
4818 n = PyTuple_GET_SIZE(args);
4819 newargs = PyTuple_New(n+1);
4820 if (newargs == NULL)
4821 return NULL;
4822 Py_INCREF(type);
4823 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4824 for (i = 0; i < n; i++) {
4825 x = PyTuple_GET_ITEM(args, i);
4826 Py_INCREF(x);
4827 PyTuple_SET_ITEM(newargs, i+1, x);
4828 }
4829 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004830 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004831 Py_DECREF(func);
4832 return x;
4833}
4834
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004835static void
4836slot_tp_del(PyObject *self)
4837{
4838 static PyObject *del_str = NULL;
4839 PyObject *del, *res;
4840 PyObject *error_type, *error_value, *error_traceback;
4841
4842 /* Temporarily resurrect the object. */
4843 assert(self->ob_refcnt == 0);
4844 self->ob_refcnt = 1;
4845
4846 /* Save the current exception, if any. */
4847 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4848
4849 /* Execute __del__ method, if any. */
4850 del = lookup_maybe(self, "__del__", &del_str);
4851 if (del != NULL) {
4852 res = PyEval_CallObject(del, NULL);
4853 if (res == NULL)
4854 PyErr_WriteUnraisable(del);
4855 else
4856 Py_DECREF(res);
4857 Py_DECREF(del);
4858 }
4859
4860 /* Restore the saved exception. */
4861 PyErr_Restore(error_type, error_value, error_traceback);
4862
4863 /* Undo the temporary resurrection; can't use DECREF here, it would
4864 * cause a recursive call.
4865 */
4866 assert(self->ob_refcnt > 0);
4867 if (--self->ob_refcnt == 0)
4868 return; /* this is the normal path out */
4869
4870 /* __del__ resurrected it! Make it look like the original Py_DECREF
4871 * never happened.
4872 */
4873 {
4874 int refcnt = self->ob_refcnt;
4875 _Py_NewReference(self);
4876 self->ob_refcnt = refcnt;
4877 }
4878 assert(!PyType_IS_GC(self->ob_type) ||
4879 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00004880 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
4881 * we need to undo that. */
4882 _Py_DEC_REFTOTAL;
4883 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4884 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004885 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4886 * _Py_NewReference bumped tp_allocs: both of those need to be
4887 * undone.
4888 */
4889#ifdef COUNT_ALLOCS
4890 --self->ob_type->tp_frees;
4891 --self->ob_type->tp_allocs;
4892#endif
4893}
4894
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004895
4896/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004897 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004898 structure, which incorporates the additional structures used for numbers,
4899 sequences and mappings.
4900 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004901 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004902 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4903 terminated with an all-zero entry. (This table is further initialized and
4904 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004905
Guido van Rossum6d204072001-10-21 00:44:31 +00004906typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004907
4908#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004909#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004910#undef ETSLOT
4911#undef SQSLOT
4912#undef MPSLOT
4913#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004914#undef UNSLOT
4915#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004916#undef BINSLOT
4917#undef RBINSLOT
4918
Guido van Rossum6d204072001-10-21 00:44:31 +00004919#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004920 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4921 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004922#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4923 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004924 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004925#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004926 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004927 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004928#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4929 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4930#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4931 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4932#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4933 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4934#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4935 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4936 "x." NAME "() <==> " DOC)
4937#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4938 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4939 "x." NAME "(y) <==> x" DOC "y")
4940#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4941 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4942 "x." NAME "(y) <==> x" DOC "y")
4943#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4944 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4945 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00004946#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
4947 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4948 "x." NAME "(y) <==> " DOC)
4949#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
4950 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4951 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004952
4953static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004954 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4955 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00004956 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
4957 The logic in abstract.c always falls back to nb_add/nb_multiply in
4958 this case. Defining both the nb_* and the sq_* slots to call the
4959 user-defined methods has unexpected side-effects, as shown by
4960 test_descr.notimplemented() */
4961 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
4962 "x.__add__(y) <==> x+y"),
4963 SQSLOT("__mul__", sq_repeat, NULL, wrap_intargfunc,
4964 "x.__mul__(n) <==> x*n"),
4965 SQSLOT("__rmul__", sq_repeat, NULL, wrap_intargfunc,
4966 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004967 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4968 "x.__getitem__(y) <==> x[y]"),
4969 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00004970 "x.__getslice__(i, j) <==> x[i:j]\n\
4971 \n\
4972 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004973 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004974 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004975 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004976 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004977 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004978 wrap_intintobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00004979 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
4980 \n\
4981 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004982 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00004983 "x.__delslice__(i, j) <==> del x[i:j]\n\
4984 \n\
4985 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004986 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4987 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00004988 SQSLOT("__iadd__", sq_inplace_concat, NULL,
4989 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
4990 SQSLOT("__imul__", sq_inplace_repeat, NULL,
4991 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004992
Guido van Rossum6d204072001-10-21 00:44:31 +00004993 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4994 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004995 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004996 wrap_binaryfunc,
4997 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004998 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004999 wrap_objobjargproc,
5000 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005001 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005002 wrap_delitem,
5003 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005004
Guido van Rossum6d204072001-10-21 00:44:31 +00005005 BINSLOT("__add__", nb_add, slot_nb_add,
5006 "+"),
5007 RBINSLOT("__radd__", nb_add, slot_nb_add,
5008 "+"),
5009 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5010 "-"),
5011 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5012 "-"),
5013 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5014 "*"),
5015 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5016 "*"),
5017 BINSLOT("__div__", nb_divide, slot_nb_divide,
5018 "/"),
5019 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5020 "/"),
5021 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5022 "%"),
5023 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5024 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005025 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005026 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005027 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005028 "divmod(y, x)"),
5029 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5030 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5031 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5032 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5033 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5034 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5035 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5036 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005037 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005038 "x != 0"),
5039 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5040 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5041 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5042 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5043 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5044 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5045 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5046 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5047 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5048 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5049 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5050 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5051 "x.__coerce__(y) <==> coerce(x, y)"),
5052 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5053 "int(x)"),
5054 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5055 "long(x)"),
5056 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5057 "float(x)"),
5058 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5059 "oct(x)"),
5060 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5061 "hex(x)"),
5062 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5063 wrap_binaryfunc, "+"),
5064 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5065 wrap_binaryfunc, "-"),
5066 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5067 wrap_binaryfunc, "*"),
5068 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5069 wrap_binaryfunc, "/"),
5070 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5071 wrap_binaryfunc, "%"),
5072 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005073 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005074 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5075 wrap_binaryfunc, "<<"),
5076 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5077 wrap_binaryfunc, ">>"),
5078 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5079 wrap_binaryfunc, "&"),
5080 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5081 wrap_binaryfunc, "^"),
5082 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5083 wrap_binaryfunc, "|"),
5084 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5085 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5086 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5087 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5088 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5089 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5090 IBSLOT("__itruediv__", nb_inplace_true_divide,
5091 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005092
Guido van Rossum6d204072001-10-21 00:44:31 +00005093 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5094 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005095 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005096 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5097 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005098 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005099 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5100 "x.__cmp__(y) <==> cmp(x,y)"),
5101 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5102 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005103 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5104 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005105 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005106 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5107 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5108 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5109 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5110 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5111 "x.__setattr__('name', value) <==> x.name = value"),
5112 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5113 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5114 "x.__delattr__('name') <==> del x.name"),
5115 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5116 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5117 "x.__lt__(y) <==> x<y"),
5118 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5119 "x.__le__(y) <==> x<=y"),
5120 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5121 "x.__eq__(y) <==> x==y"),
5122 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5123 "x.__ne__(y) <==> x!=y"),
5124 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5125 "x.__gt__(y) <==> x>y"),
5126 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5127 "x.__ge__(y) <==> x>=y"),
5128 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5129 "x.__iter__() <==> iter(x)"),
5130 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5131 "x.next() -> the next value, or raise StopIteration"),
5132 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5133 "descr.__get__(obj[, type]) -> value"),
5134 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5135 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005136 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5137 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005138 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005139 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005140 "see x.__class__.__doc__ for signature",
5141 PyWrapperFlag_KEYWORDS),
5142 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005143 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005144 {NULL}
5145};
5146
Guido van Rossumc334df52002-04-04 23:44:47 +00005147/* Given a type pointer and an offset gotten from a slotdef entry, return a
5148 pointer to the actual slot. This is not quite the same as simply adding
5149 the offset to the type pointer, since it takes care to indirect through the
5150 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5151 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005152static void **
5153slotptr(PyTypeObject *type, int offset)
5154{
5155 char *ptr;
5156
Guido van Rossume5c691a2003-03-07 15:13:17 +00005157 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005158 assert(offset >= 0);
Guido van Rossume5c691a2003-03-07 15:13:17 +00005159 assert(offset < offsetof(PyHeapTypeObject, as_buffer));
5160 if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005161 ptr = (void *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005162 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005163 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005164 else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Guido van Rossum09638c12002-06-13 19:17:46 +00005165 ptr = (void *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005166 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005167 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005168 else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005169 ptr = (void *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005170 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005171 }
5172 else {
5173 ptr = (void *)type;
5174 }
5175 if (ptr != NULL)
5176 ptr += offset;
5177 return (void **)ptr;
5178}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005179
Guido van Rossumc334df52002-04-04 23:44:47 +00005180/* Length of array of slotdef pointers used to store slots with the
5181 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5182 the same __name__, for any __name__. Since that's a static property, it is
5183 appropriate to declare fixed-size arrays for this. */
5184#define MAX_EQUIV 10
5185
5186/* Return a slot pointer for a given name, but ONLY if the attribute has
5187 exactly one slot function. The name must be an interned string. */
5188static void **
5189resolve_slotdups(PyTypeObject *type, PyObject *name)
5190{
5191 /* XXX Maybe this could be optimized more -- but is it worth it? */
5192
5193 /* pname and ptrs act as a little cache */
5194 static PyObject *pname;
5195 static slotdef *ptrs[MAX_EQUIV];
5196 slotdef *p, **pp;
5197 void **res, **ptr;
5198
5199 if (pname != name) {
5200 /* Collect all slotdefs that match name into ptrs. */
5201 pname = name;
5202 pp = ptrs;
5203 for (p = slotdefs; p->name_strobj; p++) {
5204 if (p->name_strobj == name)
5205 *pp++ = p;
5206 }
5207 *pp = NULL;
5208 }
5209
5210 /* Look in all matching slots of the type; if exactly one of these has
5211 a filled-in slot, return its value. Otherwise return NULL. */
5212 res = NULL;
5213 for (pp = ptrs; *pp; pp++) {
5214 ptr = slotptr(type, (*pp)->offset);
5215 if (ptr == NULL || *ptr == NULL)
5216 continue;
5217 if (res != NULL)
5218 return NULL;
5219 res = ptr;
5220 }
5221 return res;
5222}
5223
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005224/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005225 does some incredibly complex thinking and then sticks something into the
5226 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5227 interests, and then stores a generic wrapper or a specific function into
5228 the slot.) Return a pointer to the next slotdef with a different offset,
5229 because that's convenient for fixup_slot_dispatchers(). */
5230static slotdef *
5231update_one_slot(PyTypeObject *type, slotdef *p)
5232{
5233 PyObject *descr;
5234 PyWrapperDescrObject *d;
5235 void *generic = NULL, *specific = NULL;
5236 int use_generic = 0;
5237 int offset = p->offset;
5238 void **ptr = slotptr(type, offset);
5239
5240 if (ptr == NULL) {
5241 do {
5242 ++p;
5243 } while (p->offset == offset);
5244 return p;
5245 }
5246 do {
5247 descr = _PyType_Lookup(type, p->name_strobj);
5248 if (descr == NULL)
5249 continue;
5250 if (descr->ob_type == &PyWrapperDescr_Type) {
5251 void **tptr = resolve_slotdups(type, p->name_strobj);
5252 if (tptr == NULL || tptr == ptr)
5253 generic = p->function;
5254 d = (PyWrapperDescrObject *)descr;
5255 if (d->d_base->wrapper == p->wrapper &&
5256 PyType_IsSubtype(type, d->d_type))
5257 {
5258 if (specific == NULL ||
5259 specific == d->d_wrapped)
5260 specific = d->d_wrapped;
5261 else
5262 use_generic = 1;
5263 }
5264 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005265 else if (descr->ob_type == &PyCFunction_Type &&
5266 PyCFunction_GET_FUNCTION(descr) ==
5267 (PyCFunction)tp_new_wrapper &&
5268 strcmp(p->name, "__new__") == 0)
5269 {
5270 /* The __new__ wrapper is not a wrapper descriptor,
5271 so must be special-cased differently.
5272 If we don't do this, creating an instance will
5273 always use slot_tp_new which will look up
5274 __new__ in the MRO which will call tp_new_wrapper
5275 which will look through the base classes looking
5276 for a static base and call its tp_new (usually
5277 PyType_GenericNew), after performing various
5278 sanity checks and constructing a new argument
5279 list. Cut all that nonsense short -- this speeds
5280 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005281 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005282 /* XXX I'm not 100% sure that there isn't a hole
5283 in this reasoning that requires additional
5284 sanity checks. I'll buy the first person to
5285 point out a bug in this reasoning a beer. */
5286 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005287 else {
5288 use_generic = 1;
5289 generic = p->function;
5290 }
5291 } while ((++p)->offset == offset);
5292 if (specific && !use_generic)
5293 *ptr = specific;
5294 else
5295 *ptr = generic;
5296 return p;
5297}
5298
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005299/* In the type, update the slots whose slotdefs are gathered in the pp array.
5300 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005301static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005302update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005303{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005304 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005305
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005306 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005307 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005308 return 0;
5309}
5310
Guido van Rossumc334df52002-04-04 23:44:47 +00005311/* Comparison function for qsort() to compare slotdefs by their offset, and
5312 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005313static int
5314slotdef_cmp(const void *aa, const void *bb)
5315{
5316 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5317 int c = a->offset - b->offset;
5318 if (c != 0)
5319 return c;
5320 else
5321 return a - b;
5322}
5323
Guido van Rossumc334df52002-04-04 23:44:47 +00005324/* Initialize the slotdefs table by adding interned string objects for the
5325 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005326static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005327init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005328{
5329 slotdef *p;
5330 static int initialized = 0;
5331
5332 if (initialized)
5333 return;
5334 for (p = slotdefs; p->name; p++) {
5335 p->name_strobj = PyString_InternFromString(p->name);
5336 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005337 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005338 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005339 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5340 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005341 initialized = 1;
5342}
5343
Guido van Rossumc334df52002-04-04 23:44:47 +00005344/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005345static int
5346update_slot(PyTypeObject *type, PyObject *name)
5347{
Guido van Rossumc334df52002-04-04 23:44:47 +00005348 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005349 slotdef *p;
5350 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005351 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005352
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005353 init_slotdefs();
5354 pp = ptrs;
5355 for (p = slotdefs; p->name; p++) {
5356 /* XXX assume name is interned! */
5357 if (p->name_strobj == name)
5358 *pp++ = p;
5359 }
5360 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005361 for (pp = ptrs; *pp; pp++) {
5362 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005363 offset = p->offset;
5364 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005365 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005366 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005367 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005368 if (ptrs[0] == NULL)
5369 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005370 return update_subclasses(type, name,
5371 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005372}
5373
Guido van Rossumc334df52002-04-04 23:44:47 +00005374/* Store the proper functions in the slot dispatches at class (type)
5375 definition time, based upon which operations the class overrides in its
5376 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005377static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005378fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005379{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005380 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005381
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005382 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005383 for (p = slotdefs; p->name; )
5384 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005385}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005386
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005387static void
5388update_all_slots(PyTypeObject* type)
5389{
5390 slotdef *p;
5391
5392 init_slotdefs();
5393 for (p = slotdefs; p->name; p++) {
5394 /* update_slot returns int but can't actually fail */
5395 update_slot(type, p->name_strobj);
5396 }
5397}
5398
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005399/* recurse_down_subclasses() and update_subclasses() are mutually
5400 recursive functions to call a callback for all subclasses,
5401 but refraining from recursing into subclasses that define 'name'. */
5402
5403static int
5404update_subclasses(PyTypeObject *type, PyObject *name,
5405 update_callback callback, void *data)
5406{
5407 if (callback(type, data) < 0)
5408 return -1;
5409 return recurse_down_subclasses(type, name, callback, data);
5410}
5411
5412static int
5413recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5414 update_callback callback, void *data)
5415{
5416 PyTypeObject *subclass;
5417 PyObject *ref, *subclasses, *dict;
5418 int i, n;
5419
5420 subclasses = type->tp_subclasses;
5421 if (subclasses == NULL)
5422 return 0;
5423 assert(PyList_Check(subclasses));
5424 n = PyList_GET_SIZE(subclasses);
5425 for (i = 0; i < n; i++) {
5426 ref = PyList_GET_ITEM(subclasses, i);
5427 assert(PyWeakref_CheckRef(ref));
5428 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5429 assert(subclass != NULL);
5430 if ((PyObject *)subclass == Py_None)
5431 continue;
5432 assert(PyType_Check(subclass));
5433 /* Avoid recursing down into unaffected classes */
5434 dict = subclass->tp_dict;
5435 if (dict != NULL && PyDict_Check(dict) &&
5436 PyDict_GetItem(dict, name) != NULL)
5437 continue;
5438 if (update_subclasses(subclass, name, callback, data) < 0)
5439 return -1;
5440 }
5441 return 0;
5442}
5443
Guido van Rossum6d204072001-10-21 00:44:31 +00005444/* This function is called by PyType_Ready() to populate the type's
5445 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005446 function slot (like tp_repr) that's defined in the type, one or more
5447 corresponding descriptors are added in the type's tp_dict dictionary
5448 under the appropriate name (like __repr__). Some function slots
5449 cause more than one descriptor to be added (for example, the nb_add
5450 slot adds both __add__ and __radd__ descriptors) and some function
5451 slots compete for the same descriptor (for example both sq_item and
5452 mp_subscript generate a __getitem__ descriptor).
5453
5454 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005455 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005456 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005457 between competing slots: the members of PyHeapTypeObject are listed
5458 from most general to least general, so the most general slot is
5459 preferred. In particular, because as_mapping comes before as_sequence,
5460 for a type that defines both mp_subscript and sq_item, mp_subscript
5461 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005462
5463 This only adds new descriptors and doesn't overwrite entries in
5464 tp_dict that were previously defined. The descriptors contain a
5465 reference to the C function they must call, so that it's safe if they
5466 are copied into a subtype's __dict__ and the subtype has a different
5467 C function in its slot -- calling the method defined by the
5468 descriptor will call the C function that was used to create it,
5469 rather than the C function present in the slot when it is called.
5470 (This is important because a subtype may have a C function in the
5471 slot that calls the method from the dictionary, and we want to avoid
5472 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005473
5474static int
5475add_operators(PyTypeObject *type)
5476{
5477 PyObject *dict = type->tp_dict;
5478 slotdef *p;
5479 PyObject *descr;
5480 void **ptr;
5481
5482 init_slotdefs();
5483 for (p = slotdefs; p->name; p++) {
5484 if (p->wrapper == NULL)
5485 continue;
5486 ptr = slotptr(type, p->offset);
5487 if (!ptr || !*ptr)
5488 continue;
5489 if (PyDict_GetItem(dict, p->name_strobj))
5490 continue;
5491 descr = PyDescr_NewWrapper(type, p, *ptr);
5492 if (descr == NULL)
5493 return -1;
5494 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5495 return -1;
5496 Py_DECREF(descr);
5497 }
5498 if (type->tp_new != NULL) {
5499 if (add_tp_new_wrapper(type) < 0)
5500 return -1;
5501 }
5502 return 0;
5503}
5504
Guido van Rossum705f0f52001-08-24 16:47:00 +00005505
5506/* Cooperative 'super' */
5507
5508typedef struct {
5509 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005510 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005511 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005512 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005513} superobject;
5514
Guido van Rossum6f799372001-09-20 20:46:19 +00005515static PyMemberDef super_members[] = {
5516 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5517 "the class invoking super()"},
5518 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5519 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005520 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005521 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005522 {0}
5523};
5524
Guido van Rossum705f0f52001-08-24 16:47:00 +00005525static void
5526super_dealloc(PyObject *self)
5527{
5528 superobject *su = (superobject *)self;
5529
Guido van Rossum048eb752001-10-02 21:24:57 +00005530 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005531 Py_XDECREF(su->obj);
5532 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005533 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005534 self->ob_type->tp_free(self);
5535}
5536
5537static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005538super_repr(PyObject *self)
5539{
5540 superobject *su = (superobject *)self;
5541
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005542 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005543 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005544 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005545 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005546 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005547 else
5548 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005549 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005550 su->type ? su->type->tp_name : "NULL");
5551}
5552
5553static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005554super_getattro(PyObject *self, PyObject *name)
5555{
5556 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005557 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005558
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005559 if (!skip) {
5560 /* We want __class__ to return the class of the super object
5561 (i.e. super, or a subclass), not the class of su->obj. */
5562 skip = (PyString_Check(name) &&
5563 PyString_GET_SIZE(name) == 9 &&
5564 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5565 }
5566
5567 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005568 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005569 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005570 descrgetfunc f;
5571 int i, n;
5572
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005573 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005574 mro = starttype->tp_mro;
5575
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005576 if (mro == NULL)
5577 n = 0;
5578 else {
5579 assert(PyTuple_Check(mro));
5580 n = PyTuple_GET_SIZE(mro);
5581 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005582 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005583 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005584 break;
5585 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005586 i++;
5587 res = NULL;
5588 for (; i < n; i++) {
5589 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005590 if (PyType_Check(tmp))
5591 dict = ((PyTypeObject *)tmp)->tp_dict;
5592 else if (PyClass_Check(tmp))
5593 dict = ((PyClassObject *)tmp)->cl_dict;
5594 else
5595 continue;
5596 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005597 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005598 Py_INCREF(res);
5599 f = res->ob_type->tp_descr_get;
5600 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005601 tmp = f(res,
5602 /* Only pass 'obj' param if
5603 this is instance-mode super
5604 (See SF ID #743627)
5605 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005606 (su->obj == (PyObject *)
5607 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005608 ? (PyObject *)NULL
5609 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005610 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005611 Py_DECREF(res);
5612 res = tmp;
5613 }
5614 return res;
5615 }
5616 }
5617 }
5618 return PyObject_GenericGetAttr(self, name);
5619}
5620
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005621static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005622supercheck(PyTypeObject *type, PyObject *obj)
5623{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005624 /* Check that a super() call makes sense. Return a type object.
5625
5626 obj can be a new-style class, or an instance of one:
5627
5628 - If it is a class, it must be a subclass of 'type'. This case is
5629 used for class methods; the return value is obj.
5630
5631 - If it is an instance, it must be an instance of 'type'. This is
5632 the normal case; the return value is obj.__class__.
5633
5634 But... when obj is an instance, we want to allow for the case where
5635 obj->ob_type is not a subclass of type, but obj.__class__ is!
5636 This will allow using super() with a proxy for obj.
5637 */
5638
Guido van Rossum8e80a722003-02-18 19:22:22 +00005639 /* Check for first bullet above (special case) */
5640 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5641 Py_INCREF(obj);
5642 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005643 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005644
5645 /* Normal case */
5646 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005647 Py_INCREF(obj->ob_type);
5648 return obj->ob_type;
5649 }
5650 else {
5651 /* Try the slow way */
5652 static PyObject *class_str = NULL;
5653 PyObject *class_attr;
5654
5655 if (class_str == NULL) {
5656 class_str = PyString_FromString("__class__");
5657 if (class_str == NULL)
5658 return NULL;
5659 }
5660
5661 class_attr = PyObject_GetAttr(obj, class_str);
5662
5663 if (class_attr != NULL &&
5664 PyType_Check(class_attr) &&
5665 (PyTypeObject *)class_attr != obj->ob_type)
5666 {
5667 int ok = PyType_IsSubtype(
5668 (PyTypeObject *)class_attr, type);
5669 if (ok)
5670 return (PyTypeObject *)class_attr;
5671 }
5672
5673 if (class_attr == NULL)
5674 PyErr_Clear();
5675 else
5676 Py_DECREF(class_attr);
5677 }
5678
Tim Peters97e5ff52003-02-18 19:32:50 +00005679 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005680 "super(type, obj): "
5681 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005682 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005683}
5684
Guido van Rossum705f0f52001-08-24 16:47:00 +00005685static PyObject *
5686super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5687{
5688 superobject *su = (superobject *)self;
5689 superobject *new;
5690
5691 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5692 /* Not binding to an object, or already bound */
5693 Py_INCREF(self);
5694 return self;
5695 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005696 if (su->ob_type != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005697 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005698 call its type */
5699 return PyObject_CallFunction((PyObject *)su->ob_type,
5700 "OO", su->type, obj);
5701 else {
5702 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005703 PyTypeObject *obj_type = supercheck(su->type, obj);
5704 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005705 return NULL;
5706 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5707 NULL, NULL);
5708 if (new == NULL)
5709 return NULL;
5710 Py_INCREF(su->type);
5711 Py_INCREF(obj);
5712 new->type = su->type;
5713 new->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005714 new->obj_type = obj_type;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005715 return (PyObject *)new;
5716 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005717}
5718
5719static int
5720super_init(PyObject *self, PyObject *args, PyObject *kwds)
5721{
5722 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005723 PyTypeObject *type;
5724 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005725 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005726
5727 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5728 return -1;
5729 if (obj == Py_None)
5730 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005731 if (obj != NULL) {
5732 obj_type = supercheck(type, obj);
5733 if (obj_type == NULL)
5734 return -1;
5735 Py_INCREF(obj);
5736 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005737 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005738 su->type = type;
5739 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005740 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005741 return 0;
5742}
5743
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005744PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005745"super(type) -> unbound super object\n"
5746"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005747"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005748"Typical use to call a cooperative superclass method:\n"
5749"class C(B):\n"
5750" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005751" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005752
Guido van Rossum048eb752001-10-02 21:24:57 +00005753static int
5754super_traverse(PyObject *self, visitproc visit, void *arg)
5755{
5756 superobject *su = (superobject *)self;
5757 int err;
5758
5759#define VISIT(SLOT) \
5760 if (SLOT) { \
5761 err = visit((PyObject *)(SLOT), arg); \
5762 if (err) \
5763 return err; \
5764 }
5765
5766 VISIT(su->obj);
5767 VISIT(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005768 VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005769
5770#undef VISIT
5771
5772 return 0;
5773}
5774
Guido van Rossum705f0f52001-08-24 16:47:00 +00005775PyTypeObject PySuper_Type = {
5776 PyObject_HEAD_INIT(&PyType_Type)
5777 0, /* ob_size */
5778 "super", /* tp_name */
5779 sizeof(superobject), /* tp_basicsize */
5780 0, /* tp_itemsize */
5781 /* methods */
5782 super_dealloc, /* tp_dealloc */
5783 0, /* tp_print */
5784 0, /* tp_getattr */
5785 0, /* tp_setattr */
5786 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005787 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005788 0, /* tp_as_number */
5789 0, /* tp_as_sequence */
5790 0, /* tp_as_mapping */
5791 0, /* tp_hash */
5792 0, /* tp_call */
5793 0, /* tp_str */
5794 super_getattro, /* tp_getattro */
5795 0, /* tp_setattro */
5796 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005797 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5798 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005799 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005800 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005801 0, /* tp_clear */
5802 0, /* tp_richcompare */
5803 0, /* tp_weaklistoffset */
5804 0, /* tp_iter */
5805 0, /* tp_iternext */
5806 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005807 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005808 0, /* tp_getset */
5809 0, /* tp_base */
5810 0, /* tp_dict */
5811 super_descr_get, /* tp_descr_get */
5812 0, /* tp_descr_set */
5813 0, /* tp_dictoffset */
5814 super_init, /* tp_init */
5815 PyType_GenericAlloc, /* tp_alloc */
5816 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005817 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005818};