blob: a0af2c9b420bb17d438602f466921e13479745d6 [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
Georg Brandlc255c7b2006-02-20 22:27:28 +000029 Py_INCREF(et->ht_name);
30 return et->ht_name;
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000031 }
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
Georg Brandlc255c7b2006-02-20 22:27:28 +000074 Py_DECREF(et->ht_name);
75 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000076
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;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000148 Py_ssize_t 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{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000187 Py_ssize_t i;
188 int r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000189 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000190 PyTypeObject *new_base, *old_base;
191 PyObject *old_bases, *old_mro;
192
193 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
194 PyErr_Format(PyExc_TypeError,
195 "can't set %s.__bases__", type->tp_name);
196 return -1;
197 }
198 if (!value) {
199 PyErr_Format(PyExc_TypeError,
200 "can't delete %s.__bases__", type->tp_name);
201 return -1;
202 }
203 if (!PyTuple_Check(value)) {
204 PyErr_Format(PyExc_TypeError,
205 "can only assign tuple to %s.__bases__, not %s",
206 type->tp_name, value->ob_type->tp_name);
207 return -1;
208 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000209 if (PyTuple_GET_SIZE(value) == 0) {
210 PyErr_Format(PyExc_TypeError,
211 "can only assign non-empty tuple to %s.__bases__, not ()",
212 type->tp_name);
213 return -1;
214 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000215 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
216 ob = PyTuple_GET_ITEM(value, i);
217 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
218 PyErr_Format(
219 PyExc_TypeError,
220 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
221 type->tp_name, ob->ob_type->tp_name);
222 return -1;
223 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000224 if (PyType_Check(ob)) {
225 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
226 PyErr_SetString(PyExc_TypeError,
227 "a __bases__ item causes an inheritance cycle");
228 return -1;
229 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000230 }
231 }
232
233 new_base = best_base(value);
234
235 if (!new_base) {
236 return -1;
237 }
238
239 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
240 return -1;
241
242 Py_INCREF(new_base);
243 Py_INCREF(value);
244
245 old_bases = type->tp_bases;
246 old_base = type->tp_base;
247 old_mro = type->tp_mro;
248
249 type->tp_bases = value;
250 type->tp_base = new_base;
251
252 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000253 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000254 }
255
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000256 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000257 if (!temp)
258 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000259
260 r = mro_subclasses(type, temp);
261
262 if (r < 0) {
263 for (i = 0; i < PyList_Size(temp); i++) {
264 PyTypeObject* cls;
265 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000266 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
267 "", 2, 2, &cls, &mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000268 Py_DECREF(cls->tp_mro);
269 cls->tp_mro = mro;
270 Py_INCREF(cls->tp_mro);
271 }
272 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000273 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000274 }
275
276 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000277
278 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000279 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000280 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000281 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000282
283 /* for now, sod that: just remove from all old_bases,
284 add to all new_bases */
285
286 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
287 ob = PyTuple_GET_ITEM(old_bases, i);
288 if (PyType_Check(ob)) {
289 remove_subclass(
290 (PyTypeObject*)ob, type);
291 }
292 }
293
294 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
295 ob = PyTuple_GET_ITEM(value, i);
296 if (PyType_Check(ob)) {
297 if (add_subclass((PyTypeObject*)ob, type) < 0)
298 r = -1;
299 }
300 }
301
302 update_all_slots(type);
303
304 Py_DECREF(old_bases);
305 Py_DECREF(old_base);
306 Py_DECREF(old_mro);
307
308 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000309
310 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000311 Py_DECREF(type->tp_bases);
312 Py_DECREF(type->tp_base);
313 if (type->tp_mro != old_mro) {
314 Py_DECREF(type->tp_mro);
315 }
316
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000317 type->tp_bases = old_bases;
318 type->tp_base = old_base;
319 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000320
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000321 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000322}
323
324static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000325type_dict(PyTypeObject *type, void *context)
326{
327 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000328 Py_INCREF(Py_None);
329 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000330 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000331 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000332}
333
Tim Peters24008312002-03-17 18:56:20 +0000334static PyObject *
335type_get_doc(PyTypeObject *type, void *context)
336{
337 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000338 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000339 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000340 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000341 if (result == NULL) {
342 result = Py_None;
343 Py_INCREF(result);
344 }
345 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000346 result = result->ob_type->tp_descr_get(result, NULL,
347 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000348 }
349 else {
350 Py_INCREF(result);
351 }
Tim Peters24008312002-03-17 18:56:20 +0000352 return result;
353}
354
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000355static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000356 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
357 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000358 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000359 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000360 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000361 {0}
362};
363
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000364static int
365type_compare(PyObject *v, PyObject *w)
366{
367 /* This is called with type objects only. So we
368 can just compare the addresses. */
369 Py_uintptr_t vv = (Py_uintptr_t)v;
370 Py_uintptr_t ww = (Py_uintptr_t)w;
371 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
372}
373
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000374static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000375type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000376{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000377 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000378 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000379
380 mod = type_module(type, NULL);
381 if (mod == NULL)
382 PyErr_Clear();
383 else if (!PyString_Check(mod)) {
384 Py_DECREF(mod);
385 mod = NULL;
386 }
387 name = type_name(type, NULL);
388 if (name == NULL)
389 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000390
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000391 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
392 kind = "class";
393 else
394 kind = "type";
395
Barry Warsaw7ce36942001-08-24 18:34:26 +0000396 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000397 rtn = PyString_FromFormat("<%s '%s.%s'>",
398 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000399 PyString_AS_STRING(mod),
400 PyString_AS_STRING(name));
401 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000402 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000403 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000404
Guido van Rossumc3542212001-08-16 09:18:56 +0000405 Py_XDECREF(mod);
406 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000407 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000408}
409
Tim Peters6d6c1a32001-08-02 04:15:00 +0000410static PyObject *
411type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
412{
413 PyObject *obj;
414
415 if (type->tp_new == NULL) {
416 PyErr_Format(PyExc_TypeError,
417 "cannot create '%.100s' instances",
418 type->tp_name);
419 return NULL;
420 }
421
Tim Peters3f996e72001-09-13 19:18:27 +0000422 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000423 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000424 /* Ugly exception: when the call was type(something),
425 don't call tp_init on the result. */
426 if (type == &PyType_Type &&
427 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
428 (kwds == NULL ||
429 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
430 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000431 /* If the returned object is not an instance of type,
432 it won't be initialized. */
433 if (!PyType_IsSubtype(obj->ob_type, type))
434 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000435 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000436 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
437 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000438 type->tp_init(obj, args, kwds) < 0) {
439 Py_DECREF(obj);
440 obj = NULL;
441 }
442 }
443 return obj;
444}
445
446PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000447PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000448{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000449 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000450 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
451 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000452
453 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000454 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000455 else
Anthony Baxtera6286212006-04-11 07:42:36 +0000456 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000457
Neil Schemenauerc806c882001-08-29 23:54:54 +0000458 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000459 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000460
Neil Schemenauerc806c882001-08-29 23:54:54 +0000461 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000462
Tim Peters6d6c1a32001-08-02 04:15:00 +0000463 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
464 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000465
Tim Peters6d6c1a32001-08-02 04:15:00 +0000466 if (type->tp_itemsize == 0)
467 PyObject_INIT(obj, type);
468 else
469 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000470
Tim Peters6d6c1a32001-08-02 04:15:00 +0000471 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000472 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000473 return obj;
474}
475
476PyObject *
477PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
478{
479 return type->tp_alloc(type, 0);
480}
481
Guido van Rossum9475a232001-10-05 20:51:39 +0000482/* Helpers for subtyping */
483
484static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000485traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
486{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000487 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000488 PyMemberDef *mp;
489
490 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000491 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000492 for (i = 0; i < n; i++, mp++) {
493 if (mp->type == T_OBJECT_EX) {
494 char *addr = (char *)self + mp->offset;
495 PyObject *obj = *(PyObject **)addr;
496 if (obj != NULL) {
497 int err = visit(obj, arg);
498 if (err)
499 return err;
500 }
501 }
502 }
503 return 0;
504}
505
506static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000507subtype_traverse(PyObject *self, visitproc visit, void *arg)
508{
509 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000510 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000511
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000512 /* Find the nearest base with a different tp_traverse,
513 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000514 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000515 base = type;
516 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
517 if (base->ob_size) {
518 int err = traverse_slots(base, self, visit, arg);
519 if (err)
520 return err;
521 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000522 base = base->tp_base;
523 assert(base);
524 }
525
526 if (type->tp_dictoffset != base->tp_dictoffset) {
527 PyObject **dictptr = _PyObject_GetDictPtr(self);
528 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000529 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000530 if (err)
531 return err;
532 }
533 }
534
Guido van Rossuma3862092002-06-10 15:24:42 +0000535 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
536 /* For a heaptype, the instances count as references
537 to the type. Traverse the type so the collector
538 can find cycles involving this link. */
539 int err = visit((PyObject *)type, arg);
540 if (err)
541 return err;
542 }
543
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000544 if (basetraverse)
545 return basetraverse(self, visit, arg);
546 return 0;
547}
548
549static void
550clear_slots(PyTypeObject *type, PyObject *self)
551{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000552 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000553 PyMemberDef *mp;
554
555 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000556 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000557 for (i = 0; i < n; i++, mp++) {
558 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
559 char *addr = (char *)self + mp->offset;
560 PyObject *obj = *(PyObject **)addr;
561 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000562 *(PyObject **)addr = NULL;
Thomas Woutersedf17d82006-04-15 17:28:34 +0000563 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000564 }
565 }
566 }
567}
568
569static int
570subtype_clear(PyObject *self)
571{
572 PyTypeObject *type, *base;
573 inquiry baseclear;
574
575 /* Find the nearest base with a different tp_clear
576 and clear slots while we're at it */
577 type = self->ob_type;
578 base = type;
579 while ((baseclear = base->tp_clear) == subtype_clear) {
580 if (base->ob_size)
581 clear_slots(base, self);
582 base = base->tp_base;
583 assert(base);
584 }
585
Guido van Rossuma3862092002-06-10 15:24:42 +0000586 /* There's no need to clear the instance dict (if any);
587 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000588
589 if (baseclear)
590 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000591 return 0;
592}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000593
594static void
595subtype_dealloc(PyObject *self)
596{
Guido van Rossum14227b42001-12-06 02:35:58 +0000597 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000598 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000599
Guido van Rossum22b13872002-08-06 21:41:44 +0000600 /* Extract the type; we expect it to be a heap type */
601 type = self->ob_type;
602 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000603
Guido van Rossum22b13872002-08-06 21:41:44 +0000604 /* Test whether the type has GC exactly once */
605
606 if (!PyType_IS_GC(type)) {
607 /* It's really rare to find a dynamic type that doesn't have
608 GC; it can only happen when deriving from 'object' and not
609 adding any slots or instance variables. This allows
610 certain simplifications: there's no need to call
611 clear_slots(), or DECREF the dict, or clear weakrefs. */
612
613 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000614 if (type->tp_del) {
615 type->tp_del(self);
616 if (self->ob_refcnt > 0)
617 return;
618 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000619
620 /* Find the nearest base with a different tp_dealloc */
621 base = type;
622 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
623 assert(base->ob_size == 0);
624 base = base->tp_base;
625 assert(base);
626 }
627
628 /* Call the base tp_dealloc() */
629 assert(basedealloc);
630 basedealloc(self);
631
632 /* Can't reference self beyond this point */
633 Py_DECREF(type);
634
635 /* Done */
636 return;
637 }
638
639 /* We get here only if the type has GC */
640
641 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000642 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000643 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000644 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000645 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000646 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000647 /* DO NOT restore GC tracking at this point. weakref callbacks
648 * (if any, and whether directly here or indirectly in something we
649 * call) may trigger GC, and if self is tracked at that point, it
650 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000651 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000652
Guido van Rossum59195fd2003-06-13 20:54:40 +0000653 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000654 base = type;
655 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000656 base = base->tp_base;
657 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000658 }
659
Guido van Rossum1987c662003-05-29 14:29:23 +0000660 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000661 the finalizer (__del__), clearing slots, or clearing the instance
662 dict. */
663
Guido van Rossum1987c662003-05-29 14:29:23 +0000664 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
665 PyObject_ClearWeakRefs(self);
666
667 /* Maybe call finalizer; exit early if resurrected */
668 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000669 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000670 type->tp_del(self);
671 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000672 goto endlabel; /* resurrected */
673 else
674 _PyObject_GC_UNTRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000675 }
676
Guido van Rossum59195fd2003-06-13 20:54:40 +0000677 /* Clear slots up to the nearest base with a different tp_dealloc */
678 base = type;
679 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
680 if (base->ob_size)
681 clear_slots(base, self);
682 base = base->tp_base;
683 assert(base);
684 }
685
Tim Peters6d6c1a32001-08-02 04:15:00 +0000686 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000687 if (type->tp_dictoffset && !base->tp_dictoffset) {
688 PyObject **dictptr = _PyObject_GetDictPtr(self);
689 if (dictptr != NULL) {
690 PyObject *dict = *dictptr;
691 if (dict != NULL) {
692 Py_DECREF(dict);
693 *dictptr = NULL;
694 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000695 }
696 }
697
Tim Peters0bd743c2003-11-13 22:50:00 +0000698 /* Call the base tp_dealloc(); first retrack self if
699 * basedealloc knows about gc.
700 */
701 if (PyType_IS_GC(base))
702 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000703 assert(basedealloc);
704 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000705
706 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000707 Py_DECREF(type);
708
Guido van Rossum0906e072002-08-07 20:42:09 +0000709 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000710 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000711 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000712 --_PyTrash_delete_nesting;
713
714 /* Explanation of the weirdness around the trashcan macros:
715
716 Q. What do the trashcan macros do?
717
718 A. Read the comment titled "Trashcan mechanism" in object.h.
719 For one, this explains why there must be a call to GC-untrack
720 before the trashcan begin macro. Without understanding the
721 trashcan code, the answers to the following questions don't make
722 sense.
723
724 Q. Why do we GC-untrack before the trashcan and then immediately
725 GC-track again afterward?
726
727 A. In the case that the base class is GC-aware, the base class
728 probably GC-untracks the object. If it does that using the
729 UNTRACK macro, this will crash when the object is already
730 untracked. Because we don't know what the base class does, the
731 only safe thing is to make sure the object is tracked when we
732 call the base class dealloc. But... The trashcan begin macro
733 requires that the object is *untracked* before it is called. So
734 the dance becomes:
735
736 GC untrack
737 trashcan begin
738 GC track
739
Tim Petersf7f9e992003-11-13 21:59:32 +0000740 Q. Why did the last question say "immediately GC-track again"?
741 It's nowhere near immediately.
742
743 A. Because the code *used* to re-track immediately. Bad Idea.
744 self has a refcount of 0, and if gc ever gets its hands on it
745 (which can happen if any weakref callback gets invoked), it
746 looks like trash to gc too, and gc also tries to delete self
747 then. But we're already deleting self. Double dealloction is
748 a subtle disaster.
749
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000750 Q. Why the bizarre (net-zero) manipulation of
751 _PyTrash_delete_nesting around the trashcan macros?
752
753 A. Some base classes (e.g. list) also use the trashcan mechanism.
754 The following scenario used to be possible:
755
756 - suppose the trashcan level is one below the trashcan limit
757
758 - subtype_dealloc() is called
759
760 - the trashcan limit is not yet reached, so the trashcan level
761 is incremented and the code between trashcan begin and end is
762 executed
763
764 - this destroys much of the object's contents, including its
765 slots and __dict__
766
767 - basedealloc() is called; this is really list_dealloc(), or
768 some other type which also uses the trashcan macros
769
770 - the trashcan limit is now reached, so the object is put on the
771 trashcan's to-be-deleted-later list
772
773 - basedealloc() returns
774
775 - subtype_dealloc() decrefs the object's type
776
777 - subtype_dealloc() returns
778
779 - later, the trashcan code starts deleting the objects from its
780 to-be-deleted-later list
781
782 - subtype_dealloc() is called *AGAIN* for the same object
783
784 - at the very least (if the destroyed slots and __dict__ don't
785 cause problems) the object's type gets decref'ed a second
786 time, which is *BAD*!!!
787
788 The remedy is to make sure that if the code between trashcan
789 begin and end in subtype_dealloc() is called, the code between
790 trashcan begin and end in basedealloc() will also be called.
791 This is done by decrementing the level after passing into the
792 trashcan block, and incrementing it just before leaving the
793 block.
794
795 But now it's possible that a chain of objects consisting solely
796 of objects whose deallocator is subtype_dealloc() will defeat
797 the trashcan mechanism completely: the decremented level means
798 that the effective level never reaches the limit. Therefore, we
799 *increment* the level *before* entering the trashcan block, and
800 matchingly decrement it after leaving. This means the trashcan
801 code will trigger a little early, but that's no big deal.
802
803 Q. Are there any live examples of code in need of all this
804 complexity?
805
806 A. Yes. See SF bug 668433 for code that crashed (when Python was
807 compiled in debug mode) before the trashcan level manipulations
808 were added. For more discussion, see SF patches 581742, 575073
809 and bug 574207.
810 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000811}
812
Jeremy Hylton938ace62002-07-17 16:30:39 +0000813static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000814
Tim Peters6d6c1a32001-08-02 04:15:00 +0000815/* type test with subclassing support */
816
817int
818PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
819{
820 PyObject *mro;
821
Guido van Rossum9478d072001-09-07 18:52:13 +0000822 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
823 return b == a || b == &PyBaseObject_Type;
824
Tim Peters6d6c1a32001-08-02 04:15:00 +0000825 mro = a->tp_mro;
826 if (mro != NULL) {
827 /* Deal with multiple inheritance without recursion
828 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000829 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000830 assert(PyTuple_Check(mro));
831 n = PyTuple_GET_SIZE(mro);
832 for (i = 0; i < n; i++) {
833 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
834 return 1;
835 }
836 return 0;
837 }
838 else {
839 /* a is not completely initilized yet; follow tp_base */
840 do {
841 if (a == b)
842 return 1;
843 a = a->tp_base;
844 } while (a != NULL);
845 return b == &PyBaseObject_Type;
846 }
847}
848
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000849/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000850 without looking in the instance dictionary
851 (so we can't use PyObject_GetAttr) but still binding
852 it to the instance. The arguments are the object,
853 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000854 static variable used to cache the interned Python string.
855
856 Two variants:
857
858 - lookup_maybe() returns NULL without raising an exception
859 when the _PyType_Lookup() call fails;
860
861 - lookup_method() always raises an exception upon errors.
862*/
Guido van Rossum60718732001-08-28 17:47:51 +0000863
864static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000865lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000866{
867 PyObject *res;
868
869 if (*attrobj == NULL) {
870 *attrobj = PyString_InternFromString(attrstr);
871 if (*attrobj == NULL)
872 return NULL;
873 }
874 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000875 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000876 descrgetfunc f;
877 if ((f = res->ob_type->tp_descr_get) == NULL)
878 Py_INCREF(res);
879 else
880 res = f(res, self, (PyObject *)(self->ob_type));
881 }
882 return res;
883}
884
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000885static PyObject *
886lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
887{
888 PyObject *res = lookup_maybe(self, attrstr, attrobj);
889 if (res == NULL && !PyErr_Occurred())
890 PyErr_SetObject(PyExc_AttributeError, *attrobj);
891 return res;
892}
893
Guido van Rossum2730b132001-08-28 18:22:14 +0000894/* A variation of PyObject_CallMethod that uses lookup_method()
895 instead of PyObject_GetAttrString(). This uses the same convention
896 as lookup_method to cache the interned name string object. */
897
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000898static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000899call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
900{
901 va_list va;
902 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000903 va_start(va, format);
904
Guido van Rossumda21c012001-10-03 00:50:18 +0000905 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000906 if (func == NULL) {
907 va_end(va);
908 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000909 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000910 return NULL;
911 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000912
913 if (format && *format)
914 args = Py_VaBuildValue(format, va);
915 else
916 args = PyTuple_New(0);
917
918 va_end(va);
919
920 if (args == NULL)
921 return NULL;
922
923 assert(PyTuple_Check(args));
924 retval = PyObject_Call(func, args, NULL);
925
926 Py_DECREF(args);
927 Py_DECREF(func);
928
929 return retval;
930}
931
932/* Clone of call_method() that returns NotImplemented when the lookup fails. */
933
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000934static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000935call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
936{
937 va_list va;
938 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000939 va_start(va, format);
940
Guido van Rossumda21c012001-10-03 00:50:18 +0000941 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000942 if (func == NULL) {
943 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000944 if (!PyErr_Occurred()) {
945 Py_INCREF(Py_NotImplemented);
946 return Py_NotImplemented;
947 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000948 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000949 }
950
951 if (format && *format)
952 args = Py_VaBuildValue(format, va);
953 else
954 args = PyTuple_New(0);
955
956 va_end(va);
957
Guido van Rossum717ce002001-09-14 16:58:08 +0000958 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000959 return NULL;
960
Guido van Rossum717ce002001-09-14 16:58:08 +0000961 assert(PyTuple_Check(args));
962 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000963
964 Py_DECREF(args);
965 Py_DECREF(func);
966
967 return retval;
968}
969
Tim Petersa91e9642001-11-14 23:32:33 +0000970static int
971fill_classic_mro(PyObject *mro, PyObject *cls)
972{
973 PyObject *bases, *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000974 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +0000975
976 assert(PyList_Check(mro));
977 assert(PyClass_Check(cls));
978 i = PySequence_Contains(mro, cls);
979 if (i < 0)
980 return -1;
981 if (!i) {
982 if (PyList_Append(mro, cls) < 0)
983 return -1;
984 }
985 bases = ((PyClassObject *)cls)->cl_bases;
986 assert(bases && PyTuple_Check(bases));
987 n = PyTuple_GET_SIZE(bases);
988 for (i = 0; i < n; i++) {
989 base = PyTuple_GET_ITEM(bases, i);
990 if (fill_classic_mro(mro, base) < 0)
991 return -1;
992 }
993 return 0;
994}
995
996static PyObject *
997classic_mro(PyObject *cls)
998{
999 PyObject *mro;
1000
1001 assert(PyClass_Check(cls));
1002 mro = PyList_New(0);
1003 if (mro != NULL) {
1004 if (fill_classic_mro(mro, cls) == 0)
1005 return mro;
1006 Py_DECREF(mro);
1007 }
1008 return NULL;
1009}
1010
Tim Petersea7f75d2002-12-07 21:39:16 +00001011/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001012 Method resolution order algorithm C3 described in
1013 "A Monotonic Superclass Linearization for Dylan",
1014 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001015 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001016 (OOPSLA 1996)
1017
Guido van Rossum98f33732002-11-25 21:36:54 +00001018 Some notes about the rules implied by C3:
1019
Tim Petersea7f75d2002-12-07 21:39:16 +00001020 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001021 It isn't legal to repeat a class in a list of base classes.
1022
1023 The next three properties are the 3 constraints in "C3".
1024
Tim Petersea7f75d2002-12-07 21:39:16 +00001025 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001026 If A precedes B in C's MRO, then A will precede B in the MRO of all
1027 subclasses of C.
1028
1029 Monotonicity.
1030 The MRO of a class must be an extension without reordering of the
1031 MRO of each of its superclasses.
1032
1033 Extended Precedence Graph (EPG).
1034 Linearization is consistent if there is a path in the EPG from
1035 each class to all its successors in the linearization. See
1036 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001037 */
1038
Tim Petersea7f75d2002-12-07 21:39:16 +00001039static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001040tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001041 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +00001042 size = PyList_GET_SIZE(list);
1043
1044 for (j = whence+1; j < size; j++) {
1045 if (PyList_GET_ITEM(list, j) == o)
1046 return 1;
1047 }
1048 return 0;
1049}
1050
Guido van Rossum98f33732002-11-25 21:36:54 +00001051static PyObject *
1052class_name(PyObject *cls)
1053{
1054 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1055 if (name == NULL) {
1056 PyErr_Clear();
1057 Py_XDECREF(name);
1058 name = PyObject_Repr(cls);
1059 }
1060 if (name == NULL)
1061 return NULL;
1062 if (!PyString_Check(name)) {
1063 Py_DECREF(name);
1064 return NULL;
1065 }
1066 return name;
1067}
1068
1069static int
1070check_duplicates(PyObject *list)
1071{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001072 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001073 /* Let's use a quadratic time algorithm,
1074 assuming that the bases lists is short.
1075 */
1076 n = PyList_GET_SIZE(list);
1077 for (i = 0; i < n; i++) {
1078 PyObject *o = PyList_GET_ITEM(list, i);
1079 for (j = i + 1; j < n; j++) {
1080 if (PyList_GET_ITEM(list, j) == o) {
1081 o = class_name(o);
1082 PyErr_Format(PyExc_TypeError,
1083 "duplicate base class %s",
1084 o ? PyString_AS_STRING(o) : "?");
1085 Py_XDECREF(o);
1086 return -1;
1087 }
1088 }
1089 }
1090 return 0;
1091}
1092
1093/* Raise a TypeError for an MRO order disagreement.
1094
1095 It's hard to produce a good error message. In the absence of better
1096 insight into error reporting, report the classes that were candidates
1097 to be put next into the MRO. There is some conflict between the
1098 order in which they should be put in the MRO, but it's hard to
1099 diagnose what constraint can't be satisfied.
1100*/
1101
1102static void
1103set_mro_error(PyObject *to_merge, int *remain)
1104{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001105 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001106 char buf[1000];
1107 PyObject *k, *v;
1108 PyObject *set = PyDict_New();
Georg Brandl5c170fd2006-03-17 19:03:25 +00001109 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001110
1111 to_merge_size = PyList_GET_SIZE(to_merge);
1112 for (i = 0; i < to_merge_size; i++) {
1113 PyObject *L = PyList_GET_ITEM(to_merge, i);
1114 if (remain[i] < PyList_GET_SIZE(L)) {
1115 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Georg Brandl5c170fd2006-03-17 19:03:25 +00001116 if (PyDict_SetItem(set, c, Py_None) < 0) {
1117 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001118 return;
Georg Brandl5c170fd2006-03-17 19:03:25 +00001119 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001120 }
1121 }
1122 n = PyDict_Size(set);
1123
Raymond Hettingerf394df42003-04-06 19:13:41 +00001124 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1125consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001126 i = 0;
1127 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1128 PyObject *name = class_name(k);
1129 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1130 name ? PyString_AS_STRING(name) : "?");
1131 Py_XDECREF(name);
1132 if (--n && off+1 < sizeof(buf)) {
1133 buf[off++] = ',';
1134 buf[off] = '\0';
1135 }
1136 }
1137 PyErr_SetString(PyExc_TypeError, buf);
1138 Py_DECREF(set);
1139}
1140
Tim Petersea7f75d2002-12-07 21:39:16 +00001141static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001142pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001143 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001144 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001145 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001146
Guido van Rossum1f121312002-11-14 19:49:16 +00001147 to_merge_size = PyList_GET_SIZE(to_merge);
1148
Guido van Rossum98f33732002-11-25 21:36:54 +00001149 /* remain stores an index into each sublist of to_merge.
1150 remain[i] is the index of the next base in to_merge[i]
1151 that is not included in acc.
1152 */
Anthony Baxtera6286212006-04-11 07:42:36 +00001153 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001154 if (remain == NULL)
1155 return -1;
1156 for (i = 0; i < to_merge_size; i++)
1157 remain[i] = 0;
1158
1159 again:
1160 empty_cnt = 0;
1161 for (i = 0; i < to_merge_size; i++) {
1162 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001163
Guido van Rossum1f121312002-11-14 19:49:16 +00001164 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1165
1166 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1167 empty_cnt++;
1168 continue;
1169 }
1170
Guido van Rossum98f33732002-11-25 21:36:54 +00001171 /* Choose next candidate for MRO.
1172
1173 The input sequences alone can determine the choice.
1174 If not, choose the class which appears in the MRO
1175 of the earliest direct superclass of the new class.
1176 */
1177
Guido van Rossum1f121312002-11-14 19:49:16 +00001178 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1179 for (j = 0; j < to_merge_size; j++) {
1180 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001181 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001182 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001183 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001184 }
1185 ok = PyList_Append(acc, candidate);
1186 if (ok < 0) {
1187 PyMem_Free(remain);
1188 return -1;
1189 }
1190 for (j = 0; j < to_merge_size; j++) {
1191 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001192 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1193 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001194 remain[j]++;
1195 }
1196 }
1197 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001198 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001199 }
1200
Guido van Rossum98f33732002-11-25 21:36:54 +00001201 if (empty_cnt == to_merge_size) {
1202 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001203 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001204 }
1205 set_mro_error(to_merge, remain);
1206 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001207 return -1;
1208}
1209
Tim Peters6d6c1a32001-08-02 04:15:00 +00001210static PyObject *
1211mro_implementation(PyTypeObject *type)
1212{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001213 Py_ssize_t i, n;
1214 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001215 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001216 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001217
Guido van Rossum63517572002-06-18 16:44:57 +00001218 if(type->tp_dict == NULL) {
1219 if(PyType_Ready(type) < 0)
1220 return NULL;
1221 }
1222
Guido van Rossum98f33732002-11-25 21:36:54 +00001223 /* Find a superclass linearization that honors the constraints
1224 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001225 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001226
1227 to_merge is a list of lists, where each list is a superclass
1228 linearization implied by a base class. The last element of
1229 to_merge is the declared list of bases.
1230 */
1231
Tim Peters6d6c1a32001-08-02 04:15:00 +00001232 bases = type->tp_bases;
1233 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001234
1235 to_merge = PyList_New(n+1);
1236 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001237 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001238
Tim Peters6d6c1a32001-08-02 04:15:00 +00001239 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001240 PyObject *base = PyTuple_GET_ITEM(bases, i);
1241 PyObject *parentMRO;
1242 if (PyType_Check(base))
1243 parentMRO = PySequence_List(
1244 ((PyTypeObject*)base)->tp_mro);
1245 else
1246 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001247 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001248 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001249 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001250 }
1251
1252 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001253 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001254
1255 bases_aslist = PySequence_List(bases);
1256 if (bases_aslist == NULL) {
1257 Py_DECREF(to_merge);
1258 return NULL;
1259 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001260 /* This is just a basic sanity check. */
1261 if (check_duplicates(bases_aslist) < 0) {
1262 Py_DECREF(to_merge);
1263 Py_DECREF(bases_aslist);
1264 return NULL;
1265 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001266 PyList_SET_ITEM(to_merge, n, bases_aslist);
1267
1268 result = Py_BuildValue("[O]", (PyObject *)type);
1269 if (result == NULL) {
1270 Py_DECREF(to_merge);
1271 return NULL;
1272 }
1273
1274 ok = pmerge(result, to_merge);
1275 Py_DECREF(to_merge);
1276 if (ok < 0) {
1277 Py_DECREF(result);
1278 return NULL;
1279 }
1280
Tim Peters6d6c1a32001-08-02 04:15:00 +00001281 return result;
1282}
1283
1284static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001285mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001286{
1287 PyTypeObject *type = (PyTypeObject *)self;
1288
Tim Peters6d6c1a32001-08-02 04:15:00 +00001289 return mro_implementation(type);
1290}
1291
1292static int
1293mro_internal(PyTypeObject *type)
1294{
1295 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001296 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001297
1298 if (type->ob_type == &PyType_Type) {
1299 result = mro_implementation(type);
1300 }
1301 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001302 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001303 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001304 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001305 if (mro == NULL)
1306 return -1;
1307 result = PyObject_CallObject(mro, NULL);
1308 Py_DECREF(mro);
1309 }
1310 if (result == NULL)
1311 return -1;
1312 tuple = PySequence_Tuple(result);
1313 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001314 if (tuple == NULL)
1315 return -1;
1316 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001317 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001318 PyObject *cls;
1319 PyTypeObject *solid;
1320
1321 solid = solid_base(type);
1322
1323 len = PyTuple_GET_SIZE(tuple);
1324
1325 for (i = 0; i < len; i++) {
1326 PyTypeObject *t;
1327 cls = PyTuple_GET_ITEM(tuple, i);
1328 if (PyClass_Check(cls))
1329 continue;
1330 else if (!PyType_Check(cls)) {
1331 PyErr_Format(PyExc_TypeError,
1332 "mro() returned a non-class ('%.500s')",
1333 cls->ob_type->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001334 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001335 return -1;
1336 }
1337 t = (PyTypeObject*)cls;
1338 if (!PyType_IsSubtype(solid, solid_base(t))) {
1339 PyErr_Format(PyExc_TypeError,
1340 "mro() returned base with unsuitable layout ('%.500s')",
1341 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001342 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001343 return -1;
1344 }
1345 }
1346 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001347 type->tp_mro = tuple;
1348 return 0;
1349}
1350
1351
1352/* Calculate the best base amongst multiple base classes.
1353 This is the first one that's on the path to the "solid base". */
1354
1355static PyTypeObject *
1356best_base(PyObject *bases)
1357{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001358 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001359 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001360 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001361
1362 assert(PyTuple_Check(bases));
1363 n = PyTuple_GET_SIZE(bases);
1364 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001365 base = NULL;
1366 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001367 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001368 base_proto = PyTuple_GET_ITEM(bases, i);
1369 if (PyClass_Check(base_proto))
1370 continue;
1371 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001372 PyErr_SetString(
1373 PyExc_TypeError,
1374 "bases must be types");
1375 return NULL;
1376 }
Tim Petersa91e9642001-11-14 23:32:33 +00001377 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001378 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001379 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001380 return NULL;
1381 }
1382 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001383 if (winner == NULL) {
1384 winner = candidate;
1385 base = base_i;
1386 }
1387 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001388 ;
1389 else if (PyType_IsSubtype(candidate, winner)) {
1390 winner = candidate;
1391 base = base_i;
1392 }
1393 else {
1394 PyErr_SetString(
1395 PyExc_TypeError,
1396 "multiple bases have "
1397 "instance lay-out conflict");
1398 return NULL;
1399 }
1400 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001401 if (base == NULL)
1402 PyErr_SetString(PyExc_TypeError,
1403 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001404 return base;
1405}
1406
1407static int
1408extra_ivars(PyTypeObject *type, PyTypeObject *base)
1409{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001410 size_t t_size = type->tp_basicsize;
1411 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001412
Guido van Rossum9676b222001-08-17 20:32:36 +00001413 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001414 if (type->tp_itemsize || base->tp_itemsize) {
1415 /* If itemsize is involved, stricter rules */
1416 return t_size != b_size ||
1417 type->tp_itemsize != base->tp_itemsize;
1418 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001419 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1420 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1421 t_size -= sizeof(PyObject *);
1422 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1423 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1424 t_size -= sizeof(PyObject *);
1425
1426 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001427}
1428
1429static PyTypeObject *
1430solid_base(PyTypeObject *type)
1431{
1432 PyTypeObject *base;
1433
1434 if (type->tp_base)
1435 base = solid_base(type->tp_base);
1436 else
1437 base = &PyBaseObject_Type;
1438 if (extra_ivars(type, base))
1439 return type;
1440 else
1441 return base;
1442}
1443
Jeremy Hylton938ace62002-07-17 16:30:39 +00001444static void object_dealloc(PyObject *);
1445static int object_init(PyObject *, PyObject *, PyObject *);
1446static int update_slot(PyTypeObject *, PyObject *);
1447static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001448
1449static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001450subtype_dict(PyObject *obj, void *context)
1451{
1452 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1453 PyObject *dict;
1454
1455 if (dictptr == NULL) {
1456 PyErr_SetString(PyExc_AttributeError,
1457 "This object has no __dict__");
1458 return NULL;
1459 }
1460 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001461 if (dict == NULL)
1462 *dictptr = dict = PyDict_New();
1463 Py_XINCREF(dict);
1464 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001465}
1466
Guido van Rossum6661be32001-10-26 04:26:12 +00001467static int
1468subtype_setdict(PyObject *obj, PyObject *value, void *context)
1469{
1470 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1471 PyObject *dict;
1472
1473 if (dictptr == NULL) {
1474 PyErr_SetString(PyExc_AttributeError,
1475 "This object has no __dict__");
1476 return -1;
1477 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001478 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001479 PyErr_SetString(PyExc_TypeError,
1480 "__dict__ must be set to a dictionary");
1481 return -1;
1482 }
1483 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001484 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001485 *dictptr = value;
1486 Py_XDECREF(dict);
1487 return 0;
1488}
1489
Guido van Rossumad47da02002-08-12 19:05:44 +00001490static PyObject *
1491subtype_getweakref(PyObject *obj, void *context)
1492{
1493 PyObject **weaklistptr;
1494 PyObject *result;
1495
1496 if (obj->ob_type->tp_weaklistoffset == 0) {
1497 PyErr_SetString(PyExc_AttributeError,
1498 "This object has no __weaklist__");
1499 return NULL;
1500 }
1501 assert(obj->ob_type->tp_weaklistoffset > 0);
1502 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001503 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001504 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001505 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001506 if (*weaklistptr == NULL)
1507 result = Py_None;
1508 else
1509 result = *weaklistptr;
1510 Py_INCREF(result);
1511 return result;
1512}
1513
Guido van Rossum373c7412003-01-07 13:41:37 +00001514/* Three variants on the subtype_getsets list. */
1515
1516static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001517 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001518 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001519 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001520 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001521 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001522};
1523
Guido van Rossum373c7412003-01-07 13:41:37 +00001524static PyGetSetDef subtype_getsets_dict_only[] = {
1525 {"__dict__", subtype_dict, subtype_setdict,
1526 PyDoc_STR("dictionary for instance variables (if defined)")},
1527 {0}
1528};
1529
1530static PyGetSetDef subtype_getsets_weakref_only[] = {
1531 {"__weakref__", subtype_getweakref, NULL,
1532 PyDoc_STR("list of weak references to the object (if defined)")},
1533 {0}
1534};
1535
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001536static int
1537valid_identifier(PyObject *s)
1538{
Guido van Rossum03013a02002-07-16 14:30:28 +00001539 unsigned char *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001540 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001541
1542 if (!PyString_Check(s)) {
1543 PyErr_SetString(PyExc_TypeError,
1544 "__slots__ must be strings");
1545 return 0;
1546 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001547 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001548 n = PyString_GET_SIZE(s);
1549 /* We must reject an empty name. As a hack, we bump the
1550 length to 1 so that the loop will balk on the trailing \0. */
1551 if (n == 0)
1552 n = 1;
1553 for (i = 0; i < n; i++, p++) {
1554 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1555 PyErr_SetString(PyExc_TypeError,
1556 "__slots__ must be identifiers");
1557 return 0;
1558 }
1559 }
1560 return 1;
1561}
1562
Martin v. Löwisd919a592002-10-14 21:07:28 +00001563#ifdef Py_USING_UNICODE
1564/* Replace Unicode objects in slots. */
1565
1566static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001567_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001568{
1569 PyObject *tmp = slots;
1570 PyObject *o, *o1;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001571 Py_ssize_t i;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001572 ssizessizeargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001573 for (i = 0; i < nslots; i++) {
1574 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1575 if (tmp == slots) {
1576 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1577 if (tmp == NULL)
1578 return NULL;
1579 }
1580 o1 = _PyUnicode_AsDefaultEncodedString
1581 (o, NULL);
1582 if (o1 == NULL) {
1583 Py_DECREF(tmp);
1584 return 0;
1585 }
1586 Py_INCREF(o1);
1587 Py_DECREF(o);
1588 PyTuple_SET_ITEM(tmp, i, o1);
1589 }
1590 }
1591 return tmp;
1592}
1593#endif
1594
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001595static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001596type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1597{
1598 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001599 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001600 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001601 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001602 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001603 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001604 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001605 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001606
Tim Peters3abca122001-10-27 19:37:48 +00001607 assert(args != NULL && PyTuple_Check(args));
1608 assert(kwds == NULL || PyDict_Check(kwds));
1609
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001610 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001611 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001612 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1613 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001614
1615 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1616 PyObject *x = PyTuple_GET_ITEM(args, 0);
1617 Py_INCREF(x->ob_type);
1618 return (PyObject *) x->ob_type;
1619 }
1620
1621 /* SF bug 475327 -- if that didn't trigger, we need 3
1622 arguments. but PyArg_ParseTupleAndKeywords below may give
1623 a msg saying type() needs exactly 3. */
1624 if (nargs + nkwds != 3) {
1625 PyErr_SetString(PyExc_TypeError,
1626 "type() takes 1 or 3 arguments");
1627 return NULL;
1628 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001629 }
1630
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001631 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001632 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1633 &name,
1634 &PyTuple_Type, &bases,
1635 &PyDict_Type, &dict))
1636 return NULL;
1637
1638 /* Determine the proper metatype to deal with this,
1639 and check for metatype conflicts while we're at it.
1640 Note that if some other metatype wins to contract,
1641 it's possible that its instances are not types. */
1642 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001643 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001644 for (i = 0; i < nbases; i++) {
1645 tmp = PyTuple_GET_ITEM(bases, i);
1646 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001647 if (tmptype == &PyClass_Type)
1648 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001649 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001650 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001651 if (PyType_IsSubtype(tmptype, winner)) {
1652 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001653 continue;
1654 }
1655 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001656 "metaclass conflict: "
1657 "the metaclass of a derived class "
1658 "must be a (non-strict) subclass "
1659 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001660 return NULL;
1661 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001662 if (winner != metatype) {
1663 if (winner->tp_new != type_new) /* Pass it to the winner */
1664 return winner->tp_new(winner, args, kwds);
1665 metatype = winner;
1666 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001667
1668 /* Adjust for empty tuple bases */
1669 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001670 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001671 if (bases == NULL)
1672 return NULL;
1673 nbases = 1;
1674 }
1675 else
1676 Py_INCREF(bases);
1677
1678 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1679
1680 /* Calculate best base, and check that all bases are type objects */
1681 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001682 if (base == NULL) {
1683 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001684 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001685 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001686 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1687 PyErr_Format(PyExc_TypeError,
1688 "type '%.100s' is not an acceptable base type",
1689 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001690 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001691 return NULL;
1692 }
1693
Tim Peters6d6c1a32001-08-02 04:15:00 +00001694 /* Check for a __slots__ sequence variable in dict, and count it */
1695 slots = PyDict_GetItemString(dict, "__slots__");
1696 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001697 add_dict = 0;
1698 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001699 may_add_dict = base->tp_dictoffset == 0;
1700 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1701 if (slots == NULL) {
1702 if (may_add_dict) {
1703 add_dict++;
1704 }
1705 if (may_add_weak) {
1706 add_weak++;
1707 }
1708 }
1709 else {
1710 /* Have slots */
1711
Tim Peters6d6c1a32001-08-02 04:15:00 +00001712 /* Make it into a tuple */
1713 if (PyString_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001714 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001715 else
1716 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001717 if (slots == NULL) {
1718 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001719 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001720 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001721 assert(PyTuple_Check(slots));
1722
1723 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001724 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001725 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001726 PyErr_Format(PyExc_TypeError,
1727 "nonempty __slots__ "
1728 "not supported for subtype of '%s'",
1729 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001730 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001731 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001732 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001733 return NULL;
1734 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001735
Martin v. Löwisd919a592002-10-14 21:07:28 +00001736#ifdef Py_USING_UNICODE
1737 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001738 if (tmp != slots) {
1739 Py_DECREF(slots);
1740 slots = tmp;
1741 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001742 if (!tmp)
1743 return NULL;
1744#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001745 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001746 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001747 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1748 char *s;
1749 if (!valid_identifier(tmp))
1750 goto bad_slots;
1751 assert(PyString_Check(tmp));
1752 s = PyString_AS_STRING(tmp);
1753 if (strcmp(s, "__dict__") == 0) {
1754 if (!may_add_dict || add_dict) {
1755 PyErr_SetString(PyExc_TypeError,
1756 "__dict__ slot disallowed: "
1757 "we already got one");
1758 goto bad_slots;
1759 }
1760 add_dict++;
1761 }
1762 if (strcmp(s, "__weakref__") == 0) {
1763 if (!may_add_weak || add_weak) {
1764 PyErr_SetString(PyExc_TypeError,
1765 "__weakref__ slot disallowed: "
1766 "either we already got one, "
1767 "or __itemsize__ != 0");
1768 goto bad_slots;
1769 }
1770 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001771 }
1772 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001773
Guido van Rossumad47da02002-08-12 19:05:44 +00001774 /* Copy slots into yet another tuple, demangling names */
1775 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001776 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001777 goto bad_slots;
1778 for (i = j = 0; i < nslots; i++) {
1779 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001780 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001781 s = PyString_AS_STRING(tmp);
1782 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1783 (add_weak && strcmp(s, "__weakref__") == 0))
1784 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001785 tmp =_Py_Mangle(name, tmp);
1786 if (!tmp)
1787 goto bad_slots;
Guido van Rossumad47da02002-08-12 19:05:44 +00001788 PyTuple_SET_ITEM(newslots, j, tmp);
1789 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001790 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001791 assert(j == nslots - add_dict - add_weak);
1792 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001793 Py_DECREF(slots);
1794 slots = newslots;
1795
Guido van Rossumad47da02002-08-12 19:05:44 +00001796 /* Secondary bases may provide weakrefs or dict */
1797 if (nbases > 1 &&
1798 ((may_add_dict && !add_dict) ||
1799 (may_add_weak && !add_weak))) {
1800 for (i = 0; i < nbases; i++) {
1801 tmp = PyTuple_GET_ITEM(bases, i);
1802 if (tmp == (PyObject *)base)
1803 continue; /* Skip primary base */
1804 if (PyClass_Check(tmp)) {
1805 /* Classic base class provides both */
1806 if (may_add_dict && !add_dict)
1807 add_dict++;
1808 if (may_add_weak && !add_weak)
1809 add_weak++;
1810 break;
1811 }
1812 assert(PyType_Check(tmp));
1813 tmptype = (PyTypeObject *)tmp;
1814 if (may_add_dict && !add_dict &&
1815 tmptype->tp_dictoffset != 0)
1816 add_dict++;
1817 if (may_add_weak && !add_weak &&
1818 tmptype->tp_weaklistoffset != 0)
1819 add_weak++;
1820 if (may_add_dict && !add_dict)
1821 continue;
1822 if (may_add_weak && !add_weak)
1823 continue;
1824 /* Nothing more to check */
1825 break;
1826 }
1827 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001828 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001829
1830 /* XXX From here until type is safely allocated,
1831 "return NULL" may leak slots! */
1832
1833 /* Allocate the type object */
1834 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001835 if (type == NULL) {
1836 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001837 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001838 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001839 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001840
1841 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001842 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001843 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00001844 et->ht_name = name;
1845 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001846
Guido van Rossumdc91b992001-08-08 22:26:22 +00001847 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001848 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1849 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001850 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1851 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001852
1853 /* It's a new-style number unless it specifically inherits any
1854 old-style numeric behavior */
1855 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1856 (base->tp_as_number == NULL))
1857 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1858
1859 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001860 type->tp_as_number = &et->as_number;
1861 type->tp_as_sequence = &et->as_sequence;
1862 type->tp_as_mapping = &et->as_mapping;
1863 type->tp_as_buffer = &et->as_buffer;
1864 type->tp_name = PyString_AS_STRING(name);
1865
1866 /* Set tp_base and tp_bases */
1867 type->tp_bases = bases;
1868 Py_INCREF(base);
1869 type->tp_base = base;
1870
Guido van Rossum687ae002001-10-15 22:03:32 +00001871 /* Initialize tp_dict from passed-in dict */
1872 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001873 if (dict == NULL) {
1874 Py_DECREF(type);
1875 return NULL;
1876 }
1877
Guido van Rossumc3542212001-08-16 09:18:56 +00001878 /* Set __module__ in the dict */
1879 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1880 tmp = PyEval_GetGlobals();
1881 if (tmp != NULL) {
1882 tmp = PyDict_GetItemString(tmp, "__name__");
1883 if (tmp != NULL) {
1884 if (PyDict_SetItemString(dict, "__module__",
1885 tmp) < 0)
1886 return NULL;
1887 }
1888 }
1889 }
1890
Tim Peters2f93e282001-10-04 05:27:00 +00001891 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001892 and is a string. The __doc__ accessor will first look for tp_doc;
1893 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001894 */
1895 {
1896 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1897 if (doc != NULL && PyString_Check(doc)) {
1898 const size_t n = (size_t)PyString_GET_SIZE(doc);
Anthony Baxtera6286212006-04-11 07:42:36 +00001899 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001900 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00001901 Py_DECREF(type);
1902 return NULL;
1903 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001904 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
1905 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00001906 }
1907 }
1908
Tim Peters6d6c1a32001-08-02 04:15:00 +00001909 /* Special-case __new__: if it's a plain function,
1910 make it a static function */
1911 tmp = PyDict_GetItemString(dict, "__new__");
1912 if (tmp != NULL && PyFunction_Check(tmp)) {
1913 tmp = PyStaticMethod_New(tmp);
1914 if (tmp == NULL) {
1915 Py_DECREF(type);
1916 return NULL;
1917 }
1918 PyDict_SetItemString(dict, "__new__", tmp);
1919 Py_DECREF(tmp);
1920 }
1921
1922 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001923 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001924 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001925 if (slots != NULL) {
1926 for (i = 0; i < nslots; i++, mp++) {
1927 mp->name = PyString_AS_STRING(
1928 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001929 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001930 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001931 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001932 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001933 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001934 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001935 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001936 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001937 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001938 slotoffset += sizeof(PyObject *);
1939 }
1940 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001941 if (add_dict) {
1942 if (base->tp_itemsize)
1943 type->tp_dictoffset = -(long)sizeof(PyObject *);
1944 else
1945 type->tp_dictoffset = slotoffset;
1946 slotoffset += sizeof(PyObject *);
1947 }
1948 if (add_weak) {
1949 assert(!base->tp_itemsize);
1950 type->tp_weaklistoffset = slotoffset;
1951 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001952 }
1953 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001954 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001955 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001956
1957 if (type->tp_weaklistoffset && type->tp_dictoffset)
1958 type->tp_getset = subtype_getsets_full;
1959 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1960 type->tp_getset = subtype_getsets_weakref_only;
1961 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1962 type->tp_getset = subtype_getsets_dict_only;
1963 else
1964 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001965
1966 /* Special case some slots */
1967 if (type->tp_dictoffset != 0 || nslots > 0) {
1968 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1969 type->tp_getattro = PyObject_GenericGetAttr;
1970 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1971 type->tp_setattro = PyObject_GenericSetAttr;
1972 }
1973 type->tp_dealloc = subtype_dealloc;
1974
Guido van Rossum9475a232001-10-05 20:51:39 +00001975 /* Enable GC unless there are really no instance variables possible */
1976 if (!(type->tp_basicsize == sizeof(PyObject) &&
1977 type->tp_itemsize == 0))
1978 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1979
Tim Peters6d6c1a32001-08-02 04:15:00 +00001980 /* Always override allocation strategy to use regular heap */
1981 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001982 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001983 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001984 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001985 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001986 }
1987 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001988 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001989
1990 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001991 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001992 Py_DECREF(type);
1993 return NULL;
1994 }
1995
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001996 /* Put the proper slots in place */
1997 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001998
Tim Peters6d6c1a32001-08-02 04:15:00 +00001999 return (PyObject *)type;
2000}
2001
2002/* Internal API to look for a name through the MRO.
2003 This returns a borrowed reference, and doesn't set an exception! */
2004PyObject *
2005_PyType_Lookup(PyTypeObject *type, PyObject *name)
2006{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002007 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002008 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002009
Guido van Rossum687ae002001-10-15 22:03:32 +00002010 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002011 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002012
2013 /* If mro is NULL, the type is either not yet initialized
2014 by PyType_Ready(), or already cleared by type_clear().
2015 Either way the safest thing to do is to return NULL. */
2016 if (mro == NULL)
2017 return NULL;
2018
Tim Peters6d6c1a32001-08-02 04:15:00 +00002019 assert(PyTuple_Check(mro));
2020 n = PyTuple_GET_SIZE(mro);
2021 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002022 base = PyTuple_GET_ITEM(mro, i);
2023 if (PyClass_Check(base))
2024 dict = ((PyClassObject *)base)->cl_dict;
2025 else {
2026 assert(PyType_Check(base));
2027 dict = ((PyTypeObject *)base)->tp_dict;
2028 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002029 assert(dict && PyDict_Check(dict));
2030 res = PyDict_GetItem(dict, name);
2031 if (res != NULL)
2032 return res;
2033 }
2034 return NULL;
2035}
2036
2037/* This is similar to PyObject_GenericGetAttr(),
2038 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2039static PyObject *
2040type_getattro(PyTypeObject *type, PyObject *name)
2041{
2042 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002043 PyObject *meta_attribute, *attribute;
2044 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002045
2046 /* Initialize this type (we'll assume the metatype is initialized) */
2047 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002048 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002049 return NULL;
2050 }
2051
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002052 /* No readable descriptor found yet */
2053 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002054
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002055 /* Look for the attribute in the metatype */
2056 meta_attribute = _PyType_Lookup(metatype, name);
2057
2058 if (meta_attribute != NULL) {
2059 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002060
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002061 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2062 /* Data descriptors implement tp_descr_set to intercept
2063 * writes. Assume the attribute is not overridden in
2064 * type's tp_dict (and bases): call the descriptor now.
2065 */
2066 return meta_get(meta_attribute, (PyObject *)type,
2067 (PyObject *)metatype);
2068 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002069 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002070 }
2071
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002072 /* No data descriptor found on metatype. Look in tp_dict of this
2073 * type and its bases */
2074 attribute = _PyType_Lookup(type, name);
2075 if (attribute != NULL) {
2076 /* Implement descriptor functionality, if any */
2077 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002078
2079 Py_XDECREF(meta_attribute);
2080
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002081 if (local_get != NULL) {
2082 /* NULL 2nd argument indicates the descriptor was
2083 * found on the target object itself (or a base) */
2084 return local_get(attribute, (PyObject *)NULL,
2085 (PyObject *)type);
2086 }
Tim Peters34592512002-07-11 06:23:50 +00002087
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002088 Py_INCREF(attribute);
2089 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002090 }
2091
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002092 /* No attribute found in local __dict__ (or bases): use the
2093 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002094 if (meta_get != NULL) {
2095 PyObject *res;
2096 res = meta_get(meta_attribute, (PyObject *)type,
2097 (PyObject *)metatype);
2098 Py_DECREF(meta_attribute);
2099 return res;
2100 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002101
2102 /* If an ordinary attribute was found on the metatype, return it now */
2103 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002104 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002105 }
2106
2107 /* Give up */
2108 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002109 "type object '%.50s' has no attribute '%.400s'",
2110 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002111 return NULL;
2112}
2113
2114static int
2115type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2116{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002117 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2118 PyErr_Format(
2119 PyExc_TypeError,
2120 "can't set attributes of built-in/extension type '%s'",
2121 type->tp_name);
2122 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002123 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002124 /* XXX Example of how I expect this to be used...
2125 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2126 return -1;
2127 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002128 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2129 return -1;
2130 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002131}
2132
2133static void
2134type_dealloc(PyTypeObject *type)
2135{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002136 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002137
2138 /* Assert this is a heap-allocated type object */
2139 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002140 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002141 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002142 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002143 Py_XDECREF(type->tp_base);
2144 Py_XDECREF(type->tp_dict);
2145 Py_XDECREF(type->tp_bases);
2146 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002147 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002148 Py_XDECREF(type->tp_subclasses);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002149 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2150 * of most other objects. It's okay to cast it to char *.
2151 */
2152 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002153 Py_XDECREF(et->ht_name);
2154 Py_XDECREF(et->ht_slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002155 type->ob_type->tp_free((PyObject *)type);
2156}
2157
Guido van Rossum1c450732001-10-08 15:18:27 +00002158static PyObject *
2159type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2160{
2161 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002162 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002163
2164 list = PyList_New(0);
2165 if (list == NULL)
2166 return NULL;
2167 raw = type->tp_subclasses;
2168 if (raw == NULL)
2169 return list;
2170 assert(PyList_Check(raw));
2171 n = PyList_GET_SIZE(raw);
2172 for (i = 0; i < n; i++) {
2173 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002174 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002175 ref = PyWeakref_GET_OBJECT(ref);
2176 if (ref != Py_None) {
2177 if (PyList_Append(list, ref) < 0) {
2178 Py_DECREF(list);
2179 return NULL;
2180 }
2181 }
2182 }
2183 return list;
2184}
2185
Tim Peters6d6c1a32001-08-02 04:15:00 +00002186static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002187 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002188 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002189 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002190 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002191 {0}
2192};
2193
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002194PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002195"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002196"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002197
Guido van Rossum048eb752001-10-02 21:24:57 +00002198static int
2199type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2200{
Guido van Rossum048eb752001-10-02 21:24:57 +00002201 int err;
2202
Guido van Rossuma3862092002-06-10 15:24:42 +00002203 /* Because of type_is_gc(), the collector only calls this
2204 for heaptypes. */
2205 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002206
2207#define VISIT(SLOT) \
2208 if (SLOT) { \
2209 err = visit((PyObject *)(SLOT), arg); \
2210 if (err) \
2211 return err; \
2212 }
2213
2214 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002215 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002216 VISIT(type->tp_mro);
2217 VISIT(type->tp_bases);
2218 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002219
2220 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002221 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002222 in cycles; tp_subclasses is a list of weak references,
2223 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002224
2225#undef VISIT
2226
2227 return 0;
2228}
2229
2230static int
2231type_clear(PyTypeObject *type)
2232{
Guido van Rossum048eb752001-10-02 21:24:57 +00002233 PyObject *tmp;
2234
Guido van Rossuma3862092002-06-10 15:24:42 +00002235 /* Because of type_is_gc(), the collector only calls this
2236 for heaptypes. */
2237 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002238
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
Thomas Woutersedf17d82006-04-15 17:28:34 +00002264 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002265
2266 return 0;
2267}
2268
2269static int
2270type_is_gc(PyTypeObject *type)
2271{
2272 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2273}
2274
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002275PyTypeObject PyType_Type = {
2276 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002277 0, /* ob_size */
2278 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002279 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002280 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002281 (destructor)type_dealloc, /* tp_dealloc */
2282 0, /* tp_print */
2283 0, /* tp_getattr */
2284 0, /* tp_setattr */
2285 type_compare, /* tp_compare */
2286 (reprfunc)type_repr, /* tp_repr */
2287 0, /* tp_as_number */
2288 0, /* tp_as_sequence */
2289 0, /* tp_as_mapping */
2290 (hashfunc)_Py_HashPointer, /* tp_hash */
2291 (ternaryfunc)type_call, /* tp_call */
2292 0, /* tp_str */
2293 (getattrofunc)type_getattro, /* tp_getattro */
2294 (setattrofunc)type_setattro, /* tp_setattro */
2295 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002296 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2297 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002298 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002299 (traverseproc)type_traverse, /* tp_traverse */
2300 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002301 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002302 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002303 0, /* tp_iter */
2304 0, /* tp_iternext */
2305 type_methods, /* tp_methods */
2306 type_members, /* tp_members */
2307 type_getsets, /* tp_getset */
2308 0, /* tp_base */
2309 0, /* tp_dict */
2310 0, /* tp_descr_get */
2311 0, /* tp_descr_set */
2312 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2313 0, /* tp_init */
2314 0, /* tp_alloc */
2315 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002316 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002317 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002318};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002319
2320
2321/* The base type of all types (eventually)... except itself. */
2322
2323static int
2324object_init(PyObject *self, PyObject *args, PyObject *kwds)
2325{
2326 return 0;
2327}
2328
Guido van Rossum298e4212003-02-13 16:30:16 +00002329/* If we don't have a tp_new for a new-style class, new will use this one.
2330 Therefore this should take no arguments/keywords. However, this new may
2331 also be inherited by objects that define a tp_init but no tp_new. These
2332 objects WILL pass argumets to tp_new, because it gets the same args as
2333 tp_init. So only allow arguments if we aren't using the default init, in
2334 which case we expect init to handle argument parsing. */
2335static PyObject *
2336object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2337{
2338 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2339 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2340 PyErr_SetString(PyExc_TypeError,
2341 "default __new__ takes no parameters");
2342 return NULL;
2343 }
2344 return type->tp_alloc(type, 0);
2345}
2346
Tim Peters6d6c1a32001-08-02 04:15:00 +00002347static void
2348object_dealloc(PyObject *self)
2349{
2350 self->ob_type->tp_free(self);
2351}
2352
Guido van Rossum8e248182001-08-12 05:17:56 +00002353static PyObject *
2354object_repr(PyObject *self)
2355{
Guido van Rossum76e69632001-08-16 18:52:43 +00002356 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002357 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002358
Guido van Rossum76e69632001-08-16 18:52:43 +00002359 type = self->ob_type;
2360 mod = type_module(type, NULL);
2361 if (mod == NULL)
2362 PyErr_Clear();
2363 else if (!PyString_Check(mod)) {
2364 Py_DECREF(mod);
2365 mod = NULL;
2366 }
2367 name = type_name(type, NULL);
2368 if (name == NULL)
2369 return NULL;
2370 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002371 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002372 PyString_AS_STRING(mod),
2373 PyString_AS_STRING(name),
2374 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002375 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002376 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002377 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002378 Py_XDECREF(mod);
2379 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002380 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002381}
2382
Guido van Rossumb8f63662001-08-15 23:57:02 +00002383static PyObject *
2384object_str(PyObject *self)
2385{
2386 unaryfunc f;
2387
2388 f = self->ob_type->tp_repr;
2389 if (f == NULL)
2390 f = object_repr;
2391 return f(self);
2392}
2393
Guido van Rossum8e248182001-08-12 05:17:56 +00002394static long
2395object_hash(PyObject *self)
2396{
2397 return _Py_HashPointer(self);
2398}
Guido van Rossum8e248182001-08-12 05:17:56 +00002399
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002400static PyObject *
2401object_get_class(PyObject *self, void *closure)
2402{
2403 Py_INCREF(self->ob_type);
2404 return (PyObject *)(self->ob_type);
2405}
2406
2407static int
2408equiv_structs(PyTypeObject *a, PyTypeObject *b)
2409{
2410 return a == b ||
2411 (a != NULL &&
2412 b != NULL &&
2413 a->tp_basicsize == b->tp_basicsize &&
2414 a->tp_itemsize == b->tp_itemsize &&
2415 a->tp_dictoffset == b->tp_dictoffset &&
2416 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2417 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2418 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2419}
2420
2421static int
2422same_slots_added(PyTypeObject *a, PyTypeObject *b)
2423{
2424 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002425 Py_ssize_t size;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002426
2427 if (base != b->tp_base)
2428 return 0;
2429 if (equiv_structs(a, base) && equiv_structs(b, base))
2430 return 1;
2431 size = base->tp_basicsize;
2432 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2433 size += sizeof(PyObject *);
2434 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2435 size += sizeof(PyObject *);
2436 return size == a->tp_basicsize && size == b->tp_basicsize;
2437}
2438
2439static int
Anthony Baxtera6286212006-04-11 07:42:36 +00002440compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002441{
2442 PyTypeObject *newbase, *oldbase;
2443
Anthony Baxtera6286212006-04-11 07:42:36 +00002444 if (newto->tp_dealloc != oldto->tp_dealloc ||
2445 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002446 {
2447 PyErr_Format(PyExc_TypeError,
2448 "%s assignment: "
2449 "'%s' deallocator differs from '%s'",
2450 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002451 newto->tp_name,
2452 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002453 return 0;
2454 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002455 newbase = newto;
2456 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002457 while (equiv_structs(newbase, newbase->tp_base))
2458 newbase = newbase->tp_base;
2459 while (equiv_structs(oldbase, oldbase->tp_base))
2460 oldbase = oldbase->tp_base;
2461 if (newbase != oldbase &&
2462 (newbase->tp_base != oldbase->tp_base ||
2463 !same_slots_added(newbase, oldbase))) {
2464 PyErr_Format(PyExc_TypeError,
2465 "%s assignment: "
2466 "'%s' object layout differs from '%s'",
2467 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002468 newto->tp_name,
2469 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002470 return 0;
2471 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002472
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002473 return 1;
2474}
2475
2476static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002477object_set_class(PyObject *self, PyObject *value, void *closure)
2478{
Anthony Baxtera6286212006-04-11 07:42:36 +00002479 PyTypeObject *oldto = self->ob_type;
2480 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002481
Guido van Rossumb6b89422002-04-15 01:03:30 +00002482 if (value == NULL) {
2483 PyErr_SetString(PyExc_TypeError,
2484 "can't delete __class__ attribute");
2485 return -1;
2486 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002487 if (!PyType_Check(value)) {
2488 PyErr_Format(PyExc_TypeError,
2489 "__class__ must be set to new-style class, not '%s' object",
2490 value->ob_type->tp_name);
2491 return -1;
2492 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002493 newto = (PyTypeObject *)value;
2494 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2495 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002496 {
2497 PyErr_Format(PyExc_TypeError,
2498 "__class__ assignment: only for heap types");
2499 return -1;
2500 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002501 if (compatible_for_assignment(newto, oldto, "__class__")) {
2502 Py_INCREF(newto);
2503 self->ob_type = newto;
2504 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002505 return 0;
2506 }
2507 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002508 return -1;
2509 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002510}
2511
2512static PyGetSetDef object_getsets[] = {
2513 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002514 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002515 {0}
2516};
2517
Guido van Rossumc53f0092003-02-18 22:05:12 +00002518
Guido van Rossum036f9992003-02-21 22:02:54 +00002519/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2520 We fall back to helpers in copy_reg for:
2521 - pickle protocols < 2
2522 - calculating the list of slot names (done only once per class)
2523 - the __newobj__ function (which is used as a token but never called)
2524*/
2525
2526static PyObject *
2527import_copy_reg(void)
2528{
2529 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002530
2531 if (!copy_reg_str) {
2532 copy_reg_str = PyString_InternFromString("copy_reg");
2533 if (copy_reg_str == NULL)
2534 return NULL;
2535 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002536
2537 return PyImport_Import(copy_reg_str);
2538}
2539
2540static PyObject *
2541slotnames(PyObject *cls)
2542{
2543 PyObject *clsdict;
2544 PyObject *copy_reg;
2545 PyObject *slotnames;
2546
2547 if (!PyType_Check(cls)) {
2548 Py_INCREF(Py_None);
2549 return Py_None;
2550 }
2551
2552 clsdict = ((PyTypeObject *)cls)->tp_dict;
2553 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002554 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002555 Py_INCREF(slotnames);
2556 return slotnames;
2557 }
2558
2559 copy_reg = import_copy_reg();
2560 if (copy_reg == NULL)
2561 return NULL;
2562
2563 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2564 Py_DECREF(copy_reg);
2565 if (slotnames != NULL &&
2566 slotnames != Py_None &&
2567 !PyList_Check(slotnames))
2568 {
2569 PyErr_SetString(PyExc_TypeError,
2570 "copy_reg._slotnames didn't return a list or None");
2571 Py_DECREF(slotnames);
2572 slotnames = NULL;
2573 }
2574
2575 return slotnames;
2576}
2577
2578static PyObject *
2579reduce_2(PyObject *obj)
2580{
2581 PyObject *cls, *getnewargs;
2582 PyObject *args = NULL, *args2 = NULL;
2583 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2584 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2585 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002586 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00002587
2588 cls = PyObject_GetAttrString(obj, "__class__");
2589 if (cls == NULL)
2590 return NULL;
2591
2592 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2593 if (getnewargs != NULL) {
2594 args = PyObject_CallObject(getnewargs, NULL);
2595 Py_DECREF(getnewargs);
2596 if (args != NULL && !PyTuple_Check(args)) {
2597 PyErr_SetString(PyExc_TypeError,
2598 "__getnewargs__ should return a tuple");
2599 goto end;
2600 }
2601 }
2602 else {
2603 PyErr_Clear();
2604 args = PyTuple_New(0);
2605 }
2606 if (args == NULL)
2607 goto end;
2608
2609 getstate = PyObject_GetAttrString(obj, "__getstate__");
2610 if (getstate != NULL) {
2611 state = PyObject_CallObject(getstate, NULL);
2612 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002613 if (state == NULL)
2614 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002615 }
2616 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002617 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002618 state = PyObject_GetAttrString(obj, "__dict__");
2619 if (state == NULL) {
2620 PyErr_Clear();
2621 state = Py_None;
2622 Py_INCREF(state);
2623 }
2624 names = slotnames(cls);
2625 if (names == NULL)
2626 goto end;
2627 if (names != Py_None) {
2628 assert(PyList_Check(names));
2629 slots = PyDict_New();
2630 if (slots == NULL)
2631 goto end;
2632 n = 0;
2633 /* Can't pre-compute the list size; the list
2634 is stored on the class so accessible to other
2635 threads, which may be run by DECREF */
2636 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2637 PyObject *name, *value;
2638 name = PyList_GET_ITEM(names, i);
2639 value = PyObject_GetAttr(obj, name);
2640 if (value == NULL)
2641 PyErr_Clear();
2642 else {
2643 int err = PyDict_SetItem(slots, name,
2644 value);
2645 Py_DECREF(value);
2646 if (err)
2647 goto end;
2648 n++;
2649 }
2650 }
2651 if (n) {
2652 state = Py_BuildValue("(NO)", state, slots);
2653 if (state == NULL)
2654 goto end;
2655 }
2656 }
2657 }
2658
2659 if (!PyList_Check(obj)) {
2660 listitems = Py_None;
2661 Py_INCREF(listitems);
2662 }
2663 else {
2664 listitems = PyObject_GetIter(obj);
2665 if (listitems == NULL)
2666 goto end;
2667 }
2668
2669 if (!PyDict_Check(obj)) {
2670 dictitems = Py_None;
2671 Py_INCREF(dictitems);
2672 }
2673 else {
2674 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2675 if (dictitems == NULL)
2676 goto end;
2677 }
2678
2679 copy_reg = import_copy_reg();
2680 if (copy_reg == NULL)
2681 goto end;
2682 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2683 if (newobj == NULL)
2684 goto end;
2685
2686 n = PyTuple_GET_SIZE(args);
2687 args2 = PyTuple_New(n+1);
2688 if (args2 == NULL)
2689 goto end;
2690 PyTuple_SET_ITEM(args2, 0, cls);
2691 cls = NULL;
2692 for (i = 0; i < n; i++) {
2693 PyObject *v = PyTuple_GET_ITEM(args, i);
2694 Py_INCREF(v);
2695 PyTuple_SET_ITEM(args2, i+1, v);
2696 }
2697
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002698 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002699
2700 end:
2701 Py_XDECREF(cls);
2702 Py_XDECREF(args);
2703 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002704 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002705 Py_XDECREF(state);
2706 Py_XDECREF(names);
2707 Py_XDECREF(listitems);
2708 Py_XDECREF(dictitems);
2709 Py_XDECREF(copy_reg);
2710 Py_XDECREF(newobj);
2711 return res;
2712}
2713
2714static PyObject *
2715object_reduce_ex(PyObject *self, PyObject *args)
2716{
2717 /* Call copy_reg._reduce_ex(self, proto) */
2718 PyObject *reduce, *copy_reg, *res;
2719 int proto = 0;
2720
2721 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2722 return NULL;
2723
2724 reduce = PyObject_GetAttrString(self, "__reduce__");
2725 if (reduce == NULL)
2726 PyErr_Clear();
2727 else {
2728 PyObject *cls, *clsreduce, *objreduce;
2729 int override;
2730 cls = PyObject_GetAttrString(self, "__class__");
2731 if (cls == NULL) {
2732 Py_DECREF(reduce);
2733 return NULL;
2734 }
2735 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2736 Py_DECREF(cls);
2737 if (clsreduce == NULL) {
2738 Py_DECREF(reduce);
2739 return NULL;
2740 }
2741 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2742 "__reduce__");
2743 override = (clsreduce != objreduce);
2744 Py_DECREF(clsreduce);
2745 if (override) {
2746 res = PyObject_CallObject(reduce, NULL);
2747 Py_DECREF(reduce);
2748 return res;
2749 }
2750 else
2751 Py_DECREF(reduce);
2752 }
2753
2754 if (proto >= 2)
2755 return reduce_2(self);
2756
2757 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002758 if (!copy_reg)
2759 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002760
Guido van Rossumc53f0092003-02-18 22:05:12 +00002761 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002762 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002763
Guido van Rossum3926a632001-09-25 16:25:58 +00002764 return res;
2765}
2766
2767static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002768 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2769 PyDoc_STR("helper for pickle")},
2770 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002771 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002772 {0}
2773};
2774
Guido van Rossum036f9992003-02-21 22:02:54 +00002775
Tim Peters6d6c1a32001-08-02 04:15:00 +00002776PyTypeObject PyBaseObject_Type = {
2777 PyObject_HEAD_INIT(&PyType_Type)
2778 0, /* ob_size */
2779 "object", /* tp_name */
2780 sizeof(PyObject), /* tp_basicsize */
2781 0, /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00002782 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002783 0, /* tp_print */
2784 0, /* tp_getattr */
2785 0, /* tp_setattr */
2786 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002787 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002788 0, /* tp_as_number */
2789 0, /* tp_as_sequence */
2790 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002791 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002792 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002793 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002794 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002795 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002796 0, /* tp_as_buffer */
2797 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002798 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002799 0, /* tp_traverse */
2800 0, /* tp_clear */
2801 0, /* tp_richcompare */
2802 0, /* tp_weaklistoffset */
2803 0, /* tp_iter */
2804 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002805 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002806 0, /* tp_members */
2807 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002808 0, /* tp_base */
2809 0, /* tp_dict */
2810 0, /* tp_descr_get */
2811 0, /* tp_descr_set */
2812 0, /* tp_dictoffset */
2813 object_init, /* tp_init */
2814 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002815 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002816 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002817};
2818
2819
2820/* Initialize the __dict__ in a type object */
2821
2822static int
2823add_methods(PyTypeObject *type, PyMethodDef *meth)
2824{
Guido van Rossum687ae002001-10-15 22:03:32 +00002825 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002826
2827 for (; meth->ml_name != NULL; meth++) {
2828 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002829 if (PyDict_GetItemString(dict, meth->ml_name) &&
2830 !(meth->ml_flags & METH_COEXIST))
2831 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002832 if (meth->ml_flags & METH_CLASS) {
2833 if (meth->ml_flags & METH_STATIC) {
2834 PyErr_SetString(PyExc_ValueError,
2835 "method cannot be both class and static");
2836 return -1;
2837 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002838 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002839 }
2840 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002841 PyObject *cfunc = PyCFunction_New(meth, NULL);
2842 if (cfunc == NULL)
2843 return -1;
2844 descr = PyStaticMethod_New(cfunc);
2845 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002846 }
2847 else {
2848 descr = PyDescr_NewMethod(type, meth);
2849 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002850 if (descr == NULL)
2851 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002852 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002853 return -1;
2854 Py_DECREF(descr);
2855 }
2856 return 0;
2857}
2858
2859static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002860add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002861{
Guido van Rossum687ae002001-10-15 22:03:32 +00002862 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002863
2864 for (; memb->name != NULL; memb++) {
2865 PyObject *descr;
2866 if (PyDict_GetItemString(dict, memb->name))
2867 continue;
2868 descr = PyDescr_NewMember(type, memb);
2869 if (descr == NULL)
2870 return -1;
2871 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2872 return -1;
2873 Py_DECREF(descr);
2874 }
2875 return 0;
2876}
2877
2878static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002879add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002880{
Guido van Rossum687ae002001-10-15 22:03:32 +00002881 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002882
2883 for (; gsp->name != NULL; gsp++) {
2884 PyObject *descr;
2885 if (PyDict_GetItemString(dict, gsp->name))
2886 continue;
2887 descr = PyDescr_NewGetSet(type, gsp);
2888
2889 if (descr == NULL)
2890 return -1;
2891 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2892 return -1;
2893 Py_DECREF(descr);
2894 }
2895 return 0;
2896}
2897
Guido van Rossum13d52f02001-08-10 21:24:08 +00002898static void
2899inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002900{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002901 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002902
Guido van Rossum13d52f02001-08-10 21:24:08 +00002903 /* Special flag magic */
2904 if (!type->tp_as_buffer && base->tp_as_buffer) {
2905 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2906 type->tp_flags |=
2907 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2908 }
2909 if (!type->tp_as_sequence && base->tp_as_sequence) {
2910 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2911 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2912 }
2913 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2914 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2915 if ((!type->tp_as_number && base->tp_as_number) ||
2916 (!type->tp_as_sequence && base->tp_as_sequence)) {
2917 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2918 if (!type->tp_as_number && !type->tp_as_sequence) {
2919 type->tp_flags |= base->tp_flags &
2920 Py_TPFLAGS_HAVE_INPLACEOPS;
2921 }
2922 }
2923 /* Wow */
2924 }
2925 if (!type->tp_as_number && base->tp_as_number) {
2926 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2927 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2928 }
2929
2930 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002931 oldsize = base->tp_basicsize;
2932 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2933 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2934 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002935 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2936 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002937 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002938 if (type->tp_traverse == NULL)
2939 type->tp_traverse = base->tp_traverse;
2940 if (type->tp_clear == NULL)
2941 type->tp_clear = base->tp_clear;
2942 }
2943 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002944 /* The condition below could use some explanation.
2945 It appears that tp_new is not inherited for static types
2946 whose base class is 'object'; this seems to be a precaution
2947 so that old extension types don't suddenly become
2948 callable (object.__new__ wouldn't insure the invariants
2949 that the extension type's own factory function ensures).
2950 Heap types, of course, are under our control, so they do
2951 inherit tp_new; static extension types that specify some
2952 other built-in type as the default are considered
2953 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002954 if (base != &PyBaseObject_Type ||
2955 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2956 if (type->tp_new == NULL)
2957 type->tp_new = base->tp_new;
2958 }
2959 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002960 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002961
2962 /* Copy other non-function slots */
2963
2964#undef COPYVAL
2965#define COPYVAL(SLOT) \
2966 if (type->SLOT == 0) type->SLOT = base->SLOT
2967
2968 COPYVAL(tp_itemsize);
2969 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2970 COPYVAL(tp_weaklistoffset);
2971 }
2972 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2973 COPYVAL(tp_dictoffset);
2974 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002975}
2976
2977static void
2978inherit_slots(PyTypeObject *type, PyTypeObject *base)
2979{
2980 PyTypeObject *basebase;
2981
2982#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002983#undef COPYSLOT
2984#undef COPYNUM
2985#undef COPYSEQ
2986#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002987#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002988
2989#define SLOTDEFINED(SLOT) \
2990 (base->SLOT != 0 && \
2991 (basebase == NULL || base->SLOT != basebase->SLOT))
2992
Tim Peters6d6c1a32001-08-02 04:15:00 +00002993#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002994 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002995
2996#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2997#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2998#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002999#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003000
Guido van Rossum13d52f02001-08-10 21:24:08 +00003001 /* This won't inherit indirect slots (from tp_as_number etc.)
3002 if type doesn't provide the space. */
3003
3004 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3005 basebase = base->tp_base;
3006 if (basebase->tp_as_number == NULL)
3007 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003008 COPYNUM(nb_add);
3009 COPYNUM(nb_subtract);
3010 COPYNUM(nb_multiply);
3011 COPYNUM(nb_divide);
3012 COPYNUM(nb_remainder);
3013 COPYNUM(nb_divmod);
3014 COPYNUM(nb_power);
3015 COPYNUM(nb_negative);
3016 COPYNUM(nb_positive);
3017 COPYNUM(nb_absolute);
3018 COPYNUM(nb_nonzero);
3019 COPYNUM(nb_invert);
3020 COPYNUM(nb_lshift);
3021 COPYNUM(nb_rshift);
3022 COPYNUM(nb_and);
3023 COPYNUM(nb_xor);
3024 COPYNUM(nb_or);
3025 COPYNUM(nb_coerce);
3026 COPYNUM(nb_int);
3027 COPYNUM(nb_long);
3028 COPYNUM(nb_float);
3029 COPYNUM(nb_oct);
3030 COPYNUM(nb_hex);
3031 COPYNUM(nb_inplace_add);
3032 COPYNUM(nb_inplace_subtract);
3033 COPYNUM(nb_inplace_multiply);
3034 COPYNUM(nb_inplace_divide);
3035 COPYNUM(nb_inplace_remainder);
3036 COPYNUM(nb_inplace_power);
3037 COPYNUM(nb_inplace_lshift);
3038 COPYNUM(nb_inplace_rshift);
3039 COPYNUM(nb_inplace_and);
3040 COPYNUM(nb_inplace_xor);
3041 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003042 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3043 COPYNUM(nb_true_divide);
3044 COPYNUM(nb_floor_divide);
3045 COPYNUM(nb_inplace_true_divide);
3046 COPYNUM(nb_inplace_floor_divide);
3047 }
Guido van Rossum38fff8c2006-03-07 18:50:55 +00003048 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3049 COPYNUM(nb_index);
3050 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003051 }
3052
Guido van Rossum13d52f02001-08-10 21:24:08 +00003053 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3054 basebase = base->tp_base;
3055 if (basebase->tp_as_sequence == NULL)
3056 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003057 COPYSEQ(sq_length);
3058 COPYSEQ(sq_concat);
3059 COPYSEQ(sq_repeat);
3060 COPYSEQ(sq_item);
3061 COPYSEQ(sq_slice);
3062 COPYSEQ(sq_ass_item);
3063 COPYSEQ(sq_ass_slice);
3064 COPYSEQ(sq_contains);
3065 COPYSEQ(sq_inplace_concat);
3066 COPYSEQ(sq_inplace_repeat);
3067 }
3068
Guido van Rossum13d52f02001-08-10 21:24:08 +00003069 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3070 basebase = base->tp_base;
3071 if (basebase->tp_as_mapping == NULL)
3072 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003073 COPYMAP(mp_length);
3074 COPYMAP(mp_subscript);
3075 COPYMAP(mp_ass_subscript);
3076 }
3077
Tim Petersfc57ccb2001-10-12 02:38:24 +00003078 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3079 basebase = base->tp_base;
3080 if (basebase->tp_as_buffer == NULL)
3081 basebase = NULL;
3082 COPYBUF(bf_getreadbuffer);
3083 COPYBUF(bf_getwritebuffer);
3084 COPYBUF(bf_getsegcount);
3085 COPYBUF(bf_getcharbuffer);
3086 }
3087
Guido van Rossum13d52f02001-08-10 21:24:08 +00003088 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003089
Tim Peters6d6c1a32001-08-02 04:15:00 +00003090 COPYSLOT(tp_dealloc);
3091 COPYSLOT(tp_print);
3092 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3093 type->tp_getattr = base->tp_getattr;
3094 type->tp_getattro = base->tp_getattro;
3095 }
3096 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3097 type->tp_setattr = base->tp_setattr;
3098 type->tp_setattro = base->tp_setattro;
3099 }
3100 /* tp_compare see tp_richcompare */
3101 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003102 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003103 COPYSLOT(tp_call);
3104 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003105 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003106 if (type->tp_compare == NULL &&
3107 type->tp_richcompare == NULL &&
3108 type->tp_hash == NULL)
3109 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003110 type->tp_compare = base->tp_compare;
3111 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003112 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003113 }
3114 }
3115 else {
3116 COPYSLOT(tp_compare);
3117 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003118 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3119 COPYSLOT(tp_iter);
3120 COPYSLOT(tp_iternext);
3121 }
3122 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3123 COPYSLOT(tp_descr_get);
3124 COPYSLOT(tp_descr_set);
3125 COPYSLOT(tp_dictoffset);
3126 COPYSLOT(tp_init);
3127 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003128 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003129 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3130 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3131 /* They agree about gc. */
3132 COPYSLOT(tp_free);
3133 }
3134 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3135 type->tp_free == NULL &&
3136 base->tp_free == _PyObject_Del) {
3137 /* A bit of magic to plug in the correct default
3138 * tp_free function when a derived class adds gc,
3139 * didn't define tp_free, and the base uses the
3140 * default non-gc tp_free.
3141 */
3142 type->tp_free = PyObject_GC_Del;
3143 }
3144 /* else they didn't agree about gc, and there isn't something
3145 * obvious to be done -- the type is on its own.
3146 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003147 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003148}
3149
Jeremy Hylton938ace62002-07-17 16:30:39 +00003150static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003151
Tim Peters6d6c1a32001-08-02 04:15:00 +00003152int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003153PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003154{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003155 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003156 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003157 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003158
Guido van Rossumcab05802002-06-10 15:29:03 +00003159 if (type->tp_flags & Py_TPFLAGS_READY) {
3160 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003161 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003162 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003163 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003164
3165 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003166
Tim Peters36eb4df2003-03-23 03:33:13 +00003167#ifdef Py_TRACE_REFS
3168 /* PyType_Ready is the closest thing we have to a choke point
3169 * for type objects, so is the best place I can think of to try
3170 * to get type objects into the doubly-linked list of all objects.
3171 * Still, not all type objects go thru PyType_Ready.
3172 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003173 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003174#endif
3175
Tim Peters6d6c1a32001-08-02 04:15:00 +00003176 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3177 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003178 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003179 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003180 Py_INCREF(base);
3181 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003182
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003183 /* Now the only way base can still be NULL is if type is
3184 * &PyBaseObject_Type.
3185 */
3186
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003187 /* Initialize the base class */
3188 if (base && base->tp_dict == NULL) {
3189 if (PyType_Ready(base) < 0)
3190 goto error;
3191 }
3192
Guido van Rossum0986d822002-04-08 01:38:42 +00003193 /* Initialize ob_type if NULL. This means extensions that want to be
3194 compilable separately on Windows can call PyType_Ready() instead of
3195 initializing the ob_type field of their type objects. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003196 /* The test for base != NULL is really unnecessary, since base is only
3197 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3198 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3199 know that. */
3200 if (type->ob_type == NULL && base != NULL)
Guido van Rossum0986d822002-04-08 01:38:42 +00003201 type->ob_type = base->ob_type;
3202
Tim Peters6d6c1a32001-08-02 04:15:00 +00003203 /* Initialize tp_bases */
3204 bases = type->tp_bases;
3205 if (bases == NULL) {
3206 if (base == NULL)
3207 bases = PyTuple_New(0);
3208 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003209 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003210 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003211 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003212 type->tp_bases = bases;
3213 }
3214
Guido van Rossum687ae002001-10-15 22:03:32 +00003215 /* Initialize tp_dict */
3216 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003217 if (dict == NULL) {
3218 dict = PyDict_New();
3219 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003220 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003221 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003222 }
3223
Guido van Rossum687ae002001-10-15 22:03:32 +00003224 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003225 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003226 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003227 if (type->tp_methods != NULL) {
3228 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003229 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003230 }
3231 if (type->tp_members != NULL) {
3232 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003233 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003234 }
3235 if (type->tp_getset != NULL) {
3236 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003237 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003238 }
3239
Tim Peters6d6c1a32001-08-02 04:15:00 +00003240 /* Calculate method resolution order */
3241 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003242 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003243 }
3244
Guido van Rossum13d52f02001-08-10 21:24:08 +00003245 /* Inherit special flags from dominant base */
3246 if (type->tp_base != NULL)
3247 inherit_special(type, type->tp_base);
3248
Tim Peters6d6c1a32001-08-02 04:15:00 +00003249 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003250 bases = type->tp_mro;
3251 assert(bases != NULL);
3252 assert(PyTuple_Check(bases));
3253 n = PyTuple_GET_SIZE(bases);
3254 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003255 PyObject *b = PyTuple_GET_ITEM(bases, i);
3256 if (PyType_Check(b))
3257 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003258 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003259
Tim Peters3cfe7542003-05-21 21:29:48 +00003260 /* Sanity check for tp_free. */
3261 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3262 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3263 /* This base class needs to call tp_free, but doesn't have
3264 * one, or its tp_free is for non-gc'ed objects.
3265 */
3266 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3267 "gc and is a base type but has inappropriate "
3268 "tp_free slot",
3269 type->tp_name);
3270 goto error;
3271 }
3272
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003273 /* if the type dictionary doesn't contain a __doc__, set it from
3274 the tp_doc slot.
3275 */
3276 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3277 if (type->tp_doc != NULL) {
3278 PyObject *doc = PyString_FromString(type->tp_doc);
3279 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3280 Py_DECREF(doc);
3281 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003282 PyDict_SetItemString(type->tp_dict,
3283 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003284 }
3285 }
3286
Guido van Rossum13d52f02001-08-10 21:24:08 +00003287 /* Some more special stuff */
3288 base = type->tp_base;
3289 if (base != NULL) {
3290 if (type->tp_as_number == NULL)
3291 type->tp_as_number = base->tp_as_number;
3292 if (type->tp_as_sequence == NULL)
3293 type->tp_as_sequence = base->tp_as_sequence;
3294 if (type->tp_as_mapping == NULL)
3295 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003296 if (type->tp_as_buffer == NULL)
3297 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003298 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003299
Guido van Rossum1c450732001-10-08 15:18:27 +00003300 /* Link into each base class's list of subclasses */
3301 bases = type->tp_bases;
3302 n = PyTuple_GET_SIZE(bases);
3303 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003304 PyObject *b = PyTuple_GET_ITEM(bases, i);
3305 if (PyType_Check(b) &&
3306 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003307 goto error;
3308 }
3309
Guido van Rossum13d52f02001-08-10 21:24:08 +00003310 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003311 assert(type->tp_dict != NULL);
3312 type->tp_flags =
3313 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003314 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003315
3316 error:
3317 type->tp_flags &= ~Py_TPFLAGS_READYING;
3318 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003319}
3320
Guido van Rossum1c450732001-10-08 15:18:27 +00003321static int
3322add_subclass(PyTypeObject *base, PyTypeObject *type)
3323{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003324 Py_ssize_t i;
3325 int result;
Anthony Baxtera6286212006-04-11 07:42:36 +00003326 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003327
3328 list = base->tp_subclasses;
3329 if (list == NULL) {
3330 base->tp_subclasses = list = PyList_New(0);
3331 if (list == NULL)
3332 return -1;
3333 }
3334 assert(PyList_Check(list));
Anthony Baxtera6286212006-04-11 07:42:36 +00003335 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003336 i = PyList_GET_SIZE(list);
3337 while (--i >= 0) {
3338 ref = PyList_GET_ITEM(list, i);
3339 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003340 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Anthony Baxtera6286212006-04-11 07:42:36 +00003341 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003342 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003343 result = PyList_Append(list, newobj);
3344 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003345 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003346}
3347
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003348static void
3349remove_subclass(PyTypeObject *base, PyTypeObject *type)
3350{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003351 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003352 PyObject *list, *ref;
3353
3354 list = base->tp_subclasses;
3355 if (list == NULL) {
3356 return;
3357 }
3358 assert(PyList_Check(list));
3359 i = PyList_GET_SIZE(list);
3360 while (--i >= 0) {
3361 ref = PyList_GET_ITEM(list, i);
3362 assert(PyWeakref_CheckRef(ref));
3363 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3364 /* this can't fail, right? */
3365 PySequence_DelItem(list, i);
3366 return;
3367 }
3368 }
3369}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003370
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003371static int
3372check_num_args(PyObject *ob, int n)
3373{
3374 if (!PyTuple_CheckExact(ob)) {
3375 PyErr_SetString(PyExc_SystemError,
3376 "PyArg_UnpackTuple() argument list is not a tuple");
3377 return 0;
3378 }
3379 if (n == PyTuple_GET_SIZE(ob))
3380 return 1;
3381 PyErr_Format(
3382 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003383 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003384 return 0;
3385}
3386
Tim Peters6d6c1a32001-08-02 04:15:00 +00003387/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3388
3389/* There's a wrapper *function* for each distinct function typedef used
3390 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3391 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3392 Most tables have only one entry; the tables for binary operators have two
3393 entries, one regular and one with reversed arguments. */
3394
3395static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003396wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003397{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003398 lenfunc func = (lenfunc)wrapped;
3399 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003400
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003401 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003402 return NULL;
3403 res = (*func)(self);
3404 if (res == -1 && PyErr_Occurred())
3405 return NULL;
3406 return PyInt_FromLong((long)res);
3407}
3408
Tim Peters6d6c1a32001-08-02 04:15:00 +00003409static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003410wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3411{
3412 inquiry func = (inquiry)wrapped;
3413 int res;
3414
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003415 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003416 return NULL;
3417 res = (*func)(self);
3418 if (res == -1 && PyErr_Occurred())
3419 return NULL;
3420 return PyBool_FromLong((long)res);
3421}
3422
3423static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003424wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3425{
3426 binaryfunc func = (binaryfunc)wrapped;
3427 PyObject *other;
3428
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003429 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003430 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003431 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003432 return (*func)(self, other);
3433}
3434
3435static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003436wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3437{
3438 binaryfunc func = (binaryfunc)wrapped;
3439 PyObject *other;
3440
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003441 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003442 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003443 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003444 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003445 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003446 Py_INCREF(Py_NotImplemented);
3447 return Py_NotImplemented;
3448 }
3449 return (*func)(self, other);
3450}
3451
3452static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003453wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3454{
3455 binaryfunc func = (binaryfunc)wrapped;
3456 PyObject *other;
3457
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003458 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003459 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003460 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003461 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003462 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003463 Py_INCREF(Py_NotImplemented);
3464 return Py_NotImplemented;
3465 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003466 return (*func)(other, self);
3467}
3468
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003469static PyObject *
3470wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3471{
3472 coercion func = (coercion)wrapped;
3473 PyObject *other, *res;
3474 int ok;
3475
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003476 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003477 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003478 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003479 ok = func(&self, &other);
3480 if (ok < 0)
3481 return NULL;
3482 if (ok > 0) {
3483 Py_INCREF(Py_NotImplemented);
3484 return Py_NotImplemented;
3485 }
3486 res = PyTuple_New(2);
3487 if (res == NULL) {
3488 Py_DECREF(self);
3489 Py_DECREF(other);
3490 return NULL;
3491 }
3492 PyTuple_SET_ITEM(res, 0, self);
3493 PyTuple_SET_ITEM(res, 1, other);
3494 return res;
3495}
3496
Tim Peters6d6c1a32001-08-02 04:15:00 +00003497static PyObject *
3498wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3499{
3500 ternaryfunc func = (ternaryfunc)wrapped;
3501 PyObject *other;
3502 PyObject *third = Py_None;
3503
3504 /* Note: This wrapper only works for __pow__() */
3505
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003506 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003507 return NULL;
3508 return (*func)(self, other, third);
3509}
3510
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003511static PyObject *
3512wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3513{
3514 ternaryfunc func = (ternaryfunc)wrapped;
3515 PyObject *other;
3516 PyObject *third = Py_None;
3517
3518 /* Note: This wrapper only works for __pow__() */
3519
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003520 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003521 return NULL;
3522 return (*func)(other, self, third);
3523}
3524
Tim Peters6d6c1a32001-08-02 04:15:00 +00003525static PyObject *
3526wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3527{
3528 unaryfunc func = (unaryfunc)wrapped;
3529
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003530 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003531 return NULL;
3532 return (*func)(self);
3533}
3534
Tim Peters6d6c1a32001-08-02 04:15:00 +00003535static PyObject *
Armin Rigo314861c2006-03-30 14:04:02 +00003536wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003537{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003538 ssizeargfunc func = (ssizeargfunc)wrapped;
Armin Rigo314861c2006-03-30 14:04:02 +00003539 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003540 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003541
Armin Rigo314861c2006-03-30 14:04:02 +00003542 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
3543 return NULL;
3544 i = PyNumber_Index(o);
3545 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003546 return NULL;
3547 return (*func)(self, i);
3548}
3549
Martin v. Löwis18e16552006-02-15 17:27:45 +00003550static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00003551getindex(PyObject *self, PyObject *arg)
3552{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003553 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003554
Armin Rigo314861c2006-03-30 14:04:02 +00003555 i = PyNumber_Index(arg);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003556 if (i == -1 && PyErr_Occurred())
3557 return -1;
3558 if (i < 0) {
3559 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3560 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003561 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003562 if (n < 0)
3563 return -1;
3564 i += n;
3565 }
3566 }
3567 return i;
3568}
3569
3570static PyObject *
3571wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3572{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003573 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003574 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003575 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003576
Guido van Rossumf4593e02001-10-03 12:09:30 +00003577 if (PyTuple_GET_SIZE(args) == 1) {
3578 arg = PyTuple_GET_ITEM(args, 0);
3579 i = getindex(self, arg);
3580 if (i == -1 && PyErr_Occurred())
3581 return NULL;
3582 return (*func)(self, i);
3583 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003584 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003585 assert(PyErr_Occurred());
3586 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003587}
3588
Tim Peters6d6c1a32001-08-02 04:15:00 +00003589static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003590wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003591{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003592 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
3593 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003594
Martin v. Löwis18e16552006-02-15 17:27:45 +00003595 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003596 return NULL;
3597 return (*func)(self, i, j);
3598}
3599
Tim Peters6d6c1a32001-08-02 04:15:00 +00003600static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003601wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003602{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003603 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3604 Py_ssize_t i;
3605 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003606 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003607
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003608 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003609 return NULL;
3610 i = getindex(self, arg);
3611 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003612 return NULL;
3613 res = (*func)(self, i, value);
3614 if (res == -1 && PyErr_Occurred())
3615 return NULL;
3616 Py_INCREF(Py_None);
3617 return Py_None;
3618}
3619
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003620static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003621wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003622{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003623 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3624 Py_ssize_t i;
3625 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003626 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003627
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003628 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003629 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003630 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003631 i = getindex(self, arg);
3632 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003633 return NULL;
3634 res = (*func)(self, i, NULL);
3635 if (res == -1 && PyErr_Occurred())
3636 return NULL;
3637 Py_INCREF(Py_None);
3638 return Py_None;
3639}
3640
Tim Peters6d6c1a32001-08-02 04:15:00 +00003641static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003642wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003643{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003644 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3645 Py_ssize_t i, j;
3646 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003647 PyObject *value;
3648
Martin v. Löwis18e16552006-02-15 17:27:45 +00003649 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003650 return NULL;
3651 res = (*func)(self, i, j, value);
3652 if (res == -1 && PyErr_Occurred())
3653 return NULL;
3654 Py_INCREF(Py_None);
3655 return Py_None;
3656}
3657
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003658static PyObject *
3659wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3660{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003661 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3662 Py_ssize_t i, j;
3663 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003664
Martin v. Löwis18e16552006-02-15 17:27:45 +00003665 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003666 return NULL;
3667 res = (*func)(self, i, j, NULL);
3668 if (res == -1 && PyErr_Occurred())
3669 return NULL;
3670 Py_INCREF(Py_None);
3671 return Py_None;
3672}
3673
Tim Peters6d6c1a32001-08-02 04:15:00 +00003674/* XXX objobjproc is a misnomer; should be objargpred */
3675static PyObject *
3676wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3677{
3678 objobjproc func = (objobjproc)wrapped;
3679 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003680 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003681
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003682 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003683 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003684 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003685 res = (*func)(self, value);
3686 if (res == -1 && PyErr_Occurred())
3687 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003688 else
3689 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003690}
3691
Tim Peters6d6c1a32001-08-02 04:15:00 +00003692static PyObject *
3693wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3694{
3695 objobjargproc func = (objobjargproc)wrapped;
3696 int res;
3697 PyObject *key, *value;
3698
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003699 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003700 return NULL;
3701 res = (*func)(self, key, value);
3702 if (res == -1 && PyErr_Occurred())
3703 return NULL;
3704 Py_INCREF(Py_None);
3705 return Py_None;
3706}
3707
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003708static PyObject *
3709wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3710{
3711 objobjargproc func = (objobjargproc)wrapped;
3712 int res;
3713 PyObject *key;
3714
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003715 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003716 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003717 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003718 res = (*func)(self, key, NULL);
3719 if (res == -1 && PyErr_Occurred())
3720 return NULL;
3721 Py_INCREF(Py_None);
3722 return Py_None;
3723}
3724
Tim Peters6d6c1a32001-08-02 04:15:00 +00003725static PyObject *
3726wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3727{
3728 cmpfunc func = (cmpfunc)wrapped;
3729 int res;
3730 PyObject *other;
3731
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003732 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003733 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003734 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003735 if (other->ob_type->tp_compare != func &&
3736 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003737 PyErr_Format(
3738 PyExc_TypeError,
3739 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3740 self->ob_type->tp_name,
3741 self->ob_type->tp_name,
3742 other->ob_type->tp_name);
3743 return NULL;
3744 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003745 res = (*func)(self, other);
3746 if (PyErr_Occurred())
3747 return NULL;
3748 return PyInt_FromLong((long)res);
3749}
3750
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003751/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003752 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003753static int
3754hackcheck(PyObject *self, setattrofunc func, char *what)
3755{
3756 PyTypeObject *type = self->ob_type;
3757 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3758 type = type->tp_base;
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003759 /* If type is NULL now, this is a really weird type.
3760 In the same of backwards compatibility (?), just shut up. */
3761 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003762 PyErr_Format(PyExc_TypeError,
3763 "can't apply this %s to %s object",
3764 what,
3765 type->tp_name);
3766 return 0;
3767 }
3768 return 1;
3769}
3770
Tim Peters6d6c1a32001-08-02 04:15:00 +00003771static PyObject *
3772wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3773{
3774 setattrofunc func = (setattrofunc)wrapped;
3775 int res;
3776 PyObject *name, *value;
3777
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003778 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003779 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003780 if (!hackcheck(self, func, "__setattr__"))
3781 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003782 res = (*func)(self, name, value);
3783 if (res < 0)
3784 return NULL;
3785 Py_INCREF(Py_None);
3786 return Py_None;
3787}
3788
3789static PyObject *
3790wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3791{
3792 setattrofunc func = (setattrofunc)wrapped;
3793 int res;
3794 PyObject *name;
3795
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003796 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003797 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003798 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003799 if (!hackcheck(self, func, "__delattr__"))
3800 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003801 res = (*func)(self, name, NULL);
3802 if (res < 0)
3803 return NULL;
3804 Py_INCREF(Py_None);
3805 return Py_None;
3806}
3807
Tim Peters6d6c1a32001-08-02 04:15:00 +00003808static PyObject *
3809wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3810{
3811 hashfunc func = (hashfunc)wrapped;
3812 long res;
3813
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003814 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003815 return NULL;
3816 res = (*func)(self);
3817 if (res == -1 && PyErr_Occurred())
3818 return NULL;
3819 return PyInt_FromLong(res);
3820}
3821
Tim Peters6d6c1a32001-08-02 04:15:00 +00003822static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003823wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003824{
3825 ternaryfunc func = (ternaryfunc)wrapped;
3826
Guido van Rossumc8e56452001-10-22 00:43:43 +00003827 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003828}
3829
Tim Peters6d6c1a32001-08-02 04:15:00 +00003830static PyObject *
3831wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3832{
3833 richcmpfunc func = (richcmpfunc)wrapped;
3834 PyObject *other;
3835
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003836 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003837 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003838 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003839 return (*func)(self, other, op);
3840}
3841
3842#undef RICHCMP_WRAPPER
3843#define RICHCMP_WRAPPER(NAME, OP) \
3844static PyObject * \
3845richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3846{ \
3847 return wrap_richcmpfunc(self, args, wrapped, OP); \
3848}
3849
Jack Jansen8e938b42001-08-08 15:29:49 +00003850RICHCMP_WRAPPER(lt, Py_LT)
3851RICHCMP_WRAPPER(le, Py_LE)
3852RICHCMP_WRAPPER(eq, Py_EQ)
3853RICHCMP_WRAPPER(ne, Py_NE)
3854RICHCMP_WRAPPER(gt, Py_GT)
3855RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003856
Tim Peters6d6c1a32001-08-02 04:15:00 +00003857static PyObject *
3858wrap_next(PyObject *self, PyObject *args, void *wrapped)
3859{
3860 unaryfunc func = (unaryfunc)wrapped;
3861 PyObject *res;
3862
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003863 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003864 return NULL;
3865 res = (*func)(self);
3866 if (res == NULL && !PyErr_Occurred())
3867 PyErr_SetNone(PyExc_StopIteration);
3868 return res;
3869}
3870
Tim Peters6d6c1a32001-08-02 04:15:00 +00003871static PyObject *
3872wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3873{
3874 descrgetfunc func = (descrgetfunc)wrapped;
3875 PyObject *obj;
3876 PyObject *type = NULL;
3877
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003878 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003879 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003880 if (obj == Py_None)
3881 obj = NULL;
3882 if (type == Py_None)
3883 type = NULL;
3884 if (type == NULL &&obj == NULL) {
3885 PyErr_SetString(PyExc_TypeError,
3886 "__get__(None, None) is invalid");
3887 return NULL;
3888 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003889 return (*func)(self, obj, type);
3890}
3891
Tim Peters6d6c1a32001-08-02 04:15:00 +00003892static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003893wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003894{
3895 descrsetfunc func = (descrsetfunc)wrapped;
3896 PyObject *obj, *value;
3897 int ret;
3898
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003899 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003900 return NULL;
3901 ret = (*func)(self, obj, value);
3902 if (ret < 0)
3903 return NULL;
3904 Py_INCREF(Py_None);
3905 return Py_None;
3906}
Guido van Rossum22b13872002-08-06 21:41:44 +00003907
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003908static PyObject *
3909wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3910{
3911 descrsetfunc func = (descrsetfunc)wrapped;
3912 PyObject *obj;
3913 int ret;
3914
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003915 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003916 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003917 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003918 ret = (*func)(self, obj, NULL);
3919 if (ret < 0)
3920 return NULL;
3921 Py_INCREF(Py_None);
3922 return Py_None;
3923}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003924
Tim Peters6d6c1a32001-08-02 04:15:00 +00003925static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003926wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003927{
3928 initproc func = (initproc)wrapped;
3929
Guido van Rossumc8e56452001-10-22 00:43:43 +00003930 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003931 return NULL;
3932 Py_INCREF(Py_None);
3933 return Py_None;
3934}
3935
Tim Peters6d6c1a32001-08-02 04:15:00 +00003936static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003937tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003938{
Barry Warsaw60f01882001-08-22 19:24:42 +00003939 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003940 PyObject *arg0, *res;
3941
3942 if (self == NULL || !PyType_Check(self))
3943 Py_FatalError("__new__() called with non-type 'self'");
3944 type = (PyTypeObject *)self;
3945 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003946 PyErr_Format(PyExc_TypeError,
3947 "%s.__new__(): not enough arguments",
3948 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003949 return NULL;
3950 }
3951 arg0 = PyTuple_GET_ITEM(args, 0);
3952 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003953 PyErr_Format(PyExc_TypeError,
3954 "%s.__new__(X): X is not a type object (%s)",
3955 type->tp_name,
3956 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003957 return NULL;
3958 }
3959 subtype = (PyTypeObject *)arg0;
3960 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003961 PyErr_Format(PyExc_TypeError,
3962 "%s.__new__(%s): %s is not a subtype of %s",
3963 type->tp_name,
3964 subtype->tp_name,
3965 subtype->tp_name,
3966 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003967 return NULL;
3968 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003969
3970 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003971 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003972 most derived base that's not a heap type is this type. */
3973 staticbase = subtype;
3974 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3975 staticbase = staticbase->tp_base;
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003976 /* If staticbase is NULL now, it is a really weird type.
3977 In the same of backwards compatibility (?), just shut up. */
3978 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003979 PyErr_Format(PyExc_TypeError,
3980 "%s.__new__(%s) is not safe, use %s.__new__()",
3981 type->tp_name,
3982 subtype->tp_name,
3983 staticbase == NULL ? "?" : staticbase->tp_name);
3984 return NULL;
3985 }
3986
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003987 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3988 if (args == NULL)
3989 return NULL;
3990 res = type->tp_new(subtype, args, kwds);
3991 Py_DECREF(args);
3992 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003993}
3994
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003995static struct PyMethodDef tp_new_methoddef[] = {
3996 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003997 PyDoc_STR("T.__new__(S, ...) -> "
3998 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003999 {0}
4000};
4001
4002static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004003add_tp_new_wrapper(PyTypeObject *type)
4004{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004005 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004006
Guido van Rossum687ae002001-10-15 22:03:32 +00004007 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004008 return 0;
4009 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004010 if (func == NULL)
4011 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004012 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004013 Py_DECREF(func);
4014 return -1;
4015 }
4016 Py_DECREF(func);
4017 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004018}
4019
Guido van Rossumf040ede2001-08-07 16:40:56 +00004020/* Slot wrappers that call the corresponding __foo__ slot. See comments
4021 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004022
Guido van Rossumdc91b992001-08-08 22:26:22 +00004023#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004024static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004025FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004026{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004027 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004028 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004029}
4030
Guido van Rossumdc91b992001-08-08 22:26:22 +00004031#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004032static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004033FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004034{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004035 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004036 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004037}
4038
Guido van Rossumcd118802003-01-06 22:57:47 +00004039/* Boolean helper for SLOT1BINFULL().
4040 right.__class__ is a nontrivial subclass of left.__class__. */
4041static int
4042method_is_overloaded(PyObject *left, PyObject *right, char *name)
4043{
4044 PyObject *a, *b;
4045 int ok;
4046
4047 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
4048 if (b == NULL) {
4049 PyErr_Clear();
4050 /* If right doesn't have it, it's not overloaded */
4051 return 0;
4052 }
4053
4054 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
4055 if (a == NULL) {
4056 PyErr_Clear();
4057 Py_DECREF(b);
4058 /* If right has it but left doesn't, it's overloaded */
4059 return 1;
4060 }
4061
4062 ok = PyObject_RichCompareBool(a, b, Py_NE);
4063 Py_DECREF(a);
4064 Py_DECREF(b);
4065 if (ok < 0) {
4066 PyErr_Clear();
4067 return 0;
4068 }
4069
4070 return ok;
4071}
4072
Guido van Rossumdc91b992001-08-08 22:26:22 +00004073
4074#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004075static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004076FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004077{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004078 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004079 int do_other = self->ob_type != other->ob_type && \
4080 other->ob_type->tp_as_number != NULL && \
4081 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004082 if (self->ob_type->tp_as_number != NULL && \
4083 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
4084 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004085 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004086 PyType_IsSubtype(other->ob_type, self->ob_type) && \
4087 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004088 r = call_maybe( \
4089 other, ROPSTR, &rcache_str, "(O)", self); \
4090 if (r != Py_NotImplemented) \
4091 return r; \
4092 Py_DECREF(r); \
4093 do_other = 0; \
4094 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004095 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004096 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004097 if (r != Py_NotImplemented || \
4098 other->ob_type == self->ob_type) \
4099 return r; \
4100 Py_DECREF(r); \
4101 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004102 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004103 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004104 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004105 } \
4106 Py_INCREF(Py_NotImplemented); \
4107 return Py_NotImplemented; \
4108}
4109
4110#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4111 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4112
4113#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4114static PyObject * \
4115FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4116{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004117 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004118 return call_method(self, OPSTR, &cache_str, \
4119 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004120}
4121
Martin v. Löwis18e16552006-02-15 17:27:45 +00004122static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004123slot_sq_length(PyObject *self)
4124{
Guido van Rossum2730b132001-08-28 18:22:14 +00004125 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004126 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004127 Py_ssize_t temp;
4128 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004129
4130 if (res == NULL)
4131 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004132 temp = PyInt_AsSsize_t(res);
Guido van Rossum630db602005-09-20 18:49:54 +00004133 len = (int)temp;
Guido van Rossum26111622001-10-01 16:42:49 +00004134 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00004135 if (len == -1 && PyErr_Occurred())
4136 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004137#if SIZEOF_SIZE_T < SIZEOF_LONG
4138 /* Overflow check -- range of PyInt is more than C ssize_t */
Guido van Rossum630db602005-09-20 18:49:54 +00004139 if (len != temp) {
4140 PyErr_SetString(PyExc_OverflowError,
4141 "__len__() should return 0 <= outcome < 2**31");
4142 return -1;
4143 }
4144#endif
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004145 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00004146 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004147 "__len__() should return >= 0");
4148 return -1;
4149 }
Guido van Rossum26111622001-10-01 16:42:49 +00004150 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004151}
4152
Guido van Rossumf4593e02001-10-03 12:09:30 +00004153/* Super-optimized version of slot_sq_item.
4154 Other slots could do the same... */
4155static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004156slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004157{
4158 static PyObject *getitem_str;
4159 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4160 descrgetfunc f;
4161
4162 if (getitem_str == NULL) {
4163 getitem_str = PyString_InternFromString("__getitem__");
4164 if (getitem_str == NULL)
4165 return NULL;
4166 }
4167 func = _PyType_Lookup(self->ob_type, getitem_str);
4168 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004169 if ((f = func->ob_type->tp_descr_get) == NULL)
4170 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004171 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004172 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004173 if (func == NULL) {
4174 return NULL;
4175 }
4176 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004177 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004178 if (ival != NULL) {
4179 args = PyTuple_New(1);
4180 if (args != NULL) {
4181 PyTuple_SET_ITEM(args, 0, ival);
4182 retval = PyObject_Call(func, args, NULL);
4183 Py_XDECREF(args);
4184 Py_XDECREF(func);
4185 return retval;
4186 }
4187 }
4188 }
4189 else {
4190 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4191 }
4192 Py_XDECREF(args);
4193 Py_XDECREF(ival);
4194 Py_XDECREF(func);
4195 return NULL;
4196}
4197
Martin v. Löwis18e16552006-02-15 17:27:45 +00004198SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004199
4200static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004201slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004202{
4203 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004204 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004205
4206 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004207 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004208 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004209 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004210 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004211 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004212 if (res == NULL)
4213 return -1;
4214 Py_DECREF(res);
4215 return 0;
4216}
4217
4218static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004219slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004220{
4221 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004222 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004223
4224 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004225 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004226 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004227 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004228 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004229 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004230 if (res == NULL)
4231 return -1;
4232 Py_DECREF(res);
4233 return 0;
4234}
4235
4236static int
4237slot_sq_contains(PyObject *self, PyObject *value)
4238{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004239 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004240 int result = -1;
4241
Guido van Rossum60718732001-08-28 17:47:51 +00004242 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004243
Guido van Rossum55f20992001-10-01 17:18:22 +00004244 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004245 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004246 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004247 if (args == NULL)
4248 res = NULL;
4249 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004250 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004251 Py_DECREF(args);
4252 }
4253 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004254 if (res != NULL) {
4255 result = PyObject_IsTrue(res);
4256 Py_DECREF(res);
4257 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004258 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004259 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004260 /* Possible results: -1 and 1 */
4261 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004262 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004263 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004264 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004265}
4266
Tim Peters6d6c1a32001-08-02 04:15:00 +00004267#define slot_mp_length slot_sq_length
4268
Guido van Rossumdc91b992001-08-08 22:26:22 +00004269SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004270
4271static int
4272slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4273{
4274 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004275 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004276
4277 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004278 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004279 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004280 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004281 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004282 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004283 if (res == NULL)
4284 return -1;
4285 Py_DECREF(res);
4286 return 0;
4287}
4288
Guido van Rossumdc91b992001-08-08 22:26:22 +00004289SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4290SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4291SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4292SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4293SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4294SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4295
Jeremy Hylton938ace62002-07-17 16:30:39 +00004296static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004297
4298SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4299 nb_power, "__pow__", "__rpow__")
4300
4301static PyObject *
4302slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4303{
Guido van Rossum2730b132001-08-28 18:22:14 +00004304 static PyObject *pow_str;
4305
Guido van Rossumdc91b992001-08-08 22:26:22 +00004306 if (modulus == Py_None)
4307 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004308 /* Three-arg power doesn't use __rpow__. But ternary_op
4309 can call this when the second argument's type uses
4310 slot_nb_power, so check before calling self.__pow__. */
4311 if (self->ob_type->tp_as_number != NULL &&
4312 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4313 return call_method(self, "__pow__", &pow_str,
4314 "(OO)", other, modulus);
4315 }
4316 Py_INCREF(Py_NotImplemented);
4317 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004318}
4319
4320SLOT0(slot_nb_negative, "__neg__")
4321SLOT0(slot_nb_positive, "__pos__")
4322SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004323
4324static int
4325slot_nb_nonzero(PyObject *self)
4326{
Tim Petersea7f75d2002-12-07 21:39:16 +00004327 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004328 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004329 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004330
Guido van Rossum55f20992001-10-01 17:18:22 +00004331 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004332 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004333 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004334 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004335 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004336 if (func == NULL)
4337 return PyErr_Occurred() ? -1 : 1;
4338 }
4339 args = PyTuple_New(0);
4340 if (args != NULL) {
4341 PyObject *temp = PyObject_Call(func, args, NULL);
4342 Py_DECREF(args);
4343 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004344 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004345 result = PyObject_IsTrue(temp);
4346 else {
4347 PyErr_Format(PyExc_TypeError,
4348 "__nonzero__ should return "
4349 "bool or int, returned %s",
4350 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004351 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004352 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004353 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004354 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004355 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004356 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004357 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004358}
4359
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004360
4361static Py_ssize_t
4362slot_nb_index(PyObject *self)
4363{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004364 static PyObject *index_str;
Armin Rigo314861c2006-03-30 14:04:02 +00004365 PyObject *temp = call_method(self, "__index__", &index_str, "()");
4366 Py_ssize_t result;
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004367
Armin Rigo314861c2006-03-30 14:04:02 +00004368 if (temp == NULL)
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004369 return -1;
Armin Rigo314861c2006-03-30 14:04:02 +00004370 if (PyInt_CheckExact(temp) || PyLong_CheckExact(temp)) {
4371 result = temp->ob_type->tp_as_number->nb_index(temp);
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004372 }
Armin Rigo314861c2006-03-30 14:04:02 +00004373 else {
4374 PyErr_SetString(PyExc_TypeError,
4375 "__index__ must return an int or a long");
4376 result = -1;
4377 }
4378 Py_DECREF(temp);
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004379 return result;
4380}
4381
4382
Guido van Rossumdc91b992001-08-08 22:26:22 +00004383SLOT0(slot_nb_invert, "__invert__")
4384SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4385SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4386SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4387SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4388SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004389
4390static int
4391slot_nb_coerce(PyObject **a, PyObject **b)
4392{
4393 static PyObject *coerce_str;
4394 PyObject *self = *a, *other = *b;
4395
4396 if (self->ob_type->tp_as_number != NULL &&
4397 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4398 PyObject *r;
4399 r = call_maybe(
4400 self, "__coerce__", &coerce_str, "(O)", other);
4401 if (r == NULL)
4402 return -1;
4403 if (r == Py_NotImplemented) {
4404 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004405 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004406 else {
4407 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4408 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004409 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004410 Py_DECREF(r);
4411 return -1;
4412 }
4413 *a = PyTuple_GET_ITEM(r, 0);
4414 Py_INCREF(*a);
4415 *b = PyTuple_GET_ITEM(r, 1);
4416 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004417 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004418 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004419 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004420 }
4421 if (other->ob_type->tp_as_number != NULL &&
4422 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4423 PyObject *r;
4424 r = call_maybe(
4425 other, "__coerce__", &coerce_str, "(O)", self);
4426 if (r == NULL)
4427 return -1;
4428 if (r == Py_NotImplemented) {
4429 Py_DECREF(r);
4430 return 1;
4431 }
4432 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4433 PyErr_SetString(PyExc_TypeError,
4434 "__coerce__ didn't return a 2-tuple");
4435 Py_DECREF(r);
4436 return -1;
4437 }
4438 *a = PyTuple_GET_ITEM(r, 1);
4439 Py_INCREF(*a);
4440 *b = PyTuple_GET_ITEM(r, 0);
4441 Py_INCREF(*b);
4442 Py_DECREF(r);
4443 return 0;
4444 }
4445 return 1;
4446}
4447
Guido van Rossumdc91b992001-08-08 22:26:22 +00004448SLOT0(slot_nb_int, "__int__")
4449SLOT0(slot_nb_long, "__long__")
4450SLOT0(slot_nb_float, "__float__")
4451SLOT0(slot_nb_oct, "__oct__")
4452SLOT0(slot_nb_hex, "__hex__")
4453SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4454SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4455SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4456SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4457SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004458SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004459SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4460SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4461SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4462SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4463SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4464SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4465 "__floordiv__", "__rfloordiv__")
4466SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4467SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4468SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004469
4470static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004471half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004472{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004473 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004474 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004475 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004476
Guido van Rossum60718732001-08-28 17:47:51 +00004477 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004478 if (func == NULL) {
4479 PyErr_Clear();
4480 }
4481 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004482 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004483 if (args == NULL)
4484 res = NULL;
4485 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004486 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004487 Py_DECREF(args);
4488 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004489 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004490 if (res != Py_NotImplemented) {
4491 if (res == NULL)
4492 return -2;
4493 c = PyInt_AsLong(res);
4494 Py_DECREF(res);
4495 if (c == -1 && PyErr_Occurred())
4496 return -2;
4497 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4498 }
4499 Py_DECREF(res);
4500 }
4501 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004502}
4503
Guido van Rossumab3b0342001-09-18 20:38:53 +00004504/* This slot is published for the benefit of try_3way_compare in object.c */
4505int
4506_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004507{
4508 int c;
4509
Guido van Rossumab3b0342001-09-18 20:38:53 +00004510 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004511 c = half_compare(self, other);
4512 if (c <= 1)
4513 return c;
4514 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004515 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004516 c = half_compare(other, self);
4517 if (c < -1)
4518 return -2;
4519 if (c <= 1)
4520 return -c;
4521 }
4522 return (void *)self < (void *)other ? -1 :
4523 (void *)self > (void *)other ? 1 : 0;
4524}
4525
4526static PyObject *
4527slot_tp_repr(PyObject *self)
4528{
4529 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004530 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004531
Guido van Rossum60718732001-08-28 17:47:51 +00004532 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004533 if (func != NULL) {
4534 res = PyEval_CallObject(func, NULL);
4535 Py_DECREF(func);
4536 return res;
4537 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004538 PyErr_Clear();
4539 return PyString_FromFormat("<%s object at %p>",
4540 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004541}
4542
4543static PyObject *
4544slot_tp_str(PyObject *self)
4545{
4546 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004547 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004548
Guido van Rossum60718732001-08-28 17:47:51 +00004549 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004550 if (func != NULL) {
4551 res = PyEval_CallObject(func, NULL);
4552 Py_DECREF(func);
4553 return res;
4554 }
4555 else {
4556 PyErr_Clear();
4557 return slot_tp_repr(self);
4558 }
4559}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004560
4561static long
4562slot_tp_hash(PyObject *self)
4563{
Tim Peters61ce0a92002-12-06 23:38:02 +00004564 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004565 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004566 long h;
4567
Guido van Rossum60718732001-08-28 17:47:51 +00004568 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004569
4570 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004571 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004572 Py_DECREF(func);
4573 if (res == NULL)
4574 return -1;
4575 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004576 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004577 }
4578 else {
4579 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004580 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004581 if (func == NULL) {
4582 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004583 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004584 }
4585 if (func != NULL) {
4586 Py_DECREF(func);
4587 PyErr_SetString(PyExc_TypeError, "unhashable type");
4588 return -1;
4589 }
4590 PyErr_Clear();
4591 h = _Py_HashPointer((void *)self);
4592 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004593 if (h == -1 && !PyErr_Occurred())
4594 h = -2;
4595 return h;
4596}
4597
4598static PyObject *
4599slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4600{
Guido van Rossum60718732001-08-28 17:47:51 +00004601 static PyObject *call_str;
4602 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004603 PyObject *res;
4604
4605 if (meth == NULL)
4606 return NULL;
4607 res = PyObject_Call(meth, args, kwds);
4608 Py_DECREF(meth);
4609 return res;
4610}
4611
Guido van Rossum14a6f832001-10-17 13:59:09 +00004612/* There are two slot dispatch functions for tp_getattro.
4613
4614 - slot_tp_getattro() is used when __getattribute__ is overridden
4615 but no __getattr__ hook is present;
4616
4617 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4618
Guido van Rossumc334df52002-04-04 23:44:47 +00004619 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4620 detects the absence of __getattr__ and then installs the simpler slot if
4621 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004622
Tim Peters6d6c1a32001-08-02 04:15:00 +00004623static PyObject *
4624slot_tp_getattro(PyObject *self, PyObject *name)
4625{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004626 static PyObject *getattribute_str = NULL;
4627 return call_method(self, "__getattribute__", &getattribute_str,
4628 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004629}
4630
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004631static PyObject *
4632slot_tp_getattr_hook(PyObject *self, PyObject *name)
4633{
4634 PyTypeObject *tp = self->ob_type;
4635 PyObject *getattr, *getattribute, *res;
4636 static PyObject *getattribute_str = NULL;
4637 static PyObject *getattr_str = NULL;
4638
4639 if (getattr_str == NULL) {
4640 getattr_str = PyString_InternFromString("__getattr__");
4641 if (getattr_str == NULL)
4642 return NULL;
4643 }
4644 if (getattribute_str == NULL) {
4645 getattribute_str =
4646 PyString_InternFromString("__getattribute__");
4647 if (getattribute_str == NULL)
4648 return NULL;
4649 }
4650 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004651 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004652 /* No __getattr__ hook: use a simpler dispatcher */
4653 tp->tp_getattro = slot_tp_getattro;
4654 return slot_tp_getattro(self, name);
4655 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004656 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004657 if (getattribute == NULL ||
4658 (getattribute->ob_type == &PyWrapperDescr_Type &&
4659 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4660 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004661 res = PyObject_GenericGetAttr(self, name);
4662 else
4663 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004664 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004665 PyErr_Clear();
4666 res = PyObject_CallFunction(getattr, "OO", self, name);
4667 }
4668 return res;
4669}
4670
Tim Peters6d6c1a32001-08-02 04:15:00 +00004671static int
4672slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4673{
4674 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004675 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004676
4677 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004678 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004679 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004680 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004681 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004682 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004683 if (res == NULL)
4684 return -1;
4685 Py_DECREF(res);
4686 return 0;
4687}
4688
4689/* Map rich comparison operators to their __xx__ namesakes */
4690static char *name_op[] = {
4691 "__lt__",
4692 "__le__",
4693 "__eq__",
4694 "__ne__",
4695 "__gt__",
4696 "__ge__",
4697};
4698
4699static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004700half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004701{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004702 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004703 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004704
Guido van Rossum60718732001-08-28 17:47:51 +00004705 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004706 if (func == NULL) {
4707 PyErr_Clear();
4708 Py_INCREF(Py_NotImplemented);
4709 return Py_NotImplemented;
4710 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004711 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004712 if (args == NULL)
4713 res = NULL;
4714 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004715 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004716 Py_DECREF(args);
4717 }
4718 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004719 return res;
4720}
4721
Guido van Rossumb8f63662001-08-15 23:57:02 +00004722static PyObject *
4723slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4724{
4725 PyObject *res;
4726
4727 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4728 res = half_richcompare(self, other, op);
4729 if (res != Py_NotImplemented)
4730 return res;
4731 Py_DECREF(res);
4732 }
4733 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004734 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004735 if (res != Py_NotImplemented) {
4736 return res;
4737 }
4738 Py_DECREF(res);
4739 }
4740 Py_INCREF(Py_NotImplemented);
4741 return Py_NotImplemented;
4742}
4743
4744static PyObject *
4745slot_tp_iter(PyObject *self)
4746{
4747 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004748 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004749
Guido van Rossum60718732001-08-28 17:47:51 +00004750 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004751 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004752 PyObject *args;
4753 args = res = PyTuple_New(0);
4754 if (args != NULL) {
4755 res = PyObject_Call(func, args, NULL);
4756 Py_DECREF(args);
4757 }
4758 Py_DECREF(func);
4759 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004760 }
4761 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004762 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004763 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004764 PyErr_SetString(PyExc_TypeError,
4765 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004766 return NULL;
4767 }
4768 Py_DECREF(func);
4769 return PySeqIter_New(self);
4770}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004771
4772static PyObject *
4773slot_tp_iternext(PyObject *self)
4774{
Guido van Rossum2730b132001-08-28 18:22:14 +00004775 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004776 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004777}
4778
Guido van Rossum1a493502001-08-17 16:47:50 +00004779static PyObject *
4780slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4781{
4782 PyTypeObject *tp = self->ob_type;
4783 PyObject *get;
4784 static PyObject *get_str = NULL;
4785
4786 if (get_str == NULL) {
4787 get_str = PyString_InternFromString("__get__");
4788 if (get_str == NULL)
4789 return NULL;
4790 }
4791 get = _PyType_Lookup(tp, get_str);
4792 if (get == NULL) {
4793 /* Avoid further slowdowns */
4794 if (tp->tp_descr_get == slot_tp_descr_get)
4795 tp->tp_descr_get = NULL;
4796 Py_INCREF(self);
4797 return self;
4798 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004799 if (obj == NULL)
4800 obj = Py_None;
4801 if (type == NULL)
4802 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004803 return PyObject_CallFunction(get, "OOO", self, obj, type);
4804}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004805
4806static int
4807slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4808{
Guido van Rossum2c252392001-08-24 10:13:31 +00004809 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004810 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004811
4812 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004813 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004814 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004815 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004816 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004817 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004818 if (res == NULL)
4819 return -1;
4820 Py_DECREF(res);
4821 return 0;
4822}
4823
4824static int
4825slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4826{
Guido van Rossum60718732001-08-28 17:47:51 +00004827 static PyObject *init_str;
4828 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004829 PyObject *res;
4830
4831 if (meth == NULL)
4832 return -1;
4833 res = PyObject_Call(meth, args, kwds);
4834 Py_DECREF(meth);
4835 if (res == NULL)
4836 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004837 if (res != Py_None) {
4838 PyErr_SetString(PyExc_TypeError,
4839 "__init__() should return None");
4840 Py_DECREF(res);
4841 return -1;
4842 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004843 Py_DECREF(res);
4844 return 0;
4845}
4846
4847static PyObject *
4848slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4849{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004850 static PyObject *new_str;
4851 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004852 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004853 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004854
Guido van Rossum7bed2132002-08-08 21:57:53 +00004855 if (new_str == NULL) {
4856 new_str = PyString_InternFromString("__new__");
4857 if (new_str == NULL)
4858 return NULL;
4859 }
4860 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004861 if (func == NULL)
4862 return NULL;
4863 assert(PyTuple_Check(args));
4864 n = PyTuple_GET_SIZE(args);
4865 newargs = PyTuple_New(n+1);
4866 if (newargs == NULL)
4867 return NULL;
4868 Py_INCREF(type);
4869 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4870 for (i = 0; i < n; i++) {
4871 x = PyTuple_GET_ITEM(args, i);
4872 Py_INCREF(x);
4873 PyTuple_SET_ITEM(newargs, i+1, x);
4874 }
4875 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004876 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004877 Py_DECREF(func);
4878 return x;
4879}
4880
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004881static void
4882slot_tp_del(PyObject *self)
4883{
4884 static PyObject *del_str = NULL;
4885 PyObject *del, *res;
4886 PyObject *error_type, *error_value, *error_traceback;
4887
4888 /* Temporarily resurrect the object. */
4889 assert(self->ob_refcnt == 0);
4890 self->ob_refcnt = 1;
4891
4892 /* Save the current exception, if any. */
4893 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4894
4895 /* Execute __del__ method, if any. */
4896 del = lookup_maybe(self, "__del__", &del_str);
4897 if (del != NULL) {
4898 res = PyEval_CallObject(del, NULL);
4899 if (res == NULL)
4900 PyErr_WriteUnraisable(del);
4901 else
4902 Py_DECREF(res);
4903 Py_DECREF(del);
4904 }
4905
4906 /* Restore the saved exception. */
4907 PyErr_Restore(error_type, error_value, error_traceback);
4908
4909 /* Undo the temporary resurrection; can't use DECREF here, it would
4910 * cause a recursive call.
4911 */
4912 assert(self->ob_refcnt > 0);
4913 if (--self->ob_refcnt == 0)
4914 return; /* this is the normal path out */
4915
4916 /* __del__ resurrected it! Make it look like the original Py_DECREF
4917 * never happened.
4918 */
4919 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004920 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004921 _Py_NewReference(self);
4922 self->ob_refcnt = refcnt;
4923 }
4924 assert(!PyType_IS_GC(self->ob_type) ||
4925 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00004926 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
4927 * we need to undo that. */
4928 _Py_DEC_REFTOTAL;
4929 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4930 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004931 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4932 * _Py_NewReference bumped tp_allocs: both of those need to be
4933 * undone.
4934 */
4935#ifdef COUNT_ALLOCS
4936 --self->ob_type->tp_frees;
4937 --self->ob_type->tp_allocs;
4938#endif
4939}
4940
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004941
4942/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004943 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004944 structure, which incorporates the additional structures used for numbers,
4945 sequences and mappings.
4946 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004947 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004948 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4949 terminated with an all-zero entry. (This table is further initialized and
4950 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004951
Guido van Rossum6d204072001-10-21 00:44:31 +00004952typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004953
4954#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004955#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004956#undef ETSLOT
4957#undef SQSLOT
4958#undef MPSLOT
4959#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004960#undef UNSLOT
4961#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004962#undef BINSLOT
4963#undef RBINSLOT
4964
Guido van Rossum6d204072001-10-21 00:44:31 +00004965#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004966 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4967 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004968#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4969 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004970 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004971#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004972 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004973 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004974#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4975 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4976#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4977 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4978#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4979 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4980#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4981 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4982 "x." NAME "() <==> " DOC)
4983#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4984 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4985 "x." NAME "(y) <==> x" DOC "y")
4986#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4987 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4988 "x." NAME "(y) <==> x" DOC "y")
4989#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4990 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4991 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00004992#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
4993 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4994 "x." NAME "(y) <==> " DOC)
4995#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
4996 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4997 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004998
4999static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005000 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005001 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005002 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5003 The logic in abstract.c always falls back to nb_add/nb_multiply in
5004 this case. Defining both the nb_* and the sq_* slots to call the
5005 user-defined methods has unexpected side-effects, as shown by
5006 test_descr.notimplemented() */
5007 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5008 "x.__add__(y) <==> x+y"),
Armin Rigo314861c2006-03-30 14:04:02 +00005009 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Armin Rigofd163f92005-12-29 15:59:19 +00005010 "x.__mul__(n) <==> x*n"),
Armin Rigo314861c2006-03-30 14:04:02 +00005011 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Armin Rigofd163f92005-12-29 15:59:19 +00005012 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005013 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5014 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005015 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005016 "x.__getslice__(i, j) <==> x[i:j]\n\
5017 \n\
5018 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005019 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005020 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005021 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005022 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005023 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005024 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005025 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
5026 \n\
5027 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005028 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005029 "x.__delslice__(i, j) <==> del x[i:j]\n\
5030 \n\
5031 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005032 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5033 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005034 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5035 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5036 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Armin Rigo314861c2006-03-30 14:04:02 +00005037 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005038
Martin v. Löwis18e16552006-02-15 17:27:45 +00005039 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005040 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005041 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005042 wrap_binaryfunc,
5043 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005044 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005045 wrap_objobjargproc,
5046 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005047 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005048 wrap_delitem,
5049 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005050
Guido van Rossum6d204072001-10-21 00:44:31 +00005051 BINSLOT("__add__", nb_add, slot_nb_add,
5052 "+"),
5053 RBINSLOT("__radd__", nb_add, slot_nb_add,
5054 "+"),
5055 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5056 "-"),
5057 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5058 "-"),
5059 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5060 "*"),
5061 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5062 "*"),
5063 BINSLOT("__div__", nb_divide, slot_nb_divide,
5064 "/"),
5065 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5066 "/"),
5067 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5068 "%"),
5069 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5070 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005071 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005072 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005073 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005074 "divmod(y, x)"),
5075 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5076 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5077 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5078 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5079 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5080 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5081 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5082 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005083 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005084 "x != 0"),
5085 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5086 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5087 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5088 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5089 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5090 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5091 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5092 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5093 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5094 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5095 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5096 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5097 "x.__coerce__(y) <==> coerce(x, y)"),
5098 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5099 "int(x)"),
5100 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5101 "long(x)"),
5102 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5103 "float(x)"),
5104 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5105 "oct(x)"),
5106 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5107 "hex(x)"),
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005108 NBSLOT("__index__", nb_index, slot_nb_index, wrap_lenfunc,
5109 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005110 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5111 wrap_binaryfunc, "+"),
5112 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5113 wrap_binaryfunc, "-"),
5114 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5115 wrap_binaryfunc, "*"),
5116 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5117 wrap_binaryfunc, "/"),
5118 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5119 wrap_binaryfunc, "%"),
5120 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005121 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005122 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5123 wrap_binaryfunc, "<<"),
5124 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5125 wrap_binaryfunc, ">>"),
5126 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5127 wrap_binaryfunc, "&"),
5128 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5129 wrap_binaryfunc, "^"),
5130 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5131 wrap_binaryfunc, "|"),
5132 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5133 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5134 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5135 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5136 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5137 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5138 IBSLOT("__itruediv__", nb_inplace_true_divide,
5139 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005140
Guido van Rossum6d204072001-10-21 00:44:31 +00005141 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5142 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005143 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005144 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5145 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005146 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005147 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5148 "x.__cmp__(y) <==> cmp(x,y)"),
5149 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5150 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005151 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5152 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005153 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005154 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5155 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5156 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5157 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5158 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5159 "x.__setattr__('name', value) <==> x.name = value"),
5160 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5161 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5162 "x.__delattr__('name') <==> del x.name"),
5163 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5164 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5165 "x.__lt__(y) <==> x<y"),
5166 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5167 "x.__le__(y) <==> x<=y"),
5168 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5169 "x.__eq__(y) <==> x==y"),
5170 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5171 "x.__ne__(y) <==> x!=y"),
5172 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5173 "x.__gt__(y) <==> x>y"),
5174 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5175 "x.__ge__(y) <==> x>=y"),
5176 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5177 "x.__iter__() <==> iter(x)"),
5178 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5179 "x.next() -> the next value, or raise StopIteration"),
5180 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5181 "descr.__get__(obj[, type]) -> value"),
5182 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5183 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005184 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5185 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005186 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005187 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005188 "see x.__class__.__doc__ for signature",
5189 PyWrapperFlag_KEYWORDS),
5190 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005191 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005192 {NULL}
5193};
5194
Guido van Rossumc334df52002-04-04 23:44:47 +00005195/* Given a type pointer and an offset gotten from a slotdef entry, return a
5196 pointer to the actual slot. This is not quite the same as simply adding
5197 the offset to the type pointer, since it takes care to indirect through the
5198 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5199 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005200static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005201slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005202{
5203 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005204 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005205
Guido van Rossume5c691a2003-03-07 15:13:17 +00005206 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005207 assert(offset >= 0);
Guido van Rossume5c691a2003-03-07 15:13:17 +00005208 assert(offset < offsetof(PyHeapTypeObject, as_buffer));
5209 if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005210 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005211 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005212 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005213 else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005214 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005215 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005216 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005217 else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005218 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005219 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005220 }
5221 else {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005222 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005223 }
5224 if (ptr != NULL)
5225 ptr += offset;
5226 return (void **)ptr;
5227}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005228
Guido van Rossumc334df52002-04-04 23:44:47 +00005229/* Length of array of slotdef pointers used to store slots with the
5230 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5231 the same __name__, for any __name__. Since that's a static property, it is
5232 appropriate to declare fixed-size arrays for this. */
5233#define MAX_EQUIV 10
5234
5235/* Return a slot pointer for a given name, but ONLY if the attribute has
5236 exactly one slot function. The name must be an interned string. */
5237static void **
5238resolve_slotdups(PyTypeObject *type, PyObject *name)
5239{
5240 /* XXX Maybe this could be optimized more -- but is it worth it? */
5241
5242 /* pname and ptrs act as a little cache */
5243 static PyObject *pname;
5244 static slotdef *ptrs[MAX_EQUIV];
5245 slotdef *p, **pp;
5246 void **res, **ptr;
5247
5248 if (pname != name) {
5249 /* Collect all slotdefs that match name into ptrs. */
5250 pname = name;
5251 pp = ptrs;
5252 for (p = slotdefs; p->name_strobj; p++) {
5253 if (p->name_strobj == name)
5254 *pp++ = p;
5255 }
5256 *pp = NULL;
5257 }
5258
5259 /* Look in all matching slots of the type; if exactly one of these has
5260 a filled-in slot, return its value. Otherwise return NULL. */
5261 res = NULL;
5262 for (pp = ptrs; *pp; pp++) {
5263 ptr = slotptr(type, (*pp)->offset);
5264 if (ptr == NULL || *ptr == NULL)
5265 continue;
5266 if (res != NULL)
5267 return NULL;
5268 res = ptr;
5269 }
5270 return res;
5271}
5272
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005273/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005274 does some incredibly complex thinking and then sticks something into the
5275 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5276 interests, and then stores a generic wrapper or a specific function into
5277 the slot.) Return a pointer to the next slotdef with a different offset,
5278 because that's convenient for fixup_slot_dispatchers(). */
5279static slotdef *
5280update_one_slot(PyTypeObject *type, slotdef *p)
5281{
5282 PyObject *descr;
5283 PyWrapperDescrObject *d;
5284 void *generic = NULL, *specific = NULL;
5285 int use_generic = 0;
5286 int offset = p->offset;
5287 void **ptr = slotptr(type, offset);
5288
5289 if (ptr == NULL) {
5290 do {
5291 ++p;
5292 } while (p->offset == offset);
5293 return p;
5294 }
5295 do {
5296 descr = _PyType_Lookup(type, p->name_strobj);
5297 if (descr == NULL)
5298 continue;
5299 if (descr->ob_type == &PyWrapperDescr_Type) {
5300 void **tptr = resolve_slotdups(type, p->name_strobj);
5301 if (tptr == NULL || tptr == ptr)
5302 generic = p->function;
5303 d = (PyWrapperDescrObject *)descr;
5304 if (d->d_base->wrapper == p->wrapper &&
5305 PyType_IsSubtype(type, d->d_type))
5306 {
5307 if (specific == NULL ||
5308 specific == d->d_wrapped)
5309 specific = d->d_wrapped;
5310 else
5311 use_generic = 1;
5312 }
5313 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005314 else if (descr->ob_type == &PyCFunction_Type &&
5315 PyCFunction_GET_FUNCTION(descr) ==
5316 (PyCFunction)tp_new_wrapper &&
5317 strcmp(p->name, "__new__") == 0)
5318 {
5319 /* The __new__ wrapper is not a wrapper descriptor,
5320 so must be special-cased differently.
5321 If we don't do this, creating an instance will
5322 always use slot_tp_new which will look up
5323 __new__ in the MRO which will call tp_new_wrapper
5324 which will look through the base classes looking
5325 for a static base and call its tp_new (usually
5326 PyType_GenericNew), after performing various
5327 sanity checks and constructing a new argument
5328 list. Cut all that nonsense short -- this speeds
5329 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005330 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005331 /* XXX I'm not 100% sure that there isn't a hole
5332 in this reasoning that requires additional
5333 sanity checks. I'll buy the first person to
5334 point out a bug in this reasoning a beer. */
5335 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005336 else {
5337 use_generic = 1;
5338 generic = p->function;
5339 }
5340 } while ((++p)->offset == offset);
5341 if (specific && !use_generic)
5342 *ptr = specific;
5343 else
5344 *ptr = generic;
5345 return p;
5346}
5347
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005348/* In the type, update the slots whose slotdefs are gathered in the pp array.
5349 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005350static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005351update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005352{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005353 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005354
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005355 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005356 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005357 return 0;
5358}
5359
Guido van Rossumc334df52002-04-04 23:44:47 +00005360/* Comparison function for qsort() to compare slotdefs by their offset, and
5361 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005362static int
5363slotdef_cmp(const void *aa, const void *bb)
5364{
5365 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5366 int c = a->offset - b->offset;
5367 if (c != 0)
5368 return c;
5369 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005370 /* Cannot use a-b, as this gives off_t,
5371 which may lose precision when converted to int. */
5372 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005373}
5374
Guido van Rossumc334df52002-04-04 23:44:47 +00005375/* Initialize the slotdefs table by adding interned string objects for the
5376 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005377static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005378init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005379{
5380 slotdef *p;
5381 static int initialized = 0;
5382
5383 if (initialized)
5384 return;
5385 for (p = slotdefs; p->name; p++) {
5386 p->name_strobj = PyString_InternFromString(p->name);
5387 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005388 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005389 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005390 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5391 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005392 initialized = 1;
5393}
5394
Guido van Rossumc334df52002-04-04 23:44:47 +00005395/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005396static int
5397update_slot(PyTypeObject *type, PyObject *name)
5398{
Guido van Rossumc334df52002-04-04 23:44:47 +00005399 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005400 slotdef *p;
5401 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005402 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005403
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005404 init_slotdefs();
5405 pp = ptrs;
5406 for (p = slotdefs; p->name; p++) {
5407 /* XXX assume name is interned! */
5408 if (p->name_strobj == name)
5409 *pp++ = p;
5410 }
5411 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005412 for (pp = ptrs; *pp; pp++) {
5413 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005414 offset = p->offset;
5415 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005416 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005417 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005418 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005419 if (ptrs[0] == NULL)
5420 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005421 return update_subclasses(type, name,
5422 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005423}
5424
Guido van Rossumc334df52002-04-04 23:44:47 +00005425/* Store the proper functions in the slot dispatches at class (type)
5426 definition time, based upon which operations the class overrides in its
5427 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005428static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005429fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005430{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005431 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005432
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005433 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005434 for (p = slotdefs; p->name; )
5435 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005436}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005437
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005438static void
5439update_all_slots(PyTypeObject* type)
5440{
5441 slotdef *p;
5442
5443 init_slotdefs();
5444 for (p = slotdefs; p->name; p++) {
5445 /* update_slot returns int but can't actually fail */
5446 update_slot(type, p->name_strobj);
5447 }
5448}
5449
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005450/* recurse_down_subclasses() and update_subclasses() are mutually
5451 recursive functions to call a callback for all subclasses,
5452 but refraining from recursing into subclasses that define 'name'. */
5453
5454static int
5455update_subclasses(PyTypeObject *type, PyObject *name,
5456 update_callback callback, void *data)
5457{
5458 if (callback(type, data) < 0)
5459 return -1;
5460 return recurse_down_subclasses(type, name, callback, data);
5461}
5462
5463static int
5464recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5465 update_callback callback, void *data)
5466{
5467 PyTypeObject *subclass;
5468 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005469 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005470
5471 subclasses = type->tp_subclasses;
5472 if (subclasses == NULL)
5473 return 0;
5474 assert(PyList_Check(subclasses));
5475 n = PyList_GET_SIZE(subclasses);
5476 for (i = 0; i < n; i++) {
5477 ref = PyList_GET_ITEM(subclasses, i);
5478 assert(PyWeakref_CheckRef(ref));
5479 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5480 assert(subclass != NULL);
5481 if ((PyObject *)subclass == Py_None)
5482 continue;
5483 assert(PyType_Check(subclass));
5484 /* Avoid recursing down into unaffected classes */
5485 dict = subclass->tp_dict;
5486 if (dict != NULL && PyDict_Check(dict) &&
5487 PyDict_GetItem(dict, name) != NULL)
5488 continue;
5489 if (update_subclasses(subclass, name, callback, data) < 0)
5490 return -1;
5491 }
5492 return 0;
5493}
5494
Guido van Rossum6d204072001-10-21 00:44:31 +00005495/* This function is called by PyType_Ready() to populate the type's
5496 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005497 function slot (like tp_repr) that's defined in the type, one or more
5498 corresponding descriptors are added in the type's tp_dict dictionary
5499 under the appropriate name (like __repr__). Some function slots
5500 cause more than one descriptor to be added (for example, the nb_add
5501 slot adds both __add__ and __radd__ descriptors) and some function
5502 slots compete for the same descriptor (for example both sq_item and
5503 mp_subscript generate a __getitem__ descriptor).
5504
5505 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005506 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005507 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005508 between competing slots: the members of PyHeapTypeObject are listed
5509 from most general to least general, so the most general slot is
5510 preferred. In particular, because as_mapping comes before as_sequence,
5511 for a type that defines both mp_subscript and sq_item, mp_subscript
5512 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005513
5514 This only adds new descriptors and doesn't overwrite entries in
5515 tp_dict that were previously defined. The descriptors contain a
5516 reference to the C function they must call, so that it's safe if they
5517 are copied into a subtype's __dict__ and the subtype has a different
5518 C function in its slot -- calling the method defined by the
5519 descriptor will call the C function that was used to create it,
5520 rather than the C function present in the slot when it is called.
5521 (This is important because a subtype may have a C function in the
5522 slot that calls the method from the dictionary, and we want to avoid
5523 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005524
5525static int
5526add_operators(PyTypeObject *type)
5527{
5528 PyObject *dict = type->tp_dict;
5529 slotdef *p;
5530 PyObject *descr;
5531 void **ptr;
5532
5533 init_slotdefs();
5534 for (p = slotdefs; p->name; p++) {
5535 if (p->wrapper == NULL)
5536 continue;
5537 ptr = slotptr(type, p->offset);
5538 if (!ptr || !*ptr)
5539 continue;
5540 if (PyDict_GetItem(dict, p->name_strobj))
5541 continue;
5542 descr = PyDescr_NewWrapper(type, p, *ptr);
5543 if (descr == NULL)
5544 return -1;
5545 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5546 return -1;
5547 Py_DECREF(descr);
5548 }
5549 if (type->tp_new != NULL) {
5550 if (add_tp_new_wrapper(type) < 0)
5551 return -1;
5552 }
5553 return 0;
5554}
5555
Guido van Rossum705f0f52001-08-24 16:47:00 +00005556
5557/* Cooperative 'super' */
5558
5559typedef struct {
5560 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005561 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005562 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005563 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005564} superobject;
5565
Guido van Rossum6f799372001-09-20 20:46:19 +00005566static PyMemberDef super_members[] = {
5567 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5568 "the class invoking super()"},
5569 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5570 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005571 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005572 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005573 {0}
5574};
5575
Guido van Rossum705f0f52001-08-24 16:47:00 +00005576static void
5577super_dealloc(PyObject *self)
5578{
5579 superobject *su = (superobject *)self;
5580
Guido van Rossum048eb752001-10-02 21:24:57 +00005581 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005582 Py_XDECREF(su->obj);
5583 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005584 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005585 self->ob_type->tp_free(self);
5586}
5587
5588static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005589super_repr(PyObject *self)
5590{
5591 superobject *su = (superobject *)self;
5592
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005593 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005594 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005595 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005596 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005597 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005598 else
5599 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005600 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005601 su->type ? su->type->tp_name : "NULL");
5602}
5603
5604static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005605super_getattro(PyObject *self, PyObject *name)
5606{
5607 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005608 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005609
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005610 if (!skip) {
5611 /* We want __class__ to return the class of the super object
5612 (i.e. super, or a subclass), not the class of su->obj. */
5613 skip = (PyString_Check(name) &&
5614 PyString_GET_SIZE(name) == 9 &&
5615 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5616 }
5617
5618 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005619 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005620 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005621 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005622 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005623
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005624 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005625 mro = starttype->tp_mro;
5626
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005627 if (mro == NULL)
5628 n = 0;
5629 else {
5630 assert(PyTuple_Check(mro));
5631 n = PyTuple_GET_SIZE(mro);
5632 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005633 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005634 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005635 break;
5636 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005637 i++;
5638 res = NULL;
5639 for (; i < n; i++) {
5640 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005641 if (PyType_Check(tmp))
5642 dict = ((PyTypeObject *)tmp)->tp_dict;
5643 else if (PyClass_Check(tmp))
5644 dict = ((PyClassObject *)tmp)->cl_dict;
5645 else
5646 continue;
5647 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005648 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005649 Py_INCREF(res);
5650 f = res->ob_type->tp_descr_get;
5651 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005652 tmp = f(res,
5653 /* Only pass 'obj' param if
5654 this is instance-mode super
5655 (See SF ID #743627)
5656 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005657 (su->obj == (PyObject *)
5658 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005659 ? (PyObject *)NULL
5660 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005661 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005662 Py_DECREF(res);
5663 res = tmp;
5664 }
5665 return res;
5666 }
5667 }
5668 }
5669 return PyObject_GenericGetAttr(self, name);
5670}
5671
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005672static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005673supercheck(PyTypeObject *type, PyObject *obj)
5674{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005675 /* Check that a super() call makes sense. Return a type object.
5676
5677 obj can be a new-style class, or an instance of one:
5678
5679 - If it is a class, it must be a subclass of 'type'. This case is
5680 used for class methods; the return value is obj.
5681
5682 - If it is an instance, it must be an instance of 'type'. This is
5683 the normal case; the return value is obj.__class__.
5684
5685 But... when obj is an instance, we want to allow for the case where
5686 obj->ob_type is not a subclass of type, but obj.__class__ is!
5687 This will allow using super() with a proxy for obj.
5688 */
5689
Guido van Rossum8e80a722003-02-18 19:22:22 +00005690 /* Check for first bullet above (special case) */
5691 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5692 Py_INCREF(obj);
5693 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005694 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005695
5696 /* Normal case */
5697 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005698 Py_INCREF(obj->ob_type);
5699 return obj->ob_type;
5700 }
5701 else {
5702 /* Try the slow way */
5703 static PyObject *class_str = NULL;
5704 PyObject *class_attr;
5705
5706 if (class_str == NULL) {
5707 class_str = PyString_FromString("__class__");
5708 if (class_str == NULL)
5709 return NULL;
5710 }
5711
5712 class_attr = PyObject_GetAttr(obj, class_str);
5713
5714 if (class_attr != NULL &&
5715 PyType_Check(class_attr) &&
5716 (PyTypeObject *)class_attr != obj->ob_type)
5717 {
5718 int ok = PyType_IsSubtype(
5719 (PyTypeObject *)class_attr, type);
5720 if (ok)
5721 return (PyTypeObject *)class_attr;
5722 }
5723
5724 if (class_attr == NULL)
5725 PyErr_Clear();
5726 else
5727 Py_DECREF(class_attr);
5728 }
5729
Tim Peters97e5ff52003-02-18 19:32:50 +00005730 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005731 "super(type, obj): "
5732 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005733 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005734}
5735
Guido van Rossum705f0f52001-08-24 16:47:00 +00005736static PyObject *
5737super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5738{
5739 superobject *su = (superobject *)self;
Anthony Baxtera6286212006-04-11 07:42:36 +00005740 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005741
5742 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5743 /* Not binding to an object, or already bound */
5744 Py_INCREF(self);
5745 return self;
5746 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005747 if (su->ob_type != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005748 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005749 call its type */
5750 return PyObject_CallFunction((PyObject *)su->ob_type,
5751 "OO", su->type, obj);
5752 else {
5753 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005754 PyTypeObject *obj_type = supercheck(su->type, obj);
5755 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005756 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00005757 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005758 NULL, NULL);
Anthony Baxtera6286212006-04-11 07:42:36 +00005759 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005760 return NULL;
5761 Py_INCREF(su->type);
5762 Py_INCREF(obj);
Anthony Baxtera6286212006-04-11 07:42:36 +00005763 newobj->type = su->type;
5764 newobj->obj = obj;
5765 newobj->obj_type = obj_type;
5766 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005767 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005768}
5769
5770static int
5771super_init(PyObject *self, PyObject *args, PyObject *kwds)
5772{
5773 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005774 PyTypeObject *type;
5775 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005776 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005777
5778 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5779 return -1;
5780 if (obj == Py_None)
5781 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005782 if (obj != NULL) {
5783 obj_type = supercheck(type, obj);
5784 if (obj_type == NULL)
5785 return -1;
5786 Py_INCREF(obj);
5787 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005788 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005789 su->type = type;
5790 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005791 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005792 return 0;
5793}
5794
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005795PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005796"super(type) -> unbound super object\n"
5797"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005798"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005799"Typical use to call a cooperative superclass method:\n"
5800"class C(B):\n"
5801" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005802" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005803
Guido van Rossum048eb752001-10-02 21:24:57 +00005804static int
5805super_traverse(PyObject *self, visitproc visit, void *arg)
5806{
5807 superobject *su = (superobject *)self;
5808 int err;
5809
5810#define VISIT(SLOT) \
5811 if (SLOT) { \
5812 err = visit((PyObject *)(SLOT), arg); \
5813 if (err) \
5814 return err; \
5815 }
5816
5817 VISIT(su->obj);
5818 VISIT(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005819 VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005820
5821#undef VISIT
5822
5823 return 0;
5824}
5825
Guido van Rossum705f0f52001-08-24 16:47:00 +00005826PyTypeObject PySuper_Type = {
5827 PyObject_HEAD_INIT(&PyType_Type)
5828 0, /* ob_size */
5829 "super", /* tp_name */
5830 sizeof(superobject), /* tp_basicsize */
5831 0, /* tp_itemsize */
5832 /* methods */
5833 super_dealloc, /* tp_dealloc */
5834 0, /* tp_print */
5835 0, /* tp_getattr */
5836 0, /* tp_setattr */
5837 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005838 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005839 0, /* tp_as_number */
5840 0, /* tp_as_sequence */
5841 0, /* tp_as_mapping */
5842 0, /* tp_hash */
5843 0, /* tp_call */
5844 0, /* tp_str */
5845 super_getattro, /* tp_getattro */
5846 0, /* tp_setattro */
5847 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005848 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5849 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005850 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005851 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005852 0, /* tp_clear */
5853 0, /* tp_richcompare */
5854 0, /* tp_weaklistoffset */
5855 0, /* tp_iter */
5856 0, /* tp_iternext */
5857 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005858 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005859 0, /* tp_getset */
5860 0, /* tp_base */
5861 0, /* tp_dict */
5862 super_descr_get, /* tp_descr_get */
5863 0, /* tp_descr_set */
5864 0, /* tp_dictoffset */
5865 super_init, /* tp_init */
5866 PyType_GenericAlloc, /* tp_alloc */
5867 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005868 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005869};