blob: 64003fc4f10ae3ec799a44f5c274e5949e1e5baf [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
Guido van Rossum6f799372001-09-20 20:46:19 +00008static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00009 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
10 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
11 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000017 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
18 {0}
19};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000020
Guido van Rossumc0b618a1997-05-02 03:12:38 +000021static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000022type_name(PyTypeObject *type, void *context)
23{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +000024 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +000025
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000026 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +000027 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +000028
Georg Brandlc255c7b2006-02-20 22:27:28 +000029 Py_INCREF(et->ht_name);
30 return et->ht_name;
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000031 }
32 else {
33 s = strrchr(type->tp_name, '.');
34 if (s == NULL)
35 s = type->tp_name;
36 else
37 s++;
38 return PyString_FromString(s);
39 }
Guido van Rossumc3542212001-08-16 09:18:56 +000040}
41
Michael W. Hudson98bbc492002-11-26 14:47:27 +000042static int
43type_set_name(PyTypeObject *type, PyObject *value, void *context)
44{
Guido van Rossume5c691a2003-03-07 15:13:17 +000045 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000046
47 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
48 PyErr_Format(PyExc_TypeError,
49 "can't set %s.__name__", type->tp_name);
50 return -1;
51 }
52 if (!value) {
53 PyErr_Format(PyExc_TypeError,
54 "can't delete %s.__name__", type->tp_name);
55 return -1;
56 }
57 if (!PyString_Check(value)) {
58 PyErr_Format(PyExc_TypeError,
59 "can only assign string to %s.__name__, not '%s'",
60 type->tp_name, value->ob_type->tp_name);
61 return -1;
62 }
Tim Petersea7f75d2002-12-07 21:39:16 +000063 if (strlen(PyString_AS_STRING(value))
Michael W. Hudson98bbc492002-11-26 14:47:27 +000064 != (size_t)PyString_GET_SIZE(value)) {
65 PyErr_Format(PyExc_ValueError,
66 "__name__ must not contain null bytes");
67 return -1;
68 }
69
Guido van Rossume5c691a2003-03-07 15:13:17 +000070 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000071
72 Py_INCREF(value);
73
Georg Brandlc255c7b2006-02-20 22:27:28 +000074 Py_DECREF(et->ht_name);
75 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000076
77 type->tp_name = PyString_AS_STRING(value);
78
79 return 0;
80}
81
Guido van Rossumc3542212001-08-16 09:18:56 +000082static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000083type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000084{
Guido van Rossumc3542212001-08-16 09:18:56 +000085 PyObject *mod;
86 char *s;
87
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000088 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
89 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Anthony Baxter3ecdb252004-06-11 14:41:18 +000090 if (!mod) {
91 PyErr_Format(PyExc_AttributeError, "__module__");
92 return 0;
93 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000094 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +000095 return mod;
96 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000097 else {
98 s = strrchr(type->tp_name, '.');
99 if (s != NULL)
100 return PyString_FromStringAndSize(
Armin Rigo7ccbca92006-10-04 12:17:45 +0000101 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Michael W. Hudsonade8c8b2002-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
Jeremy Hyltonfa955692007-02-27 18:29:45 +0000130static PyTypeObject *most_derived_metaclass(PyTypeObject *, PyObject *);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000131static PyTypeObject *best_base(PyObject *);
132static int mro_internal(PyTypeObject *);
133static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
134static int add_subclass(PyTypeObject*, PyTypeObject*);
135static void remove_subclass(PyTypeObject *, PyTypeObject *);
136static void update_all_slots(PyTypeObject *);
137
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000138typedef int (*update_callback)(PyTypeObject *, void *);
139static int update_subclasses(PyTypeObject *type, PyObject *name,
140 update_callback callback, void *data);
141static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
142 update_callback callback, void *data);
143
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000144static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000145mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000146{
147 PyTypeObject *subclass;
148 PyObject *ref, *subclasses, *old_mro;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000149 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000150
151 subclasses = type->tp_subclasses;
152 if (subclasses == NULL)
153 return 0;
154 assert(PyList_Check(subclasses));
155 n = PyList_GET_SIZE(subclasses);
156 for (i = 0; i < n; i++) {
157 ref = PyList_GET_ITEM(subclasses, i);
158 assert(PyWeakref_CheckRef(ref));
159 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
160 assert(subclass != NULL);
161 if ((PyObject *)subclass == Py_None)
162 continue;
163 assert(PyType_Check(subclass));
164 old_mro = subclass->tp_mro;
165 if (mro_internal(subclass) < 0) {
166 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000167 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000168 }
169 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000170 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000171 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000172 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000173 if (!tuple)
174 return -1;
175 if (PyList_Append(temp, tuple) < 0)
176 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000177 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000178 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000179 if (mro_subclasses(subclass, temp) < 0)
180 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000181 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000182 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000183}
184
185static int
186type_set_bases(PyTypeObject *type, PyObject *value, void *context)
187{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000188 Py_ssize_t i;
189 int r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000190 PyObject *ob, *temp;
Jeremy Hyltonfa955692007-02-27 18:29:45 +0000191 PyTypeObject *new_base, *old_base, *metatype;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000192 PyObject *old_bases, *old_mro;
193
194 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
195 PyErr_Format(PyExc_TypeError,
196 "can't set %s.__bases__", type->tp_name);
197 return -1;
198 }
199 if (!value) {
200 PyErr_Format(PyExc_TypeError,
201 "can't delete %s.__bases__", type->tp_name);
202 return -1;
203 }
204 if (!PyTuple_Check(value)) {
205 PyErr_Format(PyExc_TypeError,
206 "can only assign tuple to %s.__bases__, not %s",
207 type->tp_name, value->ob_type->tp_name);
208 return -1;
209 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000210 if (PyTuple_GET_SIZE(value) == 0) {
211 PyErr_Format(PyExc_TypeError,
212 "can only assign non-empty tuple to %s.__bases__, not ()",
213 type->tp_name);
214 return -1;
215 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000216 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
217 ob = PyTuple_GET_ITEM(value, i);
218 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
219 PyErr_Format(
220 PyExc_TypeError,
221 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
222 type->tp_name, ob->ob_type->tp_name);
223 return -1;
224 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000225 if (PyType_Check(ob)) {
226 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
227 PyErr_SetString(PyExc_TypeError,
228 "a __bases__ item causes an inheritance cycle");
229 return -1;
230 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000231 }
232 }
233
Jeremy Hyltonfa955692007-02-27 18:29:45 +0000234
235 metatype = most_derived_metaclass(type->ob_type, value);
236 if (metatype == NULL)
237 return -1;
238 if (metatype != type->ob_type) {
239 PyErr_SetString(PyExc_TypeError,
240 "assignment to __bases__ may not change "
241 "metatype");
242 return -1;
243 }
244
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000245 new_base = best_base(value);
246
247 if (!new_base) {
248 return -1;
249 }
250
251 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
252 return -1;
253
254 Py_INCREF(new_base);
255 Py_INCREF(value);
256
257 old_bases = type->tp_bases;
258 old_base = type->tp_base;
259 old_mro = type->tp_mro;
260
261 type->tp_bases = value;
262 type->tp_base = new_base;
263
264 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000265 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000266 }
267
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000268 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000269 if (!temp)
270 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000271
272 r = mro_subclasses(type, temp);
273
274 if (r < 0) {
275 for (i = 0; i < PyList_Size(temp); i++) {
276 PyTypeObject* cls;
277 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000278 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
279 "", 2, 2, &cls, &mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000280 Py_DECREF(cls->tp_mro);
281 cls->tp_mro = mro;
282 Py_INCREF(cls->tp_mro);
283 }
284 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000285 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000286 }
287
288 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000289
290 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000291 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000292 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000293 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000294
295 /* for now, sod that: just remove from all old_bases,
296 add to all new_bases */
297
298 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
299 ob = PyTuple_GET_ITEM(old_bases, i);
300 if (PyType_Check(ob)) {
301 remove_subclass(
302 (PyTypeObject*)ob, type);
303 }
304 }
305
306 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
307 ob = PyTuple_GET_ITEM(value, i);
308 if (PyType_Check(ob)) {
309 if (add_subclass((PyTypeObject*)ob, type) < 0)
310 r = -1;
311 }
312 }
313
314 update_all_slots(type);
315
316 Py_DECREF(old_bases);
317 Py_DECREF(old_base);
318 Py_DECREF(old_mro);
319
320 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000321
322 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000323 Py_DECREF(type->tp_bases);
324 Py_DECREF(type->tp_base);
325 if (type->tp_mro != old_mro) {
326 Py_DECREF(type->tp_mro);
327 }
328
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000329 type->tp_bases = old_bases;
330 type->tp_base = old_base;
331 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000332
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000333 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000334}
335
336static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000337type_dict(PyTypeObject *type, void *context)
338{
339 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000340 Py_INCREF(Py_None);
341 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000342 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000343 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000344}
345
Tim Peters24008312002-03-17 18:56:20 +0000346static PyObject *
347type_get_doc(PyTypeObject *type, void *context)
348{
349 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000350 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000351 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000352 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000353 if (result == NULL) {
354 result = Py_None;
355 Py_INCREF(result);
356 }
357 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000358 result = result->ob_type->tp_descr_get(result, NULL,
359 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000360 }
361 else {
362 Py_INCREF(result);
363 }
Tim Peters24008312002-03-17 18:56:20 +0000364 return result;
365}
366
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000367static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000368 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
369 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000370 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000371 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000372 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000373 {0}
374};
375
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000376static int
377type_compare(PyObject *v, PyObject *w)
378{
379 /* This is called with type objects only. So we
380 can just compare the addresses. */
381 Py_uintptr_t vv = (Py_uintptr_t)v;
382 Py_uintptr_t ww = (Py_uintptr_t)w;
383 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
384}
385
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000386static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000387type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000388{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000389 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000390 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000391
392 mod = type_module(type, NULL);
393 if (mod == NULL)
394 PyErr_Clear();
395 else if (!PyString_Check(mod)) {
396 Py_DECREF(mod);
397 mod = NULL;
398 }
399 name = type_name(type, NULL);
400 if (name == NULL)
401 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000402
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000403 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
404 kind = "class";
405 else
406 kind = "type";
407
Barry Warsaw7ce36942001-08-24 18:34:26 +0000408 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000409 rtn = PyString_FromFormat("<%s '%s.%s'>",
410 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000411 PyString_AS_STRING(mod),
412 PyString_AS_STRING(name));
413 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000414 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000415 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000416
Guido van Rossumc3542212001-08-16 09:18:56 +0000417 Py_XDECREF(mod);
418 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000419 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000420}
421
Tim Peters6d6c1a32001-08-02 04:15:00 +0000422static PyObject *
423type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
424{
425 PyObject *obj;
426
427 if (type->tp_new == NULL) {
428 PyErr_Format(PyExc_TypeError,
429 "cannot create '%.100s' instances",
430 type->tp_name);
431 return NULL;
432 }
433
Tim Peters3f996e72001-09-13 19:18:27 +0000434 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000435 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000436 /* Ugly exception: when the call was type(something),
437 don't call tp_init on the result. */
438 if (type == &PyType_Type &&
439 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
440 (kwds == NULL ||
441 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
442 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000443 /* If the returned object is not an instance of type,
444 it won't be initialized. */
445 if (!PyType_IsSubtype(obj->ob_type, type))
446 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000447 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000448 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
449 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000450 type->tp_init(obj, args, kwds) < 0) {
451 Py_DECREF(obj);
452 obj = NULL;
453 }
454 }
455 return obj;
456}
457
458PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000459PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000460{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000461 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000462 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
463 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000464
465 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000466 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000467 else
Anthony Baxtera6286212006-04-11 07:42:36 +0000468 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000469
Neil Schemenauerc806c882001-08-29 23:54:54 +0000470 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000471 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000472
Neil Schemenauerc806c882001-08-29 23:54:54 +0000473 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000474
Tim Peters6d6c1a32001-08-02 04:15:00 +0000475 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
476 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000477
Tim Peters6d6c1a32001-08-02 04:15:00 +0000478 if (type->tp_itemsize == 0)
479 PyObject_INIT(obj, type);
480 else
481 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000482
Tim Peters6d6c1a32001-08-02 04:15:00 +0000483 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000484 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000485 return obj;
486}
487
488PyObject *
489PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
490{
491 return type->tp_alloc(type, 0);
492}
493
Guido van Rossum9475a232001-10-05 20:51:39 +0000494/* Helpers for subtyping */
495
496static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000497traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
498{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000499 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000500 PyMemberDef *mp;
501
502 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000503 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000504 for (i = 0; i < n; i++, mp++) {
505 if (mp->type == T_OBJECT_EX) {
506 char *addr = (char *)self + mp->offset;
507 PyObject *obj = *(PyObject **)addr;
508 if (obj != NULL) {
509 int err = visit(obj, arg);
510 if (err)
511 return err;
512 }
513 }
514 }
515 return 0;
516}
517
518static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000519subtype_traverse(PyObject *self, visitproc visit, void *arg)
520{
521 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000522 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000523
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000524 /* Find the nearest base with a different tp_traverse,
525 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000526 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000527 base = type;
528 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
529 if (base->ob_size) {
530 int err = traverse_slots(base, self, visit, arg);
531 if (err)
532 return err;
533 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000534 base = base->tp_base;
535 assert(base);
536 }
537
538 if (type->tp_dictoffset != base->tp_dictoffset) {
539 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Woutersc6e55062006-04-15 21:47:09 +0000540 if (dictptr && *dictptr)
541 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000542 }
543
Thomas Woutersc6e55062006-04-15 21:47:09 +0000544 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000545 /* For a heaptype, the instances count as references
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000546 to the type. Traverse the type so the collector
Guido van Rossuma3862092002-06-10 15:24:42 +0000547 can find cycles involving this link. */
Thomas Woutersc6e55062006-04-15 21:47:09 +0000548 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000549
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000550 if (basetraverse)
551 return basetraverse(self, visit, arg);
552 return 0;
553}
554
555static void
556clear_slots(PyTypeObject *type, PyObject *self)
557{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000558 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000559 PyMemberDef *mp;
560
561 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000562 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000563 for (i = 0; i < n; i++, mp++) {
564 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
565 char *addr = (char *)self + mp->offset;
566 PyObject *obj = *(PyObject **)addr;
567 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000568 *(PyObject **)addr = NULL;
Thomas Woutersedf17d82006-04-15 17:28:34 +0000569 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000570 }
571 }
572 }
573}
574
575static int
576subtype_clear(PyObject *self)
577{
578 PyTypeObject *type, *base;
579 inquiry baseclear;
580
581 /* Find the nearest base with a different tp_clear
582 and clear slots while we're at it */
583 type = self->ob_type;
584 base = type;
585 while ((baseclear = base->tp_clear) == subtype_clear) {
586 if (base->ob_size)
587 clear_slots(base, self);
588 base = base->tp_base;
589 assert(base);
590 }
591
Guido van Rossuma3862092002-06-10 15:24:42 +0000592 /* There's no need to clear the instance dict (if any);
593 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000594
595 if (baseclear)
596 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000597 return 0;
598}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000599
600static void
601subtype_dealloc(PyObject *self)
602{
Guido van Rossum14227b42001-12-06 02:35:58 +0000603 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000604 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000605
Guido van Rossum22b13872002-08-06 21:41:44 +0000606 /* Extract the type; we expect it to be a heap type */
607 type = self->ob_type;
608 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000609
Guido van Rossum22b13872002-08-06 21:41:44 +0000610 /* Test whether the type has GC exactly once */
611
612 if (!PyType_IS_GC(type)) {
613 /* It's really rare to find a dynamic type that doesn't have
614 GC; it can only happen when deriving from 'object' and not
615 adding any slots or instance variables. This allows
616 certain simplifications: there's no need to call
617 clear_slots(), or DECREF the dict, or clear weakrefs. */
618
619 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000620 if (type->tp_del) {
621 type->tp_del(self);
622 if (self->ob_refcnt > 0)
623 return;
624 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000625
626 /* Find the nearest base with a different tp_dealloc */
627 base = type;
628 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
629 assert(base->ob_size == 0);
630 base = base->tp_base;
631 assert(base);
632 }
633
634 /* Call the base tp_dealloc() */
635 assert(basedealloc);
636 basedealloc(self);
637
638 /* Can't reference self beyond this point */
639 Py_DECREF(type);
640
641 /* Done */
642 return;
643 }
644
645 /* We get here only if the type has GC */
646
647 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000648 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000649 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000650 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000651 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000652 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000653 /* DO NOT restore GC tracking at this point. weakref callbacks
654 * (if any, and whether directly here or indirectly in something we
655 * call) may trigger GC, and if self is tracked at that point, it
656 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000657 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000658
Guido van Rossum59195fd2003-06-13 20:54:40 +0000659 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000660 base = type;
661 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000662 base = base->tp_base;
663 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000664 }
665
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000666 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000667 the finalizer (__del__), clearing slots, or clearing the instance
668 dict. */
669
Guido van Rossum1987c662003-05-29 14:29:23 +0000670 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
671 PyObject_ClearWeakRefs(self);
672
673 /* Maybe call finalizer; exit early if resurrected */
674 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000675 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000676 type->tp_del(self);
677 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000678 goto endlabel; /* resurrected */
679 else
680 _PyObject_GC_UNTRACK(self);
Brett Cannonf5bee302007-01-23 23:21:22 +0000681 /* New weakrefs could be created during the finalizer call.
682 If this occurs, clear them out without calling their
683 finalizers since they might rely on part of the object
684 being finalized that has already been destroyed. */
685 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
686 /* Modeled after GET_WEAKREFS_LISTPTR() */
687 PyWeakReference **list = (PyWeakReference **) \
688 PyObject_GET_WEAKREFS_LISTPTR(self);
689 while (*list)
690 _PyWeakref_ClearRef(*list);
691 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000692 }
693
Guido van Rossum59195fd2003-06-13 20:54:40 +0000694 /* Clear slots up to the nearest base with a different tp_dealloc */
695 base = type;
696 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
697 if (base->ob_size)
698 clear_slots(base, self);
699 base = base->tp_base;
700 assert(base);
701 }
702
Tim Peters6d6c1a32001-08-02 04:15:00 +0000703 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000704 if (type->tp_dictoffset && !base->tp_dictoffset) {
705 PyObject **dictptr = _PyObject_GetDictPtr(self);
706 if (dictptr != NULL) {
707 PyObject *dict = *dictptr;
708 if (dict != NULL) {
709 Py_DECREF(dict);
710 *dictptr = NULL;
711 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000712 }
713 }
714
Tim Peters0bd743c2003-11-13 22:50:00 +0000715 /* Call the base tp_dealloc(); first retrack self if
716 * basedealloc knows about gc.
717 */
718 if (PyType_IS_GC(base))
719 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000720 assert(basedealloc);
721 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000722
723 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000724 Py_DECREF(type);
725
Guido van Rossum0906e072002-08-07 20:42:09 +0000726 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000727 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000728 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000729 --_PyTrash_delete_nesting;
730
731 /* Explanation of the weirdness around the trashcan macros:
732
733 Q. What do the trashcan macros do?
734
735 A. Read the comment titled "Trashcan mechanism" in object.h.
736 For one, this explains why there must be a call to GC-untrack
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000737 before the trashcan begin macro. Without understanding the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000738 trashcan code, the answers to the following questions don't make
739 sense.
740
741 Q. Why do we GC-untrack before the trashcan and then immediately
742 GC-track again afterward?
743
744 A. In the case that the base class is GC-aware, the base class
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000745 probably GC-untracks the object. If it does that using the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000746 UNTRACK macro, this will crash when the object is already
747 untracked. Because we don't know what the base class does, the
748 only safe thing is to make sure the object is tracked when we
749 call the base class dealloc. But... The trashcan begin macro
750 requires that the object is *untracked* before it is called. So
751 the dance becomes:
752
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000753 GC untrack
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000754 trashcan begin
755 GC track
756
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000757 Q. Why did the last question say "immediately GC-track again"?
758 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +0000759
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000760 A. Because the code *used* to re-track immediately. Bad Idea.
761 self has a refcount of 0, and if gc ever gets its hands on it
762 (which can happen if any weakref callback gets invoked), it
763 looks like trash to gc too, and gc also tries to delete self
764 then. But we're already deleting self. Double dealloction is
765 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +0000766
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000767 Q. Why the bizarre (net-zero) manipulation of
768 _PyTrash_delete_nesting around the trashcan macros?
769
770 A. Some base classes (e.g. list) also use the trashcan mechanism.
771 The following scenario used to be possible:
772
773 - suppose the trashcan level is one below the trashcan limit
774
775 - subtype_dealloc() is called
776
777 - the trashcan limit is not yet reached, so the trashcan level
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000778 is incremented and the code between trashcan begin and end is
779 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000780
781 - this destroys much of the object's contents, including its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000782 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000783
784 - basedealloc() is called; this is really list_dealloc(), or
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000785 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000786
787 - the trashcan limit is now reached, so the object is put on the
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000788 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000789
790 - basedealloc() returns
791
792 - subtype_dealloc() decrefs the object's type
793
794 - subtype_dealloc() returns
795
796 - later, the trashcan code starts deleting the objects from its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000797 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000798
799 - subtype_dealloc() is called *AGAIN* for the same object
800
801 - at the very least (if the destroyed slots and __dict__ don't
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000802 cause problems) the object's type gets decref'ed a second
803 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000804
805 The remedy is to make sure that if the code between trashcan
806 begin and end in subtype_dealloc() is called, the code between
807 trashcan begin and end in basedealloc() will also be called.
808 This is done by decrementing the level after passing into the
809 trashcan block, and incrementing it just before leaving the
810 block.
811
812 But now it's possible that a chain of objects consisting solely
813 of objects whose deallocator is subtype_dealloc() will defeat
814 the trashcan mechanism completely: the decremented level means
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000815 that the effective level never reaches the limit. Therefore, we
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000816 *increment* the level *before* entering the trashcan block, and
817 matchingly decrement it after leaving. This means the trashcan
818 code will trigger a little early, but that's no big deal.
819
820 Q. Are there any live examples of code in need of all this
821 complexity?
822
823 A. Yes. See SF bug 668433 for code that crashed (when Python was
824 compiled in debug mode) before the trashcan level manipulations
825 were added. For more discussion, see SF patches 581742, 575073
826 and bug 574207.
827 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000828}
829
Jeremy Hylton938ace62002-07-17 16:30:39 +0000830static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000831
Tim Peters6d6c1a32001-08-02 04:15:00 +0000832/* type test with subclassing support */
833
834int
835PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
836{
837 PyObject *mro;
838
Guido van Rossum9478d072001-09-07 18:52:13 +0000839 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
840 return b == a || b == &PyBaseObject_Type;
841
Tim Peters6d6c1a32001-08-02 04:15:00 +0000842 mro = a->tp_mro;
843 if (mro != NULL) {
844 /* Deal with multiple inheritance without recursion
845 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000846 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000847 assert(PyTuple_Check(mro));
848 n = PyTuple_GET_SIZE(mro);
849 for (i = 0; i < n; i++) {
850 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
851 return 1;
852 }
853 return 0;
854 }
855 else {
856 /* a is not completely initilized yet; follow tp_base */
857 do {
858 if (a == b)
859 return 1;
860 a = a->tp_base;
861 } while (a != NULL);
862 return b == &PyBaseObject_Type;
863 }
864}
865
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000866/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000867 without looking in the instance dictionary
868 (so we can't use PyObject_GetAttr) but still binding
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000869 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +0000870 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000871 static variable used to cache the interned Python string.
872
873 Two variants:
874
875 - lookup_maybe() returns NULL without raising an exception
876 when the _PyType_Lookup() call fails;
877
878 - lookup_method() always raises an exception upon errors.
879*/
Guido van Rossum60718732001-08-28 17:47:51 +0000880
881static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000882lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000883{
884 PyObject *res;
885
886 if (*attrobj == NULL) {
887 *attrobj = PyString_InternFromString(attrstr);
888 if (*attrobj == NULL)
889 return NULL;
890 }
891 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000892 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000893 descrgetfunc f;
894 if ((f = res->ob_type->tp_descr_get) == NULL)
895 Py_INCREF(res);
896 else
897 res = f(res, self, (PyObject *)(self->ob_type));
898 }
899 return res;
900}
901
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000902static PyObject *
903lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
904{
905 PyObject *res = lookup_maybe(self, attrstr, attrobj);
906 if (res == NULL && !PyErr_Occurred())
907 PyErr_SetObject(PyExc_AttributeError, *attrobj);
908 return res;
909}
910
Guido van Rossum2730b132001-08-28 18:22:14 +0000911/* A variation of PyObject_CallMethod that uses lookup_method()
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000912 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +0000913 as lookup_method to cache the interned name string object. */
914
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000915static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000916call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
917{
918 va_list va;
919 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000920 va_start(va, format);
921
Guido van Rossumda21c012001-10-03 00:50:18 +0000922 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000923 if (func == NULL) {
924 va_end(va);
925 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000926 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000927 return NULL;
928 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000929
930 if (format && *format)
931 args = Py_VaBuildValue(format, va);
932 else
933 args = PyTuple_New(0);
934
935 va_end(va);
936
937 if (args == NULL)
938 return NULL;
939
940 assert(PyTuple_Check(args));
941 retval = PyObject_Call(func, args, NULL);
942
943 Py_DECREF(args);
944 Py_DECREF(func);
945
946 return retval;
947}
948
949/* Clone of call_method() that returns NotImplemented when the lookup fails. */
950
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000951static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000952call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
953{
954 va_list va;
955 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000956 va_start(va, format);
957
Guido van Rossumda21c012001-10-03 00:50:18 +0000958 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000959 if (func == NULL) {
960 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000961 if (!PyErr_Occurred()) {
962 Py_INCREF(Py_NotImplemented);
963 return Py_NotImplemented;
964 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000965 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000966 }
967
968 if (format && *format)
969 args = Py_VaBuildValue(format, va);
970 else
971 args = PyTuple_New(0);
972
973 va_end(va);
974
Guido van Rossum717ce002001-09-14 16:58:08 +0000975 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000976 return NULL;
977
Guido van Rossum717ce002001-09-14 16:58:08 +0000978 assert(PyTuple_Check(args));
979 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000980
981 Py_DECREF(args);
982 Py_DECREF(func);
983
984 return retval;
985}
986
Tim Petersa91e9642001-11-14 23:32:33 +0000987static int
988fill_classic_mro(PyObject *mro, PyObject *cls)
989{
990 PyObject *bases, *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000991 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +0000992
993 assert(PyList_Check(mro));
994 assert(PyClass_Check(cls));
995 i = PySequence_Contains(mro, cls);
996 if (i < 0)
997 return -1;
998 if (!i) {
999 if (PyList_Append(mro, cls) < 0)
1000 return -1;
1001 }
1002 bases = ((PyClassObject *)cls)->cl_bases;
1003 assert(bases && PyTuple_Check(bases));
1004 n = PyTuple_GET_SIZE(bases);
1005 for (i = 0; i < n; i++) {
1006 base = PyTuple_GET_ITEM(bases, i);
1007 if (fill_classic_mro(mro, base) < 0)
1008 return -1;
1009 }
1010 return 0;
1011}
1012
1013static PyObject *
1014classic_mro(PyObject *cls)
1015{
1016 PyObject *mro;
1017
1018 assert(PyClass_Check(cls));
1019 mro = PyList_New(0);
1020 if (mro != NULL) {
1021 if (fill_classic_mro(mro, cls) == 0)
1022 return mro;
1023 Py_DECREF(mro);
1024 }
1025 return NULL;
1026}
1027
Tim Petersea7f75d2002-12-07 21:39:16 +00001028/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001029 Method resolution order algorithm C3 described in
1030 "A Monotonic Superclass Linearization for Dylan",
1031 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001032 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001033 (OOPSLA 1996)
1034
Guido van Rossum98f33732002-11-25 21:36:54 +00001035 Some notes about the rules implied by C3:
1036
Tim Petersea7f75d2002-12-07 21:39:16 +00001037 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001038 It isn't legal to repeat a class in a list of base classes.
1039
1040 The next three properties are the 3 constraints in "C3".
1041
Tim Petersea7f75d2002-12-07 21:39:16 +00001042 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001043 If A precedes B in C's MRO, then A will precede B in the MRO of all
1044 subclasses of C.
1045
1046 Monotonicity.
1047 The MRO of a class must be an extension without reordering of the
1048 MRO of each of its superclasses.
1049
1050 Extended Precedence Graph (EPG).
1051 Linearization is consistent if there is a path in the EPG from
1052 each class to all its successors in the linearization. See
1053 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001054 */
1055
Tim Petersea7f75d2002-12-07 21:39:16 +00001056static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001057tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001058 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +00001059 size = PyList_GET_SIZE(list);
1060
1061 for (j = whence+1; j < size; j++) {
1062 if (PyList_GET_ITEM(list, j) == o)
1063 return 1;
1064 }
1065 return 0;
1066}
1067
Guido van Rossum98f33732002-11-25 21:36:54 +00001068static PyObject *
1069class_name(PyObject *cls)
1070{
1071 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1072 if (name == NULL) {
1073 PyErr_Clear();
1074 Py_XDECREF(name);
1075 name = PyObject_Repr(cls);
1076 }
1077 if (name == NULL)
1078 return NULL;
1079 if (!PyString_Check(name)) {
1080 Py_DECREF(name);
1081 return NULL;
1082 }
1083 return name;
1084}
1085
1086static int
1087check_duplicates(PyObject *list)
1088{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001089 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001090 /* Let's use a quadratic time algorithm,
1091 assuming that the bases lists is short.
1092 */
1093 n = PyList_GET_SIZE(list);
1094 for (i = 0; i < n; i++) {
1095 PyObject *o = PyList_GET_ITEM(list, i);
1096 for (j = i + 1; j < n; j++) {
1097 if (PyList_GET_ITEM(list, j) == o) {
1098 o = class_name(o);
1099 PyErr_Format(PyExc_TypeError,
1100 "duplicate base class %s",
1101 o ? PyString_AS_STRING(o) : "?");
1102 Py_XDECREF(o);
1103 return -1;
1104 }
1105 }
1106 }
1107 return 0;
1108}
1109
1110/* Raise a TypeError for an MRO order disagreement.
1111
1112 It's hard to produce a good error message. In the absence of better
1113 insight into error reporting, report the classes that were candidates
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001114 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001115 order in which they should be put in the MRO, but it's hard to
1116 diagnose what constraint can't be satisfied.
1117*/
1118
1119static void
1120set_mro_error(PyObject *to_merge, int *remain)
1121{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001122 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001123 char buf[1000];
1124 PyObject *k, *v;
1125 PyObject *set = PyDict_New();
Georg Brandl5c170fd2006-03-17 19:03:25 +00001126 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001127
1128 to_merge_size = PyList_GET_SIZE(to_merge);
1129 for (i = 0; i < to_merge_size; i++) {
1130 PyObject *L = PyList_GET_ITEM(to_merge, i);
1131 if (remain[i] < PyList_GET_SIZE(L)) {
1132 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Georg Brandl5c170fd2006-03-17 19:03:25 +00001133 if (PyDict_SetItem(set, c, Py_None) < 0) {
1134 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001135 return;
Georg Brandl5c170fd2006-03-17 19:03:25 +00001136 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001137 }
1138 }
1139 n = PyDict_Size(set);
1140
Raymond Hettingerf394df42003-04-06 19:13:41 +00001141 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1142consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001143 i = 0;
Skip Montanaro429433b2006-04-18 00:35:43 +00001144 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001145 PyObject *name = class_name(k);
1146 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1147 name ? PyString_AS_STRING(name) : "?");
1148 Py_XDECREF(name);
Skip Montanaro429433b2006-04-18 00:35:43 +00001149 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001150 buf[off++] = ',';
1151 buf[off] = '\0';
1152 }
1153 }
1154 PyErr_SetString(PyExc_TypeError, buf);
1155 Py_DECREF(set);
1156}
1157
Tim Petersea7f75d2002-12-07 21:39:16 +00001158static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001159pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001160 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001161 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001162 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001163
Guido van Rossum1f121312002-11-14 19:49:16 +00001164 to_merge_size = PyList_GET_SIZE(to_merge);
1165
Guido van Rossum98f33732002-11-25 21:36:54 +00001166 /* remain stores an index into each sublist of to_merge.
1167 remain[i] is the index of the next base in to_merge[i]
1168 that is not included in acc.
1169 */
Anthony Baxtera6286212006-04-11 07:42:36 +00001170 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001171 if (remain == NULL)
1172 return -1;
1173 for (i = 0; i < to_merge_size; i++)
1174 remain[i] = 0;
1175
1176 again:
1177 empty_cnt = 0;
1178 for (i = 0; i < to_merge_size; i++) {
1179 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001180
Guido van Rossum1f121312002-11-14 19:49:16 +00001181 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1182
1183 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1184 empty_cnt++;
1185 continue;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001186 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001187
Guido van Rossum98f33732002-11-25 21:36:54 +00001188 /* Choose next candidate for MRO.
1189
1190 The input sequences alone can determine the choice.
1191 If not, choose the class which appears in the MRO
1192 of the earliest direct superclass of the new class.
1193 */
1194
Guido van Rossum1f121312002-11-14 19:49:16 +00001195 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1196 for (j = 0; j < to_merge_size; j++) {
1197 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001198 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001199 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001200 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001201 }
1202 ok = PyList_Append(acc, candidate);
1203 if (ok < 0) {
1204 PyMem_Free(remain);
1205 return -1;
1206 }
1207 for (j = 0; j < to_merge_size; j++) {
1208 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001209 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1210 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001211 remain[j]++;
1212 }
1213 }
1214 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001215 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001216 }
1217
Guido van Rossum98f33732002-11-25 21:36:54 +00001218 if (empty_cnt == to_merge_size) {
1219 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001220 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001221 }
1222 set_mro_error(to_merge, remain);
1223 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001224 return -1;
1225}
1226
Tim Peters6d6c1a32001-08-02 04:15:00 +00001227static PyObject *
1228mro_implementation(PyTypeObject *type)
1229{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001230 Py_ssize_t i, n;
1231 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001232 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001233 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001234
Guido van Rossum63517572002-06-18 16:44:57 +00001235 if(type->tp_dict == NULL) {
1236 if(PyType_Ready(type) < 0)
1237 return NULL;
1238 }
1239
Guido van Rossum98f33732002-11-25 21:36:54 +00001240 /* Find a superclass linearization that honors the constraints
1241 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001242 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001243
1244 to_merge is a list of lists, where each list is a superclass
1245 linearization implied by a base class. The last element of
1246 to_merge is the declared list of bases.
1247 */
1248
Tim Peters6d6c1a32001-08-02 04:15:00 +00001249 bases = type->tp_bases;
1250 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001251
1252 to_merge = PyList_New(n+1);
1253 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001254 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001255
Tim Peters6d6c1a32001-08-02 04:15:00 +00001256 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001257 PyObject *base = PyTuple_GET_ITEM(bases, i);
1258 PyObject *parentMRO;
1259 if (PyType_Check(base))
1260 parentMRO = PySequence_List(
1261 ((PyTypeObject*)base)->tp_mro);
1262 else
1263 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001264 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001265 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001266 return NULL;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001267 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001268
1269 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001270 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001271
1272 bases_aslist = PySequence_List(bases);
1273 if (bases_aslist == NULL) {
1274 Py_DECREF(to_merge);
1275 return NULL;
1276 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001277 /* This is just a basic sanity check. */
1278 if (check_duplicates(bases_aslist) < 0) {
1279 Py_DECREF(to_merge);
1280 Py_DECREF(bases_aslist);
1281 return NULL;
1282 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001283 PyList_SET_ITEM(to_merge, n, bases_aslist);
1284
1285 result = Py_BuildValue("[O]", (PyObject *)type);
1286 if (result == NULL) {
1287 Py_DECREF(to_merge);
1288 return NULL;
1289 }
1290
1291 ok = pmerge(result, to_merge);
1292 Py_DECREF(to_merge);
1293 if (ok < 0) {
1294 Py_DECREF(result);
1295 return NULL;
1296 }
1297
Tim Peters6d6c1a32001-08-02 04:15:00 +00001298 return result;
1299}
1300
1301static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001302mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303{
1304 PyTypeObject *type = (PyTypeObject *)self;
1305
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306 return mro_implementation(type);
1307}
1308
1309static int
1310mro_internal(PyTypeObject *type)
1311{
1312 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001313 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001314
1315 if (type->ob_type == &PyType_Type) {
1316 result = mro_implementation(type);
1317 }
1318 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001319 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001320 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001321 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001322 if (mro == NULL)
1323 return -1;
1324 result = PyObject_CallObject(mro, NULL);
1325 Py_DECREF(mro);
1326 }
1327 if (result == NULL)
1328 return -1;
1329 tuple = PySequence_Tuple(result);
1330 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001331 if (tuple == NULL)
1332 return -1;
1333 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001334 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001335 PyObject *cls;
1336 PyTypeObject *solid;
1337
1338 solid = solid_base(type);
1339
1340 len = PyTuple_GET_SIZE(tuple);
1341
1342 for (i = 0; i < len; i++) {
1343 PyTypeObject *t;
1344 cls = PyTuple_GET_ITEM(tuple, i);
1345 if (PyClass_Check(cls))
1346 continue;
1347 else if (!PyType_Check(cls)) {
1348 PyErr_Format(PyExc_TypeError,
1349 "mro() returned a non-class ('%.500s')",
1350 cls->ob_type->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001351 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001352 return -1;
1353 }
1354 t = (PyTypeObject*)cls;
1355 if (!PyType_IsSubtype(solid, solid_base(t))) {
1356 PyErr_Format(PyExc_TypeError,
1357 "mro() returned base with unsuitable layout ('%.500s')",
1358 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001359 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001360 return -1;
1361 }
1362 }
1363 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001364 type->tp_mro = tuple;
1365 return 0;
1366}
1367
1368
1369/* Calculate the best base amongst multiple base classes.
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001370 This is the first one that's on the path to the "solid base".
1371
1372 Requires that all base classes be types or classic classes.
1373
1374 Will return NULL with TypeError set if
1375 1) the base classes have conflicting layout instances, or
1376 2) all the bases are classic classes.
1377*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00001378
1379static PyTypeObject *
1380best_base(PyObject *bases)
1381{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001382 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001383 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001384 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001385
1386 assert(PyTuple_Check(bases));
1387 n = PyTuple_GET_SIZE(bases);
1388 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001389 base = NULL;
1390 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001391 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001392 base_proto = PyTuple_GET_ITEM(bases, i);
1393 if (PyClass_Check(base_proto))
1394 continue;
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001395 assert(PyType_Check(base_proto));
Tim Petersa91e9642001-11-14 23:32:33 +00001396 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001397 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001398 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001399 return NULL;
1400 }
1401 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001402 if (winner == NULL) {
1403 winner = candidate;
1404 base = base_i;
1405 }
1406 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001407 ;
1408 else if (PyType_IsSubtype(candidate, winner)) {
1409 winner = candidate;
1410 base = base_i;
1411 }
1412 else {
1413 PyErr_SetString(
1414 PyExc_TypeError,
1415 "multiple bases have "
1416 "instance lay-out conflict");
1417 return NULL;
1418 }
1419 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001420 if (base == NULL)
1421 PyErr_SetString(PyExc_TypeError,
1422 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001423 return base;
1424}
1425
1426static int
1427extra_ivars(PyTypeObject *type, PyTypeObject *base)
1428{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001429 size_t t_size = type->tp_basicsize;
1430 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001431
Guido van Rossum9676b222001-08-17 20:32:36 +00001432 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001433 if (type->tp_itemsize || base->tp_itemsize) {
1434 /* If itemsize is involved, stricter rules */
1435 return t_size != b_size ||
1436 type->tp_itemsize != base->tp_itemsize;
1437 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001438 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1439 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1440 t_size -= sizeof(PyObject *);
1441 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1442 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1443 t_size -= sizeof(PyObject *);
1444
1445 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001446}
1447
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001448/* Return the type object that will determine the layout of the instance. */
1449
Tim Peters6d6c1a32001-08-02 04:15:00 +00001450static PyTypeObject *
1451solid_base(PyTypeObject *type)
1452{
1453 PyTypeObject *base;
1454
1455 if (type->tp_base)
1456 base = solid_base(type->tp_base);
1457 else
1458 base = &PyBaseObject_Type;
1459 if (extra_ivars(type, base))
1460 return type;
1461 else
1462 return base;
1463}
1464
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001465/* Determine the proper metatype to deal with this, and check some
1466 error cases while we're at it. Note that if some other metatype
1467 wins to contract, it's possible that its instances are not types.
1468
1469 Error cases of interest: 1. The metaclass is not a subclass of a
1470 base class. 2. A non-type, non-classic base class appears before
1471 type.
1472*/
1473
1474static PyTypeObject *
1475most_derived_metaclass(PyTypeObject *metatype, PyObject *bases)
1476{
1477 Py_ssize_t nbases, i;
1478 PyTypeObject *winner;
1479 /* types_ordered: One of three states possible:
1480 0 type is in bases
1481 1 non-types also in bases
1482 2 type follows non-type in bases (error)
1483 */
1484 int types_ordered = 0;
1485
1486 nbases = PyTuple_GET_SIZE(bases);
1487 winner = metatype;
1488 for (i = 0; i < nbases; i++) {
1489 PyObject *tmp = PyTuple_GET_ITEM(bases, i);
1490 PyTypeObject *tmptype = tmp->ob_type;
1491 if (tmptype == &PyClass_Type)
1492 continue; /* Special case classic classes */
1493 if (!PyType_Check(tmp)) {
1494 PyErr_SetString(PyExc_TypeError,
1495 "bases must be types");
1496 return NULL;
1497 }
1498 if (PyObject_IsSubclass(tmp, (PyObject*)&PyType_Type)) {
1499 if (types_ordered == 1) {
1500 types_ordered = 2;
1501 }
1502 }
1503 else if (!types_ordered)
1504 types_ordered = 1;
1505 if (winner == tmptype)
1506 continue;
1507 if (PyType_IsSubtype(winner, tmptype))
1508 continue;
1509 if (PyType_IsSubtype(tmptype, winner)) {
1510 winner = tmptype;
1511 continue;
1512 }
1513 PyErr_SetString(PyExc_TypeError,
1514 "metaclass conflict: "
1515 "the metaclass of a derived class "
1516 "must be a (non-strict) subclass "
1517 "of the metaclasses of all its bases");
1518 return NULL;
1519 }
1520 if (types_ordered == 2) {
1521 PyErr_SetString(PyExc_TypeError,
1522 "metaclass conflict: "
1523 "type must occur in bases before other "
1524 "non-classic base classes");
1525 return NULL;
1526 }
1527 return winner;
1528}
1529
Jeremy Hylton938ace62002-07-17 16:30:39 +00001530static void object_dealloc(PyObject *);
1531static int object_init(PyObject *, PyObject *, PyObject *);
1532static int update_slot(PyTypeObject *, PyObject *);
1533static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001534
1535static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001536subtype_dict(PyObject *obj, void *context)
1537{
1538 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1539 PyObject *dict;
1540
1541 if (dictptr == NULL) {
1542 PyErr_SetString(PyExc_AttributeError,
1543 "This object has no __dict__");
1544 return NULL;
1545 }
1546 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001547 if (dict == NULL)
1548 *dictptr = dict = PyDict_New();
1549 Py_XINCREF(dict);
1550 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001551}
1552
Guido van Rossum6661be32001-10-26 04:26:12 +00001553static int
1554subtype_setdict(PyObject *obj, PyObject *value, void *context)
1555{
1556 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1557 PyObject *dict;
1558
1559 if (dictptr == NULL) {
1560 PyErr_SetString(PyExc_AttributeError,
1561 "This object has no __dict__");
1562 return -1;
1563 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001564 if (value != NULL && !PyDict_Check(value)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001565 PyErr_Format(PyExc_TypeError,
1566 "__dict__ must be set to a dictionary, "
1567 "not a '%.200s'", value->ob_type->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001568 return -1;
1569 }
1570 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001571 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001572 *dictptr = value;
1573 Py_XDECREF(dict);
1574 return 0;
1575}
1576
Guido van Rossumad47da02002-08-12 19:05:44 +00001577static PyObject *
1578subtype_getweakref(PyObject *obj, void *context)
1579{
1580 PyObject **weaklistptr;
1581 PyObject *result;
1582
1583 if (obj->ob_type->tp_weaklistoffset == 0) {
1584 PyErr_SetString(PyExc_AttributeError,
Fred Drake7a36f5f2006-08-04 05:17:21 +00001585 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001586 return NULL;
1587 }
1588 assert(obj->ob_type->tp_weaklistoffset > 0);
1589 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001590 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001591 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001592 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001593 if (*weaklistptr == NULL)
1594 result = Py_None;
1595 else
1596 result = *weaklistptr;
1597 Py_INCREF(result);
1598 return result;
1599}
1600
Guido van Rossum373c7412003-01-07 13:41:37 +00001601/* Three variants on the subtype_getsets list. */
1602
1603static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001604 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001605 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001606 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001607 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001608 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001609};
1610
Guido van Rossum373c7412003-01-07 13:41:37 +00001611static PyGetSetDef subtype_getsets_dict_only[] = {
1612 {"__dict__", subtype_dict, subtype_setdict,
1613 PyDoc_STR("dictionary for instance variables (if defined)")},
1614 {0}
1615};
1616
1617static PyGetSetDef subtype_getsets_weakref_only[] = {
1618 {"__weakref__", subtype_getweakref, NULL,
1619 PyDoc_STR("list of weak references to the object (if defined)")},
1620 {0}
1621};
1622
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001623static int
1624valid_identifier(PyObject *s)
1625{
Guido van Rossum03013a02002-07-16 14:30:28 +00001626 unsigned char *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001627 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001628
1629 if (!PyString_Check(s)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001630 PyErr_Format(PyExc_TypeError,
1631 "__slots__ items must be strings, not '%.200s'",
1632 s->ob_type->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001633 return 0;
1634 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001635 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001636 n = PyString_GET_SIZE(s);
1637 /* We must reject an empty name. As a hack, we bump the
1638 length to 1 so that the loop will balk on the trailing \0. */
1639 if (n == 0)
1640 n = 1;
1641 for (i = 0; i < n; i++, p++) {
1642 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1643 PyErr_SetString(PyExc_TypeError,
1644 "__slots__ must be identifiers");
1645 return 0;
1646 }
1647 }
1648 return 1;
1649}
1650
Martin v. Löwisd919a592002-10-14 21:07:28 +00001651#ifdef Py_USING_UNICODE
1652/* Replace Unicode objects in slots. */
1653
1654static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001655_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001656{
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001657 PyObject *tmp = NULL;
1658 PyObject *slot_name, *new_name;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001659 Py_ssize_t i;
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001660
Martin v. Löwisd919a592002-10-14 21:07:28 +00001661 for (i = 0; i < nslots; i++) {
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001662 if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
1663 if (tmp == NULL) {
1664 tmp = PySequence_List(slots);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001665 if (tmp == NULL)
1666 return NULL;
1667 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001668 new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
1669 NULL);
1670 if (new_name == NULL) {
Martin v. Löwisd919a592002-10-14 21:07:28 +00001671 Py_DECREF(tmp);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001672 return NULL;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001673 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001674 Py_INCREF(new_name);
1675 PyList_SET_ITEM(tmp, i, new_name);
1676 Py_DECREF(slot_name);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001677 }
1678 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001679 if (tmp != NULL) {
1680 slots = PyList_AsTuple(tmp);
1681 Py_DECREF(tmp);
1682 }
1683 return slots;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001684}
1685#endif
1686
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001687static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001688type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1689{
1690 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001691 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001692 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001693 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001694 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001695 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001696 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001697 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001698
Tim Peters3abca122001-10-27 19:37:48 +00001699 assert(args != NULL && PyTuple_Check(args));
1700 assert(kwds == NULL || PyDict_Check(kwds));
1701
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001702 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001703 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001704 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1705 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001706
1707 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1708 PyObject *x = PyTuple_GET_ITEM(args, 0);
1709 Py_INCREF(x->ob_type);
1710 return (PyObject *) x->ob_type;
1711 }
1712
1713 /* SF bug 475327 -- if that didn't trigger, we need 3
1714 arguments. but PyArg_ParseTupleAndKeywords below may give
1715 a msg saying type() needs exactly 3. */
1716 if (nargs + nkwds != 3) {
1717 PyErr_SetString(PyExc_TypeError,
1718 "type() takes 1 or 3 arguments");
1719 return NULL;
1720 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001721 }
1722
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001723 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001724 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1725 &name,
1726 &PyTuple_Type, &bases,
1727 &PyDict_Type, &dict))
1728 return NULL;
1729
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001730 winner = most_derived_metaclass(metatype, bases);
1731 if (winner == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001732 return NULL;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001733 if (winner != metatype) {
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001734 if (winner->tp_new != type_new) /* Pass it to the winner */ {
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001735 return winner->tp_new(winner, args, kwds);
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001736 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001737 metatype = winner;
1738 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001739
1740 /* Adjust for empty tuple bases */
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001741 nbases = PyTuple_GET_SIZE(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001742 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001743 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001744 if (bases == NULL)
1745 return NULL;
1746 nbases = 1;
1747 }
1748 else
1749 Py_INCREF(bases);
1750
1751 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1752
1753 /* Calculate best base, and check that all bases are type objects */
1754 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001755 if (base == NULL) {
1756 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001757 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001758 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001759 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1760 PyErr_Format(PyExc_TypeError,
1761 "type '%.100s' is not an acceptable base type",
1762 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001763 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001764 return NULL;
1765 }
1766
Tim Peters6d6c1a32001-08-02 04:15:00 +00001767 /* Check for a __slots__ sequence variable in dict, and count it */
1768 slots = PyDict_GetItemString(dict, "__slots__");
1769 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001770 add_dict = 0;
1771 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001772 may_add_dict = base->tp_dictoffset == 0;
1773 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1774 if (slots == NULL) {
1775 if (may_add_dict) {
1776 add_dict++;
1777 }
1778 if (may_add_weak) {
1779 add_weak++;
1780 }
1781 }
1782 else {
1783 /* Have slots */
1784
Tim Peters6d6c1a32001-08-02 04:15:00 +00001785 /* Make it into a tuple */
1786 if (PyString_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001787 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001788 else
1789 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001790 if (slots == NULL) {
1791 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001792 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001793 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001794 assert(PyTuple_Check(slots));
1795
1796 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001797 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001798 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001799 PyErr_Format(PyExc_TypeError,
1800 "nonempty __slots__ "
1801 "not supported for subtype of '%s'",
1802 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001803 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001804 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001805 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001806 return NULL;
1807 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001808
Martin v. Löwisd919a592002-10-14 21:07:28 +00001809#ifdef Py_USING_UNICODE
1810 tmp = _unicode_to_string(slots, nslots);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001811 if (tmp == NULL)
1812 goto bad_slots;
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001813 if (tmp != slots) {
1814 Py_DECREF(slots);
1815 slots = tmp;
1816 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001817#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001818 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001819 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001820 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1821 char *s;
1822 if (!valid_identifier(tmp))
1823 goto bad_slots;
1824 assert(PyString_Check(tmp));
1825 s = PyString_AS_STRING(tmp);
1826 if (strcmp(s, "__dict__") == 0) {
1827 if (!may_add_dict || add_dict) {
1828 PyErr_SetString(PyExc_TypeError,
1829 "__dict__ slot disallowed: "
1830 "we already got one");
1831 goto bad_slots;
1832 }
1833 add_dict++;
1834 }
1835 if (strcmp(s, "__weakref__") == 0) {
1836 if (!may_add_weak || add_weak) {
1837 PyErr_SetString(PyExc_TypeError,
1838 "__weakref__ slot disallowed: "
1839 "either we already got one, "
1840 "or __itemsize__ != 0");
1841 goto bad_slots;
1842 }
1843 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001844 }
1845 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001846
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00001847 /* Copy slots into a list, mangle names and sort them.
1848 Sorted names are needed for __class__ assignment.
1849 Convert them back to tuple at the end.
1850 */
1851 newslots = PyList_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001852 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001853 goto bad_slots;
1854 for (i = j = 0; i < nslots; i++) {
1855 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001856 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001857 s = PyString_AS_STRING(tmp);
1858 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1859 (add_weak && strcmp(s, "__weakref__") == 0))
1860 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001861 tmp =_Py_Mangle(name, tmp);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001862 if (!tmp)
1863 goto bad_slots;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00001864 PyList_SET_ITEM(newslots, j, tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00001865 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001866 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001867 assert(j == nslots - add_dict - add_weak);
1868 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001869 Py_DECREF(slots);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00001870 if (PyList_Sort(newslots) == -1) {
1871 Py_DECREF(bases);
1872 Py_DECREF(newslots);
1873 return NULL;
1874 }
1875 slots = PyList_AsTuple(newslots);
1876 Py_DECREF(newslots);
1877 if (slots == NULL) {
1878 Py_DECREF(bases);
1879 return NULL;
1880 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001881
Guido van Rossumad47da02002-08-12 19:05:44 +00001882 /* Secondary bases may provide weakrefs or dict */
1883 if (nbases > 1 &&
1884 ((may_add_dict && !add_dict) ||
1885 (may_add_weak && !add_weak))) {
1886 for (i = 0; i < nbases; i++) {
1887 tmp = PyTuple_GET_ITEM(bases, i);
1888 if (tmp == (PyObject *)base)
1889 continue; /* Skip primary base */
1890 if (PyClass_Check(tmp)) {
1891 /* Classic base class provides both */
1892 if (may_add_dict && !add_dict)
1893 add_dict++;
1894 if (may_add_weak && !add_weak)
1895 add_weak++;
1896 break;
1897 }
1898 assert(PyType_Check(tmp));
1899 tmptype = (PyTypeObject *)tmp;
1900 if (may_add_dict && !add_dict &&
1901 tmptype->tp_dictoffset != 0)
1902 add_dict++;
1903 if (may_add_weak && !add_weak &&
1904 tmptype->tp_weaklistoffset != 0)
1905 add_weak++;
1906 if (may_add_dict && !add_dict)
1907 continue;
1908 if (may_add_weak && !add_weak)
1909 continue;
1910 /* Nothing more to check */
1911 break;
1912 }
1913 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001914 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001915
1916 /* XXX From here until type is safely allocated,
1917 "return NULL" may leak slots! */
1918
1919 /* Allocate the type object */
1920 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001921 if (type == NULL) {
1922 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001923 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001924 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001925 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001926
1927 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001928 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001929 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00001930 et->ht_name = name;
1931 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001932
Guido van Rossumdc91b992001-08-08 22:26:22 +00001933 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001934 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1935 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001936 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1937 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001938
1939 /* It's a new-style number unless it specifically inherits any
1940 old-style numeric behavior */
1941 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1942 (base->tp_as_number == NULL))
1943 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1944
1945 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001946 type->tp_as_number = &et->as_number;
1947 type->tp_as_sequence = &et->as_sequence;
1948 type->tp_as_mapping = &et->as_mapping;
1949 type->tp_as_buffer = &et->as_buffer;
1950 type->tp_name = PyString_AS_STRING(name);
1951
1952 /* Set tp_base and tp_bases */
1953 type->tp_bases = bases;
1954 Py_INCREF(base);
1955 type->tp_base = base;
1956
Guido van Rossum687ae002001-10-15 22:03:32 +00001957 /* Initialize tp_dict from passed-in dict */
1958 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001959 if (dict == NULL) {
1960 Py_DECREF(type);
1961 return NULL;
1962 }
1963
Guido van Rossumc3542212001-08-16 09:18:56 +00001964 /* Set __module__ in the dict */
1965 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1966 tmp = PyEval_GetGlobals();
1967 if (tmp != NULL) {
1968 tmp = PyDict_GetItemString(tmp, "__name__");
1969 if (tmp != NULL) {
1970 if (PyDict_SetItemString(dict, "__module__",
1971 tmp) < 0)
1972 return NULL;
1973 }
1974 }
1975 }
1976
Tim Peters2f93e282001-10-04 05:27:00 +00001977 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001978 and is a string. The __doc__ accessor will first look for tp_doc;
1979 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001980 */
1981 {
1982 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1983 if (doc != NULL && PyString_Check(doc)) {
1984 const size_t n = (size_t)PyString_GET_SIZE(doc);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001985 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001986 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00001987 Py_DECREF(type);
1988 return NULL;
1989 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001990 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001991 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00001992 }
1993 }
1994
Tim Peters6d6c1a32001-08-02 04:15:00 +00001995 /* Special-case __new__: if it's a plain function,
1996 make it a static function */
1997 tmp = PyDict_GetItemString(dict, "__new__");
1998 if (tmp != NULL && PyFunction_Check(tmp)) {
1999 tmp = PyStaticMethod_New(tmp);
2000 if (tmp == NULL) {
2001 Py_DECREF(type);
2002 return NULL;
2003 }
2004 PyDict_SetItemString(dict, "__new__", tmp);
2005 Py_DECREF(tmp);
2006 }
2007
2008 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002009 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00002010 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002011 if (slots != NULL) {
2012 for (i = 0; i < nslots; i++, mp++) {
2013 mp->name = PyString_AS_STRING(
2014 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00002015 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002016 mp->offset = slotoffset;
Žiga Seilnacht89032082007-03-11 15:54:54 +00002017
2018 /* __dict__ and __weakref__ are already filtered out */
2019 assert(strcmp(mp->name, "__dict__") != 0);
2020 assert(strcmp(mp->name, "__weakref__") != 0);
2021
Tim Peters6d6c1a32001-08-02 04:15:00 +00002022 slotoffset += sizeof(PyObject *);
2023 }
2024 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002025 if (add_dict) {
2026 if (base->tp_itemsize)
2027 type->tp_dictoffset = -(long)sizeof(PyObject *);
2028 else
2029 type->tp_dictoffset = slotoffset;
2030 slotoffset += sizeof(PyObject *);
2031 }
2032 if (add_weak) {
2033 assert(!base->tp_itemsize);
2034 type->tp_weaklistoffset = slotoffset;
2035 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002036 }
2037 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002038 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00002039 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002040
2041 if (type->tp_weaklistoffset && type->tp_dictoffset)
2042 type->tp_getset = subtype_getsets_full;
2043 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2044 type->tp_getset = subtype_getsets_weakref_only;
2045 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2046 type->tp_getset = subtype_getsets_dict_only;
2047 else
2048 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002049
2050 /* Special case some slots */
2051 if (type->tp_dictoffset != 0 || nslots > 0) {
2052 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2053 type->tp_getattro = PyObject_GenericGetAttr;
2054 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2055 type->tp_setattro = PyObject_GenericSetAttr;
2056 }
2057 type->tp_dealloc = subtype_dealloc;
2058
Guido van Rossum9475a232001-10-05 20:51:39 +00002059 /* Enable GC unless there are really no instance variables possible */
2060 if (!(type->tp_basicsize == sizeof(PyObject) &&
2061 type->tp_itemsize == 0))
2062 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2063
Tim Peters6d6c1a32001-08-02 04:15:00 +00002064 /* Always override allocation strategy to use regular heap */
2065 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00002066 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002067 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00002068 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002069 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00002070 }
2071 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002072 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002073
2074 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002075 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002076 Py_DECREF(type);
2077 return NULL;
2078 }
2079
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002080 /* Put the proper slots in place */
2081 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002082
Tim Peters6d6c1a32001-08-02 04:15:00 +00002083 return (PyObject *)type;
2084}
2085
2086/* Internal API to look for a name through the MRO.
2087 This returns a borrowed reference, and doesn't set an exception! */
2088PyObject *
2089_PyType_Lookup(PyTypeObject *type, PyObject *name)
2090{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002091 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002092 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002093
Guido van Rossum687ae002001-10-15 22:03:32 +00002094 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002095 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002096
2097 /* If mro is NULL, the type is either not yet initialized
2098 by PyType_Ready(), or already cleared by type_clear().
2099 Either way the safest thing to do is to return NULL. */
2100 if (mro == NULL)
2101 return NULL;
2102
Tim Peters6d6c1a32001-08-02 04:15:00 +00002103 assert(PyTuple_Check(mro));
2104 n = PyTuple_GET_SIZE(mro);
2105 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002106 base = PyTuple_GET_ITEM(mro, i);
2107 if (PyClass_Check(base))
2108 dict = ((PyClassObject *)base)->cl_dict;
2109 else {
2110 assert(PyType_Check(base));
2111 dict = ((PyTypeObject *)base)->tp_dict;
2112 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002113 assert(dict && PyDict_Check(dict));
2114 res = PyDict_GetItem(dict, name);
2115 if (res != NULL)
2116 return res;
2117 }
2118 return NULL;
2119}
2120
2121/* This is similar to PyObject_GenericGetAttr(),
2122 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2123static PyObject *
2124type_getattro(PyTypeObject *type, PyObject *name)
2125{
2126 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002127 PyObject *meta_attribute, *attribute;
2128 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002129
2130 /* Initialize this type (we'll assume the metatype is initialized) */
2131 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002132 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002133 return NULL;
2134 }
2135
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002136 /* No readable descriptor found yet */
2137 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002138
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002139 /* Look for the attribute in the metatype */
2140 meta_attribute = _PyType_Lookup(metatype, name);
2141
2142 if (meta_attribute != NULL) {
2143 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002144
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002145 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2146 /* Data descriptors implement tp_descr_set to intercept
2147 * writes. Assume the attribute is not overridden in
2148 * type's tp_dict (and bases): call the descriptor now.
2149 */
2150 return meta_get(meta_attribute, (PyObject *)type,
2151 (PyObject *)metatype);
2152 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002153 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002154 }
2155
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002156 /* No data descriptor found on metatype. Look in tp_dict of this
2157 * type and its bases */
2158 attribute = _PyType_Lookup(type, name);
2159 if (attribute != NULL) {
2160 /* Implement descriptor functionality, if any */
2161 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002162
2163 Py_XDECREF(meta_attribute);
2164
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002165 if (local_get != NULL) {
2166 /* NULL 2nd argument indicates the descriptor was
2167 * found on the target object itself (or a base) */
2168 return local_get(attribute, (PyObject *)NULL,
2169 (PyObject *)type);
2170 }
Tim Peters34592512002-07-11 06:23:50 +00002171
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002172 Py_INCREF(attribute);
2173 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002174 }
2175
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002176 /* No attribute found in local __dict__ (or bases): use the
2177 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002178 if (meta_get != NULL) {
2179 PyObject *res;
2180 res = meta_get(meta_attribute, (PyObject *)type,
2181 (PyObject *)metatype);
2182 Py_DECREF(meta_attribute);
2183 return res;
2184 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002185
2186 /* If an ordinary attribute was found on the metatype, return it now */
2187 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002188 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002189 }
2190
2191 /* Give up */
2192 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002193 "type object '%.50s' has no attribute '%.400s'",
2194 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002195 return NULL;
2196}
2197
2198static int
2199type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2200{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002201 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2202 PyErr_Format(
2203 PyExc_TypeError,
2204 "can't set attributes of built-in/extension type '%s'",
2205 type->tp_name);
2206 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002207 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002208 /* XXX Example of how I expect this to be used...
2209 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2210 return -1;
2211 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002212 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2213 return -1;
2214 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002215}
2216
2217static void
2218type_dealloc(PyTypeObject *type)
2219{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002220 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002221
2222 /* Assert this is a heap-allocated type object */
2223 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002224 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002225 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002226 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002227 Py_XDECREF(type->tp_base);
2228 Py_XDECREF(type->tp_dict);
2229 Py_XDECREF(type->tp_bases);
2230 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002231 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002232 Py_XDECREF(type->tp_subclasses);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002233 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2234 * of most other objects. It's okay to cast it to char *.
2235 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002236 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002237 Py_XDECREF(et->ht_name);
2238 Py_XDECREF(et->ht_slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002239 type->ob_type->tp_free((PyObject *)type);
2240}
2241
Guido van Rossum1c450732001-10-08 15:18:27 +00002242static PyObject *
2243type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2244{
2245 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002246 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002247
2248 list = PyList_New(0);
2249 if (list == NULL)
2250 return NULL;
2251 raw = type->tp_subclasses;
2252 if (raw == NULL)
2253 return list;
2254 assert(PyList_Check(raw));
2255 n = PyList_GET_SIZE(raw);
2256 for (i = 0; i < n; i++) {
2257 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002258 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002259 ref = PyWeakref_GET_OBJECT(ref);
2260 if (ref != Py_None) {
2261 if (PyList_Append(list, ref) < 0) {
2262 Py_DECREF(list);
2263 return NULL;
2264 }
2265 }
2266 }
2267 return list;
2268}
2269
Tim Peters6d6c1a32001-08-02 04:15:00 +00002270static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002271 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002272 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002273 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002274 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002275 {0}
2276};
2277
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002278PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002279"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002280"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002281
Guido van Rossum048eb752001-10-02 21:24:57 +00002282static int
2283type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2284{
Guido van Rossuma3862092002-06-10 15:24:42 +00002285 /* Because of type_is_gc(), the collector only calls this
2286 for heaptypes. */
2287 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002288
Thomas Woutersc6e55062006-04-15 21:47:09 +00002289 Py_VISIT(type->tp_dict);
2290 Py_VISIT(type->tp_cache);
2291 Py_VISIT(type->tp_mro);
2292 Py_VISIT(type->tp_bases);
2293 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002294
2295 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002296 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002297 in cycles; tp_subclasses is a list of weak references,
2298 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002299
Guido van Rossum048eb752001-10-02 21:24:57 +00002300 return 0;
2301}
2302
2303static int
2304type_clear(PyTypeObject *type)
2305{
Guido van Rossuma3862092002-06-10 15:24:42 +00002306 /* Because of type_is_gc(), the collector only calls this
2307 for heaptypes. */
2308 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002309
Guido van Rossuma3862092002-06-10 15:24:42 +00002310 /* The only field we need to clear is tp_mro, which is part of a
2311 hard cycle (its first element is the class itself) that won't
2312 be broken otherwise (it's a tuple and tuples don't have a
2313 tp_clear handler). None of the other fields need to be
2314 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002315
Guido van Rossuma3862092002-06-10 15:24:42 +00002316 tp_dict:
2317 It is a dict, so the collector will call its tp_clear.
2318
2319 tp_cache:
2320 Not used; if it were, it would be a dict.
2321
2322 tp_bases, tp_base:
2323 If these are involved in a cycle, there must be at least
2324 one other, mutable object in the cycle, e.g. a base
2325 class's dict; the cycle will be broken that way.
2326
2327 tp_subclasses:
2328 A list of weak references can't be part of a cycle; and
2329 lists have their own tp_clear.
2330
Guido van Rossume5c691a2003-03-07 15:13:17 +00002331 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002332 A tuple of strings can't be part of a cycle.
2333 */
2334
Thomas Woutersedf17d82006-04-15 17:28:34 +00002335 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002336
2337 return 0;
2338}
2339
2340static int
2341type_is_gc(PyTypeObject *type)
2342{
2343 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2344}
2345
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002346PyTypeObject PyType_Type = {
2347 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002348 0, /* ob_size */
2349 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002350 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002351 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002352 (destructor)type_dealloc, /* tp_dealloc */
2353 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002354 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002355 0, /* tp_setattr */
2356 type_compare, /* tp_compare */
2357 (reprfunc)type_repr, /* tp_repr */
2358 0, /* tp_as_number */
2359 0, /* tp_as_sequence */
2360 0, /* tp_as_mapping */
2361 (hashfunc)_Py_HashPointer, /* tp_hash */
2362 (ternaryfunc)type_call, /* tp_call */
2363 0, /* tp_str */
2364 (getattrofunc)type_getattro, /* tp_getattro */
2365 (setattrofunc)type_setattro, /* tp_setattro */
2366 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002367 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002368 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002369 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002370 (traverseproc)type_traverse, /* tp_traverse */
2371 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002372 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002373 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002374 0, /* tp_iter */
2375 0, /* tp_iternext */
2376 type_methods, /* tp_methods */
2377 type_members, /* tp_members */
2378 type_getsets, /* tp_getset */
2379 0, /* tp_base */
2380 0, /* tp_dict */
2381 0, /* tp_descr_get */
2382 0, /* tp_descr_set */
2383 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2384 0, /* tp_init */
2385 0, /* tp_alloc */
2386 type_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002387 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002388 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002389};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002390
2391
2392/* The base type of all types (eventually)... except itself. */
2393
2394static int
2395object_init(PyObject *self, PyObject *args, PyObject *kwds)
2396{
2397 return 0;
2398}
2399
Guido van Rossum298e4212003-02-13 16:30:16 +00002400/* If we don't have a tp_new for a new-style class, new will use this one.
2401 Therefore this should take no arguments/keywords. However, this new may
2402 also be inherited by objects that define a tp_init but no tp_new. These
2403 objects WILL pass argumets to tp_new, because it gets the same args as
2404 tp_init. So only allow arguments if we aren't using the default init, in
2405 which case we expect init to handle argument parsing. */
2406static PyObject *
2407object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2408{
2409 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2410 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2411 PyErr_SetString(PyExc_TypeError,
2412 "default __new__ takes no parameters");
2413 return NULL;
2414 }
2415 return type->tp_alloc(type, 0);
2416}
2417
Tim Peters6d6c1a32001-08-02 04:15:00 +00002418static void
2419object_dealloc(PyObject *self)
2420{
2421 self->ob_type->tp_free(self);
2422}
2423
Guido van Rossum8e248182001-08-12 05:17:56 +00002424static PyObject *
2425object_repr(PyObject *self)
2426{
Guido van Rossum76e69632001-08-16 18:52:43 +00002427 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002428 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002429
Guido van Rossum76e69632001-08-16 18:52:43 +00002430 type = self->ob_type;
2431 mod = type_module(type, NULL);
2432 if (mod == NULL)
2433 PyErr_Clear();
2434 else if (!PyString_Check(mod)) {
2435 Py_DECREF(mod);
2436 mod = NULL;
2437 }
2438 name = type_name(type, NULL);
2439 if (name == NULL)
2440 return NULL;
2441 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002442 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002443 PyString_AS_STRING(mod),
2444 PyString_AS_STRING(name),
2445 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002446 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002447 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002448 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002449 Py_XDECREF(mod);
2450 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002451 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002452}
2453
Guido van Rossumb8f63662001-08-15 23:57:02 +00002454static PyObject *
2455object_str(PyObject *self)
2456{
2457 unaryfunc f;
2458
2459 f = self->ob_type->tp_repr;
2460 if (f == NULL)
2461 f = object_repr;
2462 return f(self);
2463}
2464
Guido van Rossum8e248182001-08-12 05:17:56 +00002465static long
2466object_hash(PyObject *self)
2467{
2468 return _Py_HashPointer(self);
2469}
Guido van Rossum8e248182001-08-12 05:17:56 +00002470
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002471static PyObject *
2472object_get_class(PyObject *self, void *closure)
2473{
2474 Py_INCREF(self->ob_type);
2475 return (PyObject *)(self->ob_type);
2476}
2477
2478static int
2479equiv_structs(PyTypeObject *a, PyTypeObject *b)
2480{
2481 return a == b ||
2482 (a != NULL &&
2483 b != NULL &&
2484 a->tp_basicsize == b->tp_basicsize &&
2485 a->tp_itemsize == b->tp_itemsize &&
2486 a->tp_dictoffset == b->tp_dictoffset &&
2487 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2488 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2489 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2490}
2491
2492static int
2493same_slots_added(PyTypeObject *a, PyTypeObject *b)
2494{
2495 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002496 Py_ssize_t size;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002497 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002498
2499 if (base != b->tp_base)
2500 return 0;
2501 if (equiv_structs(a, base) && equiv_structs(b, base))
2502 return 1;
2503 size = base->tp_basicsize;
2504 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2505 size += sizeof(PyObject *);
2506 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2507 size += sizeof(PyObject *);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002508
2509 /* Check slots compliance */
2510 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2511 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2512 if (slots_a && slots_b) {
2513 if (PyObject_Compare(slots_a, slots_b) != 0)
2514 return 0;
2515 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2516 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002517 return size == a->tp_basicsize && size == b->tp_basicsize;
2518}
2519
2520static int
Anthony Baxtera6286212006-04-11 07:42:36 +00002521compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002522{
2523 PyTypeObject *newbase, *oldbase;
2524
Anthony Baxtera6286212006-04-11 07:42:36 +00002525 if (newto->tp_dealloc != oldto->tp_dealloc ||
2526 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002527 {
2528 PyErr_Format(PyExc_TypeError,
2529 "%s assignment: "
2530 "'%s' deallocator differs from '%s'",
2531 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002532 newto->tp_name,
2533 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002534 return 0;
2535 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002536 newbase = newto;
2537 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002538 while (equiv_structs(newbase, newbase->tp_base))
2539 newbase = newbase->tp_base;
2540 while (equiv_structs(oldbase, oldbase->tp_base))
2541 oldbase = oldbase->tp_base;
2542 if (newbase != oldbase &&
2543 (newbase->tp_base != oldbase->tp_base ||
2544 !same_slots_added(newbase, oldbase))) {
2545 PyErr_Format(PyExc_TypeError,
2546 "%s assignment: "
2547 "'%s' object layout differs from '%s'",
2548 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002549 newto->tp_name,
2550 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002551 return 0;
2552 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002553
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002554 return 1;
2555}
2556
2557static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002558object_set_class(PyObject *self, PyObject *value, void *closure)
2559{
Anthony Baxtera6286212006-04-11 07:42:36 +00002560 PyTypeObject *oldto = self->ob_type;
2561 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002562
Guido van Rossumb6b89422002-04-15 01:03:30 +00002563 if (value == NULL) {
2564 PyErr_SetString(PyExc_TypeError,
2565 "can't delete __class__ attribute");
2566 return -1;
2567 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002568 if (!PyType_Check(value)) {
2569 PyErr_Format(PyExc_TypeError,
2570 "__class__ must be set to new-style class, not '%s' object",
2571 value->ob_type->tp_name);
2572 return -1;
2573 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002574 newto = (PyTypeObject *)value;
2575 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2576 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002577 {
2578 PyErr_Format(PyExc_TypeError,
2579 "__class__ assignment: only for heap types");
2580 return -1;
2581 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002582 if (compatible_for_assignment(newto, oldto, "__class__")) {
2583 Py_INCREF(newto);
2584 self->ob_type = newto;
2585 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002586 return 0;
2587 }
2588 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002589 return -1;
2590 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002591}
2592
2593static PyGetSetDef object_getsets[] = {
2594 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002595 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002596 {0}
2597};
2598
Guido van Rossumc53f0092003-02-18 22:05:12 +00002599
Guido van Rossum036f9992003-02-21 22:02:54 +00002600/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2601 We fall back to helpers in copy_reg for:
2602 - pickle protocols < 2
2603 - calculating the list of slot names (done only once per class)
2604 - the __newobj__ function (which is used as a token but never called)
2605*/
2606
2607static PyObject *
2608import_copy_reg(void)
2609{
2610 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002611
2612 if (!copy_reg_str) {
2613 copy_reg_str = PyString_InternFromString("copy_reg");
2614 if (copy_reg_str == NULL)
2615 return NULL;
2616 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002617
2618 return PyImport_Import(copy_reg_str);
2619}
2620
2621static PyObject *
2622slotnames(PyObject *cls)
2623{
2624 PyObject *clsdict;
2625 PyObject *copy_reg;
2626 PyObject *slotnames;
2627
2628 if (!PyType_Check(cls)) {
2629 Py_INCREF(Py_None);
2630 return Py_None;
2631 }
2632
2633 clsdict = ((PyTypeObject *)cls)->tp_dict;
2634 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002635 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002636 Py_INCREF(slotnames);
2637 return slotnames;
2638 }
2639
2640 copy_reg = import_copy_reg();
2641 if (copy_reg == NULL)
2642 return NULL;
2643
2644 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2645 Py_DECREF(copy_reg);
2646 if (slotnames != NULL &&
2647 slotnames != Py_None &&
2648 !PyList_Check(slotnames))
2649 {
2650 PyErr_SetString(PyExc_TypeError,
2651 "copy_reg._slotnames didn't return a list or None");
2652 Py_DECREF(slotnames);
2653 slotnames = NULL;
2654 }
2655
2656 return slotnames;
2657}
2658
2659static PyObject *
2660reduce_2(PyObject *obj)
2661{
2662 PyObject *cls, *getnewargs;
2663 PyObject *args = NULL, *args2 = NULL;
2664 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2665 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2666 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002667 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00002668
2669 cls = PyObject_GetAttrString(obj, "__class__");
2670 if (cls == NULL)
2671 return NULL;
2672
2673 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2674 if (getnewargs != NULL) {
2675 args = PyObject_CallObject(getnewargs, NULL);
2676 Py_DECREF(getnewargs);
2677 if (args != NULL && !PyTuple_Check(args)) {
Georg Brandlccff7852006-06-18 22:17:29 +00002678 PyErr_Format(PyExc_TypeError,
2679 "__getnewargs__ should return a tuple, "
2680 "not '%.200s'", args->ob_type->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00002681 goto end;
2682 }
2683 }
2684 else {
2685 PyErr_Clear();
2686 args = PyTuple_New(0);
2687 }
2688 if (args == NULL)
2689 goto end;
2690
2691 getstate = PyObject_GetAttrString(obj, "__getstate__");
2692 if (getstate != NULL) {
2693 state = PyObject_CallObject(getstate, NULL);
2694 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002695 if (state == NULL)
2696 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002697 }
2698 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002699 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002700 state = PyObject_GetAttrString(obj, "__dict__");
2701 if (state == NULL) {
2702 PyErr_Clear();
2703 state = Py_None;
2704 Py_INCREF(state);
2705 }
2706 names = slotnames(cls);
2707 if (names == NULL)
2708 goto end;
2709 if (names != Py_None) {
2710 assert(PyList_Check(names));
2711 slots = PyDict_New();
2712 if (slots == NULL)
2713 goto end;
2714 n = 0;
2715 /* Can't pre-compute the list size; the list
2716 is stored on the class so accessible to other
2717 threads, which may be run by DECREF */
2718 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2719 PyObject *name, *value;
2720 name = PyList_GET_ITEM(names, i);
2721 value = PyObject_GetAttr(obj, name);
2722 if (value == NULL)
2723 PyErr_Clear();
2724 else {
2725 int err = PyDict_SetItem(slots, name,
2726 value);
2727 Py_DECREF(value);
2728 if (err)
2729 goto end;
2730 n++;
2731 }
2732 }
2733 if (n) {
2734 state = Py_BuildValue("(NO)", state, slots);
2735 if (state == NULL)
2736 goto end;
2737 }
2738 }
2739 }
2740
2741 if (!PyList_Check(obj)) {
2742 listitems = Py_None;
2743 Py_INCREF(listitems);
2744 }
2745 else {
2746 listitems = PyObject_GetIter(obj);
2747 if (listitems == NULL)
2748 goto end;
2749 }
2750
2751 if (!PyDict_Check(obj)) {
2752 dictitems = Py_None;
2753 Py_INCREF(dictitems);
2754 }
2755 else {
2756 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2757 if (dictitems == NULL)
2758 goto end;
2759 }
2760
2761 copy_reg = import_copy_reg();
2762 if (copy_reg == NULL)
2763 goto end;
2764 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2765 if (newobj == NULL)
2766 goto end;
2767
2768 n = PyTuple_GET_SIZE(args);
2769 args2 = PyTuple_New(n+1);
2770 if (args2 == NULL)
2771 goto end;
2772 PyTuple_SET_ITEM(args2, 0, cls);
2773 cls = NULL;
2774 for (i = 0; i < n; i++) {
2775 PyObject *v = PyTuple_GET_ITEM(args, i);
2776 Py_INCREF(v);
2777 PyTuple_SET_ITEM(args2, i+1, v);
2778 }
2779
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002780 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002781
2782 end:
2783 Py_XDECREF(cls);
2784 Py_XDECREF(args);
2785 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002786 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002787 Py_XDECREF(state);
2788 Py_XDECREF(names);
2789 Py_XDECREF(listitems);
2790 Py_XDECREF(dictitems);
2791 Py_XDECREF(copy_reg);
2792 Py_XDECREF(newobj);
2793 return res;
2794}
2795
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00002796/*
2797 * There were two problems when object.__reduce__ and object.__reduce_ex__
2798 * were implemented in the same function:
2799 * - trying to pickle an object with a custom __reduce__ method that
2800 * fell back to object.__reduce__ in certain circumstances led to
2801 * infinite recursion at Python level and eventual RuntimeError.
2802 * - Pickling objects that lied about their type by overwriting the
2803 * __class__ descriptor could lead to infinite recursion at C level
2804 * and eventual segfault.
2805 *
2806 * Because of backwards compatibility, the two methods still have to
2807 * behave in the same way, even if this is not required by the pickle
2808 * protocol. This common functionality was moved to the _common_reduce
2809 * function.
2810 */
2811static PyObject *
2812_common_reduce(PyObject *self, int proto)
2813{
2814 PyObject *copy_reg, *res;
2815
2816 if (proto >= 2)
2817 return reduce_2(self);
2818
2819 copy_reg = import_copy_reg();
2820 if (!copy_reg)
2821 return NULL;
2822
2823 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
2824 Py_DECREF(copy_reg);
2825
2826 return res;
2827}
2828
2829static PyObject *
2830object_reduce(PyObject *self, PyObject *args)
2831{
2832 int proto = 0;
2833
2834 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
2835 return NULL;
2836
2837 return _common_reduce(self, proto);
2838}
2839
Guido van Rossum036f9992003-02-21 22:02:54 +00002840static PyObject *
2841object_reduce_ex(PyObject *self, PyObject *args)
2842{
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00002843 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00002844 int proto = 0;
2845
2846 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2847 return NULL;
2848
2849 reduce = PyObject_GetAttrString(self, "__reduce__");
2850 if (reduce == NULL)
2851 PyErr_Clear();
2852 else {
2853 PyObject *cls, *clsreduce, *objreduce;
2854 int override;
2855 cls = PyObject_GetAttrString(self, "__class__");
2856 if (cls == NULL) {
2857 Py_DECREF(reduce);
2858 return NULL;
2859 }
2860 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2861 Py_DECREF(cls);
2862 if (clsreduce == NULL) {
2863 Py_DECREF(reduce);
2864 return NULL;
2865 }
2866 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2867 "__reduce__");
2868 override = (clsreduce != objreduce);
2869 Py_DECREF(clsreduce);
2870 if (override) {
2871 res = PyObject_CallObject(reduce, NULL);
2872 Py_DECREF(reduce);
2873 return res;
2874 }
2875 else
2876 Py_DECREF(reduce);
2877 }
2878
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00002879 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002880}
2881
2882static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002883 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2884 PyDoc_STR("helper for pickle")},
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00002885 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002886 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002887 {0}
2888};
2889
Guido van Rossum036f9992003-02-21 22:02:54 +00002890
Tim Peters6d6c1a32001-08-02 04:15:00 +00002891PyTypeObject PyBaseObject_Type = {
2892 PyObject_HEAD_INIT(&PyType_Type)
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002893 0, /* ob_size */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002894 "object", /* tp_name */
2895 sizeof(PyObject), /* tp_basicsize */
2896 0, /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00002897 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002898 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002899 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002900 0, /* tp_setattr */
2901 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002902 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002903 0, /* tp_as_number */
2904 0, /* tp_as_sequence */
2905 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002906 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002907 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002908 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002909 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002910 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002911 0, /* tp_as_buffer */
2912 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002913 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002914 0, /* tp_traverse */
2915 0, /* tp_clear */
2916 0, /* tp_richcompare */
2917 0, /* tp_weaklistoffset */
2918 0, /* tp_iter */
2919 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002920 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002921 0, /* tp_members */
2922 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002923 0, /* tp_base */
2924 0, /* tp_dict */
2925 0, /* tp_descr_get */
2926 0, /* tp_descr_set */
2927 0, /* tp_dictoffset */
2928 object_init, /* tp_init */
2929 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002930 object_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002931 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002932};
2933
2934
2935/* Initialize the __dict__ in a type object */
2936
2937static int
2938add_methods(PyTypeObject *type, PyMethodDef *meth)
2939{
Guido van Rossum687ae002001-10-15 22:03:32 +00002940 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002941
2942 for (; meth->ml_name != NULL; meth++) {
2943 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002944 if (PyDict_GetItemString(dict, meth->ml_name) &&
2945 !(meth->ml_flags & METH_COEXIST))
2946 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002947 if (meth->ml_flags & METH_CLASS) {
2948 if (meth->ml_flags & METH_STATIC) {
2949 PyErr_SetString(PyExc_ValueError,
2950 "method cannot be both class and static");
2951 return -1;
2952 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002953 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002954 }
2955 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002956 PyObject *cfunc = PyCFunction_New(meth, NULL);
2957 if (cfunc == NULL)
2958 return -1;
2959 descr = PyStaticMethod_New(cfunc);
2960 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002961 }
2962 else {
2963 descr = PyDescr_NewMethod(type, meth);
2964 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002965 if (descr == NULL)
2966 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002967 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002968 return -1;
2969 Py_DECREF(descr);
2970 }
2971 return 0;
2972}
2973
2974static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002975add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002976{
Guido van Rossum687ae002001-10-15 22:03:32 +00002977 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002978
2979 for (; memb->name != NULL; memb++) {
2980 PyObject *descr;
2981 if (PyDict_GetItemString(dict, memb->name))
2982 continue;
2983 descr = PyDescr_NewMember(type, memb);
2984 if (descr == NULL)
2985 return -1;
2986 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2987 return -1;
2988 Py_DECREF(descr);
2989 }
2990 return 0;
2991}
2992
2993static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002994add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002995{
Guido van Rossum687ae002001-10-15 22:03:32 +00002996 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002997
2998 for (; gsp->name != NULL; gsp++) {
2999 PyObject *descr;
3000 if (PyDict_GetItemString(dict, gsp->name))
3001 continue;
3002 descr = PyDescr_NewGetSet(type, gsp);
3003
3004 if (descr == NULL)
3005 return -1;
3006 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3007 return -1;
3008 Py_DECREF(descr);
3009 }
3010 return 0;
3011}
3012
Guido van Rossum13d52f02001-08-10 21:24:08 +00003013static void
3014inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003015{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003016 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003017
Guido van Rossum13d52f02001-08-10 21:24:08 +00003018 /* Special flag magic */
3019 if (!type->tp_as_buffer && base->tp_as_buffer) {
3020 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
3021 type->tp_flags |=
3022 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
3023 }
3024 if (!type->tp_as_sequence && base->tp_as_sequence) {
3025 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
3026 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
3027 }
3028 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
3029 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
3030 if ((!type->tp_as_number && base->tp_as_number) ||
3031 (!type->tp_as_sequence && base->tp_as_sequence)) {
3032 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
3033 if (!type->tp_as_number && !type->tp_as_sequence) {
3034 type->tp_flags |= base->tp_flags &
3035 Py_TPFLAGS_HAVE_INPLACEOPS;
3036 }
3037 }
3038 /* Wow */
3039 }
3040 if (!type->tp_as_number && base->tp_as_number) {
3041 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
3042 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
3043 }
3044
3045 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003046 oldsize = base->tp_basicsize;
3047 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3048 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3049 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003050 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
3051 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003052 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003053 if (type->tp_traverse == NULL)
3054 type->tp_traverse = base->tp_traverse;
3055 if (type->tp_clear == NULL)
3056 type->tp_clear = base->tp_clear;
3057 }
3058 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00003059 /* The condition below could use some explanation.
3060 It appears that tp_new is not inherited for static types
3061 whose base class is 'object'; this seems to be a precaution
3062 so that old extension types don't suddenly become
3063 callable (object.__new__ wouldn't insure the invariants
3064 that the extension type's own factory function ensures).
3065 Heap types, of course, are under our control, so they do
3066 inherit tp_new; static extension types that specify some
3067 other built-in type as the default are considered
3068 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003069 if (base != &PyBaseObject_Type ||
3070 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3071 if (type->tp_new == NULL)
3072 type->tp_new = base->tp_new;
3073 }
3074 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003075 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003076
3077 /* Copy other non-function slots */
3078
3079#undef COPYVAL
3080#define COPYVAL(SLOT) \
3081 if (type->SLOT == 0) type->SLOT = base->SLOT
3082
3083 COPYVAL(tp_itemsize);
3084 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
3085 COPYVAL(tp_weaklistoffset);
3086 }
3087 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3088 COPYVAL(tp_dictoffset);
3089 }
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003090
3091 /* Setup fast subclass flags */
3092 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3093 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3094 else if (PyType_IsSubtype(base, &PyType_Type))
3095 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3096 else if (PyType_IsSubtype(base, &PyInt_Type))
3097 type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS;
3098 else if (PyType_IsSubtype(base, &PyLong_Type))
3099 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3100 else if (PyType_IsSubtype(base, &PyString_Type))
3101 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
3102 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3103 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3104 else if (PyType_IsSubtype(base, &PyTuple_Type))
3105 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3106 else if (PyType_IsSubtype(base, &PyList_Type))
3107 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3108 else if (PyType_IsSubtype(base, &PyDict_Type))
3109 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003110}
3111
3112static void
3113inherit_slots(PyTypeObject *type, PyTypeObject *base)
3114{
3115 PyTypeObject *basebase;
3116
3117#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003118#undef COPYSLOT
3119#undef COPYNUM
3120#undef COPYSEQ
3121#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003122#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003123
3124#define SLOTDEFINED(SLOT) \
3125 (base->SLOT != 0 && \
3126 (basebase == NULL || base->SLOT != basebase->SLOT))
3127
Tim Peters6d6c1a32001-08-02 04:15:00 +00003128#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003129 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003130
3131#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3132#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3133#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003134#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003135
Guido van Rossum13d52f02001-08-10 21:24:08 +00003136 /* This won't inherit indirect slots (from tp_as_number etc.)
3137 if type doesn't provide the space. */
3138
3139 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3140 basebase = base->tp_base;
3141 if (basebase->tp_as_number == NULL)
3142 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003143 COPYNUM(nb_add);
3144 COPYNUM(nb_subtract);
3145 COPYNUM(nb_multiply);
3146 COPYNUM(nb_divide);
3147 COPYNUM(nb_remainder);
3148 COPYNUM(nb_divmod);
3149 COPYNUM(nb_power);
3150 COPYNUM(nb_negative);
3151 COPYNUM(nb_positive);
3152 COPYNUM(nb_absolute);
3153 COPYNUM(nb_nonzero);
3154 COPYNUM(nb_invert);
3155 COPYNUM(nb_lshift);
3156 COPYNUM(nb_rshift);
3157 COPYNUM(nb_and);
3158 COPYNUM(nb_xor);
3159 COPYNUM(nb_or);
3160 COPYNUM(nb_coerce);
3161 COPYNUM(nb_int);
3162 COPYNUM(nb_long);
3163 COPYNUM(nb_float);
3164 COPYNUM(nb_oct);
3165 COPYNUM(nb_hex);
3166 COPYNUM(nb_inplace_add);
3167 COPYNUM(nb_inplace_subtract);
3168 COPYNUM(nb_inplace_multiply);
3169 COPYNUM(nb_inplace_divide);
3170 COPYNUM(nb_inplace_remainder);
3171 COPYNUM(nb_inplace_power);
3172 COPYNUM(nb_inplace_lshift);
3173 COPYNUM(nb_inplace_rshift);
3174 COPYNUM(nb_inplace_and);
3175 COPYNUM(nb_inplace_xor);
3176 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003177 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3178 COPYNUM(nb_true_divide);
3179 COPYNUM(nb_floor_divide);
3180 COPYNUM(nb_inplace_true_divide);
3181 COPYNUM(nb_inplace_floor_divide);
3182 }
Guido van Rossum38fff8c2006-03-07 18:50:55 +00003183 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3184 COPYNUM(nb_index);
3185 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003186 }
3187
Guido van Rossum13d52f02001-08-10 21:24:08 +00003188 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3189 basebase = base->tp_base;
3190 if (basebase->tp_as_sequence == NULL)
3191 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003192 COPYSEQ(sq_length);
3193 COPYSEQ(sq_concat);
3194 COPYSEQ(sq_repeat);
3195 COPYSEQ(sq_item);
3196 COPYSEQ(sq_slice);
3197 COPYSEQ(sq_ass_item);
3198 COPYSEQ(sq_ass_slice);
3199 COPYSEQ(sq_contains);
3200 COPYSEQ(sq_inplace_concat);
3201 COPYSEQ(sq_inplace_repeat);
3202 }
3203
Guido van Rossum13d52f02001-08-10 21:24:08 +00003204 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3205 basebase = base->tp_base;
3206 if (basebase->tp_as_mapping == NULL)
3207 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003208 COPYMAP(mp_length);
3209 COPYMAP(mp_subscript);
3210 COPYMAP(mp_ass_subscript);
3211 }
3212
Tim Petersfc57ccb2001-10-12 02:38:24 +00003213 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3214 basebase = base->tp_base;
3215 if (basebase->tp_as_buffer == NULL)
3216 basebase = NULL;
3217 COPYBUF(bf_getreadbuffer);
3218 COPYBUF(bf_getwritebuffer);
3219 COPYBUF(bf_getsegcount);
3220 COPYBUF(bf_getcharbuffer);
3221 }
3222
Guido van Rossum13d52f02001-08-10 21:24:08 +00003223 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003224
Tim Peters6d6c1a32001-08-02 04:15:00 +00003225 COPYSLOT(tp_dealloc);
3226 COPYSLOT(tp_print);
3227 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3228 type->tp_getattr = base->tp_getattr;
3229 type->tp_getattro = base->tp_getattro;
3230 }
3231 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3232 type->tp_setattr = base->tp_setattr;
3233 type->tp_setattro = base->tp_setattro;
3234 }
3235 /* tp_compare see tp_richcompare */
3236 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003237 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003238 COPYSLOT(tp_call);
3239 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003240 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003241 if (type->tp_compare == NULL &&
3242 type->tp_richcompare == NULL &&
3243 type->tp_hash == NULL)
3244 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003245 type->tp_compare = base->tp_compare;
3246 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003247 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003248 }
3249 }
3250 else {
3251 COPYSLOT(tp_compare);
3252 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003253 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3254 COPYSLOT(tp_iter);
3255 COPYSLOT(tp_iternext);
3256 }
3257 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3258 COPYSLOT(tp_descr_get);
3259 COPYSLOT(tp_descr_set);
3260 COPYSLOT(tp_dictoffset);
3261 COPYSLOT(tp_init);
3262 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003263 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003264 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3265 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3266 /* They agree about gc. */
3267 COPYSLOT(tp_free);
3268 }
3269 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3270 type->tp_free == NULL &&
3271 base->tp_free == _PyObject_Del) {
3272 /* A bit of magic to plug in the correct default
3273 * tp_free function when a derived class adds gc,
3274 * didn't define tp_free, and the base uses the
3275 * default non-gc tp_free.
3276 */
3277 type->tp_free = PyObject_GC_Del;
3278 }
3279 /* else they didn't agree about gc, and there isn't something
3280 * obvious to be done -- the type is on its own.
3281 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003282 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003283}
3284
Jeremy Hylton938ace62002-07-17 16:30:39 +00003285static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003286
Tim Peters6d6c1a32001-08-02 04:15:00 +00003287int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003288PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003289{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003290 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003291 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003292 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003293
Guido van Rossumcab05802002-06-10 15:29:03 +00003294 if (type->tp_flags & Py_TPFLAGS_READY) {
3295 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003296 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003297 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003298 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003299
3300 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003301
Tim Peters36eb4df2003-03-23 03:33:13 +00003302#ifdef Py_TRACE_REFS
3303 /* PyType_Ready is the closest thing we have to a choke point
3304 * for type objects, so is the best place I can think of to try
3305 * to get type objects into the doubly-linked list of all objects.
3306 * Still, not all type objects go thru PyType_Ready.
3307 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003308 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003309#endif
3310
Tim Peters6d6c1a32001-08-02 04:15:00 +00003311 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3312 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003313 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003314 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003315 Py_INCREF(base);
3316 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003317
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003318 /* Now the only way base can still be NULL is if type is
3319 * &PyBaseObject_Type.
3320 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003321
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003322 /* Initialize the base class */
3323 if (base && base->tp_dict == NULL) {
3324 if (PyType_Ready(base) < 0)
3325 goto error;
3326 }
3327
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003328 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003329 compilable separately on Windows can call PyType_Ready() instead of
3330 initializing the ob_type field of their type objects. */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003331 /* The test for base != NULL is really unnecessary, since base is only
3332 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3333 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3334 know that. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003335 if (type->ob_type == NULL && base != NULL)
Guido van Rossum0986d822002-04-08 01:38:42 +00003336 type->ob_type = base->ob_type;
3337
Tim Peters6d6c1a32001-08-02 04:15:00 +00003338 /* Initialize tp_bases */
3339 bases = type->tp_bases;
3340 if (bases == NULL) {
3341 if (base == NULL)
3342 bases = PyTuple_New(0);
3343 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003344 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003345 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003346 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003347 type->tp_bases = bases;
3348 }
3349
Guido van Rossum687ae002001-10-15 22:03:32 +00003350 /* Initialize tp_dict */
3351 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003352 if (dict == NULL) {
3353 dict = PyDict_New();
3354 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003355 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003356 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003357 }
3358
Guido van Rossum687ae002001-10-15 22:03:32 +00003359 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003360 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003361 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003362 if (type->tp_methods != NULL) {
3363 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003364 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003365 }
3366 if (type->tp_members != NULL) {
3367 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003368 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003369 }
3370 if (type->tp_getset != NULL) {
3371 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003372 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003373 }
3374
Tim Peters6d6c1a32001-08-02 04:15:00 +00003375 /* Calculate method resolution order */
3376 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003377 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003378 }
3379
Guido van Rossum13d52f02001-08-10 21:24:08 +00003380 /* Inherit special flags from dominant base */
3381 if (type->tp_base != NULL)
3382 inherit_special(type, type->tp_base);
3383
Tim Peters6d6c1a32001-08-02 04:15:00 +00003384 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003385 bases = type->tp_mro;
3386 assert(bases != NULL);
3387 assert(PyTuple_Check(bases));
3388 n = PyTuple_GET_SIZE(bases);
3389 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003390 PyObject *b = PyTuple_GET_ITEM(bases, i);
3391 if (PyType_Check(b))
3392 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003393 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003394
Tim Peters3cfe7542003-05-21 21:29:48 +00003395 /* Sanity check for tp_free. */
3396 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3397 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003398 /* This base class needs to call tp_free, but doesn't have
3399 * one, or its tp_free is for non-gc'ed objects.
3400 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003401 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3402 "gc and is a base type but has inappropriate "
3403 "tp_free slot",
3404 type->tp_name);
3405 goto error;
3406 }
3407
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003408 /* if the type dictionary doesn't contain a __doc__, set it from
3409 the tp_doc slot.
3410 */
3411 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3412 if (type->tp_doc != NULL) {
3413 PyObject *doc = PyString_FromString(type->tp_doc);
Neal Norwitze1fdb322006-07-21 05:32:28 +00003414 if (doc == NULL)
3415 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003416 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3417 Py_DECREF(doc);
3418 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003419 PyDict_SetItemString(type->tp_dict,
3420 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003421 }
3422 }
3423
Guido van Rossum13d52f02001-08-10 21:24:08 +00003424 /* Some more special stuff */
3425 base = type->tp_base;
3426 if (base != NULL) {
3427 if (type->tp_as_number == NULL)
3428 type->tp_as_number = base->tp_as_number;
3429 if (type->tp_as_sequence == NULL)
3430 type->tp_as_sequence = base->tp_as_sequence;
3431 if (type->tp_as_mapping == NULL)
3432 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003433 if (type->tp_as_buffer == NULL)
3434 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003435 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003436
Guido van Rossum1c450732001-10-08 15:18:27 +00003437 /* Link into each base class's list of subclasses */
3438 bases = type->tp_bases;
3439 n = PyTuple_GET_SIZE(bases);
3440 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003441 PyObject *b = PyTuple_GET_ITEM(bases, i);
3442 if (PyType_Check(b) &&
3443 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003444 goto error;
3445 }
3446
Guido van Rossum13d52f02001-08-10 21:24:08 +00003447 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003448 assert(type->tp_dict != NULL);
3449 type->tp_flags =
3450 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003451 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003452
3453 error:
3454 type->tp_flags &= ~Py_TPFLAGS_READYING;
3455 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003456}
3457
Guido van Rossum1c450732001-10-08 15:18:27 +00003458static int
3459add_subclass(PyTypeObject *base, PyTypeObject *type)
3460{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003461 Py_ssize_t i;
3462 int result;
Anthony Baxtera6286212006-04-11 07:42:36 +00003463 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003464
3465 list = base->tp_subclasses;
3466 if (list == NULL) {
3467 base->tp_subclasses = list = PyList_New(0);
3468 if (list == NULL)
3469 return -1;
3470 }
3471 assert(PyList_Check(list));
Anthony Baxtera6286212006-04-11 07:42:36 +00003472 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003473 i = PyList_GET_SIZE(list);
3474 while (--i >= 0) {
3475 ref = PyList_GET_ITEM(list, i);
3476 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003477 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Anthony Baxtera6286212006-04-11 07:42:36 +00003478 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003479 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003480 result = PyList_Append(list, newobj);
3481 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003482 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003483}
3484
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003485static void
3486remove_subclass(PyTypeObject *base, PyTypeObject *type)
3487{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003488 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003489 PyObject *list, *ref;
3490
3491 list = base->tp_subclasses;
3492 if (list == NULL) {
3493 return;
3494 }
3495 assert(PyList_Check(list));
3496 i = PyList_GET_SIZE(list);
3497 while (--i >= 0) {
3498 ref = PyList_GET_ITEM(list, i);
3499 assert(PyWeakref_CheckRef(ref));
3500 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3501 /* this can't fail, right? */
3502 PySequence_DelItem(list, i);
3503 return;
3504 }
3505 }
3506}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003507
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003508static int
3509check_num_args(PyObject *ob, int n)
3510{
3511 if (!PyTuple_CheckExact(ob)) {
3512 PyErr_SetString(PyExc_SystemError,
3513 "PyArg_UnpackTuple() argument list is not a tuple");
3514 return 0;
3515 }
3516 if (n == PyTuple_GET_SIZE(ob))
3517 return 1;
3518 PyErr_Format(
3519 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003520 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003521 return 0;
3522}
3523
Tim Peters6d6c1a32001-08-02 04:15:00 +00003524/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3525
3526/* There's a wrapper *function* for each distinct function typedef used
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003527 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00003528 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3529 Most tables have only one entry; the tables for binary operators have two
3530 entries, one regular and one with reversed arguments. */
3531
3532static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003533wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003534{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003535 lenfunc func = (lenfunc)wrapped;
3536 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003537
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003538 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003539 return NULL;
3540 res = (*func)(self);
3541 if (res == -1 && PyErr_Occurred())
3542 return NULL;
3543 return PyInt_FromLong((long)res);
3544}
3545
Tim Peters6d6c1a32001-08-02 04:15:00 +00003546static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003547wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3548{
3549 inquiry func = (inquiry)wrapped;
3550 int res;
3551
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003552 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003553 return NULL;
3554 res = (*func)(self);
3555 if (res == -1 && PyErr_Occurred())
3556 return NULL;
3557 return PyBool_FromLong((long)res);
3558}
3559
3560static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003561wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3562{
3563 binaryfunc func = (binaryfunc)wrapped;
3564 PyObject *other;
3565
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003566 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003567 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003568 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003569 return (*func)(self, other);
3570}
3571
3572static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003573wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3574{
3575 binaryfunc func = (binaryfunc)wrapped;
3576 PyObject *other;
3577
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003578 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003579 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003580 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003581 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003582 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003583 Py_INCREF(Py_NotImplemented);
3584 return Py_NotImplemented;
3585 }
3586 return (*func)(self, other);
3587}
3588
3589static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003590wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3591{
3592 binaryfunc func = (binaryfunc)wrapped;
3593 PyObject *other;
3594
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003595 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003596 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003597 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003598 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003599 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003600 Py_INCREF(Py_NotImplemented);
3601 return Py_NotImplemented;
3602 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003603 return (*func)(other, self);
3604}
3605
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003606static PyObject *
3607wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3608{
3609 coercion func = (coercion)wrapped;
3610 PyObject *other, *res;
3611 int ok;
3612
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003613 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003614 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003615 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003616 ok = func(&self, &other);
3617 if (ok < 0)
3618 return NULL;
3619 if (ok > 0) {
3620 Py_INCREF(Py_NotImplemented);
3621 return Py_NotImplemented;
3622 }
3623 res = PyTuple_New(2);
3624 if (res == NULL) {
3625 Py_DECREF(self);
3626 Py_DECREF(other);
3627 return NULL;
3628 }
3629 PyTuple_SET_ITEM(res, 0, self);
3630 PyTuple_SET_ITEM(res, 1, other);
3631 return res;
3632}
3633
Tim Peters6d6c1a32001-08-02 04:15:00 +00003634static PyObject *
3635wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3636{
3637 ternaryfunc func = (ternaryfunc)wrapped;
3638 PyObject *other;
3639 PyObject *third = Py_None;
3640
3641 /* Note: This wrapper only works for __pow__() */
3642
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003643 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003644 return NULL;
3645 return (*func)(self, other, third);
3646}
3647
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003648static PyObject *
3649wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3650{
3651 ternaryfunc func = (ternaryfunc)wrapped;
3652 PyObject *other;
3653 PyObject *third = Py_None;
3654
3655 /* Note: This wrapper only works for __pow__() */
3656
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003657 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003658 return NULL;
3659 return (*func)(other, self, third);
3660}
3661
Tim Peters6d6c1a32001-08-02 04:15:00 +00003662static PyObject *
3663wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3664{
3665 unaryfunc func = (unaryfunc)wrapped;
3666
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003667 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003668 return NULL;
3669 return (*func)(self);
3670}
3671
Tim Peters6d6c1a32001-08-02 04:15:00 +00003672static PyObject *
Armin Rigo314861c2006-03-30 14:04:02 +00003673wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003674{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003675 ssizeargfunc func = (ssizeargfunc)wrapped;
Armin Rigo314861c2006-03-30 14:04:02 +00003676 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003677 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003678
Armin Rigo314861c2006-03-30 14:04:02 +00003679 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
3680 return NULL;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00003681 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Armin Rigo314861c2006-03-30 14:04:02 +00003682 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003683 return NULL;
3684 return (*func)(self, i);
3685}
3686
Martin v. Löwis18e16552006-02-15 17:27:45 +00003687static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00003688getindex(PyObject *self, PyObject *arg)
3689{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003690 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003691
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00003692 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003693 if (i == -1 && PyErr_Occurred())
3694 return -1;
3695 if (i < 0) {
3696 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3697 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003698 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003699 if (n < 0)
3700 return -1;
3701 i += n;
3702 }
3703 }
3704 return i;
3705}
3706
3707static PyObject *
3708wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3709{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003710 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003711 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003712 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003713
Guido van Rossumf4593e02001-10-03 12:09:30 +00003714 if (PyTuple_GET_SIZE(args) == 1) {
3715 arg = PyTuple_GET_ITEM(args, 0);
3716 i = getindex(self, arg);
3717 if (i == -1 && PyErr_Occurred())
3718 return NULL;
3719 return (*func)(self, i);
3720 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003721 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003722 assert(PyErr_Occurred());
3723 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003724}
3725
Tim Peters6d6c1a32001-08-02 04:15:00 +00003726static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003727wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003728{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003729 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
3730 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003731
Martin v. Löwis18e16552006-02-15 17:27:45 +00003732 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003733 return NULL;
3734 return (*func)(self, i, j);
3735}
3736
Tim Peters6d6c1a32001-08-02 04:15:00 +00003737static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003738wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003739{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003740 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3741 Py_ssize_t i;
3742 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003743 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003744
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003745 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003746 return NULL;
3747 i = getindex(self, arg);
3748 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003749 return NULL;
3750 res = (*func)(self, i, value);
3751 if (res == -1 && PyErr_Occurred())
3752 return NULL;
3753 Py_INCREF(Py_None);
3754 return Py_None;
3755}
3756
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003757static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003758wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003759{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003760 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3761 Py_ssize_t i;
3762 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003763 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003764
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003765 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003766 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003767 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003768 i = getindex(self, arg);
3769 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003770 return NULL;
3771 res = (*func)(self, i, NULL);
3772 if (res == -1 && PyErr_Occurred())
3773 return NULL;
3774 Py_INCREF(Py_None);
3775 return Py_None;
3776}
3777
Tim Peters6d6c1a32001-08-02 04:15:00 +00003778static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003779wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003780{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003781 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3782 Py_ssize_t i, j;
3783 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003784 PyObject *value;
3785
Martin v. Löwis18e16552006-02-15 17:27:45 +00003786 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003787 return NULL;
3788 res = (*func)(self, i, j, value);
3789 if (res == -1 && PyErr_Occurred())
3790 return NULL;
3791 Py_INCREF(Py_None);
3792 return Py_None;
3793}
3794
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003795static PyObject *
3796wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3797{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003798 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3799 Py_ssize_t i, j;
3800 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003801
Martin v. Löwis18e16552006-02-15 17:27:45 +00003802 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003803 return NULL;
3804 res = (*func)(self, i, j, NULL);
3805 if (res == -1 && PyErr_Occurred())
3806 return NULL;
3807 Py_INCREF(Py_None);
3808 return Py_None;
3809}
3810
Tim Peters6d6c1a32001-08-02 04:15:00 +00003811/* XXX objobjproc is a misnomer; should be objargpred */
3812static PyObject *
3813wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3814{
3815 objobjproc func = (objobjproc)wrapped;
3816 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003817 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003818
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003819 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003820 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003821 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003822 res = (*func)(self, value);
3823 if (res == -1 && PyErr_Occurred())
3824 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003825 else
3826 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003827}
3828
Tim Peters6d6c1a32001-08-02 04:15:00 +00003829static PyObject *
3830wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3831{
3832 objobjargproc func = (objobjargproc)wrapped;
3833 int res;
3834 PyObject *key, *value;
3835
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003836 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003837 return NULL;
3838 res = (*func)(self, key, value);
3839 if (res == -1 && PyErr_Occurred())
3840 return NULL;
3841 Py_INCREF(Py_None);
3842 return Py_None;
3843}
3844
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003845static PyObject *
3846wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3847{
3848 objobjargproc func = (objobjargproc)wrapped;
3849 int res;
3850 PyObject *key;
3851
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003852 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003853 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003854 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003855 res = (*func)(self, key, NULL);
3856 if (res == -1 && PyErr_Occurred())
3857 return NULL;
3858 Py_INCREF(Py_None);
3859 return Py_None;
3860}
3861
Tim Peters6d6c1a32001-08-02 04:15:00 +00003862static PyObject *
3863wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3864{
3865 cmpfunc func = (cmpfunc)wrapped;
3866 int res;
3867 PyObject *other;
3868
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003869 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003870 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003871 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003872 if (other->ob_type->tp_compare != func &&
3873 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003874 PyErr_Format(
3875 PyExc_TypeError,
3876 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3877 self->ob_type->tp_name,
3878 self->ob_type->tp_name,
3879 other->ob_type->tp_name);
3880 return NULL;
3881 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003882 res = (*func)(self, other);
3883 if (PyErr_Occurred())
3884 return NULL;
3885 return PyInt_FromLong((long)res);
3886}
3887
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003888/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003889 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003890static int
3891hackcheck(PyObject *self, setattrofunc func, char *what)
3892{
3893 PyTypeObject *type = self->ob_type;
3894 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3895 type = type->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003896 /* If type is NULL now, this is a really weird type.
3897 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003898 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003899 PyErr_Format(PyExc_TypeError,
3900 "can't apply this %s to %s object",
3901 what,
3902 type->tp_name);
3903 return 0;
3904 }
3905 return 1;
3906}
3907
Tim Peters6d6c1a32001-08-02 04:15:00 +00003908static PyObject *
3909wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3910{
3911 setattrofunc func = (setattrofunc)wrapped;
3912 int res;
3913 PyObject *name, *value;
3914
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003915 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003916 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003917 if (!hackcheck(self, func, "__setattr__"))
3918 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003919 res = (*func)(self, name, value);
3920 if (res < 0)
3921 return NULL;
3922 Py_INCREF(Py_None);
3923 return Py_None;
3924}
3925
3926static PyObject *
3927wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3928{
3929 setattrofunc func = (setattrofunc)wrapped;
3930 int res;
3931 PyObject *name;
3932
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003933 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003934 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003935 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003936 if (!hackcheck(self, func, "__delattr__"))
3937 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003938 res = (*func)(self, name, NULL);
3939 if (res < 0)
3940 return NULL;
3941 Py_INCREF(Py_None);
3942 return Py_None;
3943}
3944
Tim Peters6d6c1a32001-08-02 04:15:00 +00003945static PyObject *
3946wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3947{
3948 hashfunc func = (hashfunc)wrapped;
3949 long res;
3950
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003951 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003952 return NULL;
3953 res = (*func)(self);
3954 if (res == -1 && PyErr_Occurred())
3955 return NULL;
3956 return PyInt_FromLong(res);
3957}
3958
Tim Peters6d6c1a32001-08-02 04:15:00 +00003959static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003960wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003961{
3962 ternaryfunc func = (ternaryfunc)wrapped;
3963
Guido van Rossumc8e56452001-10-22 00:43:43 +00003964 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003965}
3966
Tim Peters6d6c1a32001-08-02 04:15:00 +00003967static PyObject *
3968wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3969{
3970 richcmpfunc func = (richcmpfunc)wrapped;
3971 PyObject *other;
3972
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003973 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003974 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003975 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003976 return (*func)(self, other, op);
3977}
3978
3979#undef RICHCMP_WRAPPER
3980#define RICHCMP_WRAPPER(NAME, OP) \
3981static PyObject * \
3982richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3983{ \
3984 return wrap_richcmpfunc(self, args, wrapped, OP); \
3985}
3986
Jack Jansen8e938b42001-08-08 15:29:49 +00003987RICHCMP_WRAPPER(lt, Py_LT)
3988RICHCMP_WRAPPER(le, Py_LE)
3989RICHCMP_WRAPPER(eq, Py_EQ)
3990RICHCMP_WRAPPER(ne, Py_NE)
3991RICHCMP_WRAPPER(gt, Py_GT)
3992RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003993
Tim Peters6d6c1a32001-08-02 04:15:00 +00003994static PyObject *
3995wrap_next(PyObject *self, PyObject *args, void *wrapped)
3996{
3997 unaryfunc func = (unaryfunc)wrapped;
3998 PyObject *res;
3999
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004000 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004001 return NULL;
4002 res = (*func)(self);
4003 if (res == NULL && !PyErr_Occurred())
4004 PyErr_SetNone(PyExc_StopIteration);
4005 return res;
4006}
4007
Tim Peters6d6c1a32001-08-02 04:15:00 +00004008static PyObject *
4009wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4010{
4011 descrgetfunc func = (descrgetfunc)wrapped;
4012 PyObject *obj;
4013 PyObject *type = NULL;
4014
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004015 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004016 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004017 if (obj == Py_None)
4018 obj = NULL;
4019 if (type == Py_None)
4020 type = NULL;
4021 if (type == NULL &&obj == NULL) {
4022 PyErr_SetString(PyExc_TypeError,
4023 "__get__(None, None) is invalid");
4024 return NULL;
4025 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004026 return (*func)(self, obj, type);
4027}
4028
Tim Peters6d6c1a32001-08-02 04:15:00 +00004029static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004030wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004031{
4032 descrsetfunc func = (descrsetfunc)wrapped;
4033 PyObject *obj, *value;
4034 int ret;
4035
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004036 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004037 return NULL;
4038 ret = (*func)(self, obj, value);
4039 if (ret < 0)
4040 return NULL;
4041 Py_INCREF(Py_None);
4042 return Py_None;
4043}
Guido van Rossum22b13872002-08-06 21:41:44 +00004044
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004045static PyObject *
4046wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4047{
4048 descrsetfunc func = (descrsetfunc)wrapped;
4049 PyObject *obj;
4050 int ret;
4051
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004052 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004053 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004054 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004055 ret = (*func)(self, obj, NULL);
4056 if (ret < 0)
4057 return NULL;
4058 Py_INCREF(Py_None);
4059 return Py_None;
4060}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004061
Tim Peters6d6c1a32001-08-02 04:15:00 +00004062static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004063wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004064{
4065 initproc func = (initproc)wrapped;
4066
Guido van Rossumc8e56452001-10-22 00:43:43 +00004067 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004068 return NULL;
4069 Py_INCREF(Py_None);
4070 return Py_None;
4071}
4072
Tim Peters6d6c1a32001-08-02 04:15:00 +00004073static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004074tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004075{
Barry Warsaw60f01882001-08-22 19:24:42 +00004076 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004077 PyObject *arg0, *res;
4078
4079 if (self == NULL || !PyType_Check(self))
4080 Py_FatalError("__new__() called with non-type 'self'");
4081 type = (PyTypeObject *)self;
4082 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004083 PyErr_Format(PyExc_TypeError,
4084 "%s.__new__(): not enough arguments",
4085 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004086 return NULL;
4087 }
4088 arg0 = PyTuple_GET_ITEM(args, 0);
4089 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004090 PyErr_Format(PyExc_TypeError,
4091 "%s.__new__(X): X is not a type object (%s)",
4092 type->tp_name,
4093 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004094 return NULL;
4095 }
4096 subtype = (PyTypeObject *)arg0;
4097 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004098 PyErr_Format(PyExc_TypeError,
4099 "%s.__new__(%s): %s is not a subtype of %s",
4100 type->tp_name,
4101 subtype->tp_name,
4102 subtype->tp_name,
4103 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004104 return NULL;
4105 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004106
4107 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004108 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004109 most derived base that's not a heap type is this type. */
4110 staticbase = subtype;
4111 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4112 staticbase = staticbase->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004113 /* If staticbase is NULL now, it is a really weird type.
4114 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004115 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004116 PyErr_Format(PyExc_TypeError,
4117 "%s.__new__(%s) is not safe, use %s.__new__()",
4118 type->tp_name,
4119 subtype->tp_name,
4120 staticbase == NULL ? "?" : staticbase->tp_name);
4121 return NULL;
4122 }
4123
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004124 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4125 if (args == NULL)
4126 return NULL;
4127 res = type->tp_new(subtype, args, kwds);
4128 Py_DECREF(args);
4129 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004130}
4131
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004132static struct PyMethodDef tp_new_methoddef[] = {
4133 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004134 PyDoc_STR("T.__new__(S, ...) -> "
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004135 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004136 {0}
4137};
4138
4139static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004140add_tp_new_wrapper(PyTypeObject *type)
4141{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004142 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004143
Guido van Rossum687ae002001-10-15 22:03:32 +00004144 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004145 return 0;
4146 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004147 if (func == NULL)
4148 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004149 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004150 Py_DECREF(func);
4151 return -1;
4152 }
4153 Py_DECREF(func);
4154 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004155}
4156
Guido van Rossumf040ede2001-08-07 16:40:56 +00004157/* Slot wrappers that call the corresponding __foo__ slot. See comments
4158 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004159
Guido van Rossumdc91b992001-08-08 22:26:22 +00004160#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004161static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004162FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004163{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004164 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004165 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004166}
4167
Guido van Rossumdc91b992001-08-08 22:26:22 +00004168#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004169static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004170FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004171{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004172 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004173 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004174}
4175
Guido van Rossumcd118802003-01-06 22:57:47 +00004176/* Boolean helper for SLOT1BINFULL().
4177 right.__class__ is a nontrivial subclass of left.__class__. */
4178static int
4179method_is_overloaded(PyObject *left, PyObject *right, char *name)
4180{
4181 PyObject *a, *b;
4182 int ok;
4183
4184 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
4185 if (b == NULL) {
4186 PyErr_Clear();
4187 /* If right doesn't have it, it's not overloaded */
4188 return 0;
4189 }
4190
4191 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
4192 if (a == NULL) {
4193 PyErr_Clear();
4194 Py_DECREF(b);
4195 /* If right has it but left doesn't, it's overloaded */
4196 return 1;
4197 }
4198
4199 ok = PyObject_RichCompareBool(a, b, Py_NE);
4200 Py_DECREF(a);
4201 Py_DECREF(b);
4202 if (ok < 0) {
4203 PyErr_Clear();
4204 return 0;
4205 }
4206
4207 return ok;
4208}
4209
Guido van Rossumdc91b992001-08-08 22:26:22 +00004210
4211#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004212static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004213FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004214{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004215 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004216 int do_other = self->ob_type != other->ob_type && \
4217 other->ob_type->tp_as_number != NULL && \
4218 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004219 if (self->ob_type->tp_as_number != NULL && \
4220 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
4221 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004222 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004223 PyType_IsSubtype(other->ob_type, self->ob_type) && \
4224 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004225 r = call_maybe( \
4226 other, ROPSTR, &rcache_str, "(O)", self); \
4227 if (r != Py_NotImplemented) \
4228 return r; \
4229 Py_DECREF(r); \
4230 do_other = 0; \
4231 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004232 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004233 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004234 if (r != Py_NotImplemented || \
4235 other->ob_type == self->ob_type) \
4236 return r; \
4237 Py_DECREF(r); \
4238 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004239 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004240 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004241 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004242 } \
4243 Py_INCREF(Py_NotImplemented); \
4244 return Py_NotImplemented; \
4245}
4246
4247#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4248 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4249
4250#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4251static PyObject * \
4252FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4253{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004254 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004255 return call_method(self, OPSTR, &cache_str, \
4256 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004257}
4258
Martin v. Löwis18e16552006-02-15 17:27:45 +00004259static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004260slot_sq_length(PyObject *self)
4261{
Guido van Rossum2730b132001-08-28 18:22:14 +00004262 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004263 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004264 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004265
4266 if (res == NULL)
4267 return -1;
Neal Norwitz1872b1c2006-08-12 18:44:06 +00004268 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004269 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004270 if (len < 0) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00004271 if (!PyErr_Occurred())
4272 PyErr_SetString(PyExc_ValueError,
4273 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004274 return -1;
4275 }
Guido van Rossum26111622001-10-01 16:42:49 +00004276 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004277}
4278
Guido van Rossumf4593e02001-10-03 12:09:30 +00004279/* Super-optimized version of slot_sq_item.
4280 Other slots could do the same... */
4281static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004282slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004283{
4284 static PyObject *getitem_str;
4285 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4286 descrgetfunc f;
4287
4288 if (getitem_str == NULL) {
4289 getitem_str = PyString_InternFromString("__getitem__");
4290 if (getitem_str == NULL)
4291 return NULL;
4292 }
4293 func = _PyType_Lookup(self->ob_type, getitem_str);
4294 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004295 if ((f = func->ob_type->tp_descr_get) == NULL)
4296 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004297 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004298 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004299 if (func == NULL) {
4300 return NULL;
4301 }
4302 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004303 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004304 if (ival != NULL) {
4305 args = PyTuple_New(1);
4306 if (args != NULL) {
4307 PyTuple_SET_ITEM(args, 0, ival);
4308 retval = PyObject_Call(func, args, NULL);
4309 Py_XDECREF(args);
4310 Py_XDECREF(func);
4311 return retval;
4312 }
4313 }
4314 }
4315 else {
4316 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4317 }
4318 Py_XDECREF(args);
4319 Py_XDECREF(ival);
4320 Py_XDECREF(func);
4321 return NULL;
4322}
4323
Martin v. Löwis18e16552006-02-15 17:27:45 +00004324SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004325
4326static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004327slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004328{
4329 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004330 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004331
4332 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004333 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004334 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004335 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004336 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004337 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004338 if (res == NULL)
4339 return -1;
4340 Py_DECREF(res);
4341 return 0;
4342}
4343
4344static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004345slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004346{
4347 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004348 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004349
4350 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004351 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004352 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004353 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004354 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004355 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004356 if (res == NULL)
4357 return -1;
4358 Py_DECREF(res);
4359 return 0;
4360}
4361
4362static int
4363slot_sq_contains(PyObject *self, PyObject *value)
4364{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004365 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004366 int result = -1;
4367
Guido van Rossum60718732001-08-28 17:47:51 +00004368 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004369
Guido van Rossum55f20992001-10-01 17:18:22 +00004370 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004371 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004372 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004373 if (args == NULL)
4374 res = NULL;
4375 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004376 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004377 Py_DECREF(args);
4378 }
4379 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004380 if (res != NULL) {
4381 result = PyObject_IsTrue(res);
4382 Py_DECREF(res);
4383 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004384 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004385 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004386 /* Possible results: -1 and 1 */
4387 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004388 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004389 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004390 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004391}
4392
Tim Peters6d6c1a32001-08-02 04:15:00 +00004393#define slot_mp_length slot_sq_length
4394
Guido van Rossumdc91b992001-08-08 22:26:22 +00004395SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004396
4397static int
4398slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4399{
4400 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004401 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004402
4403 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004404 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004405 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004406 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004407 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004408 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004409 if (res == NULL)
4410 return -1;
4411 Py_DECREF(res);
4412 return 0;
4413}
4414
Guido van Rossumdc91b992001-08-08 22:26:22 +00004415SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4416SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4417SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4418SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4419SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4420SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4421
Jeremy Hylton938ace62002-07-17 16:30:39 +00004422static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004423
4424SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4425 nb_power, "__pow__", "__rpow__")
4426
4427static PyObject *
4428slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4429{
Guido van Rossum2730b132001-08-28 18:22:14 +00004430 static PyObject *pow_str;
4431
Guido van Rossumdc91b992001-08-08 22:26:22 +00004432 if (modulus == Py_None)
4433 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004434 /* Three-arg power doesn't use __rpow__. But ternary_op
4435 can call this when the second argument's type uses
4436 slot_nb_power, so check before calling self.__pow__. */
4437 if (self->ob_type->tp_as_number != NULL &&
4438 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4439 return call_method(self, "__pow__", &pow_str,
4440 "(OO)", other, modulus);
4441 }
4442 Py_INCREF(Py_NotImplemented);
4443 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004444}
4445
4446SLOT0(slot_nb_negative, "__neg__")
4447SLOT0(slot_nb_positive, "__pos__")
4448SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004449
4450static int
4451slot_nb_nonzero(PyObject *self)
4452{
Tim Petersea7f75d2002-12-07 21:39:16 +00004453 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004454 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004455 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004456
Guido van Rossum55f20992001-10-01 17:18:22 +00004457 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004458 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004459 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004460 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004461 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004462 if (func == NULL)
4463 return PyErr_Occurred() ? -1 : 1;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004464 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004465 args = PyTuple_New(0);
4466 if (args != NULL) {
4467 PyObject *temp = PyObject_Call(func, args, NULL);
4468 Py_DECREF(args);
4469 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004470 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004471 result = PyObject_IsTrue(temp);
4472 else {
4473 PyErr_Format(PyExc_TypeError,
4474 "__nonzero__ should return "
4475 "bool or int, returned %s",
4476 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004477 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004478 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004479 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004480 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004481 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004482 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004483 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004484}
4485
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004486
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004487static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004488slot_nb_index(PyObject *self)
4489{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004490 static PyObject *index_str;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004491 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004492}
4493
4494
Guido van Rossumdc91b992001-08-08 22:26:22 +00004495SLOT0(slot_nb_invert, "__invert__")
4496SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4497SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4498SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4499SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4500SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004501
4502static int
4503slot_nb_coerce(PyObject **a, PyObject **b)
4504{
4505 static PyObject *coerce_str;
4506 PyObject *self = *a, *other = *b;
4507
4508 if (self->ob_type->tp_as_number != NULL &&
4509 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4510 PyObject *r;
4511 r = call_maybe(
4512 self, "__coerce__", &coerce_str, "(O)", other);
4513 if (r == NULL)
4514 return -1;
4515 if (r == Py_NotImplemented) {
4516 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004517 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004518 else {
4519 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4520 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004521 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004522 Py_DECREF(r);
4523 return -1;
4524 }
4525 *a = PyTuple_GET_ITEM(r, 0);
4526 Py_INCREF(*a);
4527 *b = PyTuple_GET_ITEM(r, 1);
4528 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004529 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004530 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004531 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004532 }
4533 if (other->ob_type->tp_as_number != NULL &&
4534 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4535 PyObject *r;
4536 r = call_maybe(
4537 other, "__coerce__", &coerce_str, "(O)", self);
4538 if (r == NULL)
4539 return -1;
4540 if (r == Py_NotImplemented) {
4541 Py_DECREF(r);
4542 return 1;
4543 }
4544 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4545 PyErr_SetString(PyExc_TypeError,
4546 "__coerce__ didn't return a 2-tuple");
4547 Py_DECREF(r);
4548 return -1;
4549 }
4550 *a = PyTuple_GET_ITEM(r, 1);
4551 Py_INCREF(*a);
4552 *b = PyTuple_GET_ITEM(r, 0);
4553 Py_INCREF(*b);
4554 Py_DECREF(r);
4555 return 0;
4556 }
4557 return 1;
4558}
4559
Guido van Rossumdc91b992001-08-08 22:26:22 +00004560SLOT0(slot_nb_int, "__int__")
4561SLOT0(slot_nb_long, "__long__")
4562SLOT0(slot_nb_float, "__float__")
4563SLOT0(slot_nb_oct, "__oct__")
4564SLOT0(slot_nb_hex, "__hex__")
4565SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4566SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4567SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4568SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4569SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Martin v. Löwisfd963262007-02-09 12:19:32 +00004570/* Can't use SLOT1 here, because nb_inplace_power is ternary */
4571static PyObject *
4572slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4573{
4574 static PyObject *cache_str;
4575 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
4576}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004577SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4578SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4579SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4580SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4581SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4582SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4583 "__floordiv__", "__rfloordiv__")
4584SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4585SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4586SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004587
4588static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004589half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004590{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004591 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004592 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004593 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004594
Guido van Rossum60718732001-08-28 17:47:51 +00004595 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004596 if (func == NULL) {
4597 PyErr_Clear();
4598 }
4599 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004600 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004601 if (args == NULL)
4602 res = NULL;
4603 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004604 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004605 Py_DECREF(args);
4606 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004607 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004608 if (res != Py_NotImplemented) {
4609 if (res == NULL)
4610 return -2;
4611 c = PyInt_AsLong(res);
4612 Py_DECREF(res);
4613 if (c == -1 && PyErr_Occurred())
4614 return -2;
4615 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4616 }
4617 Py_DECREF(res);
4618 }
4619 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004620}
4621
Guido van Rossumab3b0342001-09-18 20:38:53 +00004622/* This slot is published for the benefit of try_3way_compare in object.c */
4623int
4624_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004625{
4626 int c;
4627
Guido van Rossumab3b0342001-09-18 20:38:53 +00004628 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004629 c = half_compare(self, other);
4630 if (c <= 1)
4631 return c;
4632 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004633 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004634 c = half_compare(other, self);
4635 if (c < -1)
4636 return -2;
4637 if (c <= 1)
4638 return -c;
4639 }
4640 return (void *)self < (void *)other ? -1 :
4641 (void *)self > (void *)other ? 1 : 0;
4642}
4643
4644static PyObject *
4645slot_tp_repr(PyObject *self)
4646{
4647 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004648 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004649
Guido van Rossum60718732001-08-28 17:47:51 +00004650 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004651 if (func != NULL) {
4652 res = PyEval_CallObject(func, NULL);
4653 Py_DECREF(func);
4654 return res;
4655 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004656 PyErr_Clear();
4657 return PyString_FromFormat("<%s object at %p>",
4658 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004659}
4660
4661static PyObject *
4662slot_tp_str(PyObject *self)
4663{
4664 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004665 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004666
Guido van Rossum60718732001-08-28 17:47:51 +00004667 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004668 if (func != NULL) {
4669 res = PyEval_CallObject(func, NULL);
4670 Py_DECREF(func);
4671 return res;
4672 }
4673 else {
4674 PyErr_Clear();
4675 return slot_tp_repr(self);
4676 }
4677}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004678
4679static long
4680slot_tp_hash(PyObject *self)
4681{
Tim Peters61ce0a92002-12-06 23:38:02 +00004682 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004683 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004684 long h;
4685
Guido van Rossum60718732001-08-28 17:47:51 +00004686 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004687
4688 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004689 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004690 Py_DECREF(func);
4691 if (res == NULL)
4692 return -1;
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00004693 if (PyLong_Check(res))
Armin Rigo51fc8c42006-08-09 14:55:26 +00004694 h = PyLong_Type.tp_hash(res);
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00004695 else
4696 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004697 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004698 }
4699 else {
4700 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004701 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004702 if (func == NULL) {
4703 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004704 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004705 }
4706 if (func != NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00004707 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
4708 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004709 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004710 return -1;
4711 }
4712 PyErr_Clear();
4713 h = _Py_HashPointer((void *)self);
4714 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004715 if (h == -1 && !PyErr_Occurred())
4716 h = -2;
4717 return h;
4718}
4719
4720static PyObject *
4721slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4722{
Guido van Rossum60718732001-08-28 17:47:51 +00004723 static PyObject *call_str;
4724 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004725 PyObject *res;
4726
4727 if (meth == NULL)
4728 return NULL;
Armin Rigo53c1692f2006-06-21 21:58:50 +00004729
4730 /* PyObject_Call() will end up calling slot_tp_call() again if
4731 the object returned for __call__ has __call__ itself defined
4732 upon it. This can be an infinite recursion if you set
4733 __call__ in a class to an instance of it. */
Neal Norwitzb1149842006-06-23 03:32:44 +00004734 if (Py_EnterRecursiveCall(" in __call__")) {
4735 Py_DECREF(meth);
Armin Rigo53c1692f2006-06-21 21:58:50 +00004736 return NULL;
Neal Norwitzb1149842006-06-23 03:32:44 +00004737 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004738 res = PyObject_Call(meth, args, kwds);
Armin Rigo53c1692f2006-06-21 21:58:50 +00004739 Py_LeaveRecursiveCall();
4740
Tim Peters6d6c1a32001-08-02 04:15:00 +00004741 Py_DECREF(meth);
4742 return res;
4743}
4744
Guido van Rossum14a6f832001-10-17 13:59:09 +00004745/* There are two slot dispatch functions for tp_getattro.
4746
4747 - slot_tp_getattro() is used when __getattribute__ is overridden
4748 but no __getattr__ hook is present;
4749
4750 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4751
Guido van Rossumc334df52002-04-04 23:44:47 +00004752 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4753 detects the absence of __getattr__ and then installs the simpler slot if
4754 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004755
Tim Peters6d6c1a32001-08-02 04:15:00 +00004756static PyObject *
4757slot_tp_getattro(PyObject *self, PyObject *name)
4758{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004759 static PyObject *getattribute_str = NULL;
4760 return call_method(self, "__getattribute__", &getattribute_str,
4761 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004762}
4763
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004764static PyObject *
4765slot_tp_getattr_hook(PyObject *self, PyObject *name)
4766{
4767 PyTypeObject *tp = self->ob_type;
4768 PyObject *getattr, *getattribute, *res;
4769 static PyObject *getattribute_str = NULL;
4770 static PyObject *getattr_str = NULL;
4771
4772 if (getattr_str == NULL) {
4773 getattr_str = PyString_InternFromString("__getattr__");
4774 if (getattr_str == NULL)
4775 return NULL;
4776 }
4777 if (getattribute_str == NULL) {
4778 getattribute_str =
4779 PyString_InternFromString("__getattribute__");
4780 if (getattribute_str == NULL)
4781 return NULL;
4782 }
4783 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004784 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004785 /* No __getattr__ hook: use a simpler dispatcher */
4786 tp->tp_getattro = slot_tp_getattro;
4787 return slot_tp_getattro(self, name);
4788 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004789 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004790 if (getattribute == NULL ||
4791 (getattribute->ob_type == &PyWrapperDescr_Type &&
4792 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4793 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004794 res = PyObject_GenericGetAttr(self, name);
4795 else
Georg Brandl684fd0c2006-05-25 19:15:31 +00004796 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004797 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004798 PyErr_Clear();
Georg Brandl684fd0c2006-05-25 19:15:31 +00004799 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004800 }
4801 return res;
4802}
4803
Tim Peters6d6c1a32001-08-02 04:15:00 +00004804static int
4805slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4806{
4807 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004808 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004809
4810 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004811 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004812 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004813 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004814 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004815 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004816 if (res == NULL)
4817 return -1;
4818 Py_DECREF(res);
4819 return 0;
4820}
4821
4822/* Map rich comparison operators to their __xx__ namesakes */
4823static char *name_op[] = {
4824 "__lt__",
4825 "__le__",
4826 "__eq__",
4827 "__ne__",
4828 "__gt__",
4829 "__ge__",
4830};
4831
4832static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004833half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004834{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004835 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004836 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004837
Guido van Rossum60718732001-08-28 17:47:51 +00004838 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004839 if (func == NULL) {
4840 PyErr_Clear();
4841 Py_INCREF(Py_NotImplemented);
4842 return Py_NotImplemented;
4843 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004844 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004845 if (args == NULL)
4846 res = NULL;
4847 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004848 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004849 Py_DECREF(args);
4850 }
4851 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004852 return res;
4853}
4854
Guido van Rossumb8f63662001-08-15 23:57:02 +00004855static PyObject *
4856slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4857{
4858 PyObject *res;
4859
4860 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4861 res = half_richcompare(self, other, op);
4862 if (res != Py_NotImplemented)
4863 return res;
4864 Py_DECREF(res);
4865 }
4866 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004867 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004868 if (res != Py_NotImplemented) {
4869 return res;
4870 }
4871 Py_DECREF(res);
4872 }
4873 Py_INCREF(Py_NotImplemented);
4874 return Py_NotImplemented;
4875}
4876
4877static PyObject *
4878slot_tp_iter(PyObject *self)
4879{
4880 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004881 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004882
Guido van Rossum60718732001-08-28 17:47:51 +00004883 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004884 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004885 PyObject *args;
4886 args = res = PyTuple_New(0);
4887 if (args != NULL) {
4888 res = PyObject_Call(func, args, NULL);
4889 Py_DECREF(args);
4890 }
4891 Py_DECREF(func);
4892 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004893 }
4894 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004895 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004896 if (func == NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00004897 PyErr_Format(PyExc_TypeError,
4898 "'%.200s' object is not iterable",
4899 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004900 return NULL;
4901 }
4902 Py_DECREF(func);
4903 return PySeqIter_New(self);
4904}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004905
4906static PyObject *
4907slot_tp_iternext(PyObject *self)
4908{
Guido van Rossum2730b132001-08-28 18:22:14 +00004909 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004910 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004911}
4912
Guido van Rossum1a493502001-08-17 16:47:50 +00004913static PyObject *
4914slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4915{
4916 PyTypeObject *tp = self->ob_type;
4917 PyObject *get;
4918 static PyObject *get_str = NULL;
4919
4920 if (get_str == NULL) {
4921 get_str = PyString_InternFromString("__get__");
4922 if (get_str == NULL)
4923 return NULL;
4924 }
4925 get = _PyType_Lookup(tp, get_str);
4926 if (get == NULL) {
4927 /* Avoid further slowdowns */
4928 if (tp->tp_descr_get == slot_tp_descr_get)
4929 tp->tp_descr_get = NULL;
4930 Py_INCREF(self);
4931 return self;
4932 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004933 if (obj == NULL)
4934 obj = Py_None;
4935 if (type == NULL)
4936 type = Py_None;
Georg Brandl684fd0c2006-05-25 19:15:31 +00004937 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00004938}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004939
4940static int
4941slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4942{
Guido van Rossum2c252392001-08-24 10:13:31 +00004943 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004944 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004945
4946 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004947 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004948 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004949 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004950 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004951 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004952 if (res == NULL)
4953 return -1;
4954 Py_DECREF(res);
4955 return 0;
4956}
4957
4958static int
4959slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4960{
Guido van Rossum60718732001-08-28 17:47:51 +00004961 static PyObject *init_str;
4962 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004963 PyObject *res;
4964
4965 if (meth == NULL)
4966 return -1;
4967 res = PyObject_Call(meth, args, kwds);
4968 Py_DECREF(meth);
4969 if (res == NULL)
4970 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004971 if (res != Py_None) {
Georg Brandlccff7852006-06-18 22:17:29 +00004972 PyErr_Format(PyExc_TypeError,
4973 "__init__() should return None, not '%.200s'",
4974 res->ob_type->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004975 Py_DECREF(res);
4976 return -1;
4977 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004978 Py_DECREF(res);
4979 return 0;
4980}
4981
4982static PyObject *
4983slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4984{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004985 static PyObject *new_str;
4986 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004987 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004988 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004989
Guido van Rossum7bed2132002-08-08 21:57:53 +00004990 if (new_str == NULL) {
4991 new_str = PyString_InternFromString("__new__");
4992 if (new_str == NULL)
4993 return NULL;
4994 }
4995 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004996 if (func == NULL)
4997 return NULL;
4998 assert(PyTuple_Check(args));
4999 n = PyTuple_GET_SIZE(args);
5000 newargs = PyTuple_New(n+1);
5001 if (newargs == NULL)
5002 return NULL;
5003 Py_INCREF(type);
5004 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5005 for (i = 0; i < n; i++) {
5006 x = PyTuple_GET_ITEM(args, i);
5007 Py_INCREF(x);
5008 PyTuple_SET_ITEM(newargs, i+1, x);
5009 }
5010 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00005011 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005012 Py_DECREF(func);
5013 return x;
5014}
5015
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005016static void
5017slot_tp_del(PyObject *self)
5018{
5019 static PyObject *del_str = NULL;
5020 PyObject *del, *res;
5021 PyObject *error_type, *error_value, *error_traceback;
5022
5023 /* Temporarily resurrect the object. */
5024 assert(self->ob_refcnt == 0);
5025 self->ob_refcnt = 1;
5026
5027 /* Save the current exception, if any. */
5028 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5029
5030 /* Execute __del__ method, if any. */
5031 del = lookup_maybe(self, "__del__", &del_str);
5032 if (del != NULL) {
5033 res = PyEval_CallObject(del, NULL);
5034 if (res == NULL)
5035 PyErr_WriteUnraisable(del);
5036 else
5037 Py_DECREF(res);
5038 Py_DECREF(del);
5039 }
5040
5041 /* Restore the saved exception. */
5042 PyErr_Restore(error_type, error_value, error_traceback);
5043
5044 /* Undo the temporary resurrection; can't use DECREF here, it would
5045 * cause a recursive call.
5046 */
5047 assert(self->ob_refcnt > 0);
5048 if (--self->ob_refcnt == 0)
5049 return; /* this is the normal path out */
5050
5051 /* __del__ resurrected it! Make it look like the original Py_DECREF
5052 * never happened.
5053 */
5054 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005055 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005056 _Py_NewReference(self);
5057 self->ob_refcnt = refcnt;
5058 }
5059 assert(!PyType_IS_GC(self->ob_type) ||
5060 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00005061 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5062 * we need to undo that. */
5063 _Py_DEC_REFTOTAL;
5064 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5065 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005066 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5067 * _Py_NewReference bumped tp_allocs: both of those need to be
5068 * undone.
5069 */
5070#ifdef COUNT_ALLOCS
5071 --self->ob_type->tp_frees;
5072 --self->ob_type->tp_allocs;
5073#endif
5074}
5075
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005076
5077/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005078 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005079 structure, which incorporates the additional structures used for numbers,
5080 sequences and mappings.
5081 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005082 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005083 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5084 terminated with an all-zero entry. (This table is further initialized and
5085 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005086
Guido van Rossum6d204072001-10-21 00:44:31 +00005087typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005088
5089#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005090#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005091#undef ETSLOT
5092#undef SQSLOT
5093#undef MPSLOT
5094#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005095#undef UNSLOT
5096#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005097#undef BINSLOT
5098#undef RBINSLOT
5099
Guido van Rossum6d204072001-10-21 00:44:31 +00005100#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005101 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5102 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005103#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5104 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005105 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005106#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005107 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005108 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005109#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5110 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5111#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5112 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5113#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5114 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5115#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5116 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5117 "x." NAME "() <==> " DOC)
5118#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5119 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5120 "x." NAME "(y) <==> x" DOC "y")
5121#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5122 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5123 "x." NAME "(y) <==> x" DOC "y")
5124#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5125 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5126 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005127#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5128 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5129 "x." NAME "(y) <==> " DOC)
5130#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5131 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5132 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005133
5134static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005135 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005136 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005137 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5138 The logic in abstract.c always falls back to nb_add/nb_multiply in
5139 this case. Defining both the nb_* and the sq_* slots to call the
5140 user-defined methods has unexpected side-effects, as shown by
5141 test_descr.notimplemented() */
5142 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005143 "x.__add__(y) <==> x+y"),
Armin Rigo314861c2006-03-30 14:04:02 +00005144 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005145 "x.__mul__(n) <==> x*n"),
Armin Rigo314861c2006-03-30 14:04:02 +00005146 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005147 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005148 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5149 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005150 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005151 "x.__getslice__(i, j) <==> x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005152 \n\
5153 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005154 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005155 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005156 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005157 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005158 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005159 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005160 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005161 \n\
5162 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005163 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005164 "x.__delslice__(i, j) <==> del x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005165 \n\
5166 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005167 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5168 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005169 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005170 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005171 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005172 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005173
Martin v. Löwis18e16552006-02-15 17:27:45 +00005174 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005175 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005176 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005177 wrap_binaryfunc,
5178 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005179 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005180 wrap_objobjargproc,
5181 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005182 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005183 wrap_delitem,
5184 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005185
Guido van Rossum6d204072001-10-21 00:44:31 +00005186 BINSLOT("__add__", nb_add, slot_nb_add,
5187 "+"),
5188 RBINSLOT("__radd__", nb_add, slot_nb_add,
5189 "+"),
5190 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5191 "-"),
5192 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5193 "-"),
5194 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5195 "*"),
5196 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5197 "*"),
5198 BINSLOT("__div__", nb_divide, slot_nb_divide,
5199 "/"),
5200 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5201 "/"),
5202 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5203 "%"),
5204 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5205 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005206 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005207 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005208 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005209 "divmod(y, x)"),
5210 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5211 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5212 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5213 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5214 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5215 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5216 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5217 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005218 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005219 "x != 0"),
5220 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5221 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5222 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5223 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5224 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5225 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5226 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5227 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5228 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5229 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5230 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5231 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5232 "x.__coerce__(y) <==> coerce(x, y)"),
5233 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5234 "int(x)"),
5235 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5236 "long(x)"),
5237 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5238 "float(x)"),
5239 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5240 "oct(x)"),
5241 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5242 "hex(x)"),
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005243 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005244 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005245 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5246 wrap_binaryfunc, "+"),
5247 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5248 wrap_binaryfunc, "-"),
5249 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5250 wrap_binaryfunc, "*"),
5251 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5252 wrap_binaryfunc, "/"),
5253 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5254 wrap_binaryfunc, "%"),
5255 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005256 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005257 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5258 wrap_binaryfunc, "<<"),
5259 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5260 wrap_binaryfunc, ">>"),
5261 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5262 wrap_binaryfunc, "&"),
5263 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5264 wrap_binaryfunc, "^"),
5265 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5266 wrap_binaryfunc, "|"),
5267 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5268 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5269 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5270 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5271 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5272 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5273 IBSLOT("__itruediv__", nb_inplace_true_divide,
5274 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005275
Guido van Rossum6d204072001-10-21 00:44:31 +00005276 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5277 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005278 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005279 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5280 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005281 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005282 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5283 "x.__cmp__(y) <==> cmp(x,y)"),
5284 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5285 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005286 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5287 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005288 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005289 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5290 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5291 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5292 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5293 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5294 "x.__setattr__('name', value) <==> x.name = value"),
5295 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5296 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5297 "x.__delattr__('name') <==> del x.name"),
5298 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5299 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5300 "x.__lt__(y) <==> x<y"),
5301 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5302 "x.__le__(y) <==> x<=y"),
5303 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5304 "x.__eq__(y) <==> x==y"),
5305 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5306 "x.__ne__(y) <==> x!=y"),
5307 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5308 "x.__gt__(y) <==> x>y"),
5309 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5310 "x.__ge__(y) <==> x>=y"),
5311 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5312 "x.__iter__() <==> iter(x)"),
5313 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5314 "x.next() -> the next value, or raise StopIteration"),
5315 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5316 "descr.__get__(obj[, type]) -> value"),
5317 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5318 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005319 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5320 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005321 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005322 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005323 "see x.__class__.__doc__ for signature",
5324 PyWrapperFlag_KEYWORDS),
5325 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005326 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005327 {NULL}
5328};
5329
Guido van Rossumc334df52002-04-04 23:44:47 +00005330/* Given a type pointer and an offset gotten from a slotdef entry, return a
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005331 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005332 the offset to the type pointer, since it takes care to indirect through the
5333 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5334 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005335static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005336slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005337{
5338 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005339 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005340
Guido van Rossume5c691a2003-03-07 15:13:17 +00005341 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005342 assert(offset >= 0);
Skip Montanaro429433b2006-04-18 00:35:43 +00005343 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5344 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005345 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005346 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005347 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005348 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005349 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005350 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005351 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005352 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005353 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005354 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005355 }
5356 else {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005357 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005358 }
5359 if (ptr != NULL)
5360 ptr += offset;
5361 return (void **)ptr;
5362}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005363
Guido van Rossumc334df52002-04-04 23:44:47 +00005364/* Length of array of slotdef pointers used to store slots with the
5365 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5366 the same __name__, for any __name__. Since that's a static property, it is
5367 appropriate to declare fixed-size arrays for this. */
5368#define MAX_EQUIV 10
5369
5370/* Return a slot pointer for a given name, but ONLY if the attribute has
5371 exactly one slot function. The name must be an interned string. */
5372static void **
5373resolve_slotdups(PyTypeObject *type, PyObject *name)
5374{
5375 /* XXX Maybe this could be optimized more -- but is it worth it? */
5376
5377 /* pname and ptrs act as a little cache */
5378 static PyObject *pname;
5379 static slotdef *ptrs[MAX_EQUIV];
5380 slotdef *p, **pp;
5381 void **res, **ptr;
5382
5383 if (pname != name) {
5384 /* Collect all slotdefs that match name into ptrs. */
5385 pname = name;
5386 pp = ptrs;
5387 for (p = slotdefs; p->name_strobj; p++) {
5388 if (p->name_strobj == name)
5389 *pp++ = p;
5390 }
5391 *pp = NULL;
5392 }
5393
5394 /* Look in all matching slots of the type; if exactly one of these has
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005395 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005396 res = NULL;
5397 for (pp = ptrs; *pp; pp++) {
5398 ptr = slotptr(type, (*pp)->offset);
5399 if (ptr == NULL || *ptr == NULL)
5400 continue;
5401 if (res != NULL)
5402 return NULL;
5403 res = ptr;
5404 }
5405 return res;
5406}
5407
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005408/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005409 does some incredibly complex thinking and then sticks something into the
5410 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5411 interests, and then stores a generic wrapper or a specific function into
5412 the slot.) Return a pointer to the next slotdef with a different offset,
5413 because that's convenient for fixup_slot_dispatchers(). */
5414static slotdef *
5415update_one_slot(PyTypeObject *type, slotdef *p)
5416{
5417 PyObject *descr;
5418 PyWrapperDescrObject *d;
5419 void *generic = NULL, *specific = NULL;
5420 int use_generic = 0;
5421 int offset = p->offset;
5422 void **ptr = slotptr(type, offset);
5423
5424 if (ptr == NULL) {
5425 do {
5426 ++p;
5427 } while (p->offset == offset);
5428 return p;
5429 }
5430 do {
5431 descr = _PyType_Lookup(type, p->name_strobj);
5432 if (descr == NULL)
5433 continue;
5434 if (descr->ob_type == &PyWrapperDescr_Type) {
5435 void **tptr = resolve_slotdups(type, p->name_strobj);
5436 if (tptr == NULL || tptr == ptr)
5437 generic = p->function;
5438 d = (PyWrapperDescrObject *)descr;
5439 if (d->d_base->wrapper == p->wrapper &&
5440 PyType_IsSubtype(type, d->d_type))
5441 {
5442 if (specific == NULL ||
5443 specific == d->d_wrapped)
5444 specific = d->d_wrapped;
5445 else
5446 use_generic = 1;
5447 }
5448 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005449 else if (descr->ob_type == &PyCFunction_Type &&
5450 PyCFunction_GET_FUNCTION(descr) ==
5451 (PyCFunction)tp_new_wrapper &&
5452 strcmp(p->name, "__new__") == 0)
5453 {
5454 /* The __new__ wrapper is not a wrapper descriptor,
5455 so must be special-cased differently.
5456 If we don't do this, creating an instance will
5457 always use slot_tp_new which will look up
5458 __new__ in the MRO which will call tp_new_wrapper
5459 which will look through the base classes looking
5460 for a static base and call its tp_new (usually
5461 PyType_GenericNew), after performing various
5462 sanity checks and constructing a new argument
5463 list. Cut all that nonsense short -- this speeds
5464 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005465 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005466 /* XXX I'm not 100% sure that there isn't a hole
5467 in this reasoning that requires additional
5468 sanity checks. I'll buy the first person to
5469 point out a bug in this reasoning a beer. */
5470 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005471 else {
5472 use_generic = 1;
5473 generic = p->function;
5474 }
5475 } while ((++p)->offset == offset);
5476 if (specific && !use_generic)
5477 *ptr = specific;
5478 else
5479 *ptr = generic;
5480 return p;
5481}
5482
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005483/* In the type, update the slots whose slotdefs are gathered in the pp array.
5484 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005485static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005486update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005487{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005488 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005489
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005490 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005491 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005492 return 0;
5493}
5494
Guido van Rossumc334df52002-04-04 23:44:47 +00005495/* Comparison function for qsort() to compare slotdefs by their offset, and
5496 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005497static int
5498slotdef_cmp(const void *aa, const void *bb)
5499{
5500 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5501 int c = a->offset - b->offset;
5502 if (c != 0)
5503 return c;
5504 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005505 /* Cannot use a-b, as this gives off_t,
5506 which may lose precision when converted to int. */
5507 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005508}
5509
Guido van Rossumc334df52002-04-04 23:44:47 +00005510/* Initialize the slotdefs table by adding interned string objects for the
5511 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005512static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005513init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005514{
5515 slotdef *p;
5516 static int initialized = 0;
5517
5518 if (initialized)
5519 return;
5520 for (p = slotdefs; p->name; p++) {
5521 p->name_strobj = PyString_InternFromString(p->name);
5522 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005523 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005524 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005525 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5526 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005527 initialized = 1;
5528}
5529
Guido van Rossumc334df52002-04-04 23:44:47 +00005530/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005531static int
5532update_slot(PyTypeObject *type, PyObject *name)
5533{
Guido van Rossumc334df52002-04-04 23:44:47 +00005534 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005535 slotdef *p;
5536 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005537 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005538
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005539 init_slotdefs();
5540 pp = ptrs;
5541 for (p = slotdefs; p->name; p++) {
5542 /* XXX assume name is interned! */
5543 if (p->name_strobj == name)
5544 *pp++ = p;
5545 }
5546 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005547 for (pp = ptrs; *pp; pp++) {
5548 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005549 offset = p->offset;
5550 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005551 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005552 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005553 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005554 if (ptrs[0] == NULL)
5555 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005556 return update_subclasses(type, name,
5557 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005558}
5559
Guido van Rossumc334df52002-04-04 23:44:47 +00005560/* Store the proper functions in the slot dispatches at class (type)
5561 definition time, based upon which operations the class overrides in its
5562 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005563static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005564fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005565{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005566 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005567
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005568 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005569 for (p = slotdefs; p->name; )
5570 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005571}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005572
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005573static void
5574update_all_slots(PyTypeObject* type)
5575{
5576 slotdef *p;
5577
5578 init_slotdefs();
5579 for (p = slotdefs; p->name; p++) {
5580 /* update_slot returns int but can't actually fail */
5581 update_slot(type, p->name_strobj);
5582 }
5583}
5584
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005585/* recurse_down_subclasses() and update_subclasses() are mutually
5586 recursive functions to call a callback for all subclasses,
5587 but refraining from recursing into subclasses that define 'name'. */
5588
5589static int
5590update_subclasses(PyTypeObject *type, PyObject *name,
5591 update_callback callback, void *data)
5592{
5593 if (callback(type, data) < 0)
5594 return -1;
5595 return recurse_down_subclasses(type, name, callback, data);
5596}
5597
5598static int
5599recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5600 update_callback callback, void *data)
5601{
5602 PyTypeObject *subclass;
5603 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005604 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005605
5606 subclasses = type->tp_subclasses;
5607 if (subclasses == NULL)
5608 return 0;
5609 assert(PyList_Check(subclasses));
5610 n = PyList_GET_SIZE(subclasses);
5611 for (i = 0; i < n; i++) {
5612 ref = PyList_GET_ITEM(subclasses, i);
5613 assert(PyWeakref_CheckRef(ref));
5614 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5615 assert(subclass != NULL);
5616 if ((PyObject *)subclass == Py_None)
5617 continue;
5618 assert(PyType_Check(subclass));
5619 /* Avoid recursing down into unaffected classes */
5620 dict = subclass->tp_dict;
5621 if (dict != NULL && PyDict_Check(dict) &&
5622 PyDict_GetItem(dict, name) != NULL)
5623 continue;
5624 if (update_subclasses(subclass, name, callback, data) < 0)
5625 return -1;
5626 }
5627 return 0;
5628}
5629
Guido van Rossum6d204072001-10-21 00:44:31 +00005630/* This function is called by PyType_Ready() to populate the type's
5631 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005632 function slot (like tp_repr) that's defined in the type, one or more
5633 corresponding descriptors are added in the type's tp_dict dictionary
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005634 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005635 cause more than one descriptor to be added (for example, the nb_add
5636 slot adds both __add__ and __radd__ descriptors) and some function
5637 slots compete for the same descriptor (for example both sq_item and
5638 mp_subscript generate a __getitem__ descriptor).
5639
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005640 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005641 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005642 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005643 between competing slots: the members of PyHeapTypeObject are listed
5644 from most general to least general, so the most general slot is
5645 preferred. In particular, because as_mapping comes before as_sequence,
5646 for a type that defines both mp_subscript and sq_item, mp_subscript
5647 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005648
5649 This only adds new descriptors and doesn't overwrite entries in
5650 tp_dict that were previously defined. The descriptors contain a
5651 reference to the C function they must call, so that it's safe if they
5652 are copied into a subtype's __dict__ and the subtype has a different
5653 C function in its slot -- calling the method defined by the
5654 descriptor will call the C function that was used to create it,
5655 rather than the C function present in the slot when it is called.
5656 (This is important because a subtype may have a C function in the
5657 slot that calls the method from the dictionary, and we want to avoid
5658 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005659
5660static int
5661add_operators(PyTypeObject *type)
5662{
5663 PyObject *dict = type->tp_dict;
5664 slotdef *p;
5665 PyObject *descr;
5666 void **ptr;
5667
5668 init_slotdefs();
5669 for (p = slotdefs; p->name; p++) {
5670 if (p->wrapper == NULL)
5671 continue;
5672 ptr = slotptr(type, p->offset);
5673 if (!ptr || !*ptr)
5674 continue;
5675 if (PyDict_GetItem(dict, p->name_strobj))
5676 continue;
5677 descr = PyDescr_NewWrapper(type, p, *ptr);
5678 if (descr == NULL)
5679 return -1;
5680 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5681 return -1;
5682 Py_DECREF(descr);
5683 }
5684 if (type->tp_new != NULL) {
5685 if (add_tp_new_wrapper(type) < 0)
5686 return -1;
5687 }
5688 return 0;
5689}
5690
Guido van Rossum705f0f52001-08-24 16:47:00 +00005691
5692/* Cooperative 'super' */
5693
5694typedef struct {
5695 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005696 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005697 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005698 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005699} superobject;
5700
Guido van Rossum6f799372001-09-20 20:46:19 +00005701static PyMemberDef super_members[] = {
5702 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5703 "the class invoking super()"},
5704 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5705 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005706 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005707 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005708 {0}
5709};
5710
Guido van Rossum705f0f52001-08-24 16:47:00 +00005711static void
5712super_dealloc(PyObject *self)
5713{
5714 superobject *su = (superobject *)self;
5715
Guido van Rossum048eb752001-10-02 21:24:57 +00005716 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005717 Py_XDECREF(su->obj);
5718 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005719 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005720 self->ob_type->tp_free(self);
5721}
5722
5723static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005724super_repr(PyObject *self)
5725{
5726 superobject *su = (superobject *)self;
5727
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005728 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005729 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005730 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005731 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005732 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005733 else
5734 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005735 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005736 su->type ? su->type->tp_name : "NULL");
5737}
5738
5739static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005740super_getattro(PyObject *self, PyObject *name)
5741{
5742 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005743 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005744
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005745 if (!skip) {
5746 /* We want __class__ to return the class of the super object
5747 (i.e. super, or a subclass), not the class of su->obj. */
5748 skip = (PyString_Check(name) &&
5749 PyString_GET_SIZE(name) == 9 &&
5750 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5751 }
5752
5753 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005754 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005755 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005756 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005757 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005758
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005759 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005760 mro = starttype->tp_mro;
5761
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005762 if (mro == NULL)
5763 n = 0;
5764 else {
5765 assert(PyTuple_Check(mro));
5766 n = PyTuple_GET_SIZE(mro);
5767 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005768 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005769 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005770 break;
5771 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005772 i++;
5773 res = NULL;
5774 for (; i < n; i++) {
5775 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005776 if (PyType_Check(tmp))
5777 dict = ((PyTypeObject *)tmp)->tp_dict;
5778 else if (PyClass_Check(tmp))
5779 dict = ((PyClassObject *)tmp)->cl_dict;
5780 else
5781 continue;
5782 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005783 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005784 Py_INCREF(res);
5785 f = res->ob_type->tp_descr_get;
5786 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005787 tmp = f(res,
5788 /* Only pass 'obj' param if
5789 this is instance-mode super
5790 (See SF ID #743627)
5791 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005792 (su->obj == (PyObject *)
5793 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005794 ? (PyObject *)NULL
5795 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005796 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005797 Py_DECREF(res);
5798 res = tmp;
5799 }
5800 return res;
5801 }
5802 }
5803 }
5804 return PyObject_GenericGetAttr(self, name);
5805}
5806
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005807static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005808supercheck(PyTypeObject *type, PyObject *obj)
5809{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005810 /* Check that a super() call makes sense. Return a type object.
5811
5812 obj can be a new-style class, or an instance of one:
5813
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005814 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005815 used for class methods; the return value is obj.
5816
5817 - If it is an instance, it must be an instance of 'type'. This is
5818 the normal case; the return value is obj.__class__.
5819
5820 But... when obj is an instance, we want to allow for the case where
5821 obj->ob_type is not a subclass of type, but obj.__class__ is!
5822 This will allow using super() with a proxy for obj.
5823 */
5824
Guido van Rossum8e80a722003-02-18 19:22:22 +00005825 /* Check for first bullet above (special case) */
5826 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5827 Py_INCREF(obj);
5828 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005829 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005830
5831 /* Normal case */
5832 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005833 Py_INCREF(obj->ob_type);
5834 return obj->ob_type;
5835 }
5836 else {
5837 /* Try the slow way */
5838 static PyObject *class_str = NULL;
5839 PyObject *class_attr;
5840
5841 if (class_str == NULL) {
5842 class_str = PyString_FromString("__class__");
5843 if (class_str == NULL)
5844 return NULL;
5845 }
5846
5847 class_attr = PyObject_GetAttr(obj, class_str);
5848
5849 if (class_attr != NULL &&
5850 PyType_Check(class_attr) &&
5851 (PyTypeObject *)class_attr != obj->ob_type)
5852 {
5853 int ok = PyType_IsSubtype(
5854 (PyTypeObject *)class_attr, type);
5855 if (ok)
5856 return (PyTypeObject *)class_attr;
5857 }
5858
5859 if (class_attr == NULL)
5860 PyErr_Clear();
5861 else
5862 Py_DECREF(class_attr);
5863 }
5864
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005865 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005866 "super(type, obj): "
5867 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005868 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005869}
5870
Guido van Rossum705f0f52001-08-24 16:47:00 +00005871static PyObject *
5872super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5873{
5874 superobject *su = (superobject *)self;
Anthony Baxtera6286212006-04-11 07:42:36 +00005875 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005876
5877 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5878 /* Not binding to an object, or already bound */
5879 Py_INCREF(self);
5880 return self;
5881 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005882 if (su->ob_type != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005883 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005884 call its type */
Georg Brandl684fd0c2006-05-25 19:15:31 +00005885 return PyObject_CallFunctionObjArgs((PyObject *)su->ob_type,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005886 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005887 else {
5888 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005889 PyTypeObject *obj_type = supercheck(su->type, obj);
5890 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005891 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00005892 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005893 NULL, NULL);
Anthony Baxtera6286212006-04-11 07:42:36 +00005894 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005895 return NULL;
5896 Py_INCREF(su->type);
5897 Py_INCREF(obj);
Anthony Baxtera6286212006-04-11 07:42:36 +00005898 newobj->type = su->type;
5899 newobj->obj = obj;
5900 newobj->obj_type = obj_type;
5901 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005902 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005903}
5904
5905static int
5906super_init(PyObject *self, PyObject *args, PyObject *kwds)
5907{
5908 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005909 PyTypeObject *type;
5910 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005911 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005912
Georg Brandl5d59c092006-09-30 08:43:30 +00005913 if (!_PyArg_NoKeywords("super", kwds))
5914 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005915 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5916 return -1;
5917 if (obj == Py_None)
5918 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005919 if (obj != NULL) {
5920 obj_type = supercheck(type, obj);
5921 if (obj_type == NULL)
5922 return -1;
5923 Py_INCREF(obj);
5924 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005925 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005926 su->type = type;
5927 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005928 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005929 return 0;
5930}
5931
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005932PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005933"super(type) -> unbound super object\n"
5934"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005935"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005936"Typical use to call a cooperative superclass method:\n"
5937"class C(B):\n"
5938" def meth(self, arg):\n"
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005939" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005940
Guido van Rossum048eb752001-10-02 21:24:57 +00005941static int
5942super_traverse(PyObject *self, visitproc visit, void *arg)
5943{
5944 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00005945
Thomas Woutersc6e55062006-04-15 21:47:09 +00005946 Py_VISIT(su->obj);
5947 Py_VISIT(su->type);
5948 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005949
5950 return 0;
5951}
5952
Guido van Rossum705f0f52001-08-24 16:47:00 +00005953PyTypeObject PySuper_Type = {
5954 PyObject_HEAD_INIT(&PyType_Type)
5955 0, /* ob_size */
5956 "super", /* tp_name */
5957 sizeof(superobject), /* tp_basicsize */
5958 0, /* tp_itemsize */
5959 /* methods */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005960 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005961 0, /* tp_print */
5962 0, /* tp_getattr */
5963 0, /* tp_setattr */
5964 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005965 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005966 0, /* tp_as_number */
5967 0, /* tp_as_sequence */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005968 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005969 0, /* tp_hash */
5970 0, /* tp_call */
5971 0, /* tp_str */
5972 super_getattro, /* tp_getattro */
5973 0, /* tp_setattro */
5974 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005975 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5976 Py_TPFLAGS_BASETYPE, /* tp_flags */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005977 super_doc, /* tp_doc */
5978 super_traverse, /* tp_traverse */
5979 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005980 0, /* tp_richcompare */
5981 0, /* tp_weaklistoffset */
5982 0, /* tp_iter */
5983 0, /* tp_iternext */
5984 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005985 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005986 0, /* tp_getset */
5987 0, /* tp_base */
5988 0, /* tp_dict */
5989 super_descr_get, /* tp_descr_get */
5990 0, /* tp_descr_set */
5991 0, /* tp_dictoffset */
5992 super_init, /* tp_init */
5993 PyType_GenericAlloc, /* tp_alloc */
5994 PyType_GenericNew, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005995 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005996};