blob: 1ccd97b7b2903489f44908857b141eab57f4f00d [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. Hudsonade8c8b22002-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. Hudsonade8c8b22002-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. Hudsonade8c8b22002-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. Hudsonade8c8b22002-11-27 16:29:26 +000094 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +000095 return mod;
96 }
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000097 else {
98 s = strrchr(type->tp_name, '.');
99 if (s != NULL)
100 return PyString_FromStringAndSize(
Thomas Wouters89f507f2006-12-13 04:49:30 +0000101 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000102 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);
Guido van Rossum50e9fb92006-08-17 05:42:55 +0000217 if (!PyType_Check(ob)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000218 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
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000364static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000365type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000367 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000368 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000369
370 mod = type_module(type, NULL);
371 if (mod == NULL)
372 PyErr_Clear();
373 else if (!PyString_Check(mod)) {
374 Py_DECREF(mod);
375 mod = NULL;
376 }
377 name = type_name(type, NULL);
378 if (name == NULL)
379 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000380
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000381 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
382 kind = "class";
383 else
384 kind = "type";
385
Barry Warsaw7ce36942001-08-24 18:34:26 +0000386 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000387 rtn = PyString_FromFormat("<%s '%s.%s'>",
388 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000389 PyString_AS_STRING(mod),
390 PyString_AS_STRING(name));
391 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000392 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000393 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000394
Guido van Rossumc3542212001-08-16 09:18:56 +0000395 Py_XDECREF(mod);
396 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000397 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000398}
399
Tim Peters6d6c1a32001-08-02 04:15:00 +0000400static PyObject *
401type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
402{
403 PyObject *obj;
404
405 if (type->tp_new == NULL) {
406 PyErr_Format(PyExc_TypeError,
407 "cannot create '%.100s' instances",
408 type->tp_name);
409 return NULL;
410 }
411
Tim Peters3f996e72001-09-13 19:18:27 +0000412 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000413 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000414 /* Ugly exception: when the call was type(something),
415 don't call tp_init on the result. */
416 if (type == &PyType_Type &&
417 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
418 (kwds == NULL ||
419 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
420 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000421 /* If the returned object is not an instance of type,
422 it won't be initialized. */
423 if (!PyType_IsSubtype(obj->ob_type, type))
424 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000425 type = obj->ob_type;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000426 if (type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000427 type->tp_init(obj, args, kwds) < 0) {
428 Py_DECREF(obj);
429 obj = NULL;
430 }
431 }
432 return obj;
433}
434
435PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000436PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000437{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000438 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000439 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
440 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000441
442 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000443 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000444 else
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000445 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000446
Neil Schemenauerc806c882001-08-29 23:54:54 +0000447 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000448 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000449
Neil Schemenauerc806c882001-08-29 23:54:54 +0000450 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000451
Tim Peters6d6c1a32001-08-02 04:15:00 +0000452 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
453 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000454
Tim Peters6d6c1a32001-08-02 04:15:00 +0000455 if (type->tp_itemsize == 0)
456 PyObject_INIT(obj, type);
457 else
458 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000459
Tim Peters6d6c1a32001-08-02 04:15:00 +0000460 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000461 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000462 return obj;
463}
464
465PyObject *
466PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
467{
468 return type->tp_alloc(type, 0);
469}
470
Guido van Rossum9475a232001-10-05 20:51:39 +0000471/* Helpers for subtyping */
472
473static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000474traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
475{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000476 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000477 PyMemberDef *mp;
478
479 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000480 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000481 for (i = 0; i < n; i++, mp++) {
482 if (mp->type == T_OBJECT_EX) {
483 char *addr = (char *)self + mp->offset;
484 PyObject *obj = *(PyObject **)addr;
485 if (obj != NULL) {
486 int err = visit(obj, arg);
487 if (err)
488 return err;
489 }
490 }
491 }
492 return 0;
493}
494
495static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000496subtype_traverse(PyObject *self, visitproc visit, void *arg)
497{
498 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000499 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000500
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000501 /* Find the nearest base with a different tp_traverse,
502 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000503 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000504 base = type;
505 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
506 if (base->ob_size) {
507 int err = traverse_slots(base, self, visit, arg);
508 if (err)
509 return err;
510 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000511 base = base->tp_base;
512 assert(base);
513 }
514
515 if (type->tp_dictoffset != base->tp_dictoffset) {
516 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000517 if (dictptr && *dictptr)
518 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000519 }
520
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000521 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000522 /* For a heaptype, the instances count as references
523 to the type. Traverse the type so the collector
524 can find cycles involving this link. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000525 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000526
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000527 if (basetraverse)
528 return basetraverse(self, visit, arg);
529 return 0;
530}
531
532static void
533clear_slots(PyTypeObject *type, PyObject *self)
534{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000535 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000536 PyMemberDef *mp;
537
538 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000539 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000540 for (i = 0; i < n; i++, mp++) {
541 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
542 char *addr = (char *)self + mp->offset;
543 PyObject *obj = *(PyObject **)addr;
544 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000545 *(PyObject **)addr = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000546 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000547 }
548 }
549 }
550}
551
552static int
553subtype_clear(PyObject *self)
554{
555 PyTypeObject *type, *base;
556 inquiry baseclear;
557
558 /* Find the nearest base with a different tp_clear
559 and clear slots while we're at it */
560 type = self->ob_type;
561 base = type;
562 while ((baseclear = base->tp_clear) == subtype_clear) {
563 if (base->ob_size)
564 clear_slots(base, self);
565 base = base->tp_base;
566 assert(base);
567 }
568
Guido van Rossuma3862092002-06-10 15:24:42 +0000569 /* There's no need to clear the instance dict (if any);
570 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000571
572 if (baseclear)
573 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000574 return 0;
575}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000576
577static void
578subtype_dealloc(PyObject *self)
579{
Guido van Rossum14227b42001-12-06 02:35:58 +0000580 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000581 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000582
Guido van Rossum22b13872002-08-06 21:41:44 +0000583 /* Extract the type; we expect it to be a heap type */
584 type = self->ob_type;
585 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000586
Guido van Rossum22b13872002-08-06 21:41:44 +0000587 /* Test whether the type has GC exactly once */
588
589 if (!PyType_IS_GC(type)) {
590 /* It's really rare to find a dynamic type that doesn't have
591 GC; it can only happen when deriving from 'object' and not
592 adding any slots or instance variables. This allows
593 certain simplifications: there's no need to call
594 clear_slots(), or DECREF the dict, or clear weakrefs. */
595
596 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000597 if (type->tp_del) {
598 type->tp_del(self);
599 if (self->ob_refcnt > 0)
600 return;
601 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000602
603 /* Find the nearest base with a different tp_dealloc */
604 base = type;
605 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
606 assert(base->ob_size == 0);
607 base = base->tp_base;
608 assert(base);
609 }
610
611 /* Call the base tp_dealloc() */
612 assert(basedealloc);
613 basedealloc(self);
614
615 /* Can't reference self beyond this point */
616 Py_DECREF(type);
617
618 /* Done */
619 return;
620 }
621
622 /* We get here only if the type has GC */
623
624 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000625 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000626 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000627 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000628 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000629 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000630 /* DO NOT restore GC tracking at this point. weakref callbacks
631 * (if any, and whether directly here or indirectly in something we
632 * call) may trigger GC, and if self is tracked at that point, it
633 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000634 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000635
Guido van Rossum59195fd2003-06-13 20:54:40 +0000636 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000637 base = type;
638 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000639 base = base->tp_base;
640 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000641 }
642
Guido van Rossum1987c662003-05-29 14:29:23 +0000643 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000644 the finalizer (__del__), clearing slots, or clearing the instance
645 dict. */
646
Guido van Rossum1987c662003-05-29 14:29:23 +0000647 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
648 PyObject_ClearWeakRefs(self);
649
650 /* Maybe call finalizer; exit early if resurrected */
651 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000652 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000653 type->tp_del(self);
654 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000655 goto endlabel; /* resurrected */
656 else
657 _PyObject_GC_UNTRACK(self);
Thomas Woutersb2137042007-02-01 18:02:27 +0000658 /* New weakrefs could be created during the finalizer call.
659 If this occurs, clear them out without calling their
660 finalizers since they might rely on part of the object
661 being finalized that has already been destroyed. */
662 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
663 /* Modeled after GET_WEAKREFS_LISTPTR() */
664 PyWeakReference **list = (PyWeakReference **) \
665 PyObject_GET_WEAKREFS_LISTPTR(self);
666 while (*list)
667 _PyWeakref_ClearRef(*list);
668 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000669 }
670
Guido van Rossum59195fd2003-06-13 20:54:40 +0000671 /* Clear slots up to the nearest base with a different tp_dealloc */
672 base = type;
673 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
674 if (base->ob_size)
675 clear_slots(base, self);
676 base = base->tp_base;
677 assert(base);
678 }
679
Tim Peters6d6c1a32001-08-02 04:15:00 +0000680 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000681 if (type->tp_dictoffset && !base->tp_dictoffset) {
682 PyObject **dictptr = _PyObject_GetDictPtr(self);
683 if (dictptr != NULL) {
684 PyObject *dict = *dictptr;
685 if (dict != NULL) {
686 Py_DECREF(dict);
687 *dictptr = NULL;
688 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000689 }
690 }
691
Tim Peters0bd743c2003-11-13 22:50:00 +0000692 /* Call the base tp_dealloc(); first retrack self if
693 * basedealloc knows about gc.
694 */
695 if (PyType_IS_GC(base))
696 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000697 assert(basedealloc);
698 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000699
700 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000701 Py_DECREF(type);
702
Guido van Rossum0906e072002-08-07 20:42:09 +0000703 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000704 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000705 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000706 --_PyTrash_delete_nesting;
707
708 /* Explanation of the weirdness around the trashcan macros:
709
710 Q. What do the trashcan macros do?
711
712 A. Read the comment titled "Trashcan mechanism" in object.h.
713 For one, this explains why there must be a call to GC-untrack
714 before the trashcan begin macro. Without understanding the
715 trashcan code, the answers to the following questions don't make
716 sense.
717
718 Q. Why do we GC-untrack before the trashcan and then immediately
719 GC-track again afterward?
720
721 A. In the case that the base class is GC-aware, the base class
722 probably GC-untracks the object. If it does that using the
723 UNTRACK macro, this will crash when the object is already
724 untracked. Because we don't know what the base class does, the
725 only safe thing is to make sure the object is tracked when we
726 call the base class dealloc. But... The trashcan begin macro
727 requires that the object is *untracked* before it is called. So
728 the dance becomes:
729
730 GC untrack
731 trashcan begin
732 GC track
733
Tim Petersf7f9e992003-11-13 21:59:32 +0000734 Q. Why did the last question say "immediately GC-track again"?
735 It's nowhere near immediately.
736
737 A. Because the code *used* to re-track immediately. Bad Idea.
738 self has a refcount of 0, and if gc ever gets its hands on it
739 (which can happen if any weakref callback gets invoked), it
740 looks like trash to gc too, and gc also tries to delete self
741 then. But we're already deleting self. Double dealloction is
742 a subtle disaster.
743
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000744 Q. Why the bizarre (net-zero) manipulation of
745 _PyTrash_delete_nesting around the trashcan macros?
746
747 A. Some base classes (e.g. list) also use the trashcan mechanism.
748 The following scenario used to be possible:
749
750 - suppose the trashcan level is one below the trashcan limit
751
752 - subtype_dealloc() is called
753
754 - the trashcan limit is not yet reached, so the trashcan level
755 is incremented and the code between trashcan begin and end is
756 executed
757
758 - this destroys much of the object's contents, including its
759 slots and __dict__
760
761 - basedealloc() is called; this is really list_dealloc(), or
762 some other type which also uses the trashcan macros
763
764 - the trashcan limit is now reached, so the object is put on the
765 trashcan's to-be-deleted-later list
766
767 - basedealloc() returns
768
769 - subtype_dealloc() decrefs the object's type
770
771 - subtype_dealloc() returns
772
773 - later, the trashcan code starts deleting the objects from its
774 to-be-deleted-later list
775
776 - subtype_dealloc() is called *AGAIN* for the same object
777
778 - at the very least (if the destroyed slots and __dict__ don't
779 cause problems) the object's type gets decref'ed a second
780 time, which is *BAD*!!!
781
782 The remedy is to make sure that if the code between trashcan
783 begin and end in subtype_dealloc() is called, the code between
784 trashcan begin and end in basedealloc() will also be called.
785 This is done by decrementing the level after passing into the
786 trashcan block, and incrementing it just before leaving the
787 block.
788
789 But now it's possible that a chain of objects consisting solely
790 of objects whose deallocator is subtype_dealloc() will defeat
791 the trashcan mechanism completely: the decremented level means
792 that the effective level never reaches the limit. Therefore, we
793 *increment* the level *before* entering the trashcan block, and
794 matchingly decrement it after leaving. This means the trashcan
795 code will trigger a little early, but that's no big deal.
796
797 Q. Are there any live examples of code in need of all this
798 complexity?
799
800 A. Yes. See SF bug 668433 for code that crashed (when Python was
801 compiled in debug mode) before the trashcan level manipulations
802 were added. For more discussion, see SF patches 581742, 575073
803 and bug 574207.
804 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000805}
806
Jeremy Hylton938ace62002-07-17 16:30:39 +0000807static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000808
Tim Peters6d6c1a32001-08-02 04:15:00 +0000809/* type test with subclassing support */
810
811int
812PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
813{
814 PyObject *mro;
815
816 mro = a->tp_mro;
817 if (mro != NULL) {
818 /* Deal with multiple inheritance without recursion
819 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000820 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000821 assert(PyTuple_Check(mro));
822 n = PyTuple_GET_SIZE(mro);
823 for (i = 0; i < n; i++) {
824 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
825 return 1;
826 }
827 return 0;
828 }
829 else {
830 /* a is not completely initilized yet; follow tp_base */
831 do {
832 if (a == b)
833 return 1;
834 a = a->tp_base;
835 } while (a != NULL);
836 return b == &PyBaseObject_Type;
837 }
838}
839
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000840/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000841 without looking in the instance dictionary
842 (so we can't use PyObject_GetAttr) but still binding
843 it to the instance. The arguments are the object,
844 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000845 static variable used to cache the interned Python string.
846
847 Two variants:
848
849 - lookup_maybe() returns NULL without raising an exception
850 when the _PyType_Lookup() call fails;
851
852 - lookup_method() always raises an exception upon errors.
853*/
Guido van Rossum60718732001-08-28 17:47:51 +0000854
855static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000856lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000857{
858 PyObject *res;
859
860 if (*attrobj == NULL) {
861 *attrobj = PyString_InternFromString(attrstr);
862 if (*attrobj == NULL)
863 return NULL;
864 }
865 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000866 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000867 descrgetfunc f;
868 if ((f = res->ob_type->tp_descr_get) == NULL)
869 Py_INCREF(res);
870 else
871 res = f(res, self, (PyObject *)(self->ob_type));
872 }
873 return res;
874}
875
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000876static PyObject *
877lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
878{
879 PyObject *res = lookup_maybe(self, attrstr, attrobj);
880 if (res == NULL && !PyErr_Occurred())
881 PyErr_SetObject(PyExc_AttributeError, *attrobj);
882 return res;
883}
884
Guido van Rossum2730b132001-08-28 18:22:14 +0000885/* A variation of PyObject_CallMethod that uses lookup_method()
886 instead of PyObject_GetAttrString(). This uses the same convention
887 as lookup_method to cache the interned name string object. */
888
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000889static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000890call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
891{
892 va_list va;
893 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000894 va_start(va, format);
895
Guido van Rossumda21c012001-10-03 00:50:18 +0000896 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000897 if (func == NULL) {
898 va_end(va);
899 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000900 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000901 return NULL;
902 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000903
904 if (format && *format)
905 args = Py_VaBuildValue(format, va);
906 else
907 args = PyTuple_New(0);
908
909 va_end(va);
910
911 if (args == NULL)
912 return NULL;
913
914 assert(PyTuple_Check(args));
915 retval = PyObject_Call(func, args, NULL);
916
917 Py_DECREF(args);
918 Py_DECREF(func);
919
920 return retval;
921}
922
923/* Clone of call_method() that returns NotImplemented when the lookup fails. */
924
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000925static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000926call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
927{
928 va_list va;
929 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000930 va_start(va, format);
931
Guido van Rossumda21c012001-10-03 00:50:18 +0000932 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000933 if (func == NULL) {
934 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000935 if (!PyErr_Occurred()) {
936 Py_INCREF(Py_NotImplemented);
937 return Py_NotImplemented;
938 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000939 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000940 }
941
942 if (format && *format)
943 args = Py_VaBuildValue(format, va);
944 else
945 args = PyTuple_New(0);
946
947 va_end(va);
948
Guido van Rossum717ce002001-09-14 16:58:08 +0000949 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000950 return NULL;
951
Guido van Rossum717ce002001-09-14 16:58:08 +0000952 assert(PyTuple_Check(args));
953 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000954
955 Py_DECREF(args);
956 Py_DECREF(func);
957
958 return retval;
959}
960
Tim Petersea7f75d2002-12-07 21:39:16 +0000961/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000962 Method resolution order algorithm C3 described in
963 "A Monotonic Superclass Linearization for Dylan",
964 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000965 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000966 (OOPSLA 1996)
967
Guido van Rossum98f33732002-11-25 21:36:54 +0000968 Some notes about the rules implied by C3:
969
Tim Petersea7f75d2002-12-07 21:39:16 +0000970 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +0000971 It isn't legal to repeat a class in a list of base classes.
972
973 The next three properties are the 3 constraints in "C3".
974
Tim Petersea7f75d2002-12-07 21:39:16 +0000975 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +0000976 If A precedes B in C's MRO, then A will precede B in the MRO of all
977 subclasses of C.
978
979 Monotonicity.
980 The MRO of a class must be an extension without reordering of the
981 MRO of each of its superclasses.
982
983 Extended Precedence Graph (EPG).
984 Linearization is consistent if there is a path in the EPG from
985 each class to all its successors in the linearization. See
986 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +0000987 */
988
Tim Petersea7f75d2002-12-07 21:39:16 +0000989static int
Guido van Rossum1f121312002-11-14 19:49:16 +0000990tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000991 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +0000992 size = PyList_GET_SIZE(list);
993
994 for (j = whence+1; j < size; j++) {
995 if (PyList_GET_ITEM(list, j) == o)
996 return 1;
997 }
998 return 0;
999}
1000
Guido van Rossum98f33732002-11-25 21:36:54 +00001001static PyObject *
1002class_name(PyObject *cls)
1003{
1004 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1005 if (name == NULL) {
1006 PyErr_Clear();
1007 Py_XDECREF(name);
1008 name = PyObject_Repr(cls);
1009 }
1010 if (name == NULL)
1011 return NULL;
1012 if (!PyString_Check(name)) {
1013 Py_DECREF(name);
1014 return NULL;
1015 }
1016 return name;
1017}
1018
1019static int
1020check_duplicates(PyObject *list)
1021{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001022 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001023 /* Let's use a quadratic time algorithm,
1024 assuming that the bases lists is short.
1025 */
1026 n = PyList_GET_SIZE(list);
1027 for (i = 0; i < n; i++) {
1028 PyObject *o = PyList_GET_ITEM(list, i);
1029 for (j = i + 1; j < n; j++) {
1030 if (PyList_GET_ITEM(list, j) == o) {
1031 o = class_name(o);
1032 PyErr_Format(PyExc_TypeError,
1033 "duplicate base class %s",
1034 o ? PyString_AS_STRING(o) : "?");
1035 Py_XDECREF(o);
1036 return -1;
1037 }
1038 }
1039 }
1040 return 0;
1041}
1042
1043/* Raise a TypeError for an MRO order disagreement.
1044
1045 It's hard to produce a good error message. In the absence of better
1046 insight into error reporting, report the classes that were candidates
1047 to be put next into the MRO. There is some conflict between the
1048 order in which they should be put in the MRO, but it's hard to
1049 diagnose what constraint can't be satisfied.
1050*/
1051
1052static void
1053set_mro_error(PyObject *to_merge, int *remain)
1054{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001055 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001056 char buf[1000];
1057 PyObject *k, *v;
1058 PyObject *set = PyDict_New();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001059 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001060
1061 to_merge_size = PyList_GET_SIZE(to_merge);
1062 for (i = 0; i < to_merge_size; i++) {
1063 PyObject *L = PyList_GET_ITEM(to_merge, i);
1064 if (remain[i] < PyList_GET_SIZE(L)) {
1065 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001066 if (PyDict_SetItem(set, c, Py_None) < 0) {
1067 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001068 return;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001069 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001070 }
1071 }
1072 n = PyDict_Size(set);
1073
Raymond Hettingerf394df42003-04-06 19:13:41 +00001074 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1075consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001076 i = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001077 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001078 PyObject *name = class_name(k);
1079 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1080 name ? PyString_AS_STRING(name) : "?");
1081 Py_XDECREF(name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001082 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001083 buf[off++] = ',';
1084 buf[off] = '\0';
1085 }
1086 }
1087 PyErr_SetString(PyExc_TypeError, buf);
1088 Py_DECREF(set);
1089}
1090
Tim Petersea7f75d2002-12-07 21:39:16 +00001091static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001092pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001093 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001094 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001095 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001096
Guido van Rossum1f121312002-11-14 19:49:16 +00001097 to_merge_size = PyList_GET_SIZE(to_merge);
1098
Guido van Rossum98f33732002-11-25 21:36:54 +00001099 /* remain stores an index into each sublist of to_merge.
1100 remain[i] is the index of the next base in to_merge[i]
1101 that is not included in acc.
1102 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001103 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001104 if (remain == NULL)
1105 return -1;
1106 for (i = 0; i < to_merge_size; i++)
1107 remain[i] = 0;
1108
1109 again:
1110 empty_cnt = 0;
1111 for (i = 0; i < to_merge_size; i++) {
1112 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001113
Guido van Rossum1f121312002-11-14 19:49:16 +00001114 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1115
1116 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1117 empty_cnt++;
1118 continue;
1119 }
1120
Guido van Rossum98f33732002-11-25 21:36:54 +00001121 /* Choose next candidate for MRO.
1122
1123 The input sequences alone can determine the choice.
1124 If not, choose the class which appears in the MRO
1125 of the earliest direct superclass of the new class.
1126 */
1127
Guido van Rossum1f121312002-11-14 19:49:16 +00001128 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1129 for (j = 0; j < to_merge_size; j++) {
1130 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001131 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001132 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001133 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001134 }
1135 ok = PyList_Append(acc, candidate);
1136 if (ok < 0) {
1137 PyMem_Free(remain);
1138 return -1;
1139 }
1140 for (j = 0; j < to_merge_size; j++) {
1141 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001142 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1143 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001144 remain[j]++;
1145 }
1146 }
1147 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001148 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001149 }
1150
Guido van Rossum98f33732002-11-25 21:36:54 +00001151 if (empty_cnt == to_merge_size) {
1152 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001153 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001154 }
1155 set_mro_error(to_merge, remain);
1156 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001157 return -1;
1158}
1159
Tim Peters6d6c1a32001-08-02 04:15:00 +00001160static PyObject *
1161mro_implementation(PyTypeObject *type)
1162{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001163 Py_ssize_t i, n;
1164 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001165 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001166 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001167
Guido van Rossum63517572002-06-18 16:44:57 +00001168 if(type->tp_dict == NULL) {
1169 if(PyType_Ready(type) < 0)
1170 return NULL;
1171 }
1172
Guido van Rossum98f33732002-11-25 21:36:54 +00001173 /* Find a superclass linearization that honors the constraints
1174 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001175 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001176
1177 to_merge is a list of lists, where each list is a superclass
1178 linearization implied by a base class. The last element of
1179 to_merge is the declared list of bases.
1180 */
1181
Tim Peters6d6c1a32001-08-02 04:15:00 +00001182 bases = type->tp_bases;
1183 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001184
1185 to_merge = PyList_New(n+1);
1186 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001187 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001188
Tim Peters6d6c1a32001-08-02 04:15:00 +00001189 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001190 PyObject *base = PyTuple_GET_ITEM(bases, i);
1191 PyObject *parentMRO;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001192 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001193 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001194 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001195 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001196 }
1197
1198 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001199 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001200
1201 bases_aslist = PySequence_List(bases);
1202 if (bases_aslist == NULL) {
1203 Py_DECREF(to_merge);
1204 return NULL;
1205 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001206 /* This is just a basic sanity check. */
1207 if (check_duplicates(bases_aslist) < 0) {
1208 Py_DECREF(to_merge);
1209 Py_DECREF(bases_aslist);
1210 return NULL;
1211 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001212 PyList_SET_ITEM(to_merge, n, bases_aslist);
1213
1214 result = Py_BuildValue("[O]", (PyObject *)type);
1215 if (result == NULL) {
1216 Py_DECREF(to_merge);
1217 return NULL;
1218 }
1219
1220 ok = pmerge(result, to_merge);
1221 Py_DECREF(to_merge);
1222 if (ok < 0) {
1223 Py_DECREF(result);
1224 return NULL;
1225 }
1226
Tim Peters6d6c1a32001-08-02 04:15:00 +00001227 return result;
1228}
1229
1230static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001231mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001232{
1233 PyTypeObject *type = (PyTypeObject *)self;
1234
Tim Peters6d6c1a32001-08-02 04:15:00 +00001235 return mro_implementation(type);
1236}
1237
1238static int
1239mro_internal(PyTypeObject *type)
1240{
1241 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001242 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001243
1244 if (type->ob_type == &PyType_Type) {
1245 result = mro_implementation(type);
1246 }
1247 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001248 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001249 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001250 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001251 if (mro == NULL)
1252 return -1;
1253 result = PyObject_CallObject(mro, NULL);
1254 Py_DECREF(mro);
1255 }
1256 if (result == NULL)
1257 return -1;
1258 tuple = PySequence_Tuple(result);
1259 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001260 if (tuple == NULL)
1261 return -1;
1262 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001263 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001264 PyObject *cls;
1265 PyTypeObject *solid;
1266
1267 solid = solid_base(type);
1268
1269 len = PyTuple_GET_SIZE(tuple);
1270
1271 for (i = 0; i < len; i++) {
1272 PyTypeObject *t;
1273 cls = PyTuple_GET_ITEM(tuple, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001274 if (!PyType_Check(cls)) {
Armin Rigo037d1e02005-12-29 17:07:39 +00001275 PyErr_Format(PyExc_TypeError,
1276 "mro() returned a non-class ('%.500s')",
1277 cls->ob_type->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001278 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001279 return -1;
1280 }
1281 t = (PyTypeObject*)cls;
1282 if (!PyType_IsSubtype(solid, solid_base(t))) {
1283 PyErr_Format(PyExc_TypeError,
1284 "mro() returned base with unsuitable layout ('%.500s')",
1285 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001286 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001287 return -1;
1288 }
1289 }
1290 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001291 type->tp_mro = tuple;
1292 return 0;
1293}
1294
1295
1296/* Calculate the best base amongst multiple base classes.
1297 This is the first one that's on the path to the "solid base". */
1298
1299static PyTypeObject *
1300best_base(PyObject *bases)
1301{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001302 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001304 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001305
1306 assert(PyTuple_Check(bases));
1307 n = PyTuple_GET_SIZE(bases);
1308 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001309 base = NULL;
1310 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001311 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001312 base_proto = PyTuple_GET_ITEM(bases, i);
Tim Petersa91e9642001-11-14 23:32:33 +00001313 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001314 PyErr_SetString(
1315 PyExc_TypeError,
1316 "bases must be types");
1317 return NULL;
1318 }
Tim Petersa91e9642001-11-14 23:32:33 +00001319 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001320 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001321 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001322 return NULL;
1323 }
1324 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001325 if (winner == NULL) {
1326 winner = candidate;
1327 base = base_i;
1328 }
1329 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001330 ;
1331 else if (PyType_IsSubtype(candidate, winner)) {
1332 winner = candidate;
1333 base = base_i;
1334 }
1335 else {
1336 PyErr_SetString(
1337 PyExc_TypeError,
1338 "multiple bases have "
1339 "instance lay-out conflict");
1340 return NULL;
1341 }
1342 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001343 if (base == NULL)
1344 PyErr_SetString(PyExc_TypeError,
1345 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001346 return base;
1347}
1348
1349static int
1350extra_ivars(PyTypeObject *type, PyTypeObject *base)
1351{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001352 size_t t_size = type->tp_basicsize;
1353 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001354
Guido van Rossum9676b222001-08-17 20:32:36 +00001355 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001356 if (type->tp_itemsize || base->tp_itemsize) {
1357 /* If itemsize is involved, stricter rules */
1358 return t_size != b_size ||
1359 type->tp_itemsize != base->tp_itemsize;
1360 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001361 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1362 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1363 t_size -= sizeof(PyObject *);
1364 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1365 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1366 t_size -= sizeof(PyObject *);
1367
1368 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001369}
1370
1371static PyTypeObject *
1372solid_base(PyTypeObject *type)
1373{
1374 PyTypeObject *base;
1375
1376 if (type->tp_base)
1377 base = solid_base(type->tp_base);
1378 else
1379 base = &PyBaseObject_Type;
1380 if (extra_ivars(type, base))
1381 return type;
1382 else
1383 return base;
1384}
1385
Jeremy Hylton938ace62002-07-17 16:30:39 +00001386static void object_dealloc(PyObject *);
1387static int object_init(PyObject *, PyObject *, PyObject *);
1388static int update_slot(PyTypeObject *, PyObject *);
1389static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001390
1391static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001392subtype_dict(PyObject *obj, void *context)
1393{
1394 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1395 PyObject *dict;
1396
1397 if (dictptr == NULL) {
1398 PyErr_SetString(PyExc_AttributeError,
1399 "This object has no __dict__");
1400 return NULL;
1401 }
1402 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001403 if (dict == NULL)
1404 *dictptr = dict = PyDict_New();
1405 Py_XINCREF(dict);
1406 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001407}
1408
Guido van Rossum6661be32001-10-26 04:26:12 +00001409static int
1410subtype_setdict(PyObject *obj, PyObject *value, void *context)
1411{
1412 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1413 PyObject *dict;
1414
1415 if (dictptr == NULL) {
1416 PyErr_SetString(PyExc_AttributeError,
1417 "This object has no __dict__");
1418 return -1;
1419 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001420 if (value != NULL && !PyDict_Check(value)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001421 PyErr_Format(PyExc_TypeError,
1422 "__dict__ must be set to a dictionary, "
1423 "not a '%.200s'", value->ob_type->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001424 return -1;
1425 }
1426 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001427 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001428 *dictptr = value;
1429 Py_XDECREF(dict);
1430 return 0;
1431}
1432
Guido van Rossumad47da02002-08-12 19:05:44 +00001433static PyObject *
1434subtype_getweakref(PyObject *obj, void *context)
1435{
1436 PyObject **weaklistptr;
1437 PyObject *result;
1438
1439 if (obj->ob_type->tp_weaklistoffset == 0) {
1440 PyErr_SetString(PyExc_AttributeError,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001441 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001442 return NULL;
1443 }
1444 assert(obj->ob_type->tp_weaklistoffset > 0);
1445 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001446 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001447 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001448 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001449 if (*weaklistptr == NULL)
1450 result = Py_None;
1451 else
1452 result = *weaklistptr;
1453 Py_INCREF(result);
1454 return result;
1455}
1456
Guido van Rossum373c7412003-01-07 13:41:37 +00001457/* Three variants on the subtype_getsets list. */
1458
1459static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001460 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001461 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001462 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001463 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001464 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001465};
1466
Guido van Rossum373c7412003-01-07 13:41:37 +00001467static PyGetSetDef subtype_getsets_dict_only[] = {
1468 {"__dict__", subtype_dict, subtype_setdict,
1469 PyDoc_STR("dictionary for instance variables (if defined)")},
1470 {0}
1471};
1472
1473static PyGetSetDef subtype_getsets_weakref_only[] = {
1474 {"__weakref__", subtype_getweakref, NULL,
1475 PyDoc_STR("list of weak references to the object (if defined)")},
1476 {0}
1477};
1478
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001479static int
1480valid_identifier(PyObject *s)
1481{
Guido van Rossum03013a02002-07-16 14:30:28 +00001482 unsigned char *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001483 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001484
1485 if (!PyString_Check(s)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001486 PyErr_Format(PyExc_TypeError,
1487 "__slots__ items must be strings, not '%.200s'",
1488 s->ob_type->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001489 return 0;
1490 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001491 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001492 n = PyString_GET_SIZE(s);
1493 /* We must reject an empty name. As a hack, we bump the
1494 length to 1 so that the loop will balk on the trailing \0. */
1495 if (n == 0)
1496 n = 1;
1497 for (i = 0; i < n; i++, p++) {
1498 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1499 PyErr_SetString(PyExc_TypeError,
1500 "__slots__ must be identifiers");
1501 return 0;
1502 }
1503 }
1504 return 1;
1505}
1506
Martin v. Löwisd919a592002-10-14 21:07:28 +00001507#ifdef Py_USING_UNICODE
1508/* Replace Unicode objects in slots. */
1509
1510static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001511_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001512{
1513 PyObject *tmp = slots;
1514 PyObject *o, *o1;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001515 Py_ssize_t i;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001516 ssizessizeargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001517 for (i = 0; i < nslots; i++) {
1518 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1519 if (tmp == slots) {
1520 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1521 if (tmp == NULL)
1522 return NULL;
1523 }
1524 o1 = _PyUnicode_AsDefaultEncodedString
1525 (o, NULL);
1526 if (o1 == NULL) {
1527 Py_DECREF(tmp);
1528 return 0;
1529 }
1530 Py_INCREF(o1);
1531 Py_DECREF(o);
1532 PyTuple_SET_ITEM(tmp, i, o1);
1533 }
1534 }
1535 return tmp;
1536}
1537#endif
1538
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001539static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001540type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1541{
1542 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001543 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001544 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001545 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001546 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001547 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001548 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001549 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001550
Tim Peters3abca122001-10-27 19:37:48 +00001551 assert(args != NULL && PyTuple_Check(args));
1552 assert(kwds == NULL || PyDict_Check(kwds));
1553
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001554 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001555 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001556 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1557 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001558
1559 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1560 PyObject *x = PyTuple_GET_ITEM(args, 0);
1561 Py_INCREF(x->ob_type);
1562 return (PyObject *) x->ob_type;
1563 }
1564
1565 /* SF bug 475327 -- if that didn't trigger, we need 3
1566 arguments. but PyArg_ParseTupleAndKeywords below may give
1567 a msg saying type() needs exactly 3. */
1568 if (nargs + nkwds != 3) {
1569 PyErr_SetString(PyExc_TypeError,
1570 "type() takes 1 or 3 arguments");
1571 return NULL;
1572 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001573 }
1574
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001575 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001576 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1577 &name,
1578 &PyTuple_Type, &bases,
1579 &PyDict_Type, &dict))
1580 return NULL;
1581
1582 /* Determine the proper metatype to deal with this,
1583 and check for metatype conflicts while we're at it.
1584 Note that if some other metatype wins to contract,
1585 it's possible that its instances are not types. */
1586 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001587 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001588 for (i = 0; i < nbases; i++) {
1589 tmp = PyTuple_GET_ITEM(bases, i);
1590 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001591 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001592 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001593 if (PyType_IsSubtype(tmptype, winner)) {
1594 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001595 continue;
1596 }
1597 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001598 "metaclass conflict: "
1599 "the metaclass of a derived class "
1600 "must be a (non-strict) subclass "
1601 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001602 return NULL;
1603 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001604 if (winner != metatype) {
1605 if (winner->tp_new != type_new) /* Pass it to the winner */
1606 return winner->tp_new(winner, args, kwds);
1607 metatype = winner;
1608 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001609
1610 /* Adjust for empty tuple bases */
1611 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001612 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001613 if (bases == NULL)
1614 return NULL;
1615 nbases = 1;
1616 }
1617 else
1618 Py_INCREF(bases);
1619
1620 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1621
1622 /* Calculate best base, and check that all bases are type objects */
1623 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001624 if (base == NULL) {
1625 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001626 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001627 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001628 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1629 PyErr_Format(PyExc_TypeError,
1630 "type '%.100s' is not an acceptable base type",
1631 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001632 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001633 return NULL;
1634 }
1635
Tim Peters6d6c1a32001-08-02 04:15:00 +00001636 /* Check for a __slots__ sequence variable in dict, and count it */
1637 slots = PyDict_GetItemString(dict, "__slots__");
1638 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001639 add_dict = 0;
1640 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001641 may_add_dict = base->tp_dictoffset == 0;
1642 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1643 if (slots == NULL) {
1644 if (may_add_dict) {
1645 add_dict++;
1646 }
1647 if (may_add_weak) {
1648 add_weak++;
1649 }
1650 }
1651 else {
1652 /* Have slots */
1653
Tim Peters6d6c1a32001-08-02 04:15:00 +00001654 /* Make it into a tuple */
1655 if (PyString_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001656 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001657 else
1658 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001659 if (slots == NULL) {
1660 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001661 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001662 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001663 assert(PyTuple_Check(slots));
1664
1665 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001666 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001667 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001668 PyErr_Format(PyExc_TypeError,
1669 "nonempty __slots__ "
1670 "not supported for subtype of '%s'",
1671 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001672 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001673 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001674 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001675 return NULL;
1676 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001677
Martin v. Löwisd919a592002-10-14 21:07:28 +00001678#ifdef Py_USING_UNICODE
1679 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001680 if (tmp != slots) {
1681 Py_DECREF(slots);
1682 slots = tmp;
1683 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001684 if (!tmp)
1685 return NULL;
1686#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001687 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001688 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001689 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1690 char *s;
1691 if (!valid_identifier(tmp))
1692 goto bad_slots;
1693 assert(PyString_Check(tmp));
1694 s = PyString_AS_STRING(tmp);
1695 if (strcmp(s, "__dict__") == 0) {
1696 if (!may_add_dict || add_dict) {
1697 PyErr_SetString(PyExc_TypeError,
1698 "__dict__ slot disallowed: "
1699 "we already got one");
1700 goto bad_slots;
1701 }
1702 add_dict++;
1703 }
1704 if (strcmp(s, "__weakref__") == 0) {
1705 if (!may_add_weak || add_weak) {
1706 PyErr_SetString(PyExc_TypeError,
1707 "__weakref__ slot disallowed: "
1708 "either we already got one, "
1709 "or __itemsize__ != 0");
1710 goto bad_slots;
1711 }
1712 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001713 }
1714 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001715
Guido van Rossumad47da02002-08-12 19:05:44 +00001716 /* Copy slots into yet another tuple, demangling names */
1717 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001718 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001719 goto bad_slots;
1720 for (i = j = 0; i < nslots; i++) {
1721 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001722 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001723 s = PyString_AS_STRING(tmp);
1724 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1725 (add_weak && strcmp(s, "__weakref__") == 0))
1726 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001727 tmp =_Py_Mangle(name, tmp);
1728 if (!tmp)
1729 goto bad_slots;
Guido van Rossumad47da02002-08-12 19:05:44 +00001730 PyTuple_SET_ITEM(newslots, j, tmp);
1731 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001732 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001733 assert(j == nslots - add_dict - add_weak);
1734 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001735 Py_DECREF(slots);
1736 slots = newslots;
1737
Guido van Rossumad47da02002-08-12 19:05:44 +00001738 /* Secondary bases may provide weakrefs or dict */
1739 if (nbases > 1 &&
1740 ((may_add_dict && !add_dict) ||
1741 (may_add_weak && !add_weak))) {
1742 for (i = 0; i < nbases; i++) {
1743 tmp = PyTuple_GET_ITEM(bases, i);
1744 if (tmp == (PyObject *)base)
1745 continue; /* Skip primary base */
Guido van Rossumad47da02002-08-12 19:05:44 +00001746 assert(PyType_Check(tmp));
1747 tmptype = (PyTypeObject *)tmp;
1748 if (may_add_dict && !add_dict &&
1749 tmptype->tp_dictoffset != 0)
1750 add_dict++;
1751 if (may_add_weak && !add_weak &&
1752 tmptype->tp_weaklistoffset != 0)
1753 add_weak++;
1754 if (may_add_dict && !add_dict)
1755 continue;
1756 if (may_add_weak && !add_weak)
1757 continue;
1758 /* Nothing more to check */
1759 break;
1760 }
1761 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001762 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001763
1764 /* XXX From here until type is safely allocated,
1765 "return NULL" may leak slots! */
1766
1767 /* Allocate the type object */
1768 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001769 if (type == NULL) {
1770 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001771 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001772 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001773 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001774
1775 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001776 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001777 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00001778 et->ht_name = name;
1779 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001780
Guido van Rossumdc91b992001-08-08 22:26:22 +00001781 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001782 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1783 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001784 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1785 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001786
Guido van Rossumdc91b992001-08-08 22:26:22 +00001787 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001788 type->tp_as_number = &et->as_number;
1789 type->tp_as_sequence = &et->as_sequence;
1790 type->tp_as_mapping = &et->as_mapping;
1791 type->tp_as_buffer = &et->as_buffer;
1792 type->tp_name = PyString_AS_STRING(name);
1793
1794 /* Set tp_base and tp_bases */
1795 type->tp_bases = bases;
1796 Py_INCREF(base);
1797 type->tp_base = base;
1798
Guido van Rossum687ae002001-10-15 22:03:32 +00001799 /* Initialize tp_dict from passed-in dict */
1800 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001801 if (dict == NULL) {
1802 Py_DECREF(type);
1803 return NULL;
1804 }
1805
Guido van Rossumc3542212001-08-16 09:18:56 +00001806 /* Set __module__ in the dict */
1807 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1808 tmp = PyEval_GetGlobals();
1809 if (tmp != NULL) {
1810 tmp = PyDict_GetItemString(tmp, "__name__");
1811 if (tmp != NULL) {
1812 if (PyDict_SetItemString(dict, "__module__",
1813 tmp) < 0)
1814 return NULL;
1815 }
1816 }
1817 }
1818
Tim Peters2f93e282001-10-04 05:27:00 +00001819 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001820 and is a string. The __doc__ accessor will first look for tp_doc;
1821 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001822 */
1823 {
1824 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1825 if (doc != NULL && PyString_Check(doc)) {
1826 const size_t n = (size_t)PyString_GET_SIZE(doc);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001827 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001828 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00001829 Py_DECREF(type);
1830 return NULL;
1831 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001832 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
1833 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00001834 }
1835 }
1836
Tim Peters6d6c1a32001-08-02 04:15:00 +00001837 /* Special-case __new__: if it's a plain function,
1838 make it a static function */
1839 tmp = PyDict_GetItemString(dict, "__new__");
1840 if (tmp != NULL && PyFunction_Check(tmp)) {
1841 tmp = PyStaticMethod_New(tmp);
1842 if (tmp == NULL) {
1843 Py_DECREF(type);
1844 return NULL;
1845 }
1846 PyDict_SetItemString(dict, "__new__", tmp);
1847 Py_DECREF(tmp);
1848 }
1849
1850 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001851 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001852 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001853 if (slots != NULL) {
1854 for (i = 0; i < nslots; i++, mp++) {
1855 mp->name = PyString_AS_STRING(
1856 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001857 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001858 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001859 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001860 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001861 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001862 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001863 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001864 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001865 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001866 slotoffset += sizeof(PyObject *);
1867 }
1868 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001869 if (add_dict) {
1870 if (base->tp_itemsize)
1871 type->tp_dictoffset = -(long)sizeof(PyObject *);
1872 else
1873 type->tp_dictoffset = slotoffset;
1874 slotoffset += sizeof(PyObject *);
1875 }
1876 if (add_weak) {
1877 assert(!base->tp_itemsize);
1878 type->tp_weaklistoffset = slotoffset;
1879 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001880 }
1881 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001882 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001883 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001884
1885 if (type->tp_weaklistoffset && type->tp_dictoffset)
1886 type->tp_getset = subtype_getsets_full;
1887 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1888 type->tp_getset = subtype_getsets_weakref_only;
1889 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1890 type->tp_getset = subtype_getsets_dict_only;
1891 else
1892 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001893
1894 /* Special case some slots */
1895 if (type->tp_dictoffset != 0 || nslots > 0) {
1896 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1897 type->tp_getattro = PyObject_GenericGetAttr;
1898 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1899 type->tp_setattro = PyObject_GenericSetAttr;
1900 }
1901 type->tp_dealloc = subtype_dealloc;
1902
Guido van Rossum9475a232001-10-05 20:51:39 +00001903 /* Enable GC unless there are really no instance variables possible */
1904 if (!(type->tp_basicsize == sizeof(PyObject) &&
1905 type->tp_itemsize == 0))
1906 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1907
Tim Peters6d6c1a32001-08-02 04:15:00 +00001908 /* Always override allocation strategy to use regular heap */
1909 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001910 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001911 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001912 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001913 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001914 }
1915 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001916 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001917
1918 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001919 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001920 Py_DECREF(type);
1921 return NULL;
1922 }
1923
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001924 /* Put the proper slots in place */
1925 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001926
Tim Peters6d6c1a32001-08-02 04:15:00 +00001927 return (PyObject *)type;
1928}
1929
1930/* Internal API to look for a name through the MRO.
1931 This returns a borrowed reference, and doesn't set an exception! */
1932PyObject *
1933_PyType_Lookup(PyTypeObject *type, PyObject *name)
1934{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001935 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001936 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001937
Guido van Rossum687ae002001-10-15 22:03:32 +00001938 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001939 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001940
1941 /* If mro is NULL, the type is either not yet initialized
1942 by PyType_Ready(), or already cleared by type_clear().
1943 Either way the safest thing to do is to return NULL. */
1944 if (mro == NULL)
1945 return NULL;
1946
Tim Peters6d6c1a32001-08-02 04:15:00 +00001947 assert(PyTuple_Check(mro));
1948 n = PyTuple_GET_SIZE(mro);
1949 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001950 base = PyTuple_GET_ITEM(mro, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001951 assert(PyType_Check(base));
1952 dict = ((PyTypeObject *)base)->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001953 assert(dict && PyDict_Check(dict));
1954 res = PyDict_GetItem(dict, name);
1955 if (res != NULL)
1956 return res;
1957 }
1958 return NULL;
1959}
1960
1961/* This is similar to PyObject_GenericGetAttr(),
1962 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1963static PyObject *
1964type_getattro(PyTypeObject *type, PyObject *name)
1965{
1966 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001967 PyObject *meta_attribute, *attribute;
1968 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001969
1970 /* Initialize this type (we'll assume the metatype is initialized) */
1971 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001972 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001973 return NULL;
1974 }
1975
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001976 /* No readable descriptor found yet */
1977 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001978
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001979 /* Look for the attribute in the metatype */
1980 meta_attribute = _PyType_Lookup(metatype, name);
1981
1982 if (meta_attribute != NULL) {
1983 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001984
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001985 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1986 /* Data descriptors implement tp_descr_set to intercept
1987 * writes. Assume the attribute is not overridden in
1988 * type's tp_dict (and bases): call the descriptor now.
1989 */
1990 return meta_get(meta_attribute, (PyObject *)type,
1991 (PyObject *)metatype);
1992 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001993 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001994 }
1995
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001996 /* No data descriptor found on metatype. Look in tp_dict of this
1997 * type and its bases */
1998 attribute = _PyType_Lookup(type, name);
1999 if (attribute != NULL) {
2000 /* Implement descriptor functionality, if any */
2001 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002002
2003 Py_XDECREF(meta_attribute);
2004
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002005 if (local_get != NULL) {
2006 /* NULL 2nd argument indicates the descriptor was
2007 * found on the target object itself (or a base) */
2008 return local_get(attribute, (PyObject *)NULL,
2009 (PyObject *)type);
2010 }
Tim Peters34592512002-07-11 06:23:50 +00002011
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002012 Py_INCREF(attribute);
2013 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002014 }
2015
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002016 /* No attribute found in local __dict__ (or bases): use the
2017 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002018 if (meta_get != NULL) {
2019 PyObject *res;
2020 res = meta_get(meta_attribute, (PyObject *)type,
2021 (PyObject *)metatype);
2022 Py_DECREF(meta_attribute);
2023 return res;
2024 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002025
2026 /* If an ordinary attribute was found on the metatype, return it now */
2027 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002028 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002029 }
2030
2031 /* Give up */
2032 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002033 "type object '%.50s' has no attribute '%.400s'",
2034 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002035 return NULL;
2036}
2037
2038static int
2039type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2040{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002041 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2042 PyErr_Format(
2043 PyExc_TypeError,
2044 "can't set attributes of built-in/extension type '%s'",
2045 type->tp_name);
2046 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002047 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002048 /* XXX Example of how I expect this to be used...
2049 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2050 return -1;
2051 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002052 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2053 return -1;
2054 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002055}
2056
2057static void
2058type_dealloc(PyTypeObject *type)
2059{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002060 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002061
2062 /* Assert this is a heap-allocated type object */
2063 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002064 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002065 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002066 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002067 Py_XDECREF(type->tp_base);
2068 Py_XDECREF(type->tp_dict);
2069 Py_XDECREF(type->tp_bases);
2070 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002071 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002072 Py_XDECREF(type->tp_subclasses);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002073 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2074 * of most other objects. It's okay to cast it to char *.
2075 */
2076 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002077 Py_XDECREF(et->ht_name);
2078 Py_XDECREF(et->ht_slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002079 type->ob_type->tp_free((PyObject *)type);
2080}
2081
Guido van Rossum1c450732001-10-08 15:18:27 +00002082static PyObject *
2083type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2084{
2085 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002086 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002087
2088 list = PyList_New(0);
2089 if (list == NULL)
2090 return NULL;
2091 raw = type->tp_subclasses;
2092 if (raw == NULL)
2093 return list;
2094 assert(PyList_Check(raw));
2095 n = PyList_GET_SIZE(raw);
2096 for (i = 0; i < n; i++) {
2097 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002098 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002099 ref = PyWeakref_GET_OBJECT(ref);
2100 if (ref != Py_None) {
2101 if (PyList_Append(list, ref) < 0) {
2102 Py_DECREF(list);
2103 return NULL;
2104 }
2105 }
2106 }
2107 return list;
2108}
2109
Tim Peters6d6c1a32001-08-02 04:15:00 +00002110static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002111 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002112 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002113 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002114 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002115 {0}
2116};
2117
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002118PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002119"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002120"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002121
Guido van Rossum048eb752001-10-02 21:24:57 +00002122static int
2123type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2124{
Guido van Rossuma3862092002-06-10 15:24:42 +00002125 /* Because of type_is_gc(), the collector only calls this
2126 for heaptypes. */
2127 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002128
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002129 Py_VISIT(type->tp_dict);
2130 Py_VISIT(type->tp_cache);
2131 Py_VISIT(type->tp_mro);
2132 Py_VISIT(type->tp_bases);
2133 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002134
2135 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002136 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002137 in cycles; tp_subclasses is a list of weak references,
2138 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002139
Guido van Rossum048eb752001-10-02 21:24:57 +00002140 return 0;
2141}
2142
2143static int
2144type_clear(PyTypeObject *type)
2145{
Guido van Rossuma3862092002-06-10 15:24:42 +00002146 /* Because of type_is_gc(), the collector only calls this
2147 for heaptypes. */
2148 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002149
Guido van Rossuma3862092002-06-10 15:24:42 +00002150 /* The only field we need to clear is tp_mro, which is part of a
2151 hard cycle (its first element is the class itself) that won't
2152 be broken otherwise (it's a tuple and tuples don't have a
2153 tp_clear handler). None of the other fields need to be
2154 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002155
Guido van Rossuma3862092002-06-10 15:24:42 +00002156 tp_dict:
2157 It is a dict, so the collector will call its tp_clear.
2158
2159 tp_cache:
2160 Not used; if it were, it would be a dict.
2161
2162 tp_bases, tp_base:
2163 If these are involved in a cycle, there must be at least
2164 one other, mutable object in the cycle, e.g. a base
2165 class's dict; the cycle will be broken that way.
2166
2167 tp_subclasses:
2168 A list of weak references can't be part of a cycle; and
2169 lists have their own tp_clear.
2170
Guido van Rossume5c691a2003-03-07 15:13:17 +00002171 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002172 A tuple of strings can't be part of a cycle.
2173 */
2174
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002175 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002176
2177 return 0;
2178}
2179
2180static int
2181type_is_gc(PyTypeObject *type)
2182{
2183 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2184}
2185
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002186PyTypeObject PyType_Type = {
2187 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002188 0, /* ob_size */
2189 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002190 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002191 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002192 (destructor)type_dealloc, /* tp_dealloc */
2193 0, /* tp_print */
2194 0, /* tp_getattr */
2195 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002196 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002197 (reprfunc)type_repr, /* tp_repr */
2198 0, /* tp_as_number */
2199 0, /* tp_as_sequence */
2200 0, /* tp_as_mapping */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002201 0, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002202 (ternaryfunc)type_call, /* tp_call */
2203 0, /* tp_str */
2204 (getattrofunc)type_getattro, /* tp_getattro */
2205 (setattrofunc)type_setattro, /* tp_setattro */
2206 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002207 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Thomas Wouters27d517b2007-02-25 20:39:11 +00002208 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002209 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002210 (traverseproc)type_traverse, /* tp_traverse */
2211 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002212 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002213 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002214 0, /* tp_iter */
2215 0, /* tp_iternext */
2216 type_methods, /* tp_methods */
2217 type_members, /* tp_members */
2218 type_getsets, /* tp_getset */
2219 0, /* tp_base */
2220 0, /* tp_dict */
2221 0, /* tp_descr_get */
2222 0, /* tp_descr_set */
2223 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2224 0, /* tp_init */
2225 0, /* tp_alloc */
2226 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002227 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002228 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002229};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002230
2231
2232/* The base type of all types (eventually)... except itself. */
2233
2234static int
2235object_init(PyObject *self, PyObject *args, PyObject *kwds)
2236{
2237 return 0;
2238}
2239
Guido van Rossum298e4212003-02-13 16:30:16 +00002240/* If we don't have a tp_new for a new-style class, new will use this one.
2241 Therefore this should take no arguments/keywords. However, this new may
2242 also be inherited by objects that define a tp_init but no tp_new. These
2243 objects WILL pass argumets to tp_new, because it gets the same args as
2244 tp_init. So only allow arguments if we aren't using the default init, in
2245 which case we expect init to handle argument parsing. */
2246static PyObject *
2247object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2248{
2249 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2250 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2251 PyErr_SetString(PyExc_TypeError,
2252 "default __new__ takes no parameters");
2253 return NULL;
2254 }
2255 return type->tp_alloc(type, 0);
2256}
2257
Tim Peters6d6c1a32001-08-02 04:15:00 +00002258static void
2259object_dealloc(PyObject *self)
2260{
2261 self->ob_type->tp_free(self);
2262}
2263
Guido van Rossum8e248182001-08-12 05:17:56 +00002264static PyObject *
2265object_repr(PyObject *self)
2266{
Guido van Rossum76e69632001-08-16 18:52:43 +00002267 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002268 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002269
Guido van Rossum76e69632001-08-16 18:52:43 +00002270 type = self->ob_type;
2271 mod = type_module(type, NULL);
2272 if (mod == NULL)
2273 PyErr_Clear();
2274 else if (!PyString_Check(mod)) {
2275 Py_DECREF(mod);
2276 mod = NULL;
2277 }
2278 name = type_name(type, NULL);
2279 if (name == NULL)
2280 return NULL;
2281 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002282 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002283 PyString_AS_STRING(mod),
2284 PyString_AS_STRING(name),
2285 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002286 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002287 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002288 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002289 Py_XDECREF(mod);
2290 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002291 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002292}
2293
Guido van Rossumb8f63662001-08-15 23:57:02 +00002294static PyObject *
2295object_str(PyObject *self)
2296{
2297 unaryfunc f;
2298
2299 f = self->ob_type->tp_repr;
2300 if (f == NULL)
2301 f = object_repr;
2302 return f(self);
2303}
2304
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002305static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002306object_richcompare(PyObject *self, PyObject *other, int op)
2307{
2308 PyObject *res;
2309
2310 switch (op) {
2311
2312 case Py_EQ:
2313 res = (self == other) ? Py_True : Py_False;
Guido van Rossum6b18a5b2007-03-29 20:49:57 +00002314 Py_INCREF(res);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002315 break;
2316
2317 case Py_NE:
Guido van Rossume27dc722007-03-27 22:37:34 +00002318 /* By default, != returns the opposite of ==,
2319 unless the latter returns NotImplemented. */
2320 res = PyObject_RichCompare(self, other, Py_EQ);
2321 if (res != NULL && res != Py_NotImplemented) {
2322 int ok = PyObject_IsTrue(res);
2323 Py_DECREF(res);
2324 if (ok < 0)
2325 res = NULL;
2326 else {
2327 if (ok)
2328 res = Py_False;
2329 else
2330 res = Py_True;
2331 Py_INCREF(res);
2332 }
2333 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002334 break;
2335
2336 default:
2337 res = Py_NotImplemented;
Guido van Rossum6b18a5b2007-03-29 20:49:57 +00002338 Py_INCREF(res);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002339 break;
2340 }
2341
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002342 return res;
2343}
2344
2345static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002346object_get_class(PyObject *self, void *closure)
2347{
2348 Py_INCREF(self->ob_type);
2349 return (PyObject *)(self->ob_type);
2350}
2351
2352static int
2353equiv_structs(PyTypeObject *a, PyTypeObject *b)
2354{
2355 return a == b ||
2356 (a != NULL &&
2357 b != NULL &&
2358 a->tp_basicsize == b->tp_basicsize &&
2359 a->tp_itemsize == b->tp_itemsize &&
2360 a->tp_dictoffset == b->tp_dictoffset &&
2361 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2362 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2363 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2364}
2365
2366static int
2367same_slots_added(PyTypeObject *a, PyTypeObject *b)
2368{
2369 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002370 Py_ssize_t size;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002371
2372 if (base != b->tp_base)
2373 return 0;
2374 if (equiv_structs(a, base) && equiv_structs(b, base))
2375 return 1;
2376 size = base->tp_basicsize;
2377 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2378 size += sizeof(PyObject *);
2379 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2380 size += sizeof(PyObject *);
2381 return size == a->tp_basicsize && size == b->tp_basicsize;
2382}
2383
2384static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002385compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002386{
2387 PyTypeObject *newbase, *oldbase;
2388
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002389 if (newto->tp_dealloc != oldto->tp_dealloc ||
2390 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002391 {
2392 PyErr_Format(PyExc_TypeError,
2393 "%s assignment: "
2394 "'%s' deallocator differs from '%s'",
2395 attr,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002396 newto->tp_name,
2397 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002398 return 0;
2399 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002400 newbase = newto;
2401 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002402 while (equiv_structs(newbase, newbase->tp_base))
2403 newbase = newbase->tp_base;
2404 while (equiv_structs(oldbase, oldbase->tp_base))
2405 oldbase = oldbase->tp_base;
2406 if (newbase != oldbase &&
2407 (newbase->tp_base != oldbase->tp_base ||
2408 !same_slots_added(newbase, oldbase))) {
2409 PyErr_Format(PyExc_TypeError,
2410 "%s assignment: "
2411 "'%s' object layout differs from '%s'",
2412 attr,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002413 newto->tp_name,
2414 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002415 return 0;
2416 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002417
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002418 return 1;
2419}
2420
2421static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002422object_set_class(PyObject *self, PyObject *value, void *closure)
2423{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002424 PyTypeObject *oldto = self->ob_type;
2425 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002426
Guido van Rossumb6b89422002-04-15 01:03:30 +00002427 if (value == NULL) {
2428 PyErr_SetString(PyExc_TypeError,
2429 "can't delete __class__ attribute");
2430 return -1;
2431 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002432 if (!PyType_Check(value)) {
2433 PyErr_Format(PyExc_TypeError,
2434 "__class__ must be set to new-style class, not '%s' object",
2435 value->ob_type->tp_name);
2436 return -1;
2437 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002438 newto = (PyTypeObject *)value;
2439 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2440 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002441 {
2442 PyErr_Format(PyExc_TypeError,
2443 "__class__ assignment: only for heap types");
2444 return -1;
2445 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002446 if (compatible_for_assignment(newto, oldto, "__class__")) {
2447 Py_INCREF(newto);
2448 self->ob_type = newto;
2449 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002450 return 0;
2451 }
2452 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002453 return -1;
2454 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002455}
2456
2457static PyGetSetDef object_getsets[] = {
2458 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002459 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002460 {0}
2461};
2462
Guido van Rossumc53f0092003-02-18 22:05:12 +00002463
Guido van Rossum036f9992003-02-21 22:02:54 +00002464/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2465 We fall back to helpers in copy_reg for:
2466 - pickle protocols < 2
2467 - calculating the list of slot names (done only once per class)
2468 - the __newobj__ function (which is used as a token but never called)
2469*/
2470
2471static PyObject *
2472import_copy_reg(void)
2473{
2474 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002475
2476 if (!copy_reg_str) {
2477 copy_reg_str = PyString_InternFromString("copy_reg");
2478 if (copy_reg_str == NULL)
2479 return NULL;
2480 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002481
2482 return PyImport_Import(copy_reg_str);
2483}
2484
2485static PyObject *
2486slotnames(PyObject *cls)
2487{
2488 PyObject *clsdict;
2489 PyObject *copy_reg;
2490 PyObject *slotnames;
2491
2492 if (!PyType_Check(cls)) {
2493 Py_INCREF(Py_None);
2494 return Py_None;
2495 }
2496
2497 clsdict = ((PyTypeObject *)cls)->tp_dict;
2498 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002499 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002500 Py_INCREF(slotnames);
2501 return slotnames;
2502 }
2503
2504 copy_reg = import_copy_reg();
2505 if (copy_reg == NULL)
2506 return NULL;
2507
2508 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2509 Py_DECREF(copy_reg);
2510 if (slotnames != NULL &&
2511 slotnames != Py_None &&
2512 !PyList_Check(slotnames))
2513 {
2514 PyErr_SetString(PyExc_TypeError,
2515 "copy_reg._slotnames didn't return a list or None");
2516 Py_DECREF(slotnames);
2517 slotnames = NULL;
2518 }
2519
2520 return slotnames;
2521}
2522
2523static PyObject *
2524reduce_2(PyObject *obj)
2525{
2526 PyObject *cls, *getnewargs;
2527 PyObject *args = NULL, *args2 = NULL;
2528 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2529 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2530 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002531 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00002532
2533 cls = PyObject_GetAttrString(obj, "__class__");
2534 if (cls == NULL)
2535 return NULL;
2536
2537 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2538 if (getnewargs != NULL) {
2539 args = PyObject_CallObject(getnewargs, NULL);
2540 Py_DECREF(getnewargs);
2541 if (args != NULL && !PyTuple_Check(args)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002542 PyErr_Format(PyExc_TypeError,
2543 "__getnewargs__ should return a tuple, "
2544 "not '%.200s'", args->ob_type->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00002545 goto end;
2546 }
2547 }
2548 else {
2549 PyErr_Clear();
2550 args = PyTuple_New(0);
2551 }
2552 if (args == NULL)
2553 goto end;
2554
2555 getstate = PyObject_GetAttrString(obj, "__getstate__");
2556 if (getstate != NULL) {
2557 state = PyObject_CallObject(getstate, NULL);
2558 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002559 if (state == NULL)
2560 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002561 }
2562 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002563 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002564 state = PyObject_GetAttrString(obj, "__dict__");
2565 if (state == NULL) {
2566 PyErr_Clear();
2567 state = Py_None;
2568 Py_INCREF(state);
2569 }
2570 names = slotnames(cls);
2571 if (names == NULL)
2572 goto end;
2573 if (names != Py_None) {
2574 assert(PyList_Check(names));
2575 slots = PyDict_New();
2576 if (slots == NULL)
2577 goto end;
2578 n = 0;
2579 /* Can't pre-compute the list size; the list
2580 is stored on the class so accessible to other
2581 threads, which may be run by DECREF */
2582 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2583 PyObject *name, *value;
2584 name = PyList_GET_ITEM(names, i);
2585 value = PyObject_GetAttr(obj, name);
2586 if (value == NULL)
2587 PyErr_Clear();
2588 else {
2589 int err = PyDict_SetItem(slots, name,
2590 value);
2591 Py_DECREF(value);
2592 if (err)
2593 goto end;
2594 n++;
2595 }
2596 }
2597 if (n) {
2598 state = Py_BuildValue("(NO)", state, slots);
2599 if (state == NULL)
2600 goto end;
2601 }
2602 }
2603 }
2604
2605 if (!PyList_Check(obj)) {
2606 listitems = Py_None;
2607 Py_INCREF(listitems);
2608 }
2609 else {
2610 listitems = PyObject_GetIter(obj);
2611 if (listitems == NULL)
2612 goto end;
2613 }
2614
2615 if (!PyDict_Check(obj)) {
2616 dictitems = Py_None;
2617 Py_INCREF(dictitems);
2618 }
2619 else {
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002620 PyObject *items = PyObject_CallMethod(obj, "items", "");
2621 if (items == NULL)
2622 goto end;
2623 dictitems = PyObject_GetIter(items);
2624 Py_DECREF(items);
Guido van Rossum036f9992003-02-21 22:02:54 +00002625 if (dictitems == NULL)
2626 goto end;
2627 }
2628
2629 copy_reg = import_copy_reg();
2630 if (copy_reg == NULL)
2631 goto end;
2632 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2633 if (newobj == NULL)
2634 goto end;
2635
2636 n = PyTuple_GET_SIZE(args);
2637 args2 = PyTuple_New(n+1);
2638 if (args2 == NULL)
2639 goto end;
2640 PyTuple_SET_ITEM(args2, 0, cls);
2641 cls = NULL;
2642 for (i = 0; i < n; i++) {
2643 PyObject *v = PyTuple_GET_ITEM(args, i);
2644 Py_INCREF(v);
2645 PyTuple_SET_ITEM(args2, i+1, v);
2646 }
2647
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002648 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002649
2650 end:
2651 Py_XDECREF(cls);
2652 Py_XDECREF(args);
2653 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002654 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002655 Py_XDECREF(state);
2656 Py_XDECREF(names);
2657 Py_XDECREF(listitems);
2658 Py_XDECREF(dictitems);
2659 Py_XDECREF(copy_reg);
2660 Py_XDECREF(newobj);
2661 return res;
2662}
2663
2664static PyObject *
2665object_reduce_ex(PyObject *self, PyObject *args)
2666{
2667 /* Call copy_reg._reduce_ex(self, proto) */
2668 PyObject *reduce, *copy_reg, *res;
2669 int proto = 0;
2670
2671 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2672 return NULL;
2673
2674 reduce = PyObject_GetAttrString(self, "__reduce__");
2675 if (reduce == NULL)
2676 PyErr_Clear();
2677 else {
2678 PyObject *cls, *clsreduce, *objreduce;
2679 int override;
2680 cls = PyObject_GetAttrString(self, "__class__");
2681 if (cls == NULL) {
2682 Py_DECREF(reduce);
2683 return NULL;
2684 }
2685 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2686 Py_DECREF(cls);
2687 if (clsreduce == NULL) {
2688 Py_DECREF(reduce);
2689 return NULL;
2690 }
2691 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2692 "__reduce__");
2693 override = (clsreduce != objreduce);
2694 Py_DECREF(clsreduce);
2695 if (override) {
2696 res = PyObject_CallObject(reduce, NULL);
2697 Py_DECREF(reduce);
2698 return res;
2699 }
2700 else
2701 Py_DECREF(reduce);
2702 }
2703
2704 if (proto >= 2)
2705 return reduce_2(self);
2706
2707 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002708 if (!copy_reg)
2709 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002710
Guido van Rossumc53f0092003-02-18 22:05:12 +00002711 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002712 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002713
Guido van Rossum3926a632001-09-25 16:25:58 +00002714 return res;
2715}
2716
2717static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002718 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2719 PyDoc_STR("helper for pickle")},
2720 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002721 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002722 {0}
2723};
2724
Guido van Rossum036f9992003-02-21 22:02:54 +00002725
Tim Peters6d6c1a32001-08-02 04:15:00 +00002726PyTypeObject PyBaseObject_Type = {
2727 PyObject_HEAD_INIT(&PyType_Type)
2728 0, /* ob_size */
2729 "object", /* tp_name */
2730 sizeof(PyObject), /* tp_basicsize */
2731 0, /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002732 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002733 0, /* tp_print */
2734 0, /* tp_getattr */
2735 0, /* tp_setattr */
2736 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002737 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002738 0, /* tp_as_number */
2739 0, /* tp_as_sequence */
2740 0, /* tp_as_mapping */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002741 (hashfunc)_Py_HashPointer, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002742 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002743 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002744 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002745 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002746 0, /* tp_as_buffer */
2747 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002748 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002749 0, /* tp_traverse */
2750 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002751 object_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002752 0, /* tp_weaklistoffset */
2753 0, /* tp_iter */
2754 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002755 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002756 0, /* tp_members */
2757 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002758 0, /* tp_base */
2759 0, /* tp_dict */
2760 0, /* tp_descr_get */
2761 0, /* tp_descr_set */
2762 0, /* tp_dictoffset */
2763 object_init, /* tp_init */
2764 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002765 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002766 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002767};
2768
2769
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002770/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002771
2772static int
2773add_methods(PyTypeObject *type, PyMethodDef *meth)
2774{
Guido van Rossum687ae002001-10-15 22:03:32 +00002775 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002776
2777 for (; meth->ml_name != NULL; meth++) {
2778 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002779 if (PyDict_GetItemString(dict, meth->ml_name) &&
2780 !(meth->ml_flags & METH_COEXIST))
2781 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002782 if (meth->ml_flags & METH_CLASS) {
2783 if (meth->ml_flags & METH_STATIC) {
2784 PyErr_SetString(PyExc_ValueError,
2785 "method cannot be both class and static");
2786 return -1;
2787 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002788 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002789 }
2790 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002791 PyObject *cfunc = PyCFunction_New(meth, NULL);
2792 if (cfunc == NULL)
2793 return -1;
2794 descr = PyStaticMethod_New(cfunc);
2795 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002796 }
2797 else {
2798 descr = PyDescr_NewMethod(type, meth);
2799 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002800 if (descr == NULL)
2801 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002802 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002803 return -1;
2804 Py_DECREF(descr);
2805 }
2806 return 0;
2807}
2808
2809static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002810add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002811{
Guido van Rossum687ae002001-10-15 22:03:32 +00002812 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002813
2814 for (; memb->name != NULL; memb++) {
2815 PyObject *descr;
2816 if (PyDict_GetItemString(dict, memb->name))
2817 continue;
2818 descr = PyDescr_NewMember(type, memb);
2819 if (descr == NULL)
2820 return -1;
2821 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2822 return -1;
2823 Py_DECREF(descr);
2824 }
2825 return 0;
2826}
2827
2828static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002829add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002830{
Guido van Rossum687ae002001-10-15 22:03:32 +00002831 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002832
2833 for (; gsp->name != NULL; gsp++) {
2834 PyObject *descr;
2835 if (PyDict_GetItemString(dict, gsp->name))
2836 continue;
2837 descr = PyDescr_NewGetSet(type, gsp);
2838
2839 if (descr == NULL)
2840 return -1;
2841 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2842 return -1;
2843 Py_DECREF(descr);
2844 }
2845 return 0;
2846}
2847
Guido van Rossum13d52f02001-08-10 21:24:08 +00002848static void
2849inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002850{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002851 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002852
Guido van Rossum13d52f02001-08-10 21:24:08 +00002853 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002854 oldsize = base->tp_basicsize;
2855 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2856 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2857 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002858 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002859 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002860 if (type->tp_traverse == NULL)
2861 type->tp_traverse = base->tp_traverse;
2862 if (type->tp_clear == NULL)
2863 type->tp_clear = base->tp_clear;
2864 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002865 {
Guido van Rossumf884b742001-12-17 17:14:22 +00002866 /* The condition below could use some explanation.
2867 It appears that tp_new is not inherited for static types
2868 whose base class is 'object'; this seems to be a precaution
2869 so that old extension types don't suddenly become
2870 callable (object.__new__ wouldn't insure the invariants
2871 that the extension type's own factory function ensures).
2872 Heap types, of course, are under our control, so they do
2873 inherit tp_new; static extension types that specify some
2874 other built-in type as the default are considered
2875 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002876 if (base != &PyBaseObject_Type ||
2877 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2878 if (type->tp_new == NULL)
2879 type->tp_new = base->tp_new;
2880 }
2881 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002882 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002883
2884 /* Copy other non-function slots */
2885
2886#undef COPYVAL
2887#define COPYVAL(SLOT) \
2888 if (type->SLOT == 0) type->SLOT = base->SLOT
2889
2890 COPYVAL(tp_itemsize);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002891 COPYVAL(tp_weaklistoffset);
2892 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00002893
2894 /* Setup fast subclass flags */
2895 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
2896 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
2897 else if (PyType_IsSubtype(base, &PyType_Type))
2898 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
2899 else if (PyType_IsSubtype(base, &PyLong_Type))
2900 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
2901 else if (PyType_IsSubtype(base, &PyString_Type))
2902 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
2903 else if (PyType_IsSubtype(base, &PyUnicode_Type))
2904 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
2905 else if (PyType_IsSubtype(base, &PyTuple_Type))
2906 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
2907 else if (PyType_IsSubtype(base, &PyList_Type))
2908 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
2909 else if (PyType_IsSubtype(base, &PyDict_Type))
2910 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002911}
2912
Guido van Rossum38938152006-08-21 23:36:26 +00002913/* Map rich comparison operators to their __xx__ namesakes */
2914static char *name_op[] = {
2915 "__lt__",
2916 "__le__",
2917 "__eq__",
2918 "__ne__",
2919 "__gt__",
2920 "__ge__",
2921 /* These are only for overrides_cmp_or_hash(): */
2922 "__cmp__",
2923 "__hash__",
2924};
2925
2926static int
2927overrides_cmp_or_hash(PyTypeObject *type)
2928{
2929 int i;
2930 PyObject *dict = type->tp_dict;
2931
2932 assert(dict != NULL);
2933 for (i = 0; i < 8; i++) {
2934 if (PyDict_GetItemString(dict, name_op[i]) != NULL)
2935 return 1;
2936 }
2937 return 0;
2938}
2939
Guido van Rossum13d52f02001-08-10 21:24:08 +00002940static void
2941inherit_slots(PyTypeObject *type, PyTypeObject *base)
2942{
2943 PyTypeObject *basebase;
2944
2945#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002946#undef COPYSLOT
2947#undef COPYNUM
2948#undef COPYSEQ
2949#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002950#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002951
2952#define SLOTDEFINED(SLOT) \
2953 (base->SLOT != 0 && \
2954 (basebase == NULL || base->SLOT != basebase->SLOT))
2955
Tim Peters6d6c1a32001-08-02 04:15:00 +00002956#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002957 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002958
2959#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2960#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2961#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002962#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002963
Guido van Rossum13d52f02001-08-10 21:24:08 +00002964 /* This won't inherit indirect slots (from tp_as_number etc.)
2965 if type doesn't provide the space. */
2966
2967 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2968 basebase = base->tp_base;
2969 if (basebase->tp_as_number == NULL)
2970 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002971 COPYNUM(nb_add);
2972 COPYNUM(nb_subtract);
2973 COPYNUM(nb_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002974 COPYNUM(nb_remainder);
2975 COPYNUM(nb_divmod);
2976 COPYNUM(nb_power);
2977 COPYNUM(nb_negative);
2978 COPYNUM(nb_positive);
2979 COPYNUM(nb_absolute);
Jack Diederich4dafcc42006-11-28 19:15:13 +00002980 COPYNUM(nb_bool);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002981 COPYNUM(nb_invert);
2982 COPYNUM(nb_lshift);
2983 COPYNUM(nb_rshift);
2984 COPYNUM(nb_and);
2985 COPYNUM(nb_xor);
2986 COPYNUM(nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002987 COPYNUM(nb_int);
2988 COPYNUM(nb_long);
2989 COPYNUM(nb_float);
2990 COPYNUM(nb_oct);
2991 COPYNUM(nb_hex);
2992 COPYNUM(nb_inplace_add);
2993 COPYNUM(nb_inplace_subtract);
2994 COPYNUM(nb_inplace_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002995 COPYNUM(nb_inplace_remainder);
2996 COPYNUM(nb_inplace_power);
2997 COPYNUM(nb_inplace_lshift);
2998 COPYNUM(nb_inplace_rshift);
2999 COPYNUM(nb_inplace_and);
3000 COPYNUM(nb_inplace_xor);
3001 COPYNUM(nb_inplace_or);
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003002 COPYNUM(nb_true_divide);
3003 COPYNUM(nb_floor_divide);
3004 COPYNUM(nb_inplace_true_divide);
3005 COPYNUM(nb_inplace_floor_divide);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003006 COPYNUM(nb_index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003007 }
3008
Guido van Rossum13d52f02001-08-10 21:24:08 +00003009 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3010 basebase = base->tp_base;
3011 if (basebase->tp_as_sequence == NULL)
3012 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003013 COPYSEQ(sq_length);
3014 COPYSEQ(sq_concat);
3015 COPYSEQ(sq_repeat);
3016 COPYSEQ(sq_item);
3017 COPYSEQ(sq_slice);
3018 COPYSEQ(sq_ass_item);
3019 COPYSEQ(sq_ass_slice);
3020 COPYSEQ(sq_contains);
3021 COPYSEQ(sq_inplace_concat);
3022 COPYSEQ(sq_inplace_repeat);
3023 }
3024
Guido van Rossum13d52f02001-08-10 21:24:08 +00003025 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3026 basebase = base->tp_base;
3027 if (basebase->tp_as_mapping == NULL)
3028 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003029 COPYMAP(mp_length);
3030 COPYMAP(mp_subscript);
3031 COPYMAP(mp_ass_subscript);
3032 }
3033
Tim Petersfc57ccb2001-10-12 02:38:24 +00003034 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3035 basebase = base->tp_base;
3036 if (basebase->tp_as_buffer == NULL)
3037 basebase = NULL;
3038 COPYBUF(bf_getreadbuffer);
3039 COPYBUF(bf_getwritebuffer);
3040 COPYBUF(bf_getsegcount);
3041 COPYBUF(bf_getcharbuffer);
3042 }
3043
Guido van Rossum13d52f02001-08-10 21:24:08 +00003044 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003045
Tim Peters6d6c1a32001-08-02 04:15:00 +00003046 COPYSLOT(tp_dealloc);
3047 COPYSLOT(tp_print);
3048 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3049 type->tp_getattr = base->tp_getattr;
3050 type->tp_getattro = base->tp_getattro;
3051 }
3052 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3053 type->tp_setattr = base->tp_setattr;
3054 type->tp_setattro = base->tp_setattro;
3055 }
3056 /* tp_compare see tp_richcompare */
3057 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003058 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003059 COPYSLOT(tp_call);
3060 COPYSLOT(tp_str);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003061 {
Guido van Rossum38938152006-08-21 23:36:26 +00003062 /* Copy comparison-related slots only when
3063 not overriding them anywhere */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003064 if (type->tp_compare == NULL &&
3065 type->tp_richcompare == NULL &&
Guido van Rossum38938152006-08-21 23:36:26 +00003066 type->tp_hash == NULL &&
3067 !overrides_cmp_or_hash(type))
Guido van Rossumb8f63662001-08-15 23:57:02 +00003068 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003069 type->tp_compare = base->tp_compare;
3070 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003071 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003072 }
3073 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003074 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003075 COPYSLOT(tp_iter);
3076 COPYSLOT(tp_iternext);
3077 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003078 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003079 COPYSLOT(tp_descr_get);
3080 COPYSLOT(tp_descr_set);
3081 COPYSLOT(tp_dictoffset);
3082 COPYSLOT(tp_init);
3083 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003084 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003085 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3086 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3087 /* They agree about gc. */
3088 COPYSLOT(tp_free);
3089 }
3090 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3091 type->tp_free == NULL &&
3092 base->tp_free == _PyObject_Del) {
3093 /* A bit of magic to plug in the correct default
3094 * tp_free function when a derived class adds gc,
3095 * didn't define tp_free, and the base uses the
3096 * default non-gc tp_free.
3097 */
3098 type->tp_free = PyObject_GC_Del;
3099 }
3100 /* else they didn't agree about gc, and there isn't something
3101 * obvious to be done -- the type is on its own.
3102 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003103 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003104}
3105
Jeremy Hylton938ace62002-07-17 16:30:39 +00003106static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003107
Tim Peters6d6c1a32001-08-02 04:15:00 +00003108int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003109PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003110{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003111 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003112 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003113 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003114
Guido van Rossumcab05802002-06-10 15:29:03 +00003115 if (type->tp_flags & Py_TPFLAGS_READY) {
3116 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003117 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003118 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003119 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003120
3121 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003122
Tim Peters36eb4df2003-03-23 03:33:13 +00003123#ifdef Py_TRACE_REFS
3124 /* PyType_Ready is the closest thing we have to a choke point
3125 * for type objects, so is the best place I can think of to try
3126 * to get type objects into the doubly-linked list of all objects.
3127 * Still, not all type objects go thru PyType_Ready.
3128 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003129 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003130#endif
3131
Tim Peters6d6c1a32001-08-02 04:15:00 +00003132 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3133 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003134 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003135 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003136 Py_INCREF(base);
3137 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003138
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003139 /* Now the only way base can still be NULL is if type is
3140 * &PyBaseObject_Type.
3141 */
3142
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003143 /* Initialize the base class */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003144 if (base != NULL && base->tp_dict == NULL) {
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003145 if (PyType_Ready(base) < 0)
3146 goto error;
3147 }
3148
Guido van Rossum0986d822002-04-08 01:38:42 +00003149 /* Initialize ob_type if NULL. This means extensions that want to be
3150 compilable separately on Windows can call PyType_Ready() instead of
3151 initializing the ob_type field of their type objects. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003152 /* The test for base != NULL is really unnecessary, since base is only
3153 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3154 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3155 know that. */
3156 if (type->ob_type == NULL && base != NULL)
Guido van Rossum0986d822002-04-08 01:38:42 +00003157 type->ob_type = base->ob_type;
3158
Tim Peters6d6c1a32001-08-02 04:15:00 +00003159 /* Initialize tp_bases */
3160 bases = type->tp_bases;
3161 if (bases == NULL) {
3162 if (base == NULL)
3163 bases = PyTuple_New(0);
3164 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003165 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003166 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003167 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003168 type->tp_bases = bases;
3169 }
3170
Guido van Rossum687ae002001-10-15 22:03:32 +00003171 /* Initialize tp_dict */
3172 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003173 if (dict == NULL) {
3174 dict = PyDict_New();
3175 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003176 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003177 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003178 }
3179
Guido van Rossum687ae002001-10-15 22:03:32 +00003180 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003181 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003182 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003183 if (type->tp_methods != NULL) {
3184 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003185 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003186 }
3187 if (type->tp_members != NULL) {
3188 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003189 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003190 }
3191 if (type->tp_getset != NULL) {
3192 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003193 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003194 }
3195
Tim Peters6d6c1a32001-08-02 04:15:00 +00003196 /* Calculate method resolution order */
3197 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003198 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003199 }
3200
Guido van Rossum13d52f02001-08-10 21:24:08 +00003201 /* Inherit special flags from dominant base */
3202 if (type->tp_base != NULL)
3203 inherit_special(type, type->tp_base);
3204
Tim Peters6d6c1a32001-08-02 04:15:00 +00003205 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003206 bases = type->tp_mro;
3207 assert(bases != NULL);
3208 assert(PyTuple_Check(bases));
3209 n = PyTuple_GET_SIZE(bases);
3210 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003211 PyObject *b = PyTuple_GET_ITEM(bases, i);
3212 if (PyType_Check(b))
3213 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003214 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003215
Tim Peters3cfe7542003-05-21 21:29:48 +00003216 /* Sanity check for tp_free. */
3217 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3218 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3219 /* This base class needs to call tp_free, but doesn't have
3220 * one, or its tp_free is for non-gc'ed objects.
3221 */
3222 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3223 "gc and is a base type but has inappropriate "
3224 "tp_free slot",
3225 type->tp_name);
3226 goto error;
3227 }
3228
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003229 /* if the type dictionary doesn't contain a __doc__, set it from
3230 the tp_doc slot.
3231 */
3232 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3233 if (type->tp_doc != NULL) {
3234 PyObject *doc = PyString_FromString(type->tp_doc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003235 if (doc == NULL)
3236 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003237 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3238 Py_DECREF(doc);
3239 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003240 PyDict_SetItemString(type->tp_dict,
3241 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003242 }
3243 }
3244
Guido van Rossum38938152006-08-21 23:36:26 +00003245 /* Hack for tp_hash and __hash__.
3246 If after all that, tp_hash is still NULL, and __hash__ is not in
3247 tp_dict, set tp_dict['__hash__'] equal to None.
3248 This signals that __hash__ is not inherited.
3249 */
3250 if (type->tp_hash == NULL) {
3251 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
3252 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3253 goto error;
3254 }
3255 }
3256
Guido van Rossum13d52f02001-08-10 21:24:08 +00003257 /* Some more special stuff */
3258 base = type->tp_base;
3259 if (base != NULL) {
3260 if (type->tp_as_number == NULL)
3261 type->tp_as_number = base->tp_as_number;
3262 if (type->tp_as_sequence == NULL)
3263 type->tp_as_sequence = base->tp_as_sequence;
3264 if (type->tp_as_mapping == NULL)
3265 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003266 if (type->tp_as_buffer == NULL)
3267 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003268 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003269
Guido van Rossum1c450732001-10-08 15:18:27 +00003270 /* Link into each base class's list of subclasses */
3271 bases = type->tp_bases;
3272 n = PyTuple_GET_SIZE(bases);
3273 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003274 PyObject *b = PyTuple_GET_ITEM(bases, i);
3275 if (PyType_Check(b) &&
3276 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003277 goto error;
3278 }
3279
Guido van Rossum13d52f02001-08-10 21:24:08 +00003280 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003281 assert(type->tp_dict != NULL);
3282 type->tp_flags =
3283 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003284 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003285
3286 error:
3287 type->tp_flags &= ~Py_TPFLAGS_READYING;
3288 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003289}
3290
Guido van Rossum1c450732001-10-08 15:18:27 +00003291static int
3292add_subclass(PyTypeObject *base, PyTypeObject *type)
3293{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003294 Py_ssize_t i;
3295 int result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003296 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003297
3298 list = base->tp_subclasses;
3299 if (list == NULL) {
3300 base->tp_subclasses = list = PyList_New(0);
3301 if (list == NULL)
3302 return -1;
3303 }
3304 assert(PyList_Check(list));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003305 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003306 i = PyList_GET_SIZE(list);
3307 while (--i >= 0) {
3308 ref = PyList_GET_ITEM(list, i);
3309 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003310 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003311 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003312 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003313 result = PyList_Append(list, newobj);
3314 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003315 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003316}
3317
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003318static void
3319remove_subclass(PyTypeObject *base, PyTypeObject *type)
3320{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003321 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003322 PyObject *list, *ref;
3323
3324 list = base->tp_subclasses;
3325 if (list == NULL) {
3326 return;
3327 }
3328 assert(PyList_Check(list));
3329 i = PyList_GET_SIZE(list);
3330 while (--i >= 0) {
3331 ref = PyList_GET_ITEM(list, i);
3332 assert(PyWeakref_CheckRef(ref));
3333 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3334 /* this can't fail, right? */
3335 PySequence_DelItem(list, i);
3336 return;
3337 }
3338 }
3339}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003340
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003341static int
3342check_num_args(PyObject *ob, int n)
3343{
3344 if (!PyTuple_CheckExact(ob)) {
3345 PyErr_SetString(PyExc_SystemError,
3346 "PyArg_UnpackTuple() argument list is not a tuple");
3347 return 0;
3348 }
3349 if (n == PyTuple_GET_SIZE(ob))
3350 return 1;
3351 PyErr_Format(
3352 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003353 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003354 return 0;
3355}
3356
Tim Peters6d6c1a32001-08-02 04:15:00 +00003357/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3358
3359/* There's a wrapper *function* for each distinct function typedef used
3360 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3361 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3362 Most tables have only one entry; the tables for binary operators have two
3363 entries, one regular and one with reversed arguments. */
3364
3365static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003366wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003367{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003368 lenfunc func = (lenfunc)wrapped;
3369 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003370
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003371 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003372 return NULL;
3373 res = (*func)(self);
3374 if (res == -1 && PyErr_Occurred())
3375 return NULL;
3376 return PyInt_FromLong((long)res);
3377}
3378
Tim Peters6d6c1a32001-08-02 04:15:00 +00003379static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003380wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3381{
3382 inquiry func = (inquiry)wrapped;
3383 int res;
3384
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003385 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003386 return NULL;
3387 res = (*func)(self);
3388 if (res == -1 && PyErr_Occurred())
3389 return NULL;
3390 return PyBool_FromLong((long)res);
3391}
3392
3393static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003394wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3395{
3396 binaryfunc func = (binaryfunc)wrapped;
3397 PyObject *other;
3398
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003399 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003400 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003401 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003402 return (*func)(self, other);
3403}
3404
3405static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003406wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3407{
3408 binaryfunc func = (binaryfunc)wrapped;
3409 PyObject *other;
3410
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003411 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003412 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003413 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003414 return (*func)(self, other);
3415}
3416
3417static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003418wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3419{
3420 binaryfunc func = (binaryfunc)wrapped;
3421 PyObject *other;
3422
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003423 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003424 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003425 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003426 if (!PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003427 Py_INCREF(Py_NotImplemented);
3428 return Py_NotImplemented;
3429 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003430 return (*func)(other, self);
3431}
3432
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003433static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003434wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3435{
3436 ternaryfunc func = (ternaryfunc)wrapped;
3437 PyObject *other;
3438 PyObject *third = Py_None;
3439
3440 /* Note: This wrapper only works for __pow__() */
3441
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003442 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003443 return NULL;
3444 return (*func)(self, other, third);
3445}
3446
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003447static PyObject *
3448wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3449{
3450 ternaryfunc func = (ternaryfunc)wrapped;
3451 PyObject *other;
3452 PyObject *third = Py_None;
3453
3454 /* Note: This wrapper only works for __pow__() */
3455
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003456 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003457 return NULL;
3458 return (*func)(other, self, third);
3459}
3460
Tim Peters6d6c1a32001-08-02 04:15:00 +00003461static PyObject *
3462wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3463{
3464 unaryfunc func = (unaryfunc)wrapped;
3465
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003466 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003467 return NULL;
3468 return (*func)(self);
3469}
3470
Tim Peters6d6c1a32001-08-02 04:15:00 +00003471static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003472wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003473{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003474 ssizeargfunc func = (ssizeargfunc)wrapped;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003475 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003476 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003477
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003478 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
3479 return NULL;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003480 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003481 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003482 return NULL;
3483 return (*func)(self, i);
3484}
3485
Martin v. Löwis18e16552006-02-15 17:27:45 +00003486static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00003487getindex(PyObject *self, PyObject *arg)
3488{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003489 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003490
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003491 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003492 if (i == -1 && PyErr_Occurred())
3493 return -1;
3494 if (i < 0) {
3495 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3496 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003497 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003498 if (n < 0)
3499 return -1;
3500 i += n;
3501 }
3502 }
3503 return i;
3504}
3505
3506static PyObject *
3507wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3508{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003509 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003510 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003511 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003512
Guido van Rossumf4593e02001-10-03 12:09:30 +00003513 if (PyTuple_GET_SIZE(args) == 1) {
3514 arg = PyTuple_GET_ITEM(args, 0);
3515 i = getindex(self, arg);
3516 if (i == -1 && PyErr_Occurred())
3517 return NULL;
3518 return (*func)(self, i);
3519 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003520 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003521 assert(PyErr_Occurred());
3522 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003523}
3524
Tim Peters6d6c1a32001-08-02 04:15:00 +00003525static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003526wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003527{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003528 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
3529 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003530
Martin v. Löwis18e16552006-02-15 17:27:45 +00003531 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003532 return NULL;
3533 return (*func)(self, i, j);
3534}
3535
Tim Peters6d6c1a32001-08-02 04:15:00 +00003536static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003537wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003538{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003539 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3540 Py_ssize_t i;
3541 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003542 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003543
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003544 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003545 return NULL;
3546 i = getindex(self, arg);
3547 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003548 return NULL;
3549 res = (*func)(self, i, value);
3550 if (res == -1 && PyErr_Occurred())
3551 return NULL;
3552 Py_INCREF(Py_None);
3553 return Py_None;
3554}
3555
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003556static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003557wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003558{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003559 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3560 Py_ssize_t i;
3561 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003562 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003563
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003564 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003565 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003566 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003567 i = getindex(self, arg);
3568 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003569 return NULL;
3570 res = (*func)(self, i, NULL);
3571 if (res == -1 && PyErr_Occurred())
3572 return NULL;
3573 Py_INCREF(Py_None);
3574 return Py_None;
3575}
3576
Tim Peters6d6c1a32001-08-02 04:15:00 +00003577static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003578wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003579{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003580 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3581 Py_ssize_t i, j;
3582 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003583 PyObject *value;
3584
Martin v. Löwis18e16552006-02-15 17:27:45 +00003585 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003586 return NULL;
3587 res = (*func)(self, i, j, value);
3588 if (res == -1 && PyErr_Occurred())
3589 return NULL;
3590 Py_INCREF(Py_None);
3591 return Py_None;
3592}
3593
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003594static PyObject *
3595wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3596{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003597 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3598 Py_ssize_t i, j;
3599 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003600
Martin v. Löwis18e16552006-02-15 17:27:45 +00003601 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003602 return NULL;
3603 res = (*func)(self, i, j, NULL);
3604 if (res == -1 && PyErr_Occurred())
3605 return NULL;
3606 Py_INCREF(Py_None);
3607 return Py_None;
3608}
3609
Tim Peters6d6c1a32001-08-02 04:15:00 +00003610/* XXX objobjproc is a misnomer; should be objargpred */
3611static PyObject *
3612wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3613{
3614 objobjproc func = (objobjproc)wrapped;
3615 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003616 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003617
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003618 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003619 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003620 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003621 res = (*func)(self, value);
3622 if (res == -1 && PyErr_Occurred())
3623 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003624 else
3625 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003626}
3627
Tim Peters6d6c1a32001-08-02 04:15:00 +00003628static PyObject *
3629wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3630{
3631 objobjargproc func = (objobjargproc)wrapped;
3632 int res;
3633 PyObject *key, *value;
3634
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003635 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003636 return NULL;
3637 res = (*func)(self, key, value);
3638 if (res == -1 && PyErr_Occurred())
3639 return NULL;
3640 Py_INCREF(Py_None);
3641 return Py_None;
3642}
3643
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003644static PyObject *
3645wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3646{
3647 objobjargproc func = (objobjargproc)wrapped;
3648 int res;
3649 PyObject *key;
3650
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003651 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003652 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003653 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003654 res = (*func)(self, key, NULL);
3655 if (res == -1 && PyErr_Occurred())
3656 return NULL;
3657 Py_INCREF(Py_None);
3658 return Py_None;
3659}
3660
Tim Peters6d6c1a32001-08-02 04:15:00 +00003661static PyObject *
3662wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3663{
3664 cmpfunc func = (cmpfunc)wrapped;
3665 int res;
3666 PyObject *other;
3667
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003668 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003669 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003670 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003671 if (other->ob_type->tp_compare != func &&
3672 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003673 PyErr_Format(
3674 PyExc_TypeError,
3675 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3676 self->ob_type->tp_name,
3677 self->ob_type->tp_name,
3678 other->ob_type->tp_name);
3679 return NULL;
3680 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003681 res = (*func)(self, other);
3682 if (PyErr_Occurred())
3683 return NULL;
3684 return PyInt_FromLong((long)res);
3685}
3686
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003687/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003688 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003689static int
3690hackcheck(PyObject *self, setattrofunc func, char *what)
3691{
3692 PyTypeObject *type = self->ob_type;
3693 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3694 type = type->tp_base;
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003695 /* If type is NULL now, this is a really weird type.
Thomas Wouters89f507f2006-12-13 04:49:30 +00003696 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003697 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003698 PyErr_Format(PyExc_TypeError,
3699 "can't apply this %s to %s object",
3700 what,
3701 type->tp_name);
3702 return 0;
3703 }
3704 return 1;
3705}
3706
Tim Peters6d6c1a32001-08-02 04:15:00 +00003707static PyObject *
3708wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3709{
3710 setattrofunc func = (setattrofunc)wrapped;
3711 int res;
3712 PyObject *name, *value;
3713
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003714 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003715 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003716 if (!hackcheck(self, func, "__setattr__"))
3717 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003718 res = (*func)(self, name, value);
3719 if (res < 0)
3720 return NULL;
3721 Py_INCREF(Py_None);
3722 return Py_None;
3723}
3724
3725static PyObject *
3726wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3727{
3728 setattrofunc func = (setattrofunc)wrapped;
3729 int res;
3730 PyObject *name;
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 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003735 if (!hackcheck(self, func, "__delattr__"))
3736 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003737 res = (*func)(self, name, NULL);
3738 if (res < 0)
3739 return NULL;
3740 Py_INCREF(Py_None);
3741 return Py_None;
3742}
3743
Tim Peters6d6c1a32001-08-02 04:15:00 +00003744static PyObject *
3745wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3746{
3747 hashfunc func = (hashfunc)wrapped;
3748 long res;
3749
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003750 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003751 return NULL;
3752 res = (*func)(self);
3753 if (res == -1 && PyErr_Occurred())
3754 return NULL;
3755 return PyInt_FromLong(res);
3756}
3757
Tim Peters6d6c1a32001-08-02 04:15:00 +00003758static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003759wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003760{
3761 ternaryfunc func = (ternaryfunc)wrapped;
3762
Guido van Rossumc8e56452001-10-22 00:43:43 +00003763 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003764}
3765
Tim Peters6d6c1a32001-08-02 04:15:00 +00003766static PyObject *
3767wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3768{
3769 richcmpfunc func = (richcmpfunc)wrapped;
3770 PyObject *other;
3771
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003772 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003773 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003774 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003775 return (*func)(self, other, op);
3776}
3777
3778#undef RICHCMP_WRAPPER
3779#define RICHCMP_WRAPPER(NAME, OP) \
3780static PyObject * \
3781richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3782{ \
3783 return wrap_richcmpfunc(self, args, wrapped, OP); \
3784}
3785
Jack Jansen8e938b42001-08-08 15:29:49 +00003786RICHCMP_WRAPPER(lt, Py_LT)
3787RICHCMP_WRAPPER(le, Py_LE)
3788RICHCMP_WRAPPER(eq, Py_EQ)
3789RICHCMP_WRAPPER(ne, Py_NE)
3790RICHCMP_WRAPPER(gt, Py_GT)
3791RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003792
Tim Peters6d6c1a32001-08-02 04:15:00 +00003793static PyObject *
3794wrap_next(PyObject *self, PyObject *args, void *wrapped)
3795{
3796 unaryfunc func = (unaryfunc)wrapped;
3797 PyObject *res;
3798
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003799 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003800 return NULL;
3801 res = (*func)(self);
3802 if (res == NULL && !PyErr_Occurred())
3803 PyErr_SetNone(PyExc_StopIteration);
3804 return res;
3805}
3806
Tim Peters6d6c1a32001-08-02 04:15:00 +00003807static PyObject *
3808wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3809{
3810 descrgetfunc func = (descrgetfunc)wrapped;
3811 PyObject *obj;
3812 PyObject *type = NULL;
3813
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003814 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003815 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003816 if (obj == Py_None)
3817 obj = NULL;
3818 if (type == Py_None)
3819 type = NULL;
3820 if (type == NULL &&obj == NULL) {
3821 PyErr_SetString(PyExc_TypeError,
3822 "__get__(None, None) is invalid");
3823 return NULL;
3824 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003825 return (*func)(self, obj, type);
3826}
3827
Tim Peters6d6c1a32001-08-02 04:15:00 +00003828static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003829wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003830{
3831 descrsetfunc func = (descrsetfunc)wrapped;
3832 PyObject *obj, *value;
3833 int ret;
3834
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003835 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003836 return NULL;
3837 ret = (*func)(self, obj, value);
3838 if (ret < 0)
3839 return NULL;
3840 Py_INCREF(Py_None);
3841 return Py_None;
3842}
Guido van Rossum22b13872002-08-06 21:41:44 +00003843
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003844static PyObject *
3845wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3846{
3847 descrsetfunc func = (descrsetfunc)wrapped;
3848 PyObject *obj;
3849 int ret;
3850
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003851 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003852 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003853 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003854 ret = (*func)(self, obj, NULL);
3855 if (ret < 0)
3856 return NULL;
3857 Py_INCREF(Py_None);
3858 return Py_None;
3859}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003860
Tim Peters6d6c1a32001-08-02 04:15:00 +00003861static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003862wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003863{
3864 initproc func = (initproc)wrapped;
3865
Guido van Rossumc8e56452001-10-22 00:43:43 +00003866 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003867 return NULL;
3868 Py_INCREF(Py_None);
3869 return Py_None;
3870}
3871
Tim Peters6d6c1a32001-08-02 04:15:00 +00003872static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003873tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003874{
Barry Warsaw60f01882001-08-22 19:24:42 +00003875 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003876 PyObject *arg0, *res;
3877
3878 if (self == NULL || !PyType_Check(self))
3879 Py_FatalError("__new__() called with non-type 'self'");
3880 type = (PyTypeObject *)self;
3881 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003882 PyErr_Format(PyExc_TypeError,
3883 "%s.__new__(): not enough arguments",
3884 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003885 return NULL;
3886 }
3887 arg0 = PyTuple_GET_ITEM(args, 0);
3888 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003889 PyErr_Format(PyExc_TypeError,
3890 "%s.__new__(X): X is not a type object (%s)",
3891 type->tp_name,
3892 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003893 return NULL;
3894 }
3895 subtype = (PyTypeObject *)arg0;
3896 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003897 PyErr_Format(PyExc_TypeError,
3898 "%s.__new__(%s): %s is not a subtype of %s",
3899 type->tp_name,
3900 subtype->tp_name,
3901 subtype->tp_name,
3902 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003903 return NULL;
3904 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003905
3906 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003907 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003908 most derived base that's not a heap type is this type. */
3909 staticbase = subtype;
3910 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3911 staticbase = staticbase->tp_base;
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003912 /* If staticbase is NULL now, it is a really weird type.
Thomas Wouters89f507f2006-12-13 04:49:30 +00003913 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003914 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003915 PyErr_Format(PyExc_TypeError,
3916 "%s.__new__(%s) is not safe, use %s.__new__()",
3917 type->tp_name,
3918 subtype->tp_name,
3919 staticbase == NULL ? "?" : staticbase->tp_name);
3920 return NULL;
3921 }
3922
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003923 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3924 if (args == NULL)
3925 return NULL;
3926 res = type->tp_new(subtype, args, kwds);
3927 Py_DECREF(args);
3928 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003929}
3930
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003931static struct PyMethodDef tp_new_methoddef[] = {
3932 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003933 PyDoc_STR("T.__new__(S, ...) -> "
3934 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003935 {0}
3936};
3937
3938static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003939add_tp_new_wrapper(PyTypeObject *type)
3940{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003941 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003942
Guido van Rossum687ae002001-10-15 22:03:32 +00003943 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003944 return 0;
3945 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003946 if (func == NULL)
3947 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00003948 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00003949 Py_DECREF(func);
3950 return -1;
3951 }
3952 Py_DECREF(func);
3953 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003954}
3955
Guido van Rossumf040ede2001-08-07 16:40:56 +00003956/* Slot wrappers that call the corresponding __foo__ slot. See comments
3957 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003958
Guido van Rossumdc91b992001-08-08 22:26:22 +00003959#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003960static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003961FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003962{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003963 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003964 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003965}
3966
Guido van Rossumdc91b992001-08-08 22:26:22 +00003967#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003968static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003969FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003970{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003971 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003972 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003973}
3974
Guido van Rossumcd118802003-01-06 22:57:47 +00003975/* Boolean helper for SLOT1BINFULL().
3976 right.__class__ is a nontrivial subclass of left.__class__. */
3977static int
3978method_is_overloaded(PyObject *left, PyObject *right, char *name)
3979{
3980 PyObject *a, *b;
3981 int ok;
3982
3983 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3984 if (b == NULL) {
3985 PyErr_Clear();
3986 /* If right doesn't have it, it's not overloaded */
3987 return 0;
3988 }
3989
3990 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3991 if (a == NULL) {
3992 PyErr_Clear();
3993 Py_DECREF(b);
3994 /* If right has it but left doesn't, it's overloaded */
3995 return 1;
3996 }
3997
3998 ok = PyObject_RichCompareBool(a, b, Py_NE);
3999 Py_DECREF(a);
4000 Py_DECREF(b);
4001 if (ok < 0) {
4002 PyErr_Clear();
4003 return 0;
4004 }
4005
4006 return ok;
4007}
4008
Guido van Rossumdc91b992001-08-08 22:26:22 +00004009
4010#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004011static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004012FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004013{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004014 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004015 int do_other = self->ob_type != other->ob_type && \
4016 other->ob_type->tp_as_number != NULL && \
4017 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004018 if (self->ob_type->tp_as_number != NULL && \
4019 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
4020 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004021 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004022 PyType_IsSubtype(other->ob_type, self->ob_type) && \
4023 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004024 r = call_maybe( \
4025 other, ROPSTR, &rcache_str, "(O)", self); \
4026 if (r != Py_NotImplemented) \
4027 return r; \
4028 Py_DECREF(r); \
4029 do_other = 0; \
4030 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004031 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004032 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004033 if (r != Py_NotImplemented || \
4034 other->ob_type == self->ob_type) \
4035 return r; \
4036 Py_DECREF(r); \
4037 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004038 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004039 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004040 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004041 } \
4042 Py_INCREF(Py_NotImplemented); \
4043 return Py_NotImplemented; \
4044}
4045
4046#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4047 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4048
4049#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4050static PyObject * \
4051FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4052{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004053 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004054 return call_method(self, OPSTR, &cache_str, \
4055 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004056}
4057
Martin v. Löwis18e16552006-02-15 17:27:45 +00004058static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004059slot_sq_length(PyObject *self)
4060{
Guido van Rossum2730b132001-08-28 18:22:14 +00004061 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004062 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004063 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004064
4065 if (res == NULL)
4066 return -1;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004067 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004068 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004069 if (len < 0) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00004070 if (!PyErr_Occurred())
4071 PyErr_SetString(PyExc_ValueError,
4072 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004073 return -1;
4074 }
Guido van Rossum26111622001-10-01 16:42:49 +00004075 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004076}
4077
Guido van Rossumf4593e02001-10-03 12:09:30 +00004078/* Super-optimized version of slot_sq_item.
4079 Other slots could do the same... */
4080static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004081slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004082{
4083 static PyObject *getitem_str;
4084 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4085 descrgetfunc f;
4086
4087 if (getitem_str == NULL) {
4088 getitem_str = PyString_InternFromString("__getitem__");
4089 if (getitem_str == NULL)
4090 return NULL;
4091 }
4092 func = _PyType_Lookup(self->ob_type, getitem_str);
4093 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004094 if ((f = func->ob_type->tp_descr_get) == NULL)
4095 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004096 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004097 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004098 if (func == NULL) {
4099 return NULL;
4100 }
4101 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004102 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004103 if (ival != NULL) {
4104 args = PyTuple_New(1);
4105 if (args != NULL) {
4106 PyTuple_SET_ITEM(args, 0, ival);
4107 retval = PyObject_Call(func, args, NULL);
4108 Py_XDECREF(args);
4109 Py_XDECREF(func);
4110 return retval;
4111 }
4112 }
4113 }
4114 else {
4115 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4116 }
4117 Py_XDECREF(args);
4118 Py_XDECREF(ival);
4119 Py_XDECREF(func);
4120 return NULL;
4121}
4122
Martin v. Löwis18e16552006-02-15 17:27:45 +00004123SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004124
4125static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004126slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004127{
4128 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004129 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004130
4131 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004132 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004133 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004134 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004135 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004136 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004137 if (res == NULL)
4138 return -1;
4139 Py_DECREF(res);
4140 return 0;
4141}
4142
4143static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004144slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004145{
4146 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004147 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004148
4149 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004150 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004151 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004152 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004153 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004154 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004155 if (res == NULL)
4156 return -1;
4157 Py_DECREF(res);
4158 return 0;
4159}
4160
4161static int
4162slot_sq_contains(PyObject *self, PyObject *value)
4163{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004164 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004165 int result = -1;
4166
Guido van Rossum60718732001-08-28 17:47:51 +00004167 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004168
Guido van Rossum55f20992001-10-01 17:18:22 +00004169 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004170 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004171 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004172 if (args == NULL)
4173 res = NULL;
4174 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004175 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004176 Py_DECREF(args);
4177 }
4178 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004179 if (res != NULL) {
4180 result = PyObject_IsTrue(res);
4181 Py_DECREF(res);
4182 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004183 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004184 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004185 /* Possible results: -1 and 1 */
4186 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004187 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004188 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004189 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004190}
4191
Tim Peters6d6c1a32001-08-02 04:15:00 +00004192#define slot_mp_length slot_sq_length
4193
Guido van Rossumdc91b992001-08-08 22:26:22 +00004194SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004195
4196static int
4197slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4198{
4199 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004200 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004201
4202 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004203 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004204 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004205 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004206 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004207 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004208 if (res == NULL)
4209 return -1;
4210 Py_DECREF(res);
4211 return 0;
4212}
4213
Guido van Rossumdc91b992001-08-08 22:26:22 +00004214SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4215SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4216SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004217SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4218SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4219
Jeremy Hylton938ace62002-07-17 16:30:39 +00004220static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004221
4222SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4223 nb_power, "__pow__", "__rpow__")
4224
4225static PyObject *
4226slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4227{
Guido van Rossum2730b132001-08-28 18:22:14 +00004228 static PyObject *pow_str;
4229
Guido van Rossumdc91b992001-08-08 22:26:22 +00004230 if (modulus == Py_None)
4231 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004232 /* Three-arg power doesn't use __rpow__. But ternary_op
4233 can call this when the second argument's type uses
4234 slot_nb_power, so check before calling self.__pow__. */
4235 if (self->ob_type->tp_as_number != NULL &&
4236 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4237 return call_method(self, "__pow__", &pow_str,
4238 "(OO)", other, modulus);
4239 }
4240 Py_INCREF(Py_NotImplemented);
4241 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004242}
4243
4244SLOT0(slot_nb_negative, "__neg__")
4245SLOT0(slot_nb_positive, "__pos__")
4246SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004247
4248static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004249slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004250{
Tim Petersea7f75d2002-12-07 21:39:16 +00004251 PyObject *func, *args;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004252 static PyObject *bool_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004253 int result = -1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004254 int from_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004255
Jack Diederich4dafcc42006-11-28 19:15:13 +00004256 func = lookup_maybe(self, "__bool__", &bool_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004257 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004258 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004259 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004260 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004261 if (func == NULL)
4262 return PyErr_Occurred() ? -1 : 1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004263 from_len = 1;
Tim Petersea7f75d2002-12-07 21:39:16 +00004264 }
4265 args = PyTuple_New(0);
4266 if (args != NULL) {
4267 PyObject *temp = PyObject_Call(func, args, NULL);
4268 Py_DECREF(args);
4269 if (temp != NULL) {
Jack Diederich4dafcc42006-11-28 19:15:13 +00004270 if (from_len) {
4271 /* enforced by slot_nb_len */
Jeremy Hylton090a3492003-06-27 16:46:45 +00004272 result = PyObject_IsTrue(temp);
Jack Diederich4dafcc42006-11-28 19:15:13 +00004273 }
4274 else if (PyBool_Check(temp)) {
4275 result = PyObject_IsTrue(temp);
4276 }
Jeremy Hylton090a3492003-06-27 16:46:45 +00004277 else {
4278 PyErr_Format(PyExc_TypeError,
Jack Diederich4dafcc42006-11-28 19:15:13 +00004279 "__bool__ should return "
4280 "bool, returned %s",
4281 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004282 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004283 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004284 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004285 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004286 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004287 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004288 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004289}
4290
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004291
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004292static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004293slot_nb_index(PyObject *self)
4294{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004295 static PyObject *index_str;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004296 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004297}
4298
4299
Guido van Rossumdc91b992001-08-08 22:26:22 +00004300SLOT0(slot_nb_invert, "__invert__")
4301SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4302SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4303SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4304SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4305SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004306
Guido van Rossumdc91b992001-08-08 22:26:22 +00004307SLOT0(slot_nb_int, "__int__")
4308SLOT0(slot_nb_long, "__long__")
4309SLOT0(slot_nb_float, "__float__")
4310SLOT0(slot_nb_oct, "__oct__")
4311SLOT0(slot_nb_hex, "__hex__")
4312SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4313SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4314SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004315SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00004316/* Can't use SLOT1 here, because nb_inplace_power is ternary */
4317static PyObject *
4318slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4319{
4320 static PyObject *cache_str;
4321 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
4322}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004323SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4324SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4325SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4326SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4327SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4328SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4329 "__floordiv__", "__rfloordiv__")
4330SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4331SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4332SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004333
4334static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004335half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004336{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004337 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004338 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004339 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004340
Guido van Rossum60718732001-08-28 17:47:51 +00004341 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004342 if (func == NULL) {
4343 PyErr_Clear();
4344 }
4345 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004346 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004347 if (args == NULL)
4348 res = NULL;
4349 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004350 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004351 Py_DECREF(args);
4352 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004353 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004354 if (res != Py_NotImplemented) {
4355 if (res == NULL)
4356 return -2;
4357 c = PyInt_AsLong(res);
4358 Py_DECREF(res);
4359 if (c == -1 && PyErr_Occurred())
4360 return -2;
4361 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4362 }
4363 Py_DECREF(res);
4364 }
4365 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004366}
4367
Guido van Rossumab3b0342001-09-18 20:38:53 +00004368/* This slot is published for the benefit of try_3way_compare in object.c */
4369int
4370_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004371{
4372 int c;
4373
Guido van Rossumab3b0342001-09-18 20:38:53 +00004374 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004375 c = half_compare(self, other);
4376 if (c <= 1)
4377 return c;
4378 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004379 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004380 c = half_compare(other, self);
4381 if (c < -1)
4382 return -2;
4383 if (c <= 1)
4384 return -c;
4385 }
4386 return (void *)self < (void *)other ? -1 :
4387 (void *)self > (void *)other ? 1 : 0;
4388}
4389
4390static PyObject *
4391slot_tp_repr(PyObject *self)
4392{
4393 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004394 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004395
Guido van Rossum60718732001-08-28 17:47:51 +00004396 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004397 if (func != NULL) {
4398 res = PyEval_CallObject(func, NULL);
4399 Py_DECREF(func);
4400 return res;
4401 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004402 PyErr_Clear();
4403 return PyString_FromFormat("<%s object at %p>",
4404 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004405}
4406
4407static PyObject *
4408slot_tp_str(PyObject *self)
4409{
4410 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004411 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004412
Guido van Rossum60718732001-08-28 17:47:51 +00004413 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004414 if (func != NULL) {
4415 res = PyEval_CallObject(func, NULL);
4416 Py_DECREF(func);
4417 return res;
4418 }
4419 else {
4420 PyErr_Clear();
4421 return slot_tp_repr(self);
4422 }
4423}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004424
4425static long
4426slot_tp_hash(PyObject *self)
4427{
Guido van Rossum4011a242006-08-17 23:09:57 +00004428 PyObject *func, *res;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004429 static PyObject *hash_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004430 long h;
4431
Guido van Rossum60718732001-08-28 17:47:51 +00004432 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004433
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004434 if (func == Py_None) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004435 Py_DECREF(func);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004436 func = NULL;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004437 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004438
4439 if (func == NULL) {
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004440 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
4441 self->ob_type->tp_name);
4442 return -1;
4443 }
4444
Guido van Rossum4011a242006-08-17 23:09:57 +00004445 res = PyEval_CallObject(func, NULL);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004446 Py_DECREF(func);
4447 if (res == NULL)
4448 return -1;
4449 if (PyLong_Check(res))
4450 h = PyLong_Type.tp_hash(res);
4451 else
4452 h = PyInt_AsLong(res);
4453 Py_DECREF(res);
4454 if (h == -1 && !PyErr_Occurred())
4455 h = -2;
4456 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004457}
4458
4459static PyObject *
4460slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4461{
Guido van Rossum60718732001-08-28 17:47:51 +00004462 static PyObject *call_str;
4463 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004464 PyObject *res;
4465
4466 if (meth == NULL)
4467 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004468
4469 /* PyObject_Call() will end up calling slot_tp_call() again if
4470 the object returned for __call__ has __call__ itself defined
4471 upon it. This can be an infinite recursion if you set
4472 __call__ in a class to an instance of it. */
4473 if (Py_EnterRecursiveCall(" in __call__")) {
4474 Py_DECREF(meth);
4475 return NULL;
4476 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004477 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004478 Py_LeaveRecursiveCall();
4479
Tim Peters6d6c1a32001-08-02 04:15:00 +00004480 Py_DECREF(meth);
4481 return res;
4482}
4483
Guido van Rossum14a6f832001-10-17 13:59:09 +00004484/* There are two slot dispatch functions for tp_getattro.
4485
4486 - slot_tp_getattro() is used when __getattribute__ is overridden
4487 but no __getattr__ hook is present;
4488
4489 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4490
Guido van Rossumc334df52002-04-04 23:44:47 +00004491 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4492 detects the absence of __getattr__ and then installs the simpler slot if
4493 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004494
Tim Peters6d6c1a32001-08-02 04:15:00 +00004495static PyObject *
4496slot_tp_getattro(PyObject *self, PyObject *name)
4497{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004498 static PyObject *getattribute_str = NULL;
4499 return call_method(self, "__getattribute__", &getattribute_str,
4500 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004501}
4502
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004503static PyObject *
4504slot_tp_getattr_hook(PyObject *self, PyObject *name)
4505{
4506 PyTypeObject *tp = self->ob_type;
4507 PyObject *getattr, *getattribute, *res;
4508 static PyObject *getattribute_str = NULL;
4509 static PyObject *getattr_str = NULL;
4510
4511 if (getattr_str == NULL) {
4512 getattr_str = PyString_InternFromString("__getattr__");
4513 if (getattr_str == NULL)
4514 return NULL;
4515 }
4516 if (getattribute_str == NULL) {
4517 getattribute_str =
4518 PyString_InternFromString("__getattribute__");
4519 if (getattribute_str == NULL)
4520 return NULL;
4521 }
4522 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004523 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004524 /* No __getattr__ hook: use a simpler dispatcher */
4525 tp->tp_getattro = slot_tp_getattro;
4526 return slot_tp_getattro(self, name);
4527 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004528 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004529 if (getattribute == NULL ||
4530 (getattribute->ob_type == &PyWrapperDescr_Type &&
4531 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4532 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004533 res = PyObject_GenericGetAttr(self, name);
4534 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00004535 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004536 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004537 PyErr_Clear();
Thomas Wouters477c8d52006-05-27 19:21:47 +00004538 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004539 }
4540 return res;
4541}
4542
Tim Peters6d6c1a32001-08-02 04:15:00 +00004543static int
4544slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4545{
4546 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004547 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004548
4549 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004550 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004551 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004552 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004553 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004554 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004555 if (res == NULL)
4556 return -1;
4557 Py_DECREF(res);
4558 return 0;
4559}
4560
Tim Peters6d6c1a32001-08-02 04:15:00 +00004561static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004562half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004563{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004564 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004565 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004566
Guido van Rossum60718732001-08-28 17:47:51 +00004567 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004568 if (func == NULL) {
4569 PyErr_Clear();
4570 Py_INCREF(Py_NotImplemented);
4571 return Py_NotImplemented;
4572 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004573 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004574 if (args == NULL)
4575 res = NULL;
4576 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004577 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004578 Py_DECREF(args);
4579 }
4580 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004581 return res;
4582}
4583
Guido van Rossumb8f63662001-08-15 23:57:02 +00004584static PyObject *
4585slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4586{
4587 PyObject *res;
4588
4589 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4590 res = half_richcompare(self, other, op);
4591 if (res != Py_NotImplemented)
4592 return res;
4593 Py_DECREF(res);
4594 }
4595 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004596 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004597 if (res != Py_NotImplemented) {
4598 return res;
4599 }
4600 Py_DECREF(res);
4601 }
4602 Py_INCREF(Py_NotImplemented);
4603 return Py_NotImplemented;
4604}
4605
4606static PyObject *
4607slot_tp_iter(PyObject *self)
4608{
4609 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004610 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004611
Guido van Rossum60718732001-08-28 17:47:51 +00004612 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004613 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004614 PyObject *args;
4615 args = res = PyTuple_New(0);
4616 if (args != NULL) {
4617 res = PyObject_Call(func, args, NULL);
4618 Py_DECREF(args);
4619 }
4620 Py_DECREF(func);
4621 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004622 }
4623 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004624 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004625 if (func == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004626 PyErr_Format(PyExc_TypeError,
4627 "'%.200s' object is not iterable",
4628 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004629 return NULL;
4630 }
4631 Py_DECREF(func);
4632 return PySeqIter_New(self);
4633}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004634
4635static PyObject *
4636slot_tp_iternext(PyObject *self)
4637{
Guido van Rossum2730b132001-08-28 18:22:14 +00004638 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004639 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004640}
4641
Guido van Rossum1a493502001-08-17 16:47:50 +00004642static PyObject *
4643slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4644{
4645 PyTypeObject *tp = self->ob_type;
4646 PyObject *get;
4647 static PyObject *get_str = NULL;
4648
4649 if (get_str == NULL) {
4650 get_str = PyString_InternFromString("__get__");
4651 if (get_str == NULL)
4652 return NULL;
4653 }
4654 get = _PyType_Lookup(tp, get_str);
4655 if (get == NULL) {
4656 /* Avoid further slowdowns */
4657 if (tp->tp_descr_get == slot_tp_descr_get)
4658 tp->tp_descr_get = NULL;
4659 Py_INCREF(self);
4660 return self;
4661 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004662 if (obj == NULL)
4663 obj = Py_None;
4664 if (type == NULL)
4665 type = Py_None;
Thomas Wouters477c8d52006-05-27 19:21:47 +00004666 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00004667}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004668
4669static int
4670slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4671{
Guido van Rossum2c252392001-08-24 10:13:31 +00004672 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004673 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004674
4675 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004676 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004677 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004678 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004679 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004680 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004681 if (res == NULL)
4682 return -1;
4683 Py_DECREF(res);
4684 return 0;
4685}
4686
4687static int
4688slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4689{
Guido van Rossum60718732001-08-28 17:47:51 +00004690 static PyObject *init_str;
4691 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004692 PyObject *res;
4693
4694 if (meth == NULL)
4695 return -1;
4696 res = PyObject_Call(meth, args, kwds);
4697 Py_DECREF(meth);
4698 if (res == NULL)
4699 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004700 if (res != Py_None) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004701 PyErr_Format(PyExc_TypeError,
4702 "__init__() should return None, not '%.200s'",
4703 res->ob_type->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004704 Py_DECREF(res);
4705 return -1;
4706 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004707 Py_DECREF(res);
4708 return 0;
4709}
4710
4711static PyObject *
4712slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4713{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004714 static PyObject *new_str;
4715 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004716 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004717 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004718
Guido van Rossum7bed2132002-08-08 21:57:53 +00004719 if (new_str == NULL) {
4720 new_str = PyString_InternFromString("__new__");
4721 if (new_str == NULL)
4722 return NULL;
4723 }
4724 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004725 if (func == NULL)
4726 return NULL;
4727 assert(PyTuple_Check(args));
4728 n = PyTuple_GET_SIZE(args);
4729 newargs = PyTuple_New(n+1);
4730 if (newargs == NULL)
4731 return NULL;
4732 Py_INCREF(type);
4733 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4734 for (i = 0; i < n; i++) {
4735 x = PyTuple_GET_ITEM(args, i);
4736 Py_INCREF(x);
4737 PyTuple_SET_ITEM(newargs, i+1, x);
4738 }
4739 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004740 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004741 Py_DECREF(func);
4742 return x;
4743}
4744
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004745static void
4746slot_tp_del(PyObject *self)
4747{
4748 static PyObject *del_str = NULL;
4749 PyObject *del, *res;
4750 PyObject *error_type, *error_value, *error_traceback;
4751
4752 /* Temporarily resurrect the object. */
4753 assert(self->ob_refcnt == 0);
4754 self->ob_refcnt = 1;
4755
4756 /* Save the current exception, if any. */
4757 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4758
4759 /* Execute __del__ method, if any. */
4760 del = lookup_maybe(self, "__del__", &del_str);
4761 if (del != NULL) {
4762 res = PyEval_CallObject(del, NULL);
4763 if (res == NULL)
4764 PyErr_WriteUnraisable(del);
4765 else
4766 Py_DECREF(res);
4767 Py_DECREF(del);
4768 }
4769
4770 /* Restore the saved exception. */
4771 PyErr_Restore(error_type, error_value, error_traceback);
4772
4773 /* Undo the temporary resurrection; can't use DECREF here, it would
4774 * cause a recursive call.
4775 */
4776 assert(self->ob_refcnt > 0);
4777 if (--self->ob_refcnt == 0)
4778 return; /* this is the normal path out */
4779
4780 /* __del__ resurrected it! Make it look like the original Py_DECREF
4781 * never happened.
4782 */
4783 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004784 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004785 _Py_NewReference(self);
4786 self->ob_refcnt = refcnt;
4787 }
4788 assert(!PyType_IS_GC(self->ob_type) ||
4789 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00004790 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
4791 * we need to undo that. */
4792 _Py_DEC_REFTOTAL;
4793 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4794 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004795 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4796 * _Py_NewReference bumped tp_allocs: both of those need to be
4797 * undone.
4798 */
4799#ifdef COUNT_ALLOCS
4800 --self->ob_type->tp_frees;
4801 --self->ob_type->tp_allocs;
4802#endif
4803}
4804
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004805
4806/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004807 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004808 structure, which incorporates the additional structures used for numbers,
4809 sequences and mappings.
4810 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004811 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004812 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4813 terminated with an all-zero entry. (This table is further initialized and
4814 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004815
Guido van Rossum6d204072001-10-21 00:44:31 +00004816typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004817
4818#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004819#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004820#undef ETSLOT
4821#undef SQSLOT
4822#undef MPSLOT
4823#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004824#undef UNSLOT
4825#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004826#undef BINSLOT
4827#undef RBINSLOT
4828
Guido van Rossum6d204072001-10-21 00:44:31 +00004829#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004830 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4831 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004832#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4833 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004834 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004835#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004836 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004837 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004838#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4839 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4840#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4841 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4842#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4843 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4844#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4845 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4846 "x." NAME "() <==> " DOC)
4847#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4848 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4849 "x." NAME "(y) <==> x" DOC "y")
4850#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4851 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4852 "x." NAME "(y) <==> x" DOC "y")
4853#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4854 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4855 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00004856#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
4857 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4858 "x." NAME "(y) <==> " DOC)
4859#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
4860 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4861 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004862
4863static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00004864 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00004865 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00004866 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
4867 The logic in abstract.c always falls back to nb_add/nb_multiply in
4868 this case. Defining both the nb_* and the sq_* slots to call the
4869 user-defined methods has unexpected side-effects, as shown by
4870 test_descr.notimplemented() */
4871 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
4872 "x.__add__(y) <==> x+y"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004873 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Armin Rigofd163f92005-12-29 15:59:19 +00004874 "x.__mul__(n) <==> x*n"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004875 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Armin Rigofd163f92005-12-29 15:59:19 +00004876 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004877 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4878 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00004879 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00004880 "x.__getslice__(i, j) <==> x[i:j]\n\
4881 \n\
4882 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004883 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004884 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004885 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004886 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004887 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00004888 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00004889 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
4890 \n\
4891 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004892 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00004893 "x.__delslice__(i, j) <==> del x[i:j]\n\
4894 \n\
4895 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004896 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4897 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00004898 SQSLOT("__iadd__", sq_inplace_concat, NULL,
4899 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
4900 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004901 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004902
Martin v. Löwis18e16552006-02-15 17:27:45 +00004903 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00004904 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004905 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004906 wrap_binaryfunc,
4907 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004908 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004909 wrap_objobjargproc,
4910 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004911 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004912 wrap_delitem,
4913 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004914
Guido van Rossum6d204072001-10-21 00:44:31 +00004915 BINSLOT("__add__", nb_add, slot_nb_add,
4916 "+"),
4917 RBINSLOT("__radd__", nb_add, slot_nb_add,
4918 "+"),
4919 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4920 "-"),
4921 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4922 "-"),
4923 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4924 "*"),
4925 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4926 "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004927 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4928 "%"),
4929 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4930 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00004931 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00004932 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00004933 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00004934 "divmod(y, x)"),
4935 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4936 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4937 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4938 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4939 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4940 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4941 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4942 "abs(x)"),
Jack Diederich4dafcc42006-11-28 19:15:13 +00004943 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00004944 "x != 0"),
4945 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4946 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4947 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4948 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4949 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4950 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4951 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4952 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4953 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4954 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4955 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004956 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4957 "int(x)"),
4958 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4959 "long(x)"),
4960 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4961 "float(x)"),
4962 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4963 "oct(x)"),
4964 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4965 "hex(x)"),
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004966 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004967 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004968 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4969 wrap_binaryfunc, "+"),
4970 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4971 wrap_binaryfunc, "-"),
4972 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4973 wrap_binaryfunc, "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004974 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4975 wrap_binaryfunc, "%"),
4976 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004977 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004978 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4979 wrap_binaryfunc, "<<"),
4980 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4981 wrap_binaryfunc, ">>"),
4982 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4983 wrap_binaryfunc, "&"),
4984 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4985 wrap_binaryfunc, "^"),
4986 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4987 wrap_binaryfunc, "|"),
4988 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4989 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4990 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4991 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4992 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4993 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4994 IBSLOT("__itruediv__", nb_inplace_true_divide,
4995 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004996
Guido van Rossum6d204072001-10-21 00:44:31 +00004997 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4998 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004999 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005000 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5001 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005002 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005003 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5004 "x.__cmp__(y) <==> cmp(x,y)"),
5005 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5006 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005007 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5008 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005009 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005010 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5011 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5012 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5013 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5014 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5015 "x.__setattr__('name', value) <==> x.name = value"),
5016 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5017 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5018 "x.__delattr__('name') <==> del x.name"),
5019 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5020 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5021 "x.__lt__(y) <==> x<y"),
5022 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5023 "x.__le__(y) <==> x<=y"),
5024 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5025 "x.__eq__(y) <==> x==y"),
5026 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5027 "x.__ne__(y) <==> x!=y"),
5028 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5029 "x.__gt__(y) <==> x>y"),
5030 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5031 "x.__ge__(y) <==> x>=y"),
5032 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5033 "x.__iter__() <==> iter(x)"),
5034 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5035 "x.next() -> the next value, or raise StopIteration"),
5036 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5037 "descr.__get__(obj[, type]) -> value"),
5038 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5039 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005040 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5041 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005042 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005043 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005044 "see x.__class__.__doc__ for signature",
5045 PyWrapperFlag_KEYWORDS),
5046 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005047 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005048 {NULL}
5049};
5050
Guido van Rossumc334df52002-04-04 23:44:47 +00005051/* Given a type pointer and an offset gotten from a slotdef entry, return a
5052 pointer to the actual slot. This is not quite the same as simply adding
5053 the offset to the type pointer, since it takes care to indirect through the
5054 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5055 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005056static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005057slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005058{
5059 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005060 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005061
Guido van Rossume5c691a2003-03-07 15:13:17 +00005062 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005063 assert(offset >= 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005064 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5065 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5066 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005067 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005068 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005069 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5070 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005071 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005072 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005073 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5074 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005075 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005076 }
5077 else {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005078 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005079 }
5080 if (ptr != NULL)
5081 ptr += offset;
5082 return (void **)ptr;
5083}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005084
Guido van Rossumc334df52002-04-04 23:44:47 +00005085/* Length of array of slotdef pointers used to store slots with the
5086 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5087 the same __name__, for any __name__. Since that's a static property, it is
5088 appropriate to declare fixed-size arrays for this. */
5089#define MAX_EQUIV 10
5090
5091/* Return a slot pointer for a given name, but ONLY if the attribute has
5092 exactly one slot function. The name must be an interned string. */
5093static void **
5094resolve_slotdups(PyTypeObject *type, PyObject *name)
5095{
5096 /* XXX Maybe this could be optimized more -- but is it worth it? */
5097
5098 /* pname and ptrs act as a little cache */
5099 static PyObject *pname;
5100 static slotdef *ptrs[MAX_EQUIV];
5101 slotdef *p, **pp;
5102 void **res, **ptr;
5103
5104 if (pname != name) {
5105 /* Collect all slotdefs that match name into ptrs. */
5106 pname = name;
5107 pp = ptrs;
5108 for (p = slotdefs; p->name_strobj; p++) {
5109 if (p->name_strobj == name)
5110 *pp++ = p;
5111 }
5112 *pp = NULL;
5113 }
5114
5115 /* Look in all matching slots of the type; if exactly one of these has
5116 a filled-in slot, return its value. Otherwise return NULL. */
5117 res = NULL;
5118 for (pp = ptrs; *pp; pp++) {
5119 ptr = slotptr(type, (*pp)->offset);
5120 if (ptr == NULL || *ptr == NULL)
5121 continue;
5122 if (res != NULL)
5123 return NULL;
5124 res = ptr;
5125 }
5126 return res;
5127}
5128
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005129/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005130 does some incredibly complex thinking and then sticks something into the
5131 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5132 interests, and then stores a generic wrapper or a specific function into
5133 the slot.) Return a pointer to the next slotdef with a different offset,
5134 because that's convenient for fixup_slot_dispatchers(). */
5135static slotdef *
5136update_one_slot(PyTypeObject *type, slotdef *p)
5137{
5138 PyObject *descr;
5139 PyWrapperDescrObject *d;
5140 void *generic = NULL, *specific = NULL;
5141 int use_generic = 0;
5142 int offset = p->offset;
5143 void **ptr = slotptr(type, offset);
5144
5145 if (ptr == NULL) {
5146 do {
5147 ++p;
5148 } while (p->offset == offset);
5149 return p;
5150 }
5151 do {
5152 descr = _PyType_Lookup(type, p->name_strobj);
5153 if (descr == NULL)
5154 continue;
5155 if (descr->ob_type == &PyWrapperDescr_Type) {
5156 void **tptr = resolve_slotdups(type, p->name_strobj);
5157 if (tptr == NULL || tptr == ptr)
5158 generic = p->function;
5159 d = (PyWrapperDescrObject *)descr;
5160 if (d->d_base->wrapper == p->wrapper &&
5161 PyType_IsSubtype(type, d->d_type))
5162 {
5163 if (specific == NULL ||
5164 specific == d->d_wrapped)
5165 specific = d->d_wrapped;
5166 else
5167 use_generic = 1;
5168 }
5169 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005170 else if (descr->ob_type == &PyCFunction_Type &&
5171 PyCFunction_GET_FUNCTION(descr) ==
5172 (PyCFunction)tp_new_wrapper &&
5173 strcmp(p->name, "__new__") == 0)
5174 {
5175 /* The __new__ wrapper is not a wrapper descriptor,
5176 so must be special-cased differently.
5177 If we don't do this, creating an instance will
5178 always use slot_tp_new which will look up
5179 __new__ in the MRO which will call tp_new_wrapper
5180 which will look through the base classes looking
5181 for a static base and call its tp_new (usually
5182 PyType_GenericNew), after performing various
5183 sanity checks and constructing a new argument
5184 list. Cut all that nonsense short -- this speeds
5185 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005186 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005187 /* XXX I'm not 100% sure that there isn't a hole
5188 in this reasoning that requires additional
5189 sanity checks. I'll buy the first person to
5190 point out a bug in this reasoning a beer. */
5191 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005192 else {
5193 use_generic = 1;
5194 generic = p->function;
5195 }
5196 } while ((++p)->offset == offset);
5197 if (specific && !use_generic)
5198 *ptr = specific;
5199 else
5200 *ptr = generic;
5201 return p;
5202}
5203
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005204/* In the type, update the slots whose slotdefs are gathered in the pp array.
5205 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005206static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005207update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005208{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005209 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005210
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005211 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005212 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005213 return 0;
5214}
5215
Guido van Rossumc334df52002-04-04 23:44:47 +00005216/* Comparison function for qsort() to compare slotdefs by their offset, and
5217 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005218static int
5219slotdef_cmp(const void *aa, const void *bb)
5220{
5221 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5222 int c = a->offset - b->offset;
5223 if (c != 0)
5224 return c;
5225 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005226 /* Cannot use a-b, as this gives off_t,
5227 which may lose precision when converted to int. */
5228 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005229}
5230
Guido van Rossumc334df52002-04-04 23:44:47 +00005231/* Initialize the slotdefs table by adding interned string objects for the
5232 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005233static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005234init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005235{
5236 slotdef *p;
5237 static int initialized = 0;
5238
5239 if (initialized)
5240 return;
5241 for (p = slotdefs; p->name; p++) {
5242 p->name_strobj = PyString_InternFromString(p->name);
5243 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005244 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005245 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005246 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5247 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005248 initialized = 1;
5249}
5250
Guido van Rossumc334df52002-04-04 23:44:47 +00005251/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005252static int
5253update_slot(PyTypeObject *type, PyObject *name)
5254{
Guido van Rossumc334df52002-04-04 23:44:47 +00005255 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005256 slotdef *p;
5257 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005258 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005259
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005260 init_slotdefs();
5261 pp = ptrs;
5262 for (p = slotdefs; p->name; p++) {
5263 /* XXX assume name is interned! */
5264 if (p->name_strobj == name)
5265 *pp++ = p;
5266 }
5267 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005268 for (pp = ptrs; *pp; pp++) {
5269 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005270 offset = p->offset;
5271 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005272 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005273 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005274 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005275 if (ptrs[0] == NULL)
5276 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005277 return update_subclasses(type, name,
5278 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005279}
5280
Guido van Rossumc334df52002-04-04 23:44:47 +00005281/* Store the proper functions in the slot dispatches at class (type)
5282 definition time, based upon which operations the class overrides in its
5283 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005284static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005285fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005286{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005287 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005288
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005289 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005290 for (p = slotdefs; p->name; )
5291 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005292}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005293
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005294static void
5295update_all_slots(PyTypeObject* type)
5296{
5297 slotdef *p;
5298
5299 init_slotdefs();
5300 for (p = slotdefs; p->name; p++) {
5301 /* update_slot returns int but can't actually fail */
5302 update_slot(type, p->name_strobj);
5303 }
5304}
5305
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005306/* recurse_down_subclasses() and update_subclasses() are mutually
5307 recursive functions to call a callback for all subclasses,
5308 but refraining from recursing into subclasses that define 'name'. */
5309
5310static int
5311update_subclasses(PyTypeObject *type, PyObject *name,
5312 update_callback callback, void *data)
5313{
5314 if (callback(type, data) < 0)
5315 return -1;
5316 return recurse_down_subclasses(type, name, callback, data);
5317}
5318
5319static int
5320recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5321 update_callback callback, void *data)
5322{
5323 PyTypeObject *subclass;
5324 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005325 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005326
5327 subclasses = type->tp_subclasses;
5328 if (subclasses == NULL)
5329 return 0;
5330 assert(PyList_Check(subclasses));
5331 n = PyList_GET_SIZE(subclasses);
5332 for (i = 0; i < n; i++) {
5333 ref = PyList_GET_ITEM(subclasses, i);
5334 assert(PyWeakref_CheckRef(ref));
5335 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5336 assert(subclass != NULL);
5337 if ((PyObject *)subclass == Py_None)
5338 continue;
5339 assert(PyType_Check(subclass));
5340 /* Avoid recursing down into unaffected classes */
5341 dict = subclass->tp_dict;
5342 if (dict != NULL && PyDict_Check(dict) &&
5343 PyDict_GetItem(dict, name) != NULL)
5344 continue;
5345 if (update_subclasses(subclass, name, callback, data) < 0)
5346 return -1;
5347 }
5348 return 0;
5349}
5350
Guido van Rossum6d204072001-10-21 00:44:31 +00005351/* This function is called by PyType_Ready() to populate the type's
5352 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005353 function slot (like tp_repr) that's defined in the type, one or more
5354 corresponding descriptors are added in the type's tp_dict dictionary
5355 under the appropriate name (like __repr__). Some function slots
5356 cause more than one descriptor to be added (for example, the nb_add
5357 slot adds both __add__ and __radd__ descriptors) and some function
5358 slots compete for the same descriptor (for example both sq_item and
5359 mp_subscript generate a __getitem__ descriptor).
5360
5361 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005362 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005363 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005364 between competing slots: the members of PyHeapTypeObject are listed
5365 from most general to least general, so the most general slot is
5366 preferred. In particular, because as_mapping comes before as_sequence,
5367 for a type that defines both mp_subscript and sq_item, mp_subscript
5368 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005369
5370 This only adds new descriptors and doesn't overwrite entries in
5371 tp_dict that were previously defined. The descriptors contain a
5372 reference to the C function they must call, so that it's safe if they
5373 are copied into a subtype's __dict__ and the subtype has a different
5374 C function in its slot -- calling the method defined by the
5375 descriptor will call the C function that was used to create it,
5376 rather than the C function present in the slot when it is called.
5377 (This is important because a subtype may have a C function in the
5378 slot that calls the method from the dictionary, and we want to avoid
5379 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005380
5381static int
5382add_operators(PyTypeObject *type)
5383{
5384 PyObject *dict = type->tp_dict;
5385 slotdef *p;
5386 PyObject *descr;
5387 void **ptr;
5388
5389 init_slotdefs();
5390 for (p = slotdefs; p->name; p++) {
5391 if (p->wrapper == NULL)
5392 continue;
5393 ptr = slotptr(type, p->offset);
5394 if (!ptr || !*ptr)
5395 continue;
5396 if (PyDict_GetItem(dict, p->name_strobj))
5397 continue;
5398 descr = PyDescr_NewWrapper(type, p, *ptr);
5399 if (descr == NULL)
5400 return -1;
5401 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5402 return -1;
5403 Py_DECREF(descr);
5404 }
5405 if (type->tp_new != NULL) {
5406 if (add_tp_new_wrapper(type) < 0)
5407 return -1;
5408 }
5409 return 0;
5410}
5411
Guido van Rossum705f0f52001-08-24 16:47:00 +00005412
5413/* Cooperative 'super' */
5414
5415typedef struct {
5416 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005417 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005418 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005419 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005420} superobject;
5421
Guido van Rossum6f799372001-09-20 20:46:19 +00005422static PyMemberDef super_members[] = {
5423 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5424 "the class invoking super()"},
5425 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5426 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005427 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005428 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005429 {0}
5430};
5431
Guido van Rossum705f0f52001-08-24 16:47:00 +00005432static void
5433super_dealloc(PyObject *self)
5434{
5435 superobject *su = (superobject *)self;
5436
Guido van Rossum048eb752001-10-02 21:24:57 +00005437 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005438 Py_XDECREF(su->obj);
5439 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005440 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005441 self->ob_type->tp_free(self);
5442}
5443
5444static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005445super_repr(PyObject *self)
5446{
5447 superobject *su = (superobject *)self;
5448
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005449 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005450 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005451 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005452 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005453 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005454 else
5455 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005456 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005457 su->type ? su->type->tp_name : "NULL");
5458}
5459
5460static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005461super_getattro(PyObject *self, PyObject *name)
5462{
5463 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005464 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005465
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005466 if (!skip) {
5467 /* We want __class__ to return the class of the super object
5468 (i.e. super, or a subclass), not the class of su->obj. */
5469 skip = (PyString_Check(name) &&
5470 PyString_GET_SIZE(name) == 9 &&
5471 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5472 }
5473
5474 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005475 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005476 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005477 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005478 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005479
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005480 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005481 mro = starttype->tp_mro;
5482
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005483 if (mro == NULL)
5484 n = 0;
5485 else {
5486 assert(PyTuple_Check(mro));
5487 n = PyTuple_GET_SIZE(mro);
5488 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005489 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005490 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005491 break;
5492 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005493 i++;
5494 res = NULL;
5495 for (; i < n; i++) {
5496 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005497 if (PyType_Check(tmp))
5498 dict = ((PyTypeObject *)tmp)->tp_dict;
Tim Petersa91e9642001-11-14 23:32:33 +00005499 else
5500 continue;
5501 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005502 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005503 Py_INCREF(res);
5504 f = res->ob_type->tp_descr_get;
5505 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005506 tmp = f(res,
5507 /* Only pass 'obj' param if
5508 this is instance-mode super
5509 (See SF ID #743627)
5510 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005511 (su->obj == (PyObject *)
5512 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005513 ? (PyObject *)NULL
5514 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005515 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005516 Py_DECREF(res);
5517 res = tmp;
5518 }
5519 return res;
5520 }
5521 }
5522 }
5523 return PyObject_GenericGetAttr(self, name);
5524}
5525
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005526static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005527supercheck(PyTypeObject *type, PyObject *obj)
5528{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005529 /* Check that a super() call makes sense. Return a type object.
5530
5531 obj can be a new-style class, or an instance of one:
5532
5533 - If it is a class, it must be a subclass of 'type'. This case is
5534 used for class methods; the return value is obj.
5535
5536 - If it is an instance, it must be an instance of 'type'. This is
5537 the normal case; the return value is obj.__class__.
5538
5539 But... when obj is an instance, we want to allow for the case where
5540 obj->ob_type is not a subclass of type, but obj.__class__ is!
5541 This will allow using super() with a proxy for obj.
5542 */
5543
Guido van Rossum8e80a722003-02-18 19:22:22 +00005544 /* Check for first bullet above (special case) */
5545 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5546 Py_INCREF(obj);
5547 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005548 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005549
5550 /* Normal case */
5551 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005552 Py_INCREF(obj->ob_type);
5553 return obj->ob_type;
5554 }
5555 else {
5556 /* Try the slow way */
5557 static PyObject *class_str = NULL;
5558 PyObject *class_attr;
5559
5560 if (class_str == NULL) {
5561 class_str = PyString_FromString("__class__");
5562 if (class_str == NULL)
5563 return NULL;
5564 }
5565
5566 class_attr = PyObject_GetAttr(obj, class_str);
5567
5568 if (class_attr != NULL &&
5569 PyType_Check(class_attr) &&
5570 (PyTypeObject *)class_attr != obj->ob_type)
5571 {
5572 int ok = PyType_IsSubtype(
5573 (PyTypeObject *)class_attr, type);
5574 if (ok)
5575 return (PyTypeObject *)class_attr;
5576 }
5577
5578 if (class_attr == NULL)
5579 PyErr_Clear();
5580 else
5581 Py_DECREF(class_attr);
5582 }
5583
Tim Peters97e5ff52003-02-18 19:32:50 +00005584 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005585 "super(type, obj): "
5586 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005587 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005588}
5589
Guido van Rossum705f0f52001-08-24 16:47:00 +00005590static PyObject *
5591super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5592{
5593 superobject *su = (superobject *)self;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005594 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005595
5596 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5597 /* Not binding to an object, or already bound */
5598 Py_INCREF(self);
5599 return self;
5600 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005601 if (su->ob_type != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005602 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005603 call its type */
Thomas Wouters477c8d52006-05-27 19:21:47 +00005604 return PyObject_CallFunctionObjArgs((PyObject *)su->ob_type,
5605 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005606 else {
5607 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005608 PyTypeObject *obj_type = supercheck(su->type, obj);
5609 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005610 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005611 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005612 NULL, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005613 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005614 return NULL;
5615 Py_INCREF(su->type);
5616 Py_INCREF(obj);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005617 newobj->type = su->type;
5618 newobj->obj = obj;
5619 newobj->obj_type = obj_type;
5620 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005621 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005622}
5623
5624static int
5625super_init(PyObject *self, PyObject *args, PyObject *kwds)
5626{
5627 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005628 PyTypeObject *type;
5629 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005630 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005631
Thomas Wouters89f507f2006-12-13 04:49:30 +00005632 if (!_PyArg_NoKeywords("super", kwds))
5633 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005634 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5635 return -1;
5636 if (obj == Py_None)
5637 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005638 if (obj != NULL) {
5639 obj_type = supercheck(type, obj);
5640 if (obj_type == NULL)
5641 return -1;
5642 Py_INCREF(obj);
5643 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005644 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005645 su->type = type;
5646 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005647 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005648 return 0;
5649}
5650
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005651PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005652"super(type) -> unbound super object\n"
5653"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005654"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005655"Typical use to call a cooperative superclass method:\n"
5656"class C(B):\n"
5657" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005658" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005659
Guido van Rossum048eb752001-10-02 21:24:57 +00005660static int
5661super_traverse(PyObject *self, visitproc visit, void *arg)
5662{
5663 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00005664
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005665 Py_VISIT(su->obj);
5666 Py_VISIT(su->type);
5667 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005668
5669 return 0;
5670}
5671
Guido van Rossum705f0f52001-08-24 16:47:00 +00005672PyTypeObject PySuper_Type = {
5673 PyObject_HEAD_INIT(&PyType_Type)
5674 0, /* ob_size */
5675 "super", /* tp_name */
5676 sizeof(superobject), /* tp_basicsize */
5677 0, /* tp_itemsize */
5678 /* methods */
5679 super_dealloc, /* tp_dealloc */
5680 0, /* tp_print */
5681 0, /* tp_getattr */
5682 0, /* tp_setattr */
5683 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005684 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005685 0, /* tp_as_number */
5686 0, /* tp_as_sequence */
5687 0, /* tp_as_mapping */
5688 0, /* tp_hash */
5689 0, /* tp_call */
5690 0, /* tp_str */
5691 super_getattro, /* tp_getattro */
5692 0, /* tp_setattro */
5693 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005694 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5695 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005696 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005697 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005698 0, /* tp_clear */
5699 0, /* tp_richcompare */
5700 0, /* tp_weaklistoffset */
5701 0, /* tp_iter */
5702 0, /* tp_iternext */
5703 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005704 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005705 0, /* tp_getset */
5706 0, /* tp_base */
5707 0, /* tp_dict */
5708 super_descr_get, /* tp_descr_get */
5709 0, /* tp_descr_set */
5710 0, /* tp_dictoffset */
5711 super_init, /* tp_init */
5712 PyType_GenericAlloc, /* tp_alloc */
5713 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005714 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005715};