blob: c1e3ff3b56d2f046caec8ae983f258bd98ebf6ae [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
Guido van Rossum143b5642007-03-23 04:58:42 +00002394/* You may wonder why object.__new__() only complains about arguments
2395 when object.__init__() is not overridden, and vice versa.
2396
2397 Consider the use cases:
2398
2399 1. When neither is overridden, we want to hear complaints about
2400 excess (i.e., any) arguments, since their presence could
2401 indicate there's a bug.
2402
2403 2. When defining an Immutable type, we are likely to override only
2404 __new__(), since __init__() is called too late to initialize an
2405 Immutable object. Since __new__() defines the signature for the
2406 type, it would be a pain to have to override __init__() just to
2407 stop it from complaining about excess arguments.
2408
2409 3. When defining a Mutable type, we are likely to override only
2410 __init__(). So here the converse reasoning applies: we don't
2411 want to have to override __new__() just to stop it from
2412 complaining.
2413
2414 4. When __init__() is overridden, and the subclass __init__() calls
2415 object.__init__(), the latter should complain about excess
2416 arguments; ditto for __new__().
2417
2418 Use cases 2 and 3 make it unattractive to unconditionally check for
2419 excess arguments. The best solution that addresses all four use
2420 cases is as follows: __init__() complains about excess arguments
2421 unless __new__() is overridden and __init__() is not overridden
2422 (IOW, if __init__() is overridden or __new__() is not overridden);
2423 symmetrically, __new__() complains about excess arguments unless
2424 __init__() is overridden and __new__() is not overridden
2425 (IOW, if __new__() is overridden or __init__() is not overridden).
2426
2427 However, for backwards compatibility, this breaks too much code.
2428 Therefore, in 2.6, we'll *warn* about excess arguments when both
2429 methods are overridden; for all other cases we'll use the above
2430 rules.
2431
2432*/
2433
2434/* Forward */
2435static PyObject *
2436object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2437
2438static int
2439excess_args(PyObject *args, PyObject *kwds)
2440{
2441 return PyTuple_GET_SIZE(args) ||
2442 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2443}
2444
Tim Peters6d6c1a32001-08-02 04:15:00 +00002445static int
2446object_init(PyObject *self, PyObject *args, PyObject *kwds)
2447{
Guido van Rossum143b5642007-03-23 04:58:42 +00002448 int err = 0;
2449 if (excess_args(args, kwds)) {
2450 PyTypeObject *type = self->ob_type;
2451 if (type->tp_init != object_init &&
2452 type->tp_new != object_new)
2453 {
2454 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2455 "object.__init__() takes no parameters",
2456 1);
2457 }
2458 else if (type->tp_init != object_init ||
2459 type->tp_new == object_new)
2460 {
2461 PyErr_SetString(PyExc_TypeError,
2462 "object.__init__() takes no parameters");
2463 err = -1;
2464 }
2465 }
2466 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002467}
2468
Guido van Rossum298e4212003-02-13 16:30:16 +00002469static PyObject *
2470object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2471{
Guido van Rossum143b5642007-03-23 04:58:42 +00002472 int err = 0;
2473 if (excess_args(args, kwds)) {
2474 if (type->tp_new != object_new &&
2475 type->tp_init != object_init)
2476 {
2477 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2478 "object.__new__() takes no parameters",
2479 1);
2480 }
2481 else if (type->tp_new != object_new ||
2482 type->tp_init == object_init)
2483 {
2484 PyErr_SetString(PyExc_TypeError,
2485 "object.__new__() takes no parameters");
2486 err = -1;
2487 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002488 }
Guido van Rossum143b5642007-03-23 04:58:42 +00002489 if (err < 0)
2490 return NULL;
Guido van Rossum298e4212003-02-13 16:30:16 +00002491 return type->tp_alloc(type, 0);
2492}
2493
Tim Peters6d6c1a32001-08-02 04:15:00 +00002494static void
2495object_dealloc(PyObject *self)
2496{
2497 self->ob_type->tp_free(self);
2498}
2499
Guido van Rossum8e248182001-08-12 05:17:56 +00002500static PyObject *
2501object_repr(PyObject *self)
2502{
Guido van Rossum76e69632001-08-16 18:52:43 +00002503 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002504 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002505
Guido van Rossum76e69632001-08-16 18:52:43 +00002506 type = self->ob_type;
2507 mod = type_module(type, NULL);
2508 if (mod == NULL)
2509 PyErr_Clear();
2510 else if (!PyString_Check(mod)) {
2511 Py_DECREF(mod);
2512 mod = NULL;
2513 }
2514 name = type_name(type, NULL);
2515 if (name == NULL)
2516 return NULL;
2517 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002518 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002519 PyString_AS_STRING(mod),
2520 PyString_AS_STRING(name),
2521 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002522 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002523 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002524 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002525 Py_XDECREF(mod);
2526 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002527 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002528}
2529
Guido van Rossumb8f63662001-08-15 23:57:02 +00002530static PyObject *
2531object_str(PyObject *self)
2532{
2533 unaryfunc f;
2534
2535 f = self->ob_type->tp_repr;
2536 if (f == NULL)
2537 f = object_repr;
2538 return f(self);
2539}
2540
Guido van Rossum8e248182001-08-12 05:17:56 +00002541static long
2542object_hash(PyObject *self)
2543{
2544 return _Py_HashPointer(self);
2545}
Guido van Rossum8e248182001-08-12 05:17:56 +00002546
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002547static PyObject *
2548object_get_class(PyObject *self, void *closure)
2549{
2550 Py_INCREF(self->ob_type);
2551 return (PyObject *)(self->ob_type);
2552}
2553
2554static int
2555equiv_structs(PyTypeObject *a, PyTypeObject *b)
2556{
2557 return a == b ||
2558 (a != NULL &&
2559 b != NULL &&
2560 a->tp_basicsize == b->tp_basicsize &&
2561 a->tp_itemsize == b->tp_itemsize &&
2562 a->tp_dictoffset == b->tp_dictoffset &&
2563 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2564 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2565 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2566}
2567
2568static int
2569same_slots_added(PyTypeObject *a, PyTypeObject *b)
2570{
2571 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002572 Py_ssize_t size;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002573 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002574
2575 if (base != b->tp_base)
2576 return 0;
2577 if (equiv_structs(a, base) && equiv_structs(b, base))
2578 return 1;
2579 size = base->tp_basicsize;
2580 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2581 size += sizeof(PyObject *);
2582 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2583 size += sizeof(PyObject *);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002584
2585 /* Check slots compliance */
2586 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2587 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2588 if (slots_a && slots_b) {
2589 if (PyObject_Compare(slots_a, slots_b) != 0)
2590 return 0;
2591 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2592 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002593 return size == a->tp_basicsize && size == b->tp_basicsize;
2594}
2595
2596static int
Anthony Baxtera6286212006-04-11 07:42:36 +00002597compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002598{
2599 PyTypeObject *newbase, *oldbase;
2600
Anthony Baxtera6286212006-04-11 07:42:36 +00002601 if (newto->tp_dealloc != oldto->tp_dealloc ||
2602 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002603 {
2604 PyErr_Format(PyExc_TypeError,
2605 "%s assignment: "
2606 "'%s' deallocator differs from '%s'",
2607 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002608 newto->tp_name,
2609 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002610 return 0;
2611 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002612 newbase = newto;
2613 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002614 while (equiv_structs(newbase, newbase->tp_base))
2615 newbase = newbase->tp_base;
2616 while (equiv_structs(oldbase, oldbase->tp_base))
2617 oldbase = oldbase->tp_base;
2618 if (newbase != oldbase &&
2619 (newbase->tp_base != oldbase->tp_base ||
2620 !same_slots_added(newbase, oldbase))) {
2621 PyErr_Format(PyExc_TypeError,
2622 "%s assignment: "
2623 "'%s' object layout differs from '%s'",
2624 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002625 newto->tp_name,
2626 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002627 return 0;
2628 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002629
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002630 return 1;
2631}
2632
2633static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002634object_set_class(PyObject *self, PyObject *value, void *closure)
2635{
Anthony Baxtera6286212006-04-11 07:42:36 +00002636 PyTypeObject *oldto = self->ob_type;
2637 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002638
Guido van Rossumb6b89422002-04-15 01:03:30 +00002639 if (value == NULL) {
2640 PyErr_SetString(PyExc_TypeError,
2641 "can't delete __class__ attribute");
2642 return -1;
2643 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002644 if (!PyType_Check(value)) {
2645 PyErr_Format(PyExc_TypeError,
2646 "__class__ must be set to new-style class, not '%s' object",
2647 value->ob_type->tp_name);
2648 return -1;
2649 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002650 newto = (PyTypeObject *)value;
2651 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2652 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002653 {
2654 PyErr_Format(PyExc_TypeError,
2655 "__class__ assignment: only for heap types");
2656 return -1;
2657 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002658 if (compatible_for_assignment(newto, oldto, "__class__")) {
2659 Py_INCREF(newto);
2660 self->ob_type = newto;
2661 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002662 return 0;
2663 }
2664 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002665 return -1;
2666 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002667}
2668
2669static PyGetSetDef object_getsets[] = {
2670 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002671 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002672 {0}
2673};
2674
Guido van Rossumc53f0092003-02-18 22:05:12 +00002675
Guido van Rossum036f9992003-02-21 22:02:54 +00002676/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2677 We fall back to helpers in copy_reg for:
2678 - pickle protocols < 2
2679 - calculating the list of slot names (done only once per class)
2680 - the __newobj__ function (which is used as a token but never called)
2681*/
2682
2683static PyObject *
2684import_copy_reg(void)
2685{
2686 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002687
2688 if (!copy_reg_str) {
2689 copy_reg_str = PyString_InternFromString("copy_reg");
2690 if (copy_reg_str == NULL)
2691 return NULL;
2692 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002693
2694 return PyImport_Import(copy_reg_str);
2695}
2696
2697static PyObject *
2698slotnames(PyObject *cls)
2699{
2700 PyObject *clsdict;
2701 PyObject *copy_reg;
2702 PyObject *slotnames;
2703
2704 if (!PyType_Check(cls)) {
2705 Py_INCREF(Py_None);
2706 return Py_None;
2707 }
2708
2709 clsdict = ((PyTypeObject *)cls)->tp_dict;
2710 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002711 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002712 Py_INCREF(slotnames);
2713 return slotnames;
2714 }
2715
2716 copy_reg = import_copy_reg();
2717 if (copy_reg == NULL)
2718 return NULL;
2719
2720 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2721 Py_DECREF(copy_reg);
2722 if (slotnames != NULL &&
2723 slotnames != Py_None &&
2724 !PyList_Check(slotnames))
2725 {
2726 PyErr_SetString(PyExc_TypeError,
2727 "copy_reg._slotnames didn't return a list or None");
2728 Py_DECREF(slotnames);
2729 slotnames = NULL;
2730 }
2731
2732 return slotnames;
2733}
2734
2735static PyObject *
2736reduce_2(PyObject *obj)
2737{
2738 PyObject *cls, *getnewargs;
2739 PyObject *args = NULL, *args2 = NULL;
2740 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2741 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2742 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002743 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00002744
2745 cls = PyObject_GetAttrString(obj, "__class__");
2746 if (cls == NULL)
2747 return NULL;
2748
2749 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2750 if (getnewargs != NULL) {
2751 args = PyObject_CallObject(getnewargs, NULL);
2752 Py_DECREF(getnewargs);
2753 if (args != NULL && !PyTuple_Check(args)) {
Georg Brandlccff7852006-06-18 22:17:29 +00002754 PyErr_Format(PyExc_TypeError,
2755 "__getnewargs__ should return a tuple, "
2756 "not '%.200s'", args->ob_type->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00002757 goto end;
2758 }
2759 }
2760 else {
2761 PyErr_Clear();
2762 args = PyTuple_New(0);
2763 }
2764 if (args == NULL)
2765 goto end;
2766
2767 getstate = PyObject_GetAttrString(obj, "__getstate__");
2768 if (getstate != NULL) {
2769 state = PyObject_CallObject(getstate, NULL);
2770 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002771 if (state == NULL)
2772 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002773 }
2774 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002775 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002776 state = PyObject_GetAttrString(obj, "__dict__");
2777 if (state == NULL) {
2778 PyErr_Clear();
2779 state = Py_None;
2780 Py_INCREF(state);
2781 }
2782 names = slotnames(cls);
2783 if (names == NULL)
2784 goto end;
2785 if (names != Py_None) {
2786 assert(PyList_Check(names));
2787 slots = PyDict_New();
2788 if (slots == NULL)
2789 goto end;
2790 n = 0;
2791 /* Can't pre-compute the list size; the list
2792 is stored on the class so accessible to other
2793 threads, which may be run by DECREF */
2794 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2795 PyObject *name, *value;
2796 name = PyList_GET_ITEM(names, i);
2797 value = PyObject_GetAttr(obj, name);
2798 if (value == NULL)
2799 PyErr_Clear();
2800 else {
2801 int err = PyDict_SetItem(slots, name,
2802 value);
2803 Py_DECREF(value);
2804 if (err)
2805 goto end;
2806 n++;
2807 }
2808 }
2809 if (n) {
2810 state = Py_BuildValue("(NO)", state, slots);
2811 if (state == NULL)
2812 goto end;
2813 }
2814 }
2815 }
2816
2817 if (!PyList_Check(obj)) {
2818 listitems = Py_None;
2819 Py_INCREF(listitems);
2820 }
2821 else {
2822 listitems = PyObject_GetIter(obj);
2823 if (listitems == NULL)
2824 goto end;
2825 }
2826
2827 if (!PyDict_Check(obj)) {
2828 dictitems = Py_None;
2829 Py_INCREF(dictitems);
2830 }
2831 else {
2832 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2833 if (dictitems == NULL)
2834 goto end;
2835 }
2836
2837 copy_reg = import_copy_reg();
2838 if (copy_reg == NULL)
2839 goto end;
2840 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2841 if (newobj == NULL)
2842 goto end;
2843
2844 n = PyTuple_GET_SIZE(args);
2845 args2 = PyTuple_New(n+1);
2846 if (args2 == NULL)
2847 goto end;
2848 PyTuple_SET_ITEM(args2, 0, cls);
2849 cls = NULL;
2850 for (i = 0; i < n; i++) {
2851 PyObject *v = PyTuple_GET_ITEM(args, i);
2852 Py_INCREF(v);
2853 PyTuple_SET_ITEM(args2, i+1, v);
2854 }
2855
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002856 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002857
2858 end:
2859 Py_XDECREF(cls);
2860 Py_XDECREF(args);
2861 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002862 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002863 Py_XDECREF(state);
2864 Py_XDECREF(names);
2865 Py_XDECREF(listitems);
2866 Py_XDECREF(dictitems);
2867 Py_XDECREF(copy_reg);
2868 Py_XDECREF(newobj);
2869 return res;
2870}
2871
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00002872/*
2873 * There were two problems when object.__reduce__ and object.__reduce_ex__
2874 * were implemented in the same function:
2875 * - trying to pickle an object with a custom __reduce__ method that
2876 * fell back to object.__reduce__ in certain circumstances led to
2877 * infinite recursion at Python level and eventual RuntimeError.
2878 * - Pickling objects that lied about their type by overwriting the
2879 * __class__ descriptor could lead to infinite recursion at C level
2880 * and eventual segfault.
2881 *
2882 * Because of backwards compatibility, the two methods still have to
2883 * behave in the same way, even if this is not required by the pickle
2884 * protocol. This common functionality was moved to the _common_reduce
2885 * function.
2886 */
2887static PyObject *
2888_common_reduce(PyObject *self, int proto)
2889{
2890 PyObject *copy_reg, *res;
2891
2892 if (proto >= 2)
2893 return reduce_2(self);
2894
2895 copy_reg = import_copy_reg();
2896 if (!copy_reg)
2897 return NULL;
2898
2899 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
2900 Py_DECREF(copy_reg);
2901
2902 return res;
2903}
2904
2905static PyObject *
2906object_reduce(PyObject *self, PyObject *args)
2907{
2908 int proto = 0;
2909
2910 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
2911 return NULL;
2912
2913 return _common_reduce(self, proto);
2914}
2915
Guido van Rossum036f9992003-02-21 22:02:54 +00002916static PyObject *
2917object_reduce_ex(PyObject *self, PyObject *args)
2918{
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00002919 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00002920 int proto = 0;
2921
2922 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2923 return NULL;
2924
2925 reduce = PyObject_GetAttrString(self, "__reduce__");
2926 if (reduce == NULL)
2927 PyErr_Clear();
2928 else {
2929 PyObject *cls, *clsreduce, *objreduce;
2930 int override;
2931 cls = PyObject_GetAttrString(self, "__class__");
2932 if (cls == NULL) {
2933 Py_DECREF(reduce);
2934 return NULL;
2935 }
2936 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2937 Py_DECREF(cls);
2938 if (clsreduce == NULL) {
2939 Py_DECREF(reduce);
2940 return NULL;
2941 }
2942 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2943 "__reduce__");
2944 override = (clsreduce != objreduce);
2945 Py_DECREF(clsreduce);
2946 if (override) {
2947 res = PyObject_CallObject(reduce, NULL);
2948 Py_DECREF(reduce);
2949 return res;
2950 }
2951 else
2952 Py_DECREF(reduce);
2953 }
2954
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00002955 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002956}
2957
2958static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002959 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2960 PyDoc_STR("helper for pickle")},
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00002961 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002962 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002963 {0}
2964};
2965
Guido van Rossum036f9992003-02-21 22:02:54 +00002966
Tim Peters6d6c1a32001-08-02 04:15:00 +00002967PyTypeObject PyBaseObject_Type = {
2968 PyObject_HEAD_INIT(&PyType_Type)
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002969 0, /* ob_size */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002970 "object", /* tp_name */
2971 sizeof(PyObject), /* tp_basicsize */
2972 0, /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00002973 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002974 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002975 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002976 0, /* tp_setattr */
2977 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002978 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002979 0, /* tp_as_number */
2980 0, /* tp_as_sequence */
2981 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002982 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002983 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002984 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002985 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002986 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002987 0, /* tp_as_buffer */
2988 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002989 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002990 0, /* tp_traverse */
2991 0, /* tp_clear */
2992 0, /* tp_richcompare */
2993 0, /* tp_weaklistoffset */
2994 0, /* tp_iter */
2995 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002996 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002997 0, /* tp_members */
2998 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002999 0, /* tp_base */
3000 0, /* tp_dict */
3001 0, /* tp_descr_get */
3002 0, /* tp_descr_set */
3003 0, /* tp_dictoffset */
3004 object_init, /* tp_init */
3005 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00003006 object_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003007 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003008};
3009
3010
3011/* Initialize the __dict__ in a type object */
3012
3013static int
3014add_methods(PyTypeObject *type, PyMethodDef *meth)
3015{
Guido van Rossum687ae002001-10-15 22:03:32 +00003016 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003017
3018 for (; meth->ml_name != NULL; meth++) {
3019 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003020 if (PyDict_GetItemString(dict, meth->ml_name) &&
3021 !(meth->ml_flags & METH_COEXIST))
3022 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00003023 if (meth->ml_flags & METH_CLASS) {
3024 if (meth->ml_flags & METH_STATIC) {
3025 PyErr_SetString(PyExc_ValueError,
3026 "method cannot be both class and static");
3027 return -1;
3028 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00003029 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00003030 }
3031 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00003032 PyObject *cfunc = PyCFunction_New(meth, NULL);
3033 if (cfunc == NULL)
3034 return -1;
3035 descr = PyStaticMethod_New(cfunc);
3036 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003037 }
3038 else {
3039 descr = PyDescr_NewMethod(type, meth);
3040 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003041 if (descr == NULL)
3042 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003043 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003044 return -1;
3045 Py_DECREF(descr);
3046 }
3047 return 0;
3048}
3049
3050static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003051add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003052{
Guido van Rossum687ae002001-10-15 22:03:32 +00003053 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003054
3055 for (; memb->name != NULL; memb++) {
3056 PyObject *descr;
3057 if (PyDict_GetItemString(dict, memb->name))
3058 continue;
3059 descr = PyDescr_NewMember(type, memb);
3060 if (descr == NULL)
3061 return -1;
3062 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3063 return -1;
3064 Py_DECREF(descr);
3065 }
3066 return 0;
3067}
3068
3069static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003070add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003071{
Guido van Rossum687ae002001-10-15 22:03:32 +00003072 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003073
3074 for (; gsp->name != NULL; gsp++) {
3075 PyObject *descr;
3076 if (PyDict_GetItemString(dict, gsp->name))
3077 continue;
3078 descr = PyDescr_NewGetSet(type, gsp);
3079
3080 if (descr == NULL)
3081 return -1;
3082 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3083 return -1;
3084 Py_DECREF(descr);
3085 }
3086 return 0;
3087}
3088
Guido van Rossum13d52f02001-08-10 21:24:08 +00003089static void
3090inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003091{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003092 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003093
Guido van Rossum13d52f02001-08-10 21:24:08 +00003094 /* Special flag magic */
3095 if (!type->tp_as_buffer && base->tp_as_buffer) {
3096 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
3097 type->tp_flags |=
3098 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
3099 }
3100 if (!type->tp_as_sequence && base->tp_as_sequence) {
3101 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
3102 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
3103 }
3104 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
3105 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
3106 if ((!type->tp_as_number && base->tp_as_number) ||
3107 (!type->tp_as_sequence && base->tp_as_sequence)) {
3108 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
3109 if (!type->tp_as_number && !type->tp_as_sequence) {
3110 type->tp_flags |= base->tp_flags &
3111 Py_TPFLAGS_HAVE_INPLACEOPS;
3112 }
3113 }
3114 /* Wow */
3115 }
3116 if (!type->tp_as_number && base->tp_as_number) {
3117 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
3118 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
3119 }
3120
3121 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003122 oldsize = base->tp_basicsize;
3123 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3124 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3125 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003126 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
3127 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003128 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003129 if (type->tp_traverse == NULL)
3130 type->tp_traverse = base->tp_traverse;
3131 if (type->tp_clear == NULL)
3132 type->tp_clear = base->tp_clear;
3133 }
3134 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00003135 /* The condition below could use some explanation.
3136 It appears that tp_new is not inherited for static types
3137 whose base class is 'object'; this seems to be a precaution
3138 so that old extension types don't suddenly become
3139 callable (object.__new__ wouldn't insure the invariants
3140 that the extension type's own factory function ensures).
3141 Heap types, of course, are under our control, so they do
3142 inherit tp_new; static extension types that specify some
3143 other built-in type as the default are considered
3144 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003145 if (base != &PyBaseObject_Type ||
3146 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3147 if (type->tp_new == NULL)
3148 type->tp_new = base->tp_new;
3149 }
3150 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003151 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003152
3153 /* Copy other non-function slots */
3154
3155#undef COPYVAL
3156#define COPYVAL(SLOT) \
3157 if (type->SLOT == 0) type->SLOT = base->SLOT
3158
3159 COPYVAL(tp_itemsize);
3160 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
3161 COPYVAL(tp_weaklistoffset);
3162 }
3163 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3164 COPYVAL(tp_dictoffset);
3165 }
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003166
3167 /* Setup fast subclass flags */
3168 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3169 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3170 else if (PyType_IsSubtype(base, &PyType_Type))
3171 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3172 else if (PyType_IsSubtype(base, &PyInt_Type))
3173 type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS;
3174 else if (PyType_IsSubtype(base, &PyLong_Type))
3175 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3176 else if (PyType_IsSubtype(base, &PyString_Type))
3177 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
3178 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3179 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3180 else if (PyType_IsSubtype(base, &PyTuple_Type))
3181 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3182 else if (PyType_IsSubtype(base, &PyList_Type))
3183 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3184 else if (PyType_IsSubtype(base, &PyDict_Type))
3185 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003186}
3187
3188static void
3189inherit_slots(PyTypeObject *type, PyTypeObject *base)
3190{
3191 PyTypeObject *basebase;
3192
3193#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003194#undef COPYSLOT
3195#undef COPYNUM
3196#undef COPYSEQ
3197#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003198#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003199
3200#define SLOTDEFINED(SLOT) \
3201 (base->SLOT != 0 && \
3202 (basebase == NULL || base->SLOT != basebase->SLOT))
3203
Tim Peters6d6c1a32001-08-02 04:15:00 +00003204#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003205 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003206
3207#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3208#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3209#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003210#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003211
Guido van Rossum13d52f02001-08-10 21:24:08 +00003212 /* This won't inherit indirect slots (from tp_as_number etc.)
3213 if type doesn't provide the space. */
3214
3215 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3216 basebase = base->tp_base;
3217 if (basebase->tp_as_number == NULL)
3218 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003219 COPYNUM(nb_add);
3220 COPYNUM(nb_subtract);
3221 COPYNUM(nb_multiply);
3222 COPYNUM(nb_divide);
3223 COPYNUM(nb_remainder);
3224 COPYNUM(nb_divmod);
3225 COPYNUM(nb_power);
3226 COPYNUM(nb_negative);
3227 COPYNUM(nb_positive);
3228 COPYNUM(nb_absolute);
3229 COPYNUM(nb_nonzero);
3230 COPYNUM(nb_invert);
3231 COPYNUM(nb_lshift);
3232 COPYNUM(nb_rshift);
3233 COPYNUM(nb_and);
3234 COPYNUM(nb_xor);
3235 COPYNUM(nb_or);
3236 COPYNUM(nb_coerce);
3237 COPYNUM(nb_int);
3238 COPYNUM(nb_long);
3239 COPYNUM(nb_float);
3240 COPYNUM(nb_oct);
3241 COPYNUM(nb_hex);
3242 COPYNUM(nb_inplace_add);
3243 COPYNUM(nb_inplace_subtract);
3244 COPYNUM(nb_inplace_multiply);
3245 COPYNUM(nb_inplace_divide);
3246 COPYNUM(nb_inplace_remainder);
3247 COPYNUM(nb_inplace_power);
3248 COPYNUM(nb_inplace_lshift);
3249 COPYNUM(nb_inplace_rshift);
3250 COPYNUM(nb_inplace_and);
3251 COPYNUM(nb_inplace_xor);
3252 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003253 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3254 COPYNUM(nb_true_divide);
3255 COPYNUM(nb_floor_divide);
3256 COPYNUM(nb_inplace_true_divide);
3257 COPYNUM(nb_inplace_floor_divide);
3258 }
Guido van Rossum38fff8c2006-03-07 18:50:55 +00003259 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3260 COPYNUM(nb_index);
3261 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003262 }
3263
Guido van Rossum13d52f02001-08-10 21:24:08 +00003264 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3265 basebase = base->tp_base;
3266 if (basebase->tp_as_sequence == NULL)
3267 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003268 COPYSEQ(sq_length);
3269 COPYSEQ(sq_concat);
3270 COPYSEQ(sq_repeat);
3271 COPYSEQ(sq_item);
3272 COPYSEQ(sq_slice);
3273 COPYSEQ(sq_ass_item);
3274 COPYSEQ(sq_ass_slice);
3275 COPYSEQ(sq_contains);
3276 COPYSEQ(sq_inplace_concat);
3277 COPYSEQ(sq_inplace_repeat);
3278 }
3279
Guido van Rossum13d52f02001-08-10 21:24:08 +00003280 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3281 basebase = base->tp_base;
3282 if (basebase->tp_as_mapping == NULL)
3283 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003284 COPYMAP(mp_length);
3285 COPYMAP(mp_subscript);
3286 COPYMAP(mp_ass_subscript);
3287 }
3288
Tim Petersfc57ccb2001-10-12 02:38:24 +00003289 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3290 basebase = base->tp_base;
3291 if (basebase->tp_as_buffer == NULL)
3292 basebase = NULL;
3293 COPYBUF(bf_getreadbuffer);
3294 COPYBUF(bf_getwritebuffer);
3295 COPYBUF(bf_getsegcount);
3296 COPYBUF(bf_getcharbuffer);
3297 }
3298
Guido van Rossum13d52f02001-08-10 21:24:08 +00003299 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003300
Tim Peters6d6c1a32001-08-02 04:15:00 +00003301 COPYSLOT(tp_dealloc);
3302 COPYSLOT(tp_print);
3303 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3304 type->tp_getattr = base->tp_getattr;
3305 type->tp_getattro = base->tp_getattro;
3306 }
3307 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3308 type->tp_setattr = base->tp_setattr;
3309 type->tp_setattro = base->tp_setattro;
3310 }
3311 /* tp_compare see tp_richcompare */
3312 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003313 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003314 COPYSLOT(tp_call);
3315 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003316 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003317 if (type->tp_compare == NULL &&
3318 type->tp_richcompare == NULL &&
3319 type->tp_hash == NULL)
3320 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003321 type->tp_compare = base->tp_compare;
3322 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003323 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003324 }
3325 }
3326 else {
3327 COPYSLOT(tp_compare);
3328 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003329 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3330 COPYSLOT(tp_iter);
3331 COPYSLOT(tp_iternext);
3332 }
3333 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3334 COPYSLOT(tp_descr_get);
3335 COPYSLOT(tp_descr_set);
3336 COPYSLOT(tp_dictoffset);
3337 COPYSLOT(tp_init);
3338 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003339 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003340 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3341 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3342 /* They agree about gc. */
3343 COPYSLOT(tp_free);
3344 }
3345 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3346 type->tp_free == NULL &&
3347 base->tp_free == _PyObject_Del) {
3348 /* A bit of magic to plug in the correct default
3349 * tp_free function when a derived class adds gc,
3350 * didn't define tp_free, and the base uses the
3351 * default non-gc tp_free.
3352 */
3353 type->tp_free = PyObject_GC_Del;
3354 }
3355 /* else they didn't agree about gc, and there isn't something
3356 * obvious to be done -- the type is on its own.
3357 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003358 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003359}
3360
Jeremy Hylton938ace62002-07-17 16:30:39 +00003361static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003362
Tim Peters6d6c1a32001-08-02 04:15:00 +00003363int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003364PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003365{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003366 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003367 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003368 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003369
Guido van Rossumcab05802002-06-10 15:29:03 +00003370 if (type->tp_flags & Py_TPFLAGS_READY) {
3371 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003372 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003373 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003374 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003375
3376 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003377
Tim Peters36eb4df2003-03-23 03:33:13 +00003378#ifdef Py_TRACE_REFS
3379 /* PyType_Ready is the closest thing we have to a choke point
3380 * for type objects, so is the best place I can think of to try
3381 * to get type objects into the doubly-linked list of all objects.
3382 * Still, not all type objects go thru PyType_Ready.
3383 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003384 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003385#endif
3386
Tim Peters6d6c1a32001-08-02 04:15:00 +00003387 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3388 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003389 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003390 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003391 Py_INCREF(base);
3392 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003393
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003394 /* Now the only way base can still be NULL is if type is
3395 * &PyBaseObject_Type.
3396 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003397
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003398 /* Initialize the base class */
3399 if (base && base->tp_dict == NULL) {
3400 if (PyType_Ready(base) < 0)
3401 goto error;
3402 }
3403
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003404 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003405 compilable separately on Windows can call PyType_Ready() instead of
3406 initializing the ob_type field of their type objects. */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003407 /* The test for base != NULL is really unnecessary, since base is only
3408 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3409 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3410 know that. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003411 if (type->ob_type == NULL && base != NULL)
Guido van Rossum0986d822002-04-08 01:38:42 +00003412 type->ob_type = base->ob_type;
3413
Tim Peters6d6c1a32001-08-02 04:15:00 +00003414 /* Initialize tp_bases */
3415 bases = type->tp_bases;
3416 if (bases == NULL) {
3417 if (base == NULL)
3418 bases = PyTuple_New(0);
3419 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003420 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003421 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003422 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003423 type->tp_bases = bases;
3424 }
3425
Guido van Rossum687ae002001-10-15 22:03:32 +00003426 /* Initialize tp_dict */
3427 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003428 if (dict == NULL) {
3429 dict = PyDict_New();
3430 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003431 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003432 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003433 }
3434
Guido van Rossum687ae002001-10-15 22:03:32 +00003435 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003436 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003437 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003438 if (type->tp_methods != NULL) {
3439 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003440 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003441 }
3442 if (type->tp_members != NULL) {
3443 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003444 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003445 }
3446 if (type->tp_getset != NULL) {
3447 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003448 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003449 }
3450
Tim Peters6d6c1a32001-08-02 04:15:00 +00003451 /* Calculate method resolution order */
3452 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003453 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003454 }
3455
Guido van Rossum13d52f02001-08-10 21:24:08 +00003456 /* Inherit special flags from dominant base */
3457 if (type->tp_base != NULL)
3458 inherit_special(type, type->tp_base);
3459
Tim Peters6d6c1a32001-08-02 04:15:00 +00003460 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003461 bases = type->tp_mro;
3462 assert(bases != NULL);
3463 assert(PyTuple_Check(bases));
3464 n = PyTuple_GET_SIZE(bases);
3465 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003466 PyObject *b = PyTuple_GET_ITEM(bases, i);
3467 if (PyType_Check(b))
3468 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003469 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003470
Tim Peters3cfe7542003-05-21 21:29:48 +00003471 /* Sanity check for tp_free. */
3472 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3473 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003474 /* This base class needs to call tp_free, but doesn't have
3475 * one, or its tp_free is for non-gc'ed objects.
3476 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003477 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3478 "gc and is a base type but has inappropriate "
3479 "tp_free slot",
3480 type->tp_name);
3481 goto error;
3482 }
3483
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003484 /* if the type dictionary doesn't contain a __doc__, set it from
3485 the tp_doc slot.
3486 */
3487 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3488 if (type->tp_doc != NULL) {
3489 PyObject *doc = PyString_FromString(type->tp_doc);
Neal Norwitze1fdb322006-07-21 05:32:28 +00003490 if (doc == NULL)
3491 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003492 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3493 Py_DECREF(doc);
3494 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003495 PyDict_SetItemString(type->tp_dict,
3496 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003497 }
3498 }
3499
Guido van Rossum13d52f02001-08-10 21:24:08 +00003500 /* Some more special stuff */
3501 base = type->tp_base;
3502 if (base != NULL) {
3503 if (type->tp_as_number == NULL)
3504 type->tp_as_number = base->tp_as_number;
3505 if (type->tp_as_sequence == NULL)
3506 type->tp_as_sequence = base->tp_as_sequence;
3507 if (type->tp_as_mapping == NULL)
3508 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003509 if (type->tp_as_buffer == NULL)
3510 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003511 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003512
Guido van Rossum1c450732001-10-08 15:18:27 +00003513 /* Link into each base class's list of subclasses */
3514 bases = type->tp_bases;
3515 n = PyTuple_GET_SIZE(bases);
3516 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003517 PyObject *b = PyTuple_GET_ITEM(bases, i);
3518 if (PyType_Check(b) &&
3519 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003520 goto error;
3521 }
3522
Guido van Rossum13d52f02001-08-10 21:24:08 +00003523 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003524 assert(type->tp_dict != NULL);
3525 type->tp_flags =
3526 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003527 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003528
3529 error:
3530 type->tp_flags &= ~Py_TPFLAGS_READYING;
3531 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003532}
3533
Guido van Rossum1c450732001-10-08 15:18:27 +00003534static int
3535add_subclass(PyTypeObject *base, PyTypeObject *type)
3536{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003537 Py_ssize_t i;
3538 int result;
Anthony Baxtera6286212006-04-11 07:42:36 +00003539 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003540
3541 list = base->tp_subclasses;
3542 if (list == NULL) {
3543 base->tp_subclasses = list = PyList_New(0);
3544 if (list == NULL)
3545 return -1;
3546 }
3547 assert(PyList_Check(list));
Anthony Baxtera6286212006-04-11 07:42:36 +00003548 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003549 i = PyList_GET_SIZE(list);
3550 while (--i >= 0) {
3551 ref = PyList_GET_ITEM(list, i);
3552 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003553 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Anthony Baxtera6286212006-04-11 07:42:36 +00003554 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003555 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003556 result = PyList_Append(list, newobj);
3557 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003558 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003559}
3560
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003561static void
3562remove_subclass(PyTypeObject *base, PyTypeObject *type)
3563{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003564 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003565 PyObject *list, *ref;
3566
3567 list = base->tp_subclasses;
3568 if (list == NULL) {
3569 return;
3570 }
3571 assert(PyList_Check(list));
3572 i = PyList_GET_SIZE(list);
3573 while (--i >= 0) {
3574 ref = PyList_GET_ITEM(list, i);
3575 assert(PyWeakref_CheckRef(ref));
3576 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3577 /* this can't fail, right? */
3578 PySequence_DelItem(list, i);
3579 return;
3580 }
3581 }
3582}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003583
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003584static int
3585check_num_args(PyObject *ob, int n)
3586{
3587 if (!PyTuple_CheckExact(ob)) {
3588 PyErr_SetString(PyExc_SystemError,
3589 "PyArg_UnpackTuple() argument list is not a tuple");
3590 return 0;
3591 }
3592 if (n == PyTuple_GET_SIZE(ob))
3593 return 1;
3594 PyErr_Format(
3595 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003596 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003597 return 0;
3598}
3599
Tim Peters6d6c1a32001-08-02 04:15:00 +00003600/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3601
3602/* There's a wrapper *function* for each distinct function typedef used
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003603 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00003604 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3605 Most tables have only one entry; the tables for binary operators have two
3606 entries, one regular and one with reversed arguments. */
3607
3608static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003609wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003610{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003611 lenfunc func = (lenfunc)wrapped;
3612 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003613
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003614 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003615 return NULL;
3616 res = (*func)(self);
3617 if (res == -1 && PyErr_Occurred())
3618 return NULL;
3619 return PyInt_FromLong((long)res);
3620}
3621
Tim Peters6d6c1a32001-08-02 04:15:00 +00003622static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003623wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3624{
3625 inquiry func = (inquiry)wrapped;
3626 int res;
3627
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003628 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003629 return NULL;
3630 res = (*func)(self);
3631 if (res == -1 && PyErr_Occurred())
3632 return NULL;
3633 return PyBool_FromLong((long)res);
3634}
3635
3636static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003637wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3638{
3639 binaryfunc func = (binaryfunc)wrapped;
3640 PyObject *other;
3641
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003642 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003643 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003644 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003645 return (*func)(self, other);
3646}
3647
3648static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003649wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3650{
3651 binaryfunc func = (binaryfunc)wrapped;
3652 PyObject *other;
3653
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003654 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003655 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003656 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003657 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003658 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003659 Py_INCREF(Py_NotImplemented);
3660 return Py_NotImplemented;
3661 }
3662 return (*func)(self, other);
3663}
3664
3665static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003666wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3667{
3668 binaryfunc func = (binaryfunc)wrapped;
3669 PyObject *other;
3670
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003671 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003672 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003673 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003674 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003675 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003676 Py_INCREF(Py_NotImplemented);
3677 return Py_NotImplemented;
3678 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003679 return (*func)(other, self);
3680}
3681
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003682static PyObject *
3683wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3684{
3685 coercion func = (coercion)wrapped;
3686 PyObject *other, *res;
3687 int ok;
3688
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003689 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003690 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003691 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003692 ok = func(&self, &other);
3693 if (ok < 0)
3694 return NULL;
3695 if (ok > 0) {
3696 Py_INCREF(Py_NotImplemented);
3697 return Py_NotImplemented;
3698 }
3699 res = PyTuple_New(2);
3700 if (res == NULL) {
3701 Py_DECREF(self);
3702 Py_DECREF(other);
3703 return NULL;
3704 }
3705 PyTuple_SET_ITEM(res, 0, self);
3706 PyTuple_SET_ITEM(res, 1, other);
3707 return res;
3708}
3709
Tim Peters6d6c1a32001-08-02 04:15:00 +00003710static PyObject *
3711wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3712{
3713 ternaryfunc func = (ternaryfunc)wrapped;
3714 PyObject *other;
3715 PyObject *third = Py_None;
3716
3717 /* Note: This wrapper only works for __pow__() */
3718
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003719 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003720 return NULL;
3721 return (*func)(self, other, third);
3722}
3723
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003724static PyObject *
3725wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3726{
3727 ternaryfunc func = (ternaryfunc)wrapped;
3728 PyObject *other;
3729 PyObject *third = Py_None;
3730
3731 /* Note: This wrapper only works for __pow__() */
3732
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003733 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003734 return NULL;
3735 return (*func)(other, self, third);
3736}
3737
Tim Peters6d6c1a32001-08-02 04:15:00 +00003738static PyObject *
3739wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3740{
3741 unaryfunc func = (unaryfunc)wrapped;
3742
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003743 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003744 return NULL;
3745 return (*func)(self);
3746}
3747
Tim Peters6d6c1a32001-08-02 04:15:00 +00003748static PyObject *
Armin Rigo314861c2006-03-30 14:04:02 +00003749wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003750{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003751 ssizeargfunc func = (ssizeargfunc)wrapped;
Armin Rigo314861c2006-03-30 14:04:02 +00003752 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003753 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003754
Armin Rigo314861c2006-03-30 14:04:02 +00003755 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
3756 return NULL;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00003757 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Armin Rigo314861c2006-03-30 14:04:02 +00003758 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003759 return NULL;
3760 return (*func)(self, i);
3761}
3762
Martin v. Löwis18e16552006-02-15 17:27:45 +00003763static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00003764getindex(PyObject *self, PyObject *arg)
3765{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003766 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003767
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00003768 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003769 if (i == -1 && PyErr_Occurred())
3770 return -1;
3771 if (i < 0) {
3772 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3773 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003774 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003775 if (n < 0)
3776 return -1;
3777 i += n;
3778 }
3779 }
3780 return i;
3781}
3782
3783static PyObject *
3784wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3785{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003786 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003787 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003788 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003789
Guido van Rossumf4593e02001-10-03 12:09:30 +00003790 if (PyTuple_GET_SIZE(args) == 1) {
3791 arg = PyTuple_GET_ITEM(args, 0);
3792 i = getindex(self, arg);
3793 if (i == -1 && PyErr_Occurred())
3794 return NULL;
3795 return (*func)(self, i);
3796 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003797 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003798 assert(PyErr_Occurred());
3799 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003800}
3801
Tim Peters6d6c1a32001-08-02 04:15:00 +00003802static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003803wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003804{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003805 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
3806 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003807
Martin v. Löwis18e16552006-02-15 17:27:45 +00003808 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003809 return NULL;
3810 return (*func)(self, i, j);
3811}
3812
Tim Peters6d6c1a32001-08-02 04:15:00 +00003813static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003814wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003815{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003816 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3817 Py_ssize_t i;
3818 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003819 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003820
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003821 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003822 return NULL;
3823 i = getindex(self, arg);
3824 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003825 return NULL;
3826 res = (*func)(self, i, value);
3827 if (res == -1 && PyErr_Occurred())
3828 return NULL;
3829 Py_INCREF(Py_None);
3830 return Py_None;
3831}
3832
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003833static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003834wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003835{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003836 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3837 Py_ssize_t i;
3838 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003839 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003840
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003841 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003842 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003843 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003844 i = getindex(self, arg);
3845 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003846 return NULL;
3847 res = (*func)(self, i, NULL);
3848 if (res == -1 && PyErr_Occurred())
3849 return NULL;
3850 Py_INCREF(Py_None);
3851 return Py_None;
3852}
3853
Tim Peters6d6c1a32001-08-02 04:15:00 +00003854static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003855wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003856{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003857 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3858 Py_ssize_t i, j;
3859 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003860 PyObject *value;
3861
Martin v. Löwis18e16552006-02-15 17:27:45 +00003862 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003863 return NULL;
3864 res = (*func)(self, i, j, value);
3865 if (res == -1 && PyErr_Occurred())
3866 return NULL;
3867 Py_INCREF(Py_None);
3868 return Py_None;
3869}
3870
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003871static PyObject *
3872wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3873{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003874 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3875 Py_ssize_t i, j;
3876 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003877
Martin v. Löwis18e16552006-02-15 17:27:45 +00003878 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003879 return NULL;
3880 res = (*func)(self, i, j, NULL);
3881 if (res == -1 && PyErr_Occurred())
3882 return NULL;
3883 Py_INCREF(Py_None);
3884 return Py_None;
3885}
3886
Tim Peters6d6c1a32001-08-02 04:15:00 +00003887/* XXX objobjproc is a misnomer; should be objargpred */
3888static PyObject *
3889wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3890{
3891 objobjproc func = (objobjproc)wrapped;
3892 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003893 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003894
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003895 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003896 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003897 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003898 res = (*func)(self, value);
3899 if (res == -1 && PyErr_Occurred())
3900 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003901 else
3902 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003903}
3904
Tim Peters6d6c1a32001-08-02 04:15:00 +00003905static PyObject *
3906wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3907{
3908 objobjargproc func = (objobjargproc)wrapped;
3909 int res;
3910 PyObject *key, *value;
3911
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003912 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003913 return NULL;
3914 res = (*func)(self, key, value);
3915 if (res == -1 && PyErr_Occurred())
3916 return NULL;
3917 Py_INCREF(Py_None);
3918 return Py_None;
3919}
3920
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003921static PyObject *
3922wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3923{
3924 objobjargproc func = (objobjargproc)wrapped;
3925 int res;
3926 PyObject *key;
3927
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003928 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003929 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003930 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003931 res = (*func)(self, key, NULL);
3932 if (res == -1 && PyErr_Occurred())
3933 return NULL;
3934 Py_INCREF(Py_None);
3935 return Py_None;
3936}
3937
Tim Peters6d6c1a32001-08-02 04:15:00 +00003938static PyObject *
3939wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3940{
3941 cmpfunc func = (cmpfunc)wrapped;
3942 int res;
3943 PyObject *other;
3944
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003945 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003946 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003947 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003948 if (other->ob_type->tp_compare != func &&
3949 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003950 PyErr_Format(
3951 PyExc_TypeError,
3952 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3953 self->ob_type->tp_name,
3954 self->ob_type->tp_name,
3955 other->ob_type->tp_name);
3956 return NULL;
3957 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003958 res = (*func)(self, other);
3959 if (PyErr_Occurred())
3960 return NULL;
3961 return PyInt_FromLong((long)res);
3962}
3963
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003964/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003965 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003966static int
3967hackcheck(PyObject *self, setattrofunc func, char *what)
3968{
3969 PyTypeObject *type = self->ob_type;
3970 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3971 type = type->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003972 /* If type is NULL now, this is a really weird type.
3973 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003974 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003975 PyErr_Format(PyExc_TypeError,
3976 "can't apply this %s to %s object",
3977 what,
3978 type->tp_name);
3979 return 0;
3980 }
3981 return 1;
3982}
3983
Tim Peters6d6c1a32001-08-02 04:15:00 +00003984static PyObject *
3985wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3986{
3987 setattrofunc func = (setattrofunc)wrapped;
3988 int res;
3989 PyObject *name, *value;
3990
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003991 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003992 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003993 if (!hackcheck(self, func, "__setattr__"))
3994 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003995 res = (*func)(self, name, value);
3996 if (res < 0)
3997 return NULL;
3998 Py_INCREF(Py_None);
3999 return Py_None;
4000}
4001
4002static PyObject *
4003wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4004{
4005 setattrofunc func = (setattrofunc)wrapped;
4006 int res;
4007 PyObject *name;
4008
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004009 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004010 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004011 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004012 if (!hackcheck(self, func, "__delattr__"))
4013 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004014 res = (*func)(self, name, NULL);
4015 if (res < 0)
4016 return NULL;
4017 Py_INCREF(Py_None);
4018 return Py_None;
4019}
4020
Tim Peters6d6c1a32001-08-02 04:15:00 +00004021static PyObject *
4022wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4023{
4024 hashfunc func = (hashfunc)wrapped;
4025 long res;
4026
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004027 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004028 return NULL;
4029 res = (*func)(self);
4030 if (res == -1 && PyErr_Occurred())
4031 return NULL;
4032 return PyInt_FromLong(res);
4033}
4034
Tim Peters6d6c1a32001-08-02 04:15:00 +00004035static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004036wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004037{
4038 ternaryfunc func = (ternaryfunc)wrapped;
4039
Guido van Rossumc8e56452001-10-22 00:43:43 +00004040 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004041}
4042
Tim Peters6d6c1a32001-08-02 04:15:00 +00004043static PyObject *
4044wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4045{
4046 richcmpfunc func = (richcmpfunc)wrapped;
4047 PyObject *other;
4048
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004049 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004050 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004051 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004052 return (*func)(self, other, op);
4053}
4054
4055#undef RICHCMP_WRAPPER
4056#define RICHCMP_WRAPPER(NAME, OP) \
4057static PyObject * \
4058richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4059{ \
4060 return wrap_richcmpfunc(self, args, wrapped, OP); \
4061}
4062
Jack Jansen8e938b42001-08-08 15:29:49 +00004063RICHCMP_WRAPPER(lt, Py_LT)
4064RICHCMP_WRAPPER(le, Py_LE)
4065RICHCMP_WRAPPER(eq, Py_EQ)
4066RICHCMP_WRAPPER(ne, Py_NE)
4067RICHCMP_WRAPPER(gt, Py_GT)
4068RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004069
Tim Peters6d6c1a32001-08-02 04:15:00 +00004070static PyObject *
4071wrap_next(PyObject *self, PyObject *args, void *wrapped)
4072{
4073 unaryfunc func = (unaryfunc)wrapped;
4074 PyObject *res;
4075
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004076 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004077 return NULL;
4078 res = (*func)(self);
4079 if (res == NULL && !PyErr_Occurred())
4080 PyErr_SetNone(PyExc_StopIteration);
4081 return res;
4082}
4083
Tim Peters6d6c1a32001-08-02 04:15:00 +00004084static PyObject *
4085wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4086{
4087 descrgetfunc func = (descrgetfunc)wrapped;
4088 PyObject *obj;
4089 PyObject *type = NULL;
4090
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004091 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004092 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004093 if (obj == Py_None)
4094 obj = NULL;
4095 if (type == Py_None)
4096 type = NULL;
4097 if (type == NULL &&obj == NULL) {
4098 PyErr_SetString(PyExc_TypeError,
4099 "__get__(None, None) is invalid");
4100 return NULL;
4101 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004102 return (*func)(self, obj, type);
4103}
4104
Tim Peters6d6c1a32001-08-02 04:15:00 +00004105static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004106wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004107{
4108 descrsetfunc func = (descrsetfunc)wrapped;
4109 PyObject *obj, *value;
4110 int ret;
4111
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004112 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004113 return NULL;
4114 ret = (*func)(self, obj, value);
4115 if (ret < 0)
4116 return NULL;
4117 Py_INCREF(Py_None);
4118 return Py_None;
4119}
Guido van Rossum22b13872002-08-06 21:41:44 +00004120
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004121static PyObject *
4122wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4123{
4124 descrsetfunc func = (descrsetfunc)wrapped;
4125 PyObject *obj;
4126 int ret;
4127
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004128 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004129 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004130 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004131 ret = (*func)(self, obj, NULL);
4132 if (ret < 0)
4133 return NULL;
4134 Py_INCREF(Py_None);
4135 return Py_None;
4136}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004137
Tim Peters6d6c1a32001-08-02 04:15:00 +00004138static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004139wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004140{
4141 initproc func = (initproc)wrapped;
4142
Guido van Rossumc8e56452001-10-22 00:43:43 +00004143 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004144 return NULL;
4145 Py_INCREF(Py_None);
4146 return Py_None;
4147}
4148
Tim Peters6d6c1a32001-08-02 04:15:00 +00004149static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004150tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004151{
Barry Warsaw60f01882001-08-22 19:24:42 +00004152 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004153 PyObject *arg0, *res;
4154
4155 if (self == NULL || !PyType_Check(self))
4156 Py_FatalError("__new__() called with non-type 'self'");
4157 type = (PyTypeObject *)self;
4158 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004159 PyErr_Format(PyExc_TypeError,
4160 "%s.__new__(): not enough arguments",
4161 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004162 return NULL;
4163 }
4164 arg0 = PyTuple_GET_ITEM(args, 0);
4165 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004166 PyErr_Format(PyExc_TypeError,
4167 "%s.__new__(X): X is not a type object (%s)",
4168 type->tp_name,
4169 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004170 return NULL;
4171 }
4172 subtype = (PyTypeObject *)arg0;
4173 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004174 PyErr_Format(PyExc_TypeError,
4175 "%s.__new__(%s): %s is not a subtype of %s",
4176 type->tp_name,
4177 subtype->tp_name,
4178 subtype->tp_name,
4179 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004180 return NULL;
4181 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004182
4183 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004184 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004185 most derived base that's not a heap type is this type. */
4186 staticbase = subtype;
4187 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4188 staticbase = staticbase->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004189 /* If staticbase is NULL now, it is a really weird type.
4190 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004191 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004192 PyErr_Format(PyExc_TypeError,
4193 "%s.__new__(%s) is not safe, use %s.__new__()",
4194 type->tp_name,
4195 subtype->tp_name,
4196 staticbase == NULL ? "?" : staticbase->tp_name);
4197 return NULL;
4198 }
4199
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004200 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4201 if (args == NULL)
4202 return NULL;
4203 res = type->tp_new(subtype, args, kwds);
4204 Py_DECREF(args);
4205 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004206}
4207
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004208static struct PyMethodDef tp_new_methoddef[] = {
4209 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004210 PyDoc_STR("T.__new__(S, ...) -> "
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004211 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004212 {0}
4213};
4214
4215static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004216add_tp_new_wrapper(PyTypeObject *type)
4217{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004218 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004219
Guido van Rossum687ae002001-10-15 22:03:32 +00004220 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004221 return 0;
4222 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004223 if (func == NULL)
4224 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004225 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004226 Py_DECREF(func);
4227 return -1;
4228 }
4229 Py_DECREF(func);
4230 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004231}
4232
Guido van Rossumf040ede2001-08-07 16:40:56 +00004233/* Slot wrappers that call the corresponding __foo__ slot. See comments
4234 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004235
Guido van Rossumdc91b992001-08-08 22:26:22 +00004236#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004237static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004238FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004239{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004240 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004241 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004242}
4243
Guido van Rossumdc91b992001-08-08 22:26:22 +00004244#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004245static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004246FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004247{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004248 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004249 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004250}
4251
Guido van Rossumcd118802003-01-06 22:57:47 +00004252/* Boolean helper for SLOT1BINFULL().
4253 right.__class__ is a nontrivial subclass of left.__class__. */
4254static int
4255method_is_overloaded(PyObject *left, PyObject *right, char *name)
4256{
4257 PyObject *a, *b;
4258 int ok;
4259
4260 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
4261 if (b == NULL) {
4262 PyErr_Clear();
4263 /* If right doesn't have it, it's not overloaded */
4264 return 0;
4265 }
4266
4267 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
4268 if (a == NULL) {
4269 PyErr_Clear();
4270 Py_DECREF(b);
4271 /* If right has it but left doesn't, it's overloaded */
4272 return 1;
4273 }
4274
4275 ok = PyObject_RichCompareBool(a, b, Py_NE);
4276 Py_DECREF(a);
4277 Py_DECREF(b);
4278 if (ok < 0) {
4279 PyErr_Clear();
4280 return 0;
4281 }
4282
4283 return ok;
4284}
4285
Guido van Rossumdc91b992001-08-08 22:26:22 +00004286
4287#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004288static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004289FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004290{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004291 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004292 int do_other = self->ob_type != other->ob_type && \
4293 other->ob_type->tp_as_number != NULL && \
4294 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004295 if (self->ob_type->tp_as_number != NULL && \
4296 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
4297 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004298 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004299 PyType_IsSubtype(other->ob_type, self->ob_type) && \
4300 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004301 r = call_maybe( \
4302 other, ROPSTR, &rcache_str, "(O)", self); \
4303 if (r != Py_NotImplemented) \
4304 return r; \
4305 Py_DECREF(r); \
4306 do_other = 0; \
4307 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004308 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004309 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004310 if (r != Py_NotImplemented || \
4311 other->ob_type == self->ob_type) \
4312 return r; \
4313 Py_DECREF(r); \
4314 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004315 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004316 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004317 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004318 } \
4319 Py_INCREF(Py_NotImplemented); \
4320 return Py_NotImplemented; \
4321}
4322
4323#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4324 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4325
4326#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4327static PyObject * \
4328FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4329{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004330 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004331 return call_method(self, OPSTR, &cache_str, \
4332 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004333}
4334
Martin v. Löwis18e16552006-02-15 17:27:45 +00004335static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004336slot_sq_length(PyObject *self)
4337{
Guido van Rossum2730b132001-08-28 18:22:14 +00004338 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004339 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004340 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004341
4342 if (res == NULL)
4343 return -1;
Neal Norwitz1872b1c2006-08-12 18:44:06 +00004344 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004345 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004346 if (len < 0) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00004347 if (!PyErr_Occurred())
4348 PyErr_SetString(PyExc_ValueError,
4349 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004350 return -1;
4351 }
Guido van Rossum26111622001-10-01 16:42:49 +00004352 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004353}
4354
Guido van Rossumf4593e02001-10-03 12:09:30 +00004355/* Super-optimized version of slot_sq_item.
4356 Other slots could do the same... */
4357static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004358slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004359{
4360 static PyObject *getitem_str;
4361 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4362 descrgetfunc f;
4363
4364 if (getitem_str == NULL) {
4365 getitem_str = PyString_InternFromString("__getitem__");
4366 if (getitem_str == NULL)
4367 return NULL;
4368 }
4369 func = _PyType_Lookup(self->ob_type, getitem_str);
4370 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004371 if ((f = func->ob_type->tp_descr_get) == NULL)
4372 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004373 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004374 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004375 if (func == NULL) {
4376 return NULL;
4377 }
4378 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004379 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004380 if (ival != NULL) {
4381 args = PyTuple_New(1);
4382 if (args != NULL) {
4383 PyTuple_SET_ITEM(args, 0, ival);
4384 retval = PyObject_Call(func, args, NULL);
4385 Py_XDECREF(args);
4386 Py_XDECREF(func);
4387 return retval;
4388 }
4389 }
4390 }
4391 else {
4392 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4393 }
4394 Py_XDECREF(args);
4395 Py_XDECREF(ival);
4396 Py_XDECREF(func);
4397 return NULL;
4398}
4399
Martin v. Löwis18e16552006-02-15 17:27:45 +00004400SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004401
4402static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004403slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004404{
4405 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004406 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004407
4408 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004409 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004410 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004411 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004412 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004413 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004414 if (res == NULL)
4415 return -1;
4416 Py_DECREF(res);
4417 return 0;
4418}
4419
4420static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004421slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004422{
4423 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004424 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004425
4426 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004427 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004428 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004429 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004430 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004431 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004432 if (res == NULL)
4433 return -1;
4434 Py_DECREF(res);
4435 return 0;
4436}
4437
4438static int
4439slot_sq_contains(PyObject *self, PyObject *value)
4440{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004441 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004442 int result = -1;
4443
Guido van Rossum60718732001-08-28 17:47:51 +00004444 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004445
Guido van Rossum55f20992001-10-01 17:18:22 +00004446 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004447 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004448 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004449 if (args == NULL)
4450 res = NULL;
4451 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004452 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004453 Py_DECREF(args);
4454 }
4455 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004456 if (res != NULL) {
4457 result = PyObject_IsTrue(res);
4458 Py_DECREF(res);
4459 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004460 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004461 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004462 /* Possible results: -1 and 1 */
4463 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004464 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004465 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004466 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004467}
4468
Tim Peters6d6c1a32001-08-02 04:15:00 +00004469#define slot_mp_length slot_sq_length
4470
Guido van Rossumdc91b992001-08-08 22:26:22 +00004471SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004472
4473static int
4474slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4475{
4476 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004477 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004478
4479 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004480 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004481 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004482 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004483 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004484 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004485 if (res == NULL)
4486 return -1;
4487 Py_DECREF(res);
4488 return 0;
4489}
4490
Guido van Rossumdc91b992001-08-08 22:26:22 +00004491SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4492SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4493SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4494SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4495SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4496SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4497
Jeremy Hylton938ace62002-07-17 16:30:39 +00004498static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004499
4500SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4501 nb_power, "__pow__", "__rpow__")
4502
4503static PyObject *
4504slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4505{
Guido van Rossum2730b132001-08-28 18:22:14 +00004506 static PyObject *pow_str;
4507
Guido van Rossumdc91b992001-08-08 22:26:22 +00004508 if (modulus == Py_None)
4509 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004510 /* Three-arg power doesn't use __rpow__. But ternary_op
4511 can call this when the second argument's type uses
4512 slot_nb_power, so check before calling self.__pow__. */
4513 if (self->ob_type->tp_as_number != NULL &&
4514 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4515 return call_method(self, "__pow__", &pow_str,
4516 "(OO)", other, modulus);
4517 }
4518 Py_INCREF(Py_NotImplemented);
4519 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004520}
4521
4522SLOT0(slot_nb_negative, "__neg__")
4523SLOT0(slot_nb_positive, "__pos__")
4524SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004525
4526static int
4527slot_nb_nonzero(PyObject *self)
4528{
Tim Petersea7f75d2002-12-07 21:39:16 +00004529 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004530 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004531 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004532
Guido van Rossum55f20992001-10-01 17:18:22 +00004533 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004534 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004535 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004536 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004537 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004538 if (func == NULL)
4539 return PyErr_Occurred() ? -1 : 1;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004540 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004541 args = PyTuple_New(0);
4542 if (args != NULL) {
4543 PyObject *temp = PyObject_Call(func, args, NULL);
4544 Py_DECREF(args);
4545 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004546 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004547 result = PyObject_IsTrue(temp);
4548 else {
4549 PyErr_Format(PyExc_TypeError,
4550 "__nonzero__ should return "
4551 "bool or int, returned %s",
4552 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004553 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004554 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004555 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004556 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004557 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004558 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004559 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004560}
4561
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004562
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004563static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004564slot_nb_index(PyObject *self)
4565{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004566 static PyObject *index_str;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004567 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004568}
4569
4570
Guido van Rossumdc91b992001-08-08 22:26:22 +00004571SLOT0(slot_nb_invert, "__invert__")
4572SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4573SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4574SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4575SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4576SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004577
4578static int
4579slot_nb_coerce(PyObject **a, PyObject **b)
4580{
4581 static PyObject *coerce_str;
4582 PyObject *self = *a, *other = *b;
4583
4584 if (self->ob_type->tp_as_number != NULL &&
4585 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4586 PyObject *r;
4587 r = call_maybe(
4588 self, "__coerce__", &coerce_str, "(O)", other);
4589 if (r == NULL)
4590 return -1;
4591 if (r == Py_NotImplemented) {
4592 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004593 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004594 else {
4595 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4596 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004597 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004598 Py_DECREF(r);
4599 return -1;
4600 }
4601 *a = PyTuple_GET_ITEM(r, 0);
4602 Py_INCREF(*a);
4603 *b = PyTuple_GET_ITEM(r, 1);
4604 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004605 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004606 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004607 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004608 }
4609 if (other->ob_type->tp_as_number != NULL &&
4610 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4611 PyObject *r;
4612 r = call_maybe(
4613 other, "__coerce__", &coerce_str, "(O)", self);
4614 if (r == NULL)
4615 return -1;
4616 if (r == Py_NotImplemented) {
4617 Py_DECREF(r);
4618 return 1;
4619 }
4620 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4621 PyErr_SetString(PyExc_TypeError,
4622 "__coerce__ didn't return a 2-tuple");
4623 Py_DECREF(r);
4624 return -1;
4625 }
4626 *a = PyTuple_GET_ITEM(r, 1);
4627 Py_INCREF(*a);
4628 *b = PyTuple_GET_ITEM(r, 0);
4629 Py_INCREF(*b);
4630 Py_DECREF(r);
4631 return 0;
4632 }
4633 return 1;
4634}
4635
Guido van Rossumdc91b992001-08-08 22:26:22 +00004636SLOT0(slot_nb_int, "__int__")
4637SLOT0(slot_nb_long, "__long__")
4638SLOT0(slot_nb_float, "__float__")
4639SLOT0(slot_nb_oct, "__oct__")
4640SLOT0(slot_nb_hex, "__hex__")
4641SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4642SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4643SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4644SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4645SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Martin v. Löwisfd963262007-02-09 12:19:32 +00004646/* Can't use SLOT1 here, because nb_inplace_power is ternary */
4647static PyObject *
4648slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4649{
4650 static PyObject *cache_str;
4651 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
4652}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004653SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4654SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4655SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4656SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4657SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4658SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4659 "__floordiv__", "__rfloordiv__")
4660SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4661SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4662SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004663
4664static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004665half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004666{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004667 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004668 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004669 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004670
Guido van Rossum60718732001-08-28 17:47:51 +00004671 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004672 if (func == NULL) {
4673 PyErr_Clear();
4674 }
4675 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004676 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004677 if (args == NULL)
4678 res = NULL;
4679 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004680 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004681 Py_DECREF(args);
4682 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004683 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004684 if (res != Py_NotImplemented) {
4685 if (res == NULL)
4686 return -2;
4687 c = PyInt_AsLong(res);
4688 Py_DECREF(res);
4689 if (c == -1 && PyErr_Occurred())
4690 return -2;
4691 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4692 }
4693 Py_DECREF(res);
4694 }
4695 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004696}
4697
Guido van Rossumab3b0342001-09-18 20:38:53 +00004698/* This slot is published for the benefit of try_3way_compare in object.c */
4699int
4700_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004701{
4702 int c;
4703
Guido van Rossumab3b0342001-09-18 20:38:53 +00004704 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004705 c = half_compare(self, other);
4706 if (c <= 1)
4707 return c;
4708 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004709 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004710 c = half_compare(other, self);
4711 if (c < -1)
4712 return -2;
4713 if (c <= 1)
4714 return -c;
4715 }
4716 return (void *)self < (void *)other ? -1 :
4717 (void *)self > (void *)other ? 1 : 0;
4718}
4719
4720static PyObject *
4721slot_tp_repr(PyObject *self)
4722{
4723 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004724 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004725
Guido van Rossum60718732001-08-28 17:47:51 +00004726 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004727 if (func != NULL) {
4728 res = PyEval_CallObject(func, NULL);
4729 Py_DECREF(func);
4730 return res;
4731 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004732 PyErr_Clear();
4733 return PyString_FromFormat("<%s object at %p>",
4734 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004735}
4736
4737static PyObject *
4738slot_tp_str(PyObject *self)
4739{
4740 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004741 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004742
Guido van Rossum60718732001-08-28 17:47:51 +00004743 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004744 if (func != NULL) {
4745 res = PyEval_CallObject(func, NULL);
4746 Py_DECREF(func);
4747 return res;
4748 }
4749 else {
4750 PyErr_Clear();
4751 return slot_tp_repr(self);
4752 }
4753}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004754
4755static long
4756slot_tp_hash(PyObject *self)
4757{
Tim Peters61ce0a92002-12-06 23:38:02 +00004758 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004759 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004760 long h;
4761
Guido van Rossum60718732001-08-28 17:47:51 +00004762 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004763
4764 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004765 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004766 Py_DECREF(func);
4767 if (res == NULL)
4768 return -1;
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00004769 if (PyLong_Check(res))
Armin Rigo51fc8c42006-08-09 14:55:26 +00004770 h = PyLong_Type.tp_hash(res);
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00004771 else
4772 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004773 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004774 }
4775 else {
4776 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004777 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004778 if (func == NULL) {
4779 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004780 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004781 }
4782 if (func != NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00004783 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
4784 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004785 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004786 return -1;
4787 }
4788 PyErr_Clear();
4789 h = _Py_HashPointer((void *)self);
4790 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004791 if (h == -1 && !PyErr_Occurred())
4792 h = -2;
4793 return h;
4794}
4795
4796static PyObject *
4797slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4798{
Guido van Rossum60718732001-08-28 17:47:51 +00004799 static PyObject *call_str;
4800 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004801 PyObject *res;
4802
4803 if (meth == NULL)
4804 return NULL;
Armin Rigo53c1692f2006-06-21 21:58:50 +00004805
4806 /* PyObject_Call() will end up calling slot_tp_call() again if
4807 the object returned for __call__ has __call__ itself defined
4808 upon it. This can be an infinite recursion if you set
4809 __call__ in a class to an instance of it. */
Neal Norwitzb1149842006-06-23 03:32:44 +00004810 if (Py_EnterRecursiveCall(" in __call__")) {
4811 Py_DECREF(meth);
Armin Rigo53c1692f2006-06-21 21:58:50 +00004812 return NULL;
Neal Norwitzb1149842006-06-23 03:32:44 +00004813 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004814 res = PyObject_Call(meth, args, kwds);
Armin Rigo53c1692f2006-06-21 21:58:50 +00004815 Py_LeaveRecursiveCall();
4816
Tim Peters6d6c1a32001-08-02 04:15:00 +00004817 Py_DECREF(meth);
4818 return res;
4819}
4820
Guido van Rossum14a6f832001-10-17 13:59:09 +00004821/* There are two slot dispatch functions for tp_getattro.
4822
4823 - slot_tp_getattro() is used when __getattribute__ is overridden
4824 but no __getattr__ hook is present;
4825
4826 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4827
Guido van Rossumc334df52002-04-04 23:44:47 +00004828 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4829 detects the absence of __getattr__ and then installs the simpler slot if
4830 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004831
Tim Peters6d6c1a32001-08-02 04:15:00 +00004832static PyObject *
4833slot_tp_getattro(PyObject *self, PyObject *name)
4834{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004835 static PyObject *getattribute_str = NULL;
4836 return call_method(self, "__getattribute__", &getattribute_str,
4837 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004838}
4839
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004840static PyObject *
4841slot_tp_getattr_hook(PyObject *self, PyObject *name)
4842{
4843 PyTypeObject *tp = self->ob_type;
4844 PyObject *getattr, *getattribute, *res;
4845 static PyObject *getattribute_str = NULL;
4846 static PyObject *getattr_str = NULL;
4847
4848 if (getattr_str == NULL) {
4849 getattr_str = PyString_InternFromString("__getattr__");
4850 if (getattr_str == NULL)
4851 return NULL;
4852 }
4853 if (getattribute_str == NULL) {
4854 getattribute_str =
4855 PyString_InternFromString("__getattribute__");
4856 if (getattribute_str == NULL)
4857 return NULL;
4858 }
4859 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004860 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004861 /* No __getattr__ hook: use a simpler dispatcher */
4862 tp->tp_getattro = slot_tp_getattro;
4863 return slot_tp_getattro(self, name);
4864 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004865 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004866 if (getattribute == NULL ||
4867 (getattribute->ob_type == &PyWrapperDescr_Type &&
4868 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4869 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004870 res = PyObject_GenericGetAttr(self, name);
4871 else
Georg Brandl684fd0c2006-05-25 19:15:31 +00004872 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004873 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004874 PyErr_Clear();
Georg Brandl684fd0c2006-05-25 19:15:31 +00004875 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004876 }
4877 return res;
4878}
4879
Tim Peters6d6c1a32001-08-02 04:15:00 +00004880static int
4881slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4882{
4883 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004884 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004885
4886 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004887 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004888 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004889 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004890 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004891 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004892 if (res == NULL)
4893 return -1;
4894 Py_DECREF(res);
4895 return 0;
4896}
4897
4898/* Map rich comparison operators to their __xx__ namesakes */
4899static char *name_op[] = {
4900 "__lt__",
4901 "__le__",
4902 "__eq__",
4903 "__ne__",
4904 "__gt__",
4905 "__ge__",
4906};
4907
4908static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004909half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004910{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004911 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004912 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004913
Guido van Rossum60718732001-08-28 17:47:51 +00004914 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004915 if (func == NULL) {
4916 PyErr_Clear();
4917 Py_INCREF(Py_NotImplemented);
4918 return Py_NotImplemented;
4919 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004920 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004921 if (args == NULL)
4922 res = NULL;
4923 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004924 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004925 Py_DECREF(args);
4926 }
4927 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004928 return res;
4929}
4930
Guido van Rossumb8f63662001-08-15 23:57:02 +00004931static PyObject *
4932slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4933{
4934 PyObject *res;
4935
4936 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4937 res = half_richcompare(self, other, op);
4938 if (res != Py_NotImplemented)
4939 return res;
4940 Py_DECREF(res);
4941 }
4942 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004943 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004944 if (res != Py_NotImplemented) {
4945 return res;
4946 }
4947 Py_DECREF(res);
4948 }
4949 Py_INCREF(Py_NotImplemented);
4950 return Py_NotImplemented;
4951}
4952
4953static PyObject *
4954slot_tp_iter(PyObject *self)
4955{
4956 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004957 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004958
Guido van Rossum60718732001-08-28 17:47:51 +00004959 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004960 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004961 PyObject *args;
4962 args = res = PyTuple_New(0);
4963 if (args != NULL) {
4964 res = PyObject_Call(func, args, NULL);
4965 Py_DECREF(args);
4966 }
4967 Py_DECREF(func);
4968 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004969 }
4970 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004971 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004972 if (func == NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00004973 PyErr_Format(PyExc_TypeError,
4974 "'%.200s' object is not iterable",
4975 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004976 return NULL;
4977 }
4978 Py_DECREF(func);
4979 return PySeqIter_New(self);
4980}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004981
4982static PyObject *
4983slot_tp_iternext(PyObject *self)
4984{
Guido van Rossum2730b132001-08-28 18:22:14 +00004985 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004986 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004987}
4988
Guido van Rossum1a493502001-08-17 16:47:50 +00004989static PyObject *
4990slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4991{
4992 PyTypeObject *tp = self->ob_type;
4993 PyObject *get;
4994 static PyObject *get_str = NULL;
4995
4996 if (get_str == NULL) {
4997 get_str = PyString_InternFromString("__get__");
4998 if (get_str == NULL)
4999 return NULL;
5000 }
5001 get = _PyType_Lookup(tp, get_str);
5002 if (get == NULL) {
5003 /* Avoid further slowdowns */
5004 if (tp->tp_descr_get == slot_tp_descr_get)
5005 tp->tp_descr_get = NULL;
5006 Py_INCREF(self);
5007 return self;
5008 }
Guido van Rossum2c252392001-08-24 10:13:31 +00005009 if (obj == NULL)
5010 obj = Py_None;
5011 if (type == NULL)
5012 type = Py_None;
Georg Brandl684fd0c2006-05-25 19:15:31 +00005013 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005014}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005015
5016static int
5017slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5018{
Guido van Rossum2c252392001-08-24 10:13:31 +00005019 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005020 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005021
5022 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00005023 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005024 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00005025 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005026 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005027 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005028 if (res == NULL)
5029 return -1;
5030 Py_DECREF(res);
5031 return 0;
5032}
5033
5034static int
5035slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5036{
Guido van Rossum60718732001-08-28 17:47:51 +00005037 static PyObject *init_str;
5038 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005039 PyObject *res;
5040
5041 if (meth == NULL)
5042 return -1;
5043 res = PyObject_Call(meth, args, kwds);
5044 Py_DECREF(meth);
5045 if (res == NULL)
5046 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005047 if (res != Py_None) {
Georg Brandlccff7852006-06-18 22:17:29 +00005048 PyErr_Format(PyExc_TypeError,
5049 "__init__() should return None, not '%.200s'",
5050 res->ob_type->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005051 Py_DECREF(res);
5052 return -1;
5053 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005054 Py_DECREF(res);
5055 return 0;
5056}
5057
5058static PyObject *
5059slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5060{
Guido van Rossum7bed2132002-08-08 21:57:53 +00005061 static PyObject *new_str;
5062 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005063 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005064 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005065
Guido van Rossum7bed2132002-08-08 21:57:53 +00005066 if (new_str == NULL) {
5067 new_str = PyString_InternFromString("__new__");
5068 if (new_str == NULL)
5069 return NULL;
5070 }
5071 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005072 if (func == NULL)
5073 return NULL;
5074 assert(PyTuple_Check(args));
5075 n = PyTuple_GET_SIZE(args);
5076 newargs = PyTuple_New(n+1);
5077 if (newargs == NULL)
5078 return NULL;
5079 Py_INCREF(type);
5080 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5081 for (i = 0; i < n; i++) {
5082 x = PyTuple_GET_ITEM(args, i);
5083 Py_INCREF(x);
5084 PyTuple_SET_ITEM(newargs, i+1, x);
5085 }
5086 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00005087 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005088 Py_DECREF(func);
5089 return x;
5090}
5091
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005092static void
5093slot_tp_del(PyObject *self)
5094{
5095 static PyObject *del_str = NULL;
5096 PyObject *del, *res;
5097 PyObject *error_type, *error_value, *error_traceback;
5098
5099 /* Temporarily resurrect the object. */
5100 assert(self->ob_refcnt == 0);
5101 self->ob_refcnt = 1;
5102
5103 /* Save the current exception, if any. */
5104 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5105
5106 /* Execute __del__ method, if any. */
5107 del = lookup_maybe(self, "__del__", &del_str);
5108 if (del != NULL) {
5109 res = PyEval_CallObject(del, NULL);
5110 if (res == NULL)
5111 PyErr_WriteUnraisable(del);
5112 else
5113 Py_DECREF(res);
5114 Py_DECREF(del);
5115 }
5116
5117 /* Restore the saved exception. */
5118 PyErr_Restore(error_type, error_value, error_traceback);
5119
5120 /* Undo the temporary resurrection; can't use DECREF here, it would
5121 * cause a recursive call.
5122 */
5123 assert(self->ob_refcnt > 0);
5124 if (--self->ob_refcnt == 0)
5125 return; /* this is the normal path out */
5126
5127 /* __del__ resurrected it! Make it look like the original Py_DECREF
5128 * never happened.
5129 */
5130 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005131 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005132 _Py_NewReference(self);
5133 self->ob_refcnt = refcnt;
5134 }
5135 assert(!PyType_IS_GC(self->ob_type) ||
5136 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00005137 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5138 * we need to undo that. */
5139 _Py_DEC_REFTOTAL;
5140 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5141 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005142 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5143 * _Py_NewReference bumped tp_allocs: both of those need to be
5144 * undone.
5145 */
5146#ifdef COUNT_ALLOCS
5147 --self->ob_type->tp_frees;
5148 --self->ob_type->tp_allocs;
5149#endif
5150}
5151
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005152
5153/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005154 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005155 structure, which incorporates the additional structures used for numbers,
5156 sequences and mappings.
5157 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005158 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005159 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5160 terminated with an all-zero entry. (This table is further initialized and
5161 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005162
Guido van Rossum6d204072001-10-21 00:44:31 +00005163typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005164
5165#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005166#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005167#undef ETSLOT
5168#undef SQSLOT
5169#undef MPSLOT
5170#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005171#undef UNSLOT
5172#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005173#undef BINSLOT
5174#undef RBINSLOT
5175
Guido van Rossum6d204072001-10-21 00:44:31 +00005176#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005177 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5178 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005179#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5180 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005181 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005182#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005183 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005184 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005185#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5186 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5187#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5188 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5189#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5190 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5191#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5192 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5193 "x." NAME "() <==> " DOC)
5194#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5195 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5196 "x." NAME "(y) <==> x" DOC "y")
5197#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5198 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5199 "x." NAME "(y) <==> x" DOC "y")
5200#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5201 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5202 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005203#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5204 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5205 "x." NAME "(y) <==> " DOC)
5206#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5207 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5208 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005209
5210static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005211 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005212 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005213 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5214 The logic in abstract.c always falls back to nb_add/nb_multiply in
5215 this case. Defining both the nb_* and the sq_* slots to call the
5216 user-defined methods has unexpected side-effects, as shown by
5217 test_descr.notimplemented() */
5218 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005219 "x.__add__(y) <==> x+y"),
Armin Rigo314861c2006-03-30 14:04:02 +00005220 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005221 "x.__mul__(n) <==> x*n"),
Armin Rigo314861c2006-03-30 14:04:02 +00005222 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005223 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005224 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5225 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005226 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005227 "x.__getslice__(i, j) <==> x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005228 \n\
5229 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005230 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005231 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005232 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005233 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005234 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005235 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005236 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005237 \n\
5238 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005239 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005240 "x.__delslice__(i, j) <==> del x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005241 \n\
5242 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005243 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5244 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005245 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005246 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005247 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005248 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005249
Martin v. Löwis18e16552006-02-15 17:27:45 +00005250 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005251 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005252 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005253 wrap_binaryfunc,
5254 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005255 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005256 wrap_objobjargproc,
5257 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005258 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005259 wrap_delitem,
5260 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005261
Guido van Rossum6d204072001-10-21 00:44:31 +00005262 BINSLOT("__add__", nb_add, slot_nb_add,
5263 "+"),
5264 RBINSLOT("__radd__", nb_add, slot_nb_add,
5265 "+"),
5266 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5267 "-"),
5268 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5269 "-"),
5270 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5271 "*"),
5272 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5273 "*"),
5274 BINSLOT("__div__", nb_divide, slot_nb_divide,
5275 "/"),
5276 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5277 "/"),
5278 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5279 "%"),
5280 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5281 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005282 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005283 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005284 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005285 "divmod(y, x)"),
5286 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5287 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5288 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5289 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5290 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5291 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5292 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5293 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005294 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005295 "x != 0"),
5296 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5297 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5298 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5299 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5300 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5301 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5302 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5303 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5304 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5305 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5306 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5307 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5308 "x.__coerce__(y) <==> coerce(x, y)"),
5309 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5310 "int(x)"),
5311 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5312 "long(x)"),
5313 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5314 "float(x)"),
5315 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5316 "oct(x)"),
5317 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5318 "hex(x)"),
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005319 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005320 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005321 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5322 wrap_binaryfunc, "+"),
5323 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5324 wrap_binaryfunc, "-"),
5325 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5326 wrap_binaryfunc, "*"),
5327 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5328 wrap_binaryfunc, "/"),
5329 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5330 wrap_binaryfunc, "%"),
5331 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005332 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005333 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5334 wrap_binaryfunc, "<<"),
5335 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5336 wrap_binaryfunc, ">>"),
5337 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5338 wrap_binaryfunc, "&"),
5339 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5340 wrap_binaryfunc, "^"),
5341 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5342 wrap_binaryfunc, "|"),
5343 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5344 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5345 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5346 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5347 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5348 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5349 IBSLOT("__itruediv__", nb_inplace_true_divide,
5350 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005351
Guido van Rossum6d204072001-10-21 00:44:31 +00005352 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5353 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005354 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005355 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5356 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005357 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005358 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5359 "x.__cmp__(y) <==> cmp(x,y)"),
5360 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5361 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005362 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5363 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005364 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005365 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5366 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5367 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5368 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5369 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5370 "x.__setattr__('name', value) <==> x.name = value"),
5371 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5372 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5373 "x.__delattr__('name') <==> del x.name"),
5374 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5375 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5376 "x.__lt__(y) <==> x<y"),
5377 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5378 "x.__le__(y) <==> x<=y"),
5379 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5380 "x.__eq__(y) <==> x==y"),
5381 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5382 "x.__ne__(y) <==> x!=y"),
5383 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5384 "x.__gt__(y) <==> x>y"),
5385 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5386 "x.__ge__(y) <==> x>=y"),
5387 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5388 "x.__iter__() <==> iter(x)"),
5389 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5390 "x.next() -> the next value, or raise StopIteration"),
5391 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5392 "descr.__get__(obj[, type]) -> value"),
5393 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5394 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005395 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5396 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005397 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005398 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005399 "see x.__class__.__doc__ for signature",
5400 PyWrapperFlag_KEYWORDS),
5401 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005402 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005403 {NULL}
5404};
5405
Guido van Rossumc334df52002-04-04 23:44:47 +00005406/* Given a type pointer and an offset gotten from a slotdef entry, return a
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005407 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005408 the offset to the type pointer, since it takes care to indirect through the
5409 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5410 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005411static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005412slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005413{
5414 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005415 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005416
Guido van Rossume5c691a2003-03-07 15:13:17 +00005417 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005418 assert(offset >= 0);
Skip Montanaro429433b2006-04-18 00:35:43 +00005419 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5420 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005421 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005422 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005423 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005424 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005425 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005426 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005427 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005428 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005429 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005430 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005431 }
5432 else {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005433 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005434 }
5435 if (ptr != NULL)
5436 ptr += offset;
5437 return (void **)ptr;
5438}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005439
Guido van Rossumc334df52002-04-04 23:44:47 +00005440/* Length of array of slotdef pointers used to store slots with the
5441 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5442 the same __name__, for any __name__. Since that's a static property, it is
5443 appropriate to declare fixed-size arrays for this. */
5444#define MAX_EQUIV 10
5445
5446/* Return a slot pointer for a given name, but ONLY if the attribute has
5447 exactly one slot function. The name must be an interned string. */
5448static void **
5449resolve_slotdups(PyTypeObject *type, PyObject *name)
5450{
5451 /* XXX Maybe this could be optimized more -- but is it worth it? */
5452
5453 /* pname and ptrs act as a little cache */
5454 static PyObject *pname;
5455 static slotdef *ptrs[MAX_EQUIV];
5456 slotdef *p, **pp;
5457 void **res, **ptr;
5458
5459 if (pname != name) {
5460 /* Collect all slotdefs that match name into ptrs. */
5461 pname = name;
5462 pp = ptrs;
5463 for (p = slotdefs; p->name_strobj; p++) {
5464 if (p->name_strobj == name)
5465 *pp++ = p;
5466 }
5467 *pp = NULL;
5468 }
5469
5470 /* Look in all matching slots of the type; if exactly one of these has
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005471 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005472 res = NULL;
5473 for (pp = ptrs; *pp; pp++) {
5474 ptr = slotptr(type, (*pp)->offset);
5475 if (ptr == NULL || *ptr == NULL)
5476 continue;
5477 if (res != NULL)
5478 return NULL;
5479 res = ptr;
5480 }
5481 return res;
5482}
5483
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005484/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005485 does some incredibly complex thinking and then sticks something into the
5486 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5487 interests, and then stores a generic wrapper or a specific function into
5488 the slot.) Return a pointer to the next slotdef with a different offset,
5489 because that's convenient for fixup_slot_dispatchers(). */
5490static slotdef *
5491update_one_slot(PyTypeObject *type, slotdef *p)
5492{
5493 PyObject *descr;
5494 PyWrapperDescrObject *d;
5495 void *generic = NULL, *specific = NULL;
5496 int use_generic = 0;
5497 int offset = p->offset;
5498 void **ptr = slotptr(type, offset);
5499
5500 if (ptr == NULL) {
5501 do {
5502 ++p;
5503 } while (p->offset == offset);
5504 return p;
5505 }
5506 do {
5507 descr = _PyType_Lookup(type, p->name_strobj);
5508 if (descr == NULL)
5509 continue;
5510 if (descr->ob_type == &PyWrapperDescr_Type) {
5511 void **tptr = resolve_slotdups(type, p->name_strobj);
5512 if (tptr == NULL || tptr == ptr)
5513 generic = p->function;
5514 d = (PyWrapperDescrObject *)descr;
5515 if (d->d_base->wrapper == p->wrapper &&
5516 PyType_IsSubtype(type, d->d_type))
5517 {
5518 if (specific == NULL ||
5519 specific == d->d_wrapped)
5520 specific = d->d_wrapped;
5521 else
5522 use_generic = 1;
5523 }
5524 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005525 else if (descr->ob_type == &PyCFunction_Type &&
5526 PyCFunction_GET_FUNCTION(descr) ==
5527 (PyCFunction)tp_new_wrapper &&
5528 strcmp(p->name, "__new__") == 0)
5529 {
5530 /* The __new__ wrapper is not a wrapper descriptor,
5531 so must be special-cased differently.
5532 If we don't do this, creating an instance will
5533 always use slot_tp_new which will look up
5534 __new__ in the MRO which will call tp_new_wrapper
5535 which will look through the base classes looking
5536 for a static base and call its tp_new (usually
5537 PyType_GenericNew), after performing various
5538 sanity checks and constructing a new argument
5539 list. Cut all that nonsense short -- this speeds
5540 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005541 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005542 /* XXX I'm not 100% sure that there isn't a hole
5543 in this reasoning that requires additional
5544 sanity checks. I'll buy the first person to
5545 point out a bug in this reasoning a beer. */
5546 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005547 else {
5548 use_generic = 1;
5549 generic = p->function;
5550 }
5551 } while ((++p)->offset == offset);
5552 if (specific && !use_generic)
5553 *ptr = specific;
5554 else
5555 *ptr = generic;
5556 return p;
5557}
5558
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005559/* In the type, update the slots whose slotdefs are gathered in the pp array.
5560 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005561static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005562update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005563{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005564 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005565
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005566 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005567 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005568 return 0;
5569}
5570
Guido van Rossumc334df52002-04-04 23:44:47 +00005571/* Comparison function for qsort() to compare slotdefs by their offset, and
5572 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005573static int
5574slotdef_cmp(const void *aa, const void *bb)
5575{
5576 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5577 int c = a->offset - b->offset;
5578 if (c != 0)
5579 return c;
5580 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005581 /* Cannot use a-b, as this gives off_t,
5582 which may lose precision when converted to int. */
5583 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005584}
5585
Guido van Rossumc334df52002-04-04 23:44:47 +00005586/* Initialize the slotdefs table by adding interned string objects for the
5587 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005588static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005589init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005590{
5591 slotdef *p;
5592 static int initialized = 0;
5593
5594 if (initialized)
5595 return;
5596 for (p = slotdefs; p->name; p++) {
5597 p->name_strobj = PyString_InternFromString(p->name);
5598 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005599 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005600 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005601 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5602 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005603 initialized = 1;
5604}
5605
Guido van Rossumc334df52002-04-04 23:44:47 +00005606/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005607static int
5608update_slot(PyTypeObject *type, PyObject *name)
5609{
Guido van Rossumc334df52002-04-04 23:44:47 +00005610 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005611 slotdef *p;
5612 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005613 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005614
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005615 init_slotdefs();
5616 pp = ptrs;
5617 for (p = slotdefs; p->name; p++) {
5618 /* XXX assume name is interned! */
5619 if (p->name_strobj == name)
5620 *pp++ = p;
5621 }
5622 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005623 for (pp = ptrs; *pp; pp++) {
5624 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005625 offset = p->offset;
5626 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005627 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005628 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005629 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005630 if (ptrs[0] == NULL)
5631 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005632 return update_subclasses(type, name,
5633 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005634}
5635
Guido van Rossumc334df52002-04-04 23:44:47 +00005636/* Store the proper functions in the slot dispatches at class (type)
5637 definition time, based upon which operations the class overrides in its
5638 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005639static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005640fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005641{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005642 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005643
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005644 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005645 for (p = slotdefs; p->name; )
5646 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005647}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005648
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005649static void
5650update_all_slots(PyTypeObject* type)
5651{
5652 slotdef *p;
5653
5654 init_slotdefs();
5655 for (p = slotdefs; p->name; p++) {
5656 /* update_slot returns int but can't actually fail */
5657 update_slot(type, p->name_strobj);
5658 }
5659}
5660
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005661/* recurse_down_subclasses() and update_subclasses() are mutually
5662 recursive functions to call a callback for all subclasses,
5663 but refraining from recursing into subclasses that define 'name'. */
5664
5665static int
5666update_subclasses(PyTypeObject *type, PyObject *name,
5667 update_callback callback, void *data)
5668{
5669 if (callback(type, data) < 0)
5670 return -1;
5671 return recurse_down_subclasses(type, name, callback, data);
5672}
5673
5674static int
5675recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5676 update_callback callback, void *data)
5677{
5678 PyTypeObject *subclass;
5679 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005680 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005681
5682 subclasses = type->tp_subclasses;
5683 if (subclasses == NULL)
5684 return 0;
5685 assert(PyList_Check(subclasses));
5686 n = PyList_GET_SIZE(subclasses);
5687 for (i = 0; i < n; i++) {
5688 ref = PyList_GET_ITEM(subclasses, i);
5689 assert(PyWeakref_CheckRef(ref));
5690 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5691 assert(subclass != NULL);
5692 if ((PyObject *)subclass == Py_None)
5693 continue;
5694 assert(PyType_Check(subclass));
5695 /* Avoid recursing down into unaffected classes */
5696 dict = subclass->tp_dict;
5697 if (dict != NULL && PyDict_Check(dict) &&
5698 PyDict_GetItem(dict, name) != NULL)
5699 continue;
5700 if (update_subclasses(subclass, name, callback, data) < 0)
5701 return -1;
5702 }
5703 return 0;
5704}
5705
Guido van Rossum6d204072001-10-21 00:44:31 +00005706/* This function is called by PyType_Ready() to populate the type's
5707 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005708 function slot (like tp_repr) that's defined in the type, one or more
5709 corresponding descriptors are added in the type's tp_dict dictionary
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005710 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005711 cause more than one descriptor to be added (for example, the nb_add
5712 slot adds both __add__ and __radd__ descriptors) and some function
5713 slots compete for the same descriptor (for example both sq_item and
5714 mp_subscript generate a __getitem__ descriptor).
5715
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005716 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005717 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005718 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005719 between competing slots: the members of PyHeapTypeObject are listed
5720 from most general to least general, so the most general slot is
5721 preferred. In particular, because as_mapping comes before as_sequence,
5722 for a type that defines both mp_subscript and sq_item, mp_subscript
5723 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005724
5725 This only adds new descriptors and doesn't overwrite entries in
5726 tp_dict that were previously defined. The descriptors contain a
5727 reference to the C function they must call, so that it's safe if they
5728 are copied into a subtype's __dict__ and the subtype has a different
5729 C function in its slot -- calling the method defined by the
5730 descriptor will call the C function that was used to create it,
5731 rather than the C function present in the slot when it is called.
5732 (This is important because a subtype may have a C function in the
5733 slot that calls the method from the dictionary, and we want to avoid
5734 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005735
5736static int
5737add_operators(PyTypeObject *type)
5738{
5739 PyObject *dict = type->tp_dict;
5740 slotdef *p;
5741 PyObject *descr;
5742 void **ptr;
5743
5744 init_slotdefs();
5745 for (p = slotdefs; p->name; p++) {
5746 if (p->wrapper == NULL)
5747 continue;
5748 ptr = slotptr(type, p->offset);
5749 if (!ptr || !*ptr)
5750 continue;
5751 if (PyDict_GetItem(dict, p->name_strobj))
5752 continue;
5753 descr = PyDescr_NewWrapper(type, p, *ptr);
5754 if (descr == NULL)
5755 return -1;
5756 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5757 return -1;
5758 Py_DECREF(descr);
5759 }
5760 if (type->tp_new != NULL) {
5761 if (add_tp_new_wrapper(type) < 0)
5762 return -1;
5763 }
5764 return 0;
5765}
5766
Guido van Rossum705f0f52001-08-24 16:47:00 +00005767
5768/* Cooperative 'super' */
5769
5770typedef struct {
5771 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005772 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005773 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005774 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005775} superobject;
5776
Guido van Rossum6f799372001-09-20 20:46:19 +00005777static PyMemberDef super_members[] = {
5778 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5779 "the class invoking super()"},
5780 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5781 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005782 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005783 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005784 {0}
5785};
5786
Guido van Rossum705f0f52001-08-24 16:47:00 +00005787static void
5788super_dealloc(PyObject *self)
5789{
5790 superobject *su = (superobject *)self;
5791
Guido van Rossum048eb752001-10-02 21:24:57 +00005792 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005793 Py_XDECREF(su->obj);
5794 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005795 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005796 self->ob_type->tp_free(self);
5797}
5798
5799static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005800super_repr(PyObject *self)
5801{
5802 superobject *su = (superobject *)self;
5803
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005804 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005805 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005806 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005807 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005808 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005809 else
5810 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005811 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005812 su->type ? su->type->tp_name : "NULL");
5813}
5814
5815static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005816super_getattro(PyObject *self, PyObject *name)
5817{
5818 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005819 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005820
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005821 if (!skip) {
5822 /* We want __class__ to return the class of the super object
5823 (i.e. super, or a subclass), not the class of su->obj. */
5824 skip = (PyString_Check(name) &&
5825 PyString_GET_SIZE(name) == 9 &&
5826 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5827 }
5828
5829 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005830 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005831 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005832 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005833 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005834
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005835 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005836 mro = starttype->tp_mro;
5837
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005838 if (mro == NULL)
5839 n = 0;
5840 else {
5841 assert(PyTuple_Check(mro));
5842 n = PyTuple_GET_SIZE(mro);
5843 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005844 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005845 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005846 break;
5847 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005848 i++;
5849 res = NULL;
5850 for (; i < n; i++) {
5851 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005852 if (PyType_Check(tmp))
5853 dict = ((PyTypeObject *)tmp)->tp_dict;
5854 else if (PyClass_Check(tmp))
5855 dict = ((PyClassObject *)tmp)->cl_dict;
5856 else
5857 continue;
5858 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005859 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005860 Py_INCREF(res);
5861 f = res->ob_type->tp_descr_get;
5862 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005863 tmp = f(res,
5864 /* Only pass 'obj' param if
5865 this is instance-mode super
5866 (See SF ID #743627)
5867 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005868 (su->obj == (PyObject *)
5869 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005870 ? (PyObject *)NULL
5871 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005872 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005873 Py_DECREF(res);
5874 res = tmp;
5875 }
5876 return res;
5877 }
5878 }
5879 }
5880 return PyObject_GenericGetAttr(self, name);
5881}
5882
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005883static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005884supercheck(PyTypeObject *type, PyObject *obj)
5885{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005886 /* Check that a super() call makes sense. Return a type object.
5887
5888 obj can be a new-style class, or an instance of one:
5889
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005890 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005891 used for class methods; the return value is obj.
5892
5893 - If it is an instance, it must be an instance of 'type'. This is
5894 the normal case; the return value is obj.__class__.
5895
5896 But... when obj is an instance, we want to allow for the case where
5897 obj->ob_type is not a subclass of type, but obj.__class__ is!
5898 This will allow using super() with a proxy for obj.
5899 */
5900
Guido van Rossum8e80a722003-02-18 19:22:22 +00005901 /* Check for first bullet above (special case) */
5902 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5903 Py_INCREF(obj);
5904 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005905 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005906
5907 /* Normal case */
5908 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005909 Py_INCREF(obj->ob_type);
5910 return obj->ob_type;
5911 }
5912 else {
5913 /* Try the slow way */
5914 static PyObject *class_str = NULL;
5915 PyObject *class_attr;
5916
5917 if (class_str == NULL) {
5918 class_str = PyString_FromString("__class__");
5919 if (class_str == NULL)
5920 return NULL;
5921 }
5922
5923 class_attr = PyObject_GetAttr(obj, class_str);
5924
5925 if (class_attr != NULL &&
5926 PyType_Check(class_attr) &&
5927 (PyTypeObject *)class_attr != obj->ob_type)
5928 {
5929 int ok = PyType_IsSubtype(
5930 (PyTypeObject *)class_attr, type);
5931 if (ok)
5932 return (PyTypeObject *)class_attr;
5933 }
5934
5935 if (class_attr == NULL)
5936 PyErr_Clear();
5937 else
5938 Py_DECREF(class_attr);
5939 }
5940
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005941 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005942 "super(type, obj): "
5943 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005944 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005945}
5946
Guido van Rossum705f0f52001-08-24 16:47:00 +00005947static PyObject *
5948super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5949{
5950 superobject *su = (superobject *)self;
Anthony Baxtera6286212006-04-11 07:42:36 +00005951 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005952
5953 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5954 /* Not binding to an object, or already bound */
5955 Py_INCREF(self);
5956 return self;
5957 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005958 if (su->ob_type != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005959 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005960 call its type */
Georg Brandl684fd0c2006-05-25 19:15:31 +00005961 return PyObject_CallFunctionObjArgs((PyObject *)su->ob_type,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005962 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005963 else {
5964 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005965 PyTypeObject *obj_type = supercheck(su->type, obj);
5966 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005967 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00005968 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005969 NULL, NULL);
Anthony Baxtera6286212006-04-11 07:42:36 +00005970 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005971 return NULL;
5972 Py_INCREF(su->type);
5973 Py_INCREF(obj);
Anthony Baxtera6286212006-04-11 07:42:36 +00005974 newobj->type = su->type;
5975 newobj->obj = obj;
5976 newobj->obj_type = obj_type;
5977 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005978 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005979}
5980
5981static int
5982super_init(PyObject *self, PyObject *args, PyObject *kwds)
5983{
5984 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005985 PyTypeObject *type;
5986 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005987 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005988
Georg Brandl5d59c092006-09-30 08:43:30 +00005989 if (!_PyArg_NoKeywords("super", kwds))
5990 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005991 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5992 return -1;
5993 if (obj == Py_None)
5994 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005995 if (obj != NULL) {
5996 obj_type = supercheck(type, obj);
5997 if (obj_type == NULL)
5998 return -1;
5999 Py_INCREF(obj);
6000 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006001 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006002 su->type = type;
6003 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006004 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006005 return 0;
6006}
6007
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006008PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00006009"super(type) -> unbound super object\n"
6010"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006011"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006012"Typical use to call a cooperative superclass method:\n"
6013"class C(B):\n"
6014" def meth(self, arg):\n"
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006015" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006016
Guido van Rossum048eb752001-10-02 21:24:57 +00006017static int
6018super_traverse(PyObject *self, visitproc visit, void *arg)
6019{
6020 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006021
Thomas Woutersc6e55062006-04-15 21:47:09 +00006022 Py_VISIT(su->obj);
6023 Py_VISIT(su->type);
6024 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006025
6026 return 0;
6027}
6028
Guido van Rossum705f0f52001-08-24 16:47:00 +00006029PyTypeObject PySuper_Type = {
6030 PyObject_HEAD_INIT(&PyType_Type)
6031 0, /* ob_size */
6032 "super", /* tp_name */
6033 sizeof(superobject), /* tp_basicsize */
6034 0, /* tp_itemsize */
6035 /* methods */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006036 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006037 0, /* tp_print */
6038 0, /* tp_getattr */
6039 0, /* tp_setattr */
6040 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006041 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006042 0, /* tp_as_number */
6043 0, /* tp_as_sequence */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006044 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006045 0, /* tp_hash */
6046 0, /* tp_call */
6047 0, /* tp_str */
6048 super_getattro, /* tp_getattro */
6049 0, /* tp_setattro */
6050 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00006051 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6052 Py_TPFLAGS_BASETYPE, /* tp_flags */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006053 super_doc, /* tp_doc */
6054 super_traverse, /* tp_traverse */
6055 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006056 0, /* tp_richcompare */
6057 0, /* tp_weaklistoffset */
6058 0, /* tp_iter */
6059 0, /* tp_iternext */
6060 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006061 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006062 0, /* tp_getset */
6063 0, /* tp_base */
6064 0, /* tp_dict */
6065 super_descr_get, /* tp_descr_get */
6066 0, /* tp_descr_set */
6067 0, /* tp_dictoffset */
6068 super_init, /* tp_init */
6069 PyType_GenericAlloc, /* tp_alloc */
6070 PyType_GenericNew, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006071 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006072};