blob: f6ae69bda3853df46f9225534932fb3737243e04 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
Guido van Rossum6f799372001-09-20 20:46:19 +00008static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00009 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
10 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
11 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000017 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
18 {0}
19};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000020
Guido van Rossumc0b618a1997-05-02 03:12:38 +000021static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000022type_name(PyTypeObject *type, void *context)
23{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +000024 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +000025
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000026 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +000027 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +000028
Georg Brandlc255c7b2006-02-20 22:27:28 +000029 Py_INCREF(et->ht_name);
30 return et->ht_name;
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000031 }
32 else {
33 s = strrchr(type->tp_name, '.');
34 if (s == NULL)
35 s = type->tp_name;
36 else
37 s++;
38 return PyString_FromString(s);
39 }
Guido van Rossumc3542212001-08-16 09:18:56 +000040}
41
Michael W. Hudson98bbc492002-11-26 14:47:27 +000042static int
43type_set_name(PyTypeObject *type, PyObject *value, void *context)
44{
Guido van Rossume5c691a2003-03-07 15:13:17 +000045 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000046
47 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
48 PyErr_Format(PyExc_TypeError,
49 "can't set %s.__name__", type->tp_name);
50 return -1;
51 }
52 if (!value) {
53 PyErr_Format(PyExc_TypeError,
54 "can't delete %s.__name__", type->tp_name);
55 return -1;
56 }
57 if (!PyString_Check(value)) {
58 PyErr_Format(PyExc_TypeError,
59 "can only assign string to %s.__name__, not '%s'",
60 type->tp_name, value->ob_type->tp_name);
61 return -1;
62 }
Tim Petersea7f75d2002-12-07 21:39:16 +000063 if (strlen(PyString_AS_STRING(value))
Michael W. Hudson98bbc492002-11-26 14:47:27 +000064 != (size_t)PyString_GET_SIZE(value)) {
65 PyErr_Format(PyExc_ValueError,
66 "__name__ must not contain null bytes");
67 return -1;
68 }
69
Guido van Rossume5c691a2003-03-07 15:13:17 +000070 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000071
72 Py_INCREF(value);
73
Georg Brandlc255c7b2006-02-20 22:27:28 +000074 Py_DECREF(et->ht_name);
75 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000076
77 type->tp_name = PyString_AS_STRING(value);
78
79 return 0;
80}
81
Guido van Rossumc3542212001-08-16 09:18:56 +000082static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000083type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000084{
Guido van Rossumc3542212001-08-16 09:18:56 +000085 PyObject *mod;
86 char *s;
87
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000088 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
89 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Anthony Baxter3ecdb252004-06-11 14:41:18 +000090 if (!mod) {
91 PyErr_Format(PyExc_AttributeError, "__module__");
92 return 0;
93 }
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000094 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +000095 return mod;
96 }
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000097 else {
98 s = strrchr(type->tp_name, '.');
99 if (s != NULL)
100 return PyString_FromStringAndSize(
Thomas Wouters89f507f2006-12-13 04:49:30 +0000101 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000102 return PyString_FromString("__builtin__");
103 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000104}
105
Guido van Rossum3926a632001-09-25 16:25:58 +0000106static int
107type_set_module(PyTypeObject *type, PyObject *value, void *context)
108{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000109 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000110 PyErr_Format(PyExc_TypeError,
111 "can't set %s.__module__", type->tp_name);
112 return -1;
113 }
114 if (!value) {
115 PyErr_Format(PyExc_TypeError,
116 "can't delete %s.__module__", type->tp_name);
117 return -1;
118 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000119
Guido van Rossum3926a632001-09-25 16:25:58 +0000120 return PyDict_SetItemString(type->tp_dict, "__module__", value);
121}
122
Tim Peters6d6c1a32001-08-02 04:15:00 +0000123static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000124type_get_bases(PyTypeObject *type, void *context)
125{
126 Py_INCREF(type->tp_bases);
127 return type->tp_bases;
128}
129
130static PyTypeObject *best_base(PyObject *);
131static int mro_internal(PyTypeObject *);
132static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
133static int add_subclass(PyTypeObject*, PyTypeObject*);
134static void remove_subclass(PyTypeObject *, PyTypeObject *);
135static void update_all_slots(PyTypeObject *);
136
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000137typedef int (*update_callback)(PyTypeObject *, void *);
138static int update_subclasses(PyTypeObject *type, PyObject *name,
139 update_callback callback, void *data);
140static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
141 update_callback callback, void *data);
142
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000143static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000144mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000145{
146 PyTypeObject *subclass;
147 PyObject *ref, *subclasses, *old_mro;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000148 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000149
150 subclasses = type->tp_subclasses;
151 if (subclasses == NULL)
152 return 0;
153 assert(PyList_Check(subclasses));
154 n = PyList_GET_SIZE(subclasses);
155 for (i = 0; i < n; i++) {
156 ref = PyList_GET_ITEM(subclasses, i);
157 assert(PyWeakref_CheckRef(ref));
158 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
159 assert(subclass != NULL);
160 if ((PyObject *)subclass == Py_None)
161 continue;
162 assert(PyType_Check(subclass));
163 old_mro = subclass->tp_mro;
164 if (mro_internal(subclass) < 0) {
165 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000166 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000167 }
168 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000169 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000170 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000171 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000172 if (!tuple)
173 return -1;
174 if (PyList_Append(temp, tuple) < 0)
175 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000176 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000177 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000178 if (mro_subclasses(subclass, temp) < 0)
179 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000180 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000181 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000182}
183
184static int
185type_set_bases(PyTypeObject *type, PyObject *value, void *context)
186{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000187 Py_ssize_t i;
188 int r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000189 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000190 PyTypeObject *new_base, *old_base;
191 PyObject *old_bases, *old_mro;
192
193 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
194 PyErr_Format(PyExc_TypeError,
195 "can't set %s.__bases__", type->tp_name);
196 return -1;
197 }
198 if (!value) {
199 PyErr_Format(PyExc_TypeError,
200 "can't delete %s.__bases__", type->tp_name);
201 return -1;
202 }
203 if (!PyTuple_Check(value)) {
204 PyErr_Format(PyExc_TypeError,
205 "can only assign tuple to %s.__bases__, not %s",
206 type->tp_name, value->ob_type->tp_name);
207 return -1;
208 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000209 if (PyTuple_GET_SIZE(value) == 0) {
210 PyErr_Format(PyExc_TypeError,
211 "can only assign non-empty tuple to %s.__bases__, not ()",
212 type->tp_name);
213 return -1;
214 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000215 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
216 ob = PyTuple_GET_ITEM(value, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +0000217 if (!PyType_Check(ob)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000218 PyErr_Format(
219 PyExc_TypeError,
220 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
221 type->tp_name, ob->ob_type->tp_name);
222 return -1;
223 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000224 if (PyType_Check(ob)) {
225 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
226 PyErr_SetString(PyExc_TypeError,
227 "a __bases__ item causes an inheritance cycle");
228 return -1;
229 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000230 }
231 }
232
233 new_base = best_base(value);
234
235 if (!new_base) {
236 return -1;
237 }
238
239 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
240 return -1;
241
242 Py_INCREF(new_base);
243 Py_INCREF(value);
244
245 old_bases = type->tp_bases;
246 old_base = type->tp_base;
247 old_mro = type->tp_mro;
248
249 type->tp_bases = value;
250 type->tp_base = new_base;
251
252 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000253 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000254 }
255
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000256 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000257 if (!temp)
258 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000259
260 r = mro_subclasses(type, temp);
261
262 if (r < 0) {
263 for (i = 0; i < PyList_Size(temp); i++) {
264 PyTypeObject* cls;
265 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000266 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
267 "", 2, 2, &cls, &mro);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000268 Py_INCREF(mro);
269 ob = cls->tp_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000270 cls->tp_mro = mro;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000271 Py_DECREF(ob);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000272 }
273 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000274 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000275 }
276
277 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000278
279 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000280 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000281 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000282 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000283
284 /* for now, sod that: just remove from all old_bases,
285 add to all new_bases */
286
287 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
288 ob = PyTuple_GET_ITEM(old_bases, i);
289 if (PyType_Check(ob)) {
290 remove_subclass(
291 (PyTypeObject*)ob, type);
292 }
293 }
294
295 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
296 ob = PyTuple_GET_ITEM(value, i);
297 if (PyType_Check(ob)) {
298 if (add_subclass((PyTypeObject*)ob, type) < 0)
299 r = -1;
300 }
301 }
302
303 update_all_slots(type);
304
305 Py_DECREF(old_bases);
306 Py_DECREF(old_base);
307 Py_DECREF(old_mro);
308
309 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000310
311 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000312 Py_DECREF(type->tp_bases);
313 Py_DECREF(type->tp_base);
314 if (type->tp_mro != old_mro) {
315 Py_DECREF(type->tp_mro);
316 }
317
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000318 type->tp_bases = old_bases;
319 type->tp_base = old_base;
320 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000321
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000322 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000323}
324
325static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000326type_dict(PyTypeObject *type, void *context)
327{
328 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000329 Py_INCREF(Py_None);
330 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000331 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000332 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000333}
334
Tim Peters24008312002-03-17 18:56:20 +0000335static PyObject *
336type_get_doc(PyTypeObject *type, void *context)
337{
338 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000339 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000340 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000341 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000342 if (result == NULL) {
343 result = Py_None;
344 Py_INCREF(result);
345 }
346 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000347 result = result->ob_type->tp_descr_get(result, NULL,
348 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000349 }
350 else {
351 Py_INCREF(result);
352 }
Tim Peters24008312002-03-17 18:56:20 +0000353 return result;
354}
355
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000356static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000357 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
358 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000359 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000360 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000361 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000362 {0}
363};
364
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000365static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000366type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000367{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000368 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000369 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000370
371 mod = type_module(type, NULL);
372 if (mod == NULL)
373 PyErr_Clear();
374 else if (!PyString_Check(mod)) {
375 Py_DECREF(mod);
376 mod = NULL;
377 }
378 name = type_name(type, NULL);
379 if (name == NULL)
380 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000381
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000382 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
383 kind = "class";
384 else
385 kind = "type";
386
Barry Warsaw7ce36942001-08-24 18:34:26 +0000387 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000388 rtn = PyString_FromFormat("<%s '%s.%s'>",
389 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000390 PyString_AS_STRING(mod),
391 PyString_AS_STRING(name));
392 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000393 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000394 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000395
Guido van Rossumc3542212001-08-16 09:18:56 +0000396 Py_XDECREF(mod);
397 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000398 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000399}
400
Tim Peters6d6c1a32001-08-02 04:15:00 +0000401static PyObject *
402type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
403{
404 PyObject *obj;
405
406 if (type->tp_new == NULL) {
407 PyErr_Format(PyExc_TypeError,
408 "cannot create '%.100s' instances",
409 type->tp_name);
410 return NULL;
411 }
412
Tim Peters3f996e72001-09-13 19:18:27 +0000413 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000414 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000415 /* Ugly exception: when the call was type(something),
416 don't call tp_init on the result. */
417 if (type == &PyType_Type &&
418 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
419 (kwds == NULL ||
420 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
421 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000422 /* If the returned object is not an instance of type,
423 it won't be initialized. */
424 if (!PyType_IsSubtype(obj->ob_type, type))
425 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000426 type = obj->ob_type;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000427 if (type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000428 type->tp_init(obj, args, kwds) < 0) {
429 Py_DECREF(obj);
430 obj = NULL;
431 }
432 }
433 return obj;
434}
435
436PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000437PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000438{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000439 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000440 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
441 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000442
443 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000444 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000445 else
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000446 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000447
Neil Schemenauerc806c882001-08-29 23:54:54 +0000448 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000449 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000450
Neil Schemenauerc806c882001-08-29 23:54:54 +0000451 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000452
Tim Peters6d6c1a32001-08-02 04:15:00 +0000453 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
454 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000455
Tim Peters6d6c1a32001-08-02 04:15:00 +0000456 if (type->tp_itemsize == 0)
457 PyObject_INIT(obj, type);
458 else
459 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000460
Tim Peters6d6c1a32001-08-02 04:15:00 +0000461 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000462 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000463 return obj;
464}
465
466PyObject *
467PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
468{
469 return type->tp_alloc(type, 0);
470}
471
Guido van Rossum9475a232001-10-05 20:51:39 +0000472/* Helpers for subtyping */
473
474static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000475traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
476{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000477 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000478 PyMemberDef *mp;
479
480 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000481 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000482 for (i = 0; i < n; i++, mp++) {
483 if (mp->type == T_OBJECT_EX) {
484 char *addr = (char *)self + mp->offset;
485 PyObject *obj = *(PyObject **)addr;
486 if (obj != NULL) {
487 int err = visit(obj, arg);
488 if (err)
489 return err;
490 }
491 }
492 }
493 return 0;
494}
495
496static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000497subtype_traverse(PyObject *self, visitproc visit, void *arg)
498{
499 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000500 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000501
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000502 /* Find the nearest base with a different tp_traverse,
503 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000504 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000505 base = type;
506 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
507 if (base->ob_size) {
508 int err = traverse_slots(base, self, visit, arg);
509 if (err)
510 return err;
511 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000512 base = base->tp_base;
513 assert(base);
514 }
515
516 if (type->tp_dictoffset != base->tp_dictoffset) {
517 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000518 if (dictptr && *dictptr)
519 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000520 }
521
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000522 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000523 /* For a heaptype, the instances count as references
Guido van Rossumd8faa362007-04-27 19:54:29 +0000524 to the type. Traverse the type so the collector
Guido van Rossuma3862092002-06-10 15:24:42 +0000525 can find cycles involving this link. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000526 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000527
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000528 if (basetraverse)
529 return basetraverse(self, visit, arg);
530 return 0;
531}
532
533static void
534clear_slots(PyTypeObject *type, PyObject *self)
535{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000536 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000537 PyMemberDef *mp;
538
539 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000540 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000541 for (i = 0; i < n; i++, mp++) {
542 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
543 char *addr = (char *)self + mp->offset;
544 PyObject *obj = *(PyObject **)addr;
545 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000546 *(PyObject **)addr = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000547 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000548 }
549 }
550 }
551}
552
553static int
554subtype_clear(PyObject *self)
555{
556 PyTypeObject *type, *base;
557 inquiry baseclear;
558
559 /* Find the nearest base with a different tp_clear
560 and clear slots while we're at it */
561 type = self->ob_type;
562 base = type;
563 while ((baseclear = base->tp_clear) == subtype_clear) {
564 if (base->ob_size)
565 clear_slots(base, self);
566 base = base->tp_base;
567 assert(base);
568 }
569
Guido van Rossuma3862092002-06-10 15:24:42 +0000570 /* There's no need to clear the instance dict (if any);
571 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000572
573 if (baseclear)
574 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000575 return 0;
576}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000577
578static void
579subtype_dealloc(PyObject *self)
580{
Guido van Rossum14227b42001-12-06 02:35:58 +0000581 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000582 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000583
Guido van Rossum22b13872002-08-06 21:41:44 +0000584 /* Extract the type; we expect it to be a heap type */
585 type = self->ob_type;
586 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000587
Guido van Rossum22b13872002-08-06 21:41:44 +0000588 /* Test whether the type has GC exactly once */
589
590 if (!PyType_IS_GC(type)) {
591 /* It's really rare to find a dynamic type that doesn't have
592 GC; it can only happen when deriving from 'object' and not
593 adding any slots or instance variables. This allows
594 certain simplifications: there's no need to call
595 clear_slots(), or DECREF the dict, or clear weakrefs. */
596
597 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000598 if (type->tp_del) {
599 type->tp_del(self);
600 if (self->ob_refcnt > 0)
601 return;
602 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000603
604 /* Find the nearest base with a different tp_dealloc */
605 base = type;
606 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
607 assert(base->ob_size == 0);
608 base = base->tp_base;
609 assert(base);
610 }
611
612 /* Call the base tp_dealloc() */
613 assert(basedealloc);
614 basedealloc(self);
615
616 /* Can't reference self beyond this point */
617 Py_DECREF(type);
618
619 /* Done */
620 return;
621 }
622
623 /* We get here only if the type has GC */
624
625 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000626 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000627 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000628 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000629 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000630 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000631 /* DO NOT restore GC tracking at this point. weakref callbacks
632 * (if any, and whether directly here or indirectly in something we
633 * call) may trigger GC, and if self is tracked at that point, it
634 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000635 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000636
Guido van Rossum59195fd2003-06-13 20:54:40 +0000637 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000638 base = type;
639 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000640 base = base->tp_base;
641 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000642 }
643
Guido van Rossumd8faa362007-04-27 19:54:29 +0000644 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000645 the finalizer (__del__), clearing slots, or clearing the instance
646 dict. */
647
Guido van Rossum1987c662003-05-29 14:29:23 +0000648 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
649 PyObject_ClearWeakRefs(self);
650
651 /* Maybe call finalizer; exit early if resurrected */
652 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000653 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000654 type->tp_del(self);
655 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000656 goto endlabel; /* resurrected */
657 else
658 _PyObject_GC_UNTRACK(self);
Thomas Woutersb2137042007-02-01 18:02:27 +0000659 /* New weakrefs could be created during the finalizer call.
660 If this occurs, clear them out without calling their
661 finalizers since they might rely on part of the object
662 being finalized that has already been destroyed. */
663 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
664 /* Modeled after GET_WEAKREFS_LISTPTR() */
665 PyWeakReference **list = (PyWeakReference **) \
666 PyObject_GET_WEAKREFS_LISTPTR(self);
667 while (*list)
668 _PyWeakref_ClearRef(*list);
669 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000670 }
671
Guido van Rossum59195fd2003-06-13 20:54:40 +0000672 /* Clear slots up to the nearest base with a different tp_dealloc */
673 base = type;
674 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
675 if (base->ob_size)
676 clear_slots(base, self);
677 base = base->tp_base;
678 assert(base);
679 }
680
Tim Peters6d6c1a32001-08-02 04:15:00 +0000681 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000682 if (type->tp_dictoffset && !base->tp_dictoffset) {
683 PyObject **dictptr = _PyObject_GetDictPtr(self);
684 if (dictptr != NULL) {
685 PyObject *dict = *dictptr;
686 if (dict != NULL) {
687 Py_DECREF(dict);
688 *dictptr = NULL;
689 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000690 }
691 }
692
Tim Peters0bd743c2003-11-13 22:50:00 +0000693 /* Call the base tp_dealloc(); first retrack self if
694 * basedealloc knows about gc.
695 */
696 if (PyType_IS_GC(base))
697 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000698 assert(basedealloc);
699 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000700
701 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000702 Py_DECREF(type);
703
Guido van Rossum0906e072002-08-07 20:42:09 +0000704 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000705 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000706 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000707 --_PyTrash_delete_nesting;
708
709 /* Explanation of the weirdness around the trashcan macros:
710
711 Q. What do the trashcan macros do?
712
713 A. Read the comment titled "Trashcan mechanism" in object.h.
714 For one, this explains why there must be a call to GC-untrack
Guido van Rossumd8faa362007-04-27 19:54:29 +0000715 before the trashcan begin macro. Without understanding the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000716 trashcan code, the answers to the following questions don't make
717 sense.
718
719 Q. Why do we GC-untrack before the trashcan and then immediately
720 GC-track again afterward?
721
722 A. In the case that the base class is GC-aware, the base class
Guido van Rossumd8faa362007-04-27 19:54:29 +0000723 probably GC-untracks the object. If it does that using the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000724 UNTRACK macro, this will crash when the object is already
725 untracked. Because we don't know what the base class does, the
726 only safe thing is to make sure the object is tracked when we
727 call the base class dealloc. But... The trashcan begin macro
728 requires that the object is *untracked* before it is called. So
729 the dance becomes:
730
Guido van Rossumd8faa362007-04-27 19:54:29 +0000731 GC untrack
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000732 trashcan begin
733 GC track
734
Guido van Rossumd8faa362007-04-27 19:54:29 +0000735 Q. Why did the last question say "immediately GC-track again"?
736 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +0000737
Guido van Rossumd8faa362007-04-27 19:54:29 +0000738 A. Because the code *used* to re-track immediately. Bad Idea.
739 self has a refcount of 0, and if gc ever gets its hands on it
740 (which can happen if any weakref callback gets invoked), it
741 looks like trash to gc too, and gc also tries to delete self
742 then. But we're already deleting self. Double dealloction is
743 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +0000744
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000745 Q. Why the bizarre (net-zero) manipulation of
746 _PyTrash_delete_nesting around the trashcan macros?
747
748 A. Some base classes (e.g. list) also use the trashcan mechanism.
749 The following scenario used to be possible:
750
751 - suppose the trashcan level is one below the trashcan limit
752
753 - subtype_dealloc() is called
754
755 - the trashcan limit is not yet reached, so the trashcan level
Guido van Rossumd8faa362007-04-27 19:54:29 +0000756 is incremented and the code between trashcan begin and end is
757 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000758
759 - this destroys much of the object's contents, including its
Guido van Rossumd8faa362007-04-27 19:54:29 +0000760 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000761
762 - basedealloc() is called; this is really list_dealloc(), or
Guido van Rossumd8faa362007-04-27 19:54:29 +0000763 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000764
765 - the trashcan limit is now reached, so the object is put on the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000766 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000767
768 - basedealloc() returns
769
770 - subtype_dealloc() decrefs the object's type
771
772 - subtype_dealloc() returns
773
774 - later, the trashcan code starts deleting the objects from its
Guido van Rossumd8faa362007-04-27 19:54:29 +0000775 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000776
777 - subtype_dealloc() is called *AGAIN* for the same object
778
779 - at the very least (if the destroyed slots and __dict__ don't
Guido van Rossumd8faa362007-04-27 19:54:29 +0000780 cause problems) the object's type gets decref'ed a second
781 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000782
783 The remedy is to make sure that if the code between trashcan
784 begin and end in subtype_dealloc() is called, the code between
785 trashcan begin and end in basedealloc() will also be called.
786 This is done by decrementing the level after passing into the
787 trashcan block, and incrementing it just before leaving the
788 block.
789
790 But now it's possible that a chain of objects consisting solely
791 of objects whose deallocator is subtype_dealloc() will defeat
792 the trashcan mechanism completely: the decremented level means
Guido van Rossumd8faa362007-04-27 19:54:29 +0000793 that the effective level never reaches the limit. Therefore, we
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000794 *increment* the level *before* entering the trashcan block, and
795 matchingly decrement it after leaving. This means the trashcan
796 code will trigger a little early, but that's no big deal.
797
798 Q. Are there any live examples of code in need of all this
799 complexity?
800
801 A. Yes. See SF bug 668433 for code that crashed (when Python was
802 compiled in debug mode) before the trashcan level manipulations
803 were added. For more discussion, see SF patches 581742, 575073
804 and bug 574207.
805 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000806}
807
Jeremy Hylton938ace62002-07-17 16:30:39 +0000808static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000809
Tim Peters6d6c1a32001-08-02 04:15:00 +0000810/* type test with subclassing support */
811
812int
813PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
814{
815 PyObject *mro;
816
817 mro = a->tp_mro;
818 if (mro != NULL) {
819 /* Deal with multiple inheritance without recursion
820 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000821 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000822 assert(PyTuple_Check(mro));
823 n = PyTuple_GET_SIZE(mro);
824 for (i = 0; i < n; i++) {
825 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
826 return 1;
827 }
828 return 0;
829 }
830 else {
831 /* a is not completely initilized yet; follow tp_base */
832 do {
833 if (a == b)
834 return 1;
835 a = a->tp_base;
836 } while (a != NULL);
837 return b == &PyBaseObject_Type;
838 }
839}
840
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000841/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000842 without looking in the instance dictionary
843 (so we can't use PyObject_GetAttr) but still binding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000844 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +0000845 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000846 static variable used to cache the interned Python string.
847
848 Two variants:
849
850 - lookup_maybe() returns NULL without raising an exception
851 when the _PyType_Lookup() call fails;
852
853 - lookup_method() always raises an exception upon errors.
854*/
Guido van Rossum60718732001-08-28 17:47:51 +0000855
856static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000857lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000858{
859 PyObject *res;
860
861 if (*attrobj == NULL) {
862 *attrobj = PyString_InternFromString(attrstr);
863 if (*attrobj == NULL)
864 return NULL;
865 }
866 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000867 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000868 descrgetfunc f;
869 if ((f = res->ob_type->tp_descr_get) == NULL)
870 Py_INCREF(res);
871 else
872 res = f(res, self, (PyObject *)(self->ob_type));
873 }
874 return res;
875}
876
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000877static PyObject *
878lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
879{
880 PyObject *res = lookup_maybe(self, attrstr, attrobj);
881 if (res == NULL && !PyErr_Occurred())
882 PyErr_SetObject(PyExc_AttributeError, *attrobj);
883 return res;
884}
885
Guido van Rossum2730b132001-08-28 18:22:14 +0000886/* A variation of PyObject_CallMethod that uses lookup_method()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000887 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +0000888 as lookup_method to cache the interned name string object. */
889
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000890static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000891call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
892{
893 va_list va;
894 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000895 va_start(va, format);
896
Guido van Rossumda21c012001-10-03 00:50:18 +0000897 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000898 if (func == NULL) {
899 va_end(va);
900 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000901 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000902 return NULL;
903 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000904
905 if (format && *format)
906 args = Py_VaBuildValue(format, va);
907 else
908 args = PyTuple_New(0);
909
910 va_end(va);
911
912 if (args == NULL)
913 return NULL;
914
915 assert(PyTuple_Check(args));
916 retval = PyObject_Call(func, args, NULL);
917
918 Py_DECREF(args);
919 Py_DECREF(func);
920
921 return retval;
922}
923
924/* Clone of call_method() that returns NotImplemented when the lookup fails. */
925
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000926static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000927call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
928{
929 va_list va;
930 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000931 va_start(va, format);
932
Guido van Rossumda21c012001-10-03 00:50:18 +0000933 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000934 if (func == NULL) {
935 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000936 if (!PyErr_Occurred()) {
937 Py_INCREF(Py_NotImplemented);
938 return Py_NotImplemented;
939 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000940 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000941 }
942
943 if (format && *format)
944 args = Py_VaBuildValue(format, va);
945 else
946 args = PyTuple_New(0);
947
948 va_end(va);
949
Guido van Rossum717ce002001-09-14 16:58:08 +0000950 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000951 return NULL;
952
Guido van Rossum717ce002001-09-14 16:58:08 +0000953 assert(PyTuple_Check(args));
954 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000955
956 Py_DECREF(args);
957 Py_DECREF(func);
958
959 return retval;
960}
961
Tim Petersea7f75d2002-12-07 21:39:16 +0000962/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000963 Method resolution order algorithm C3 described in
964 "A Monotonic Superclass Linearization for Dylan",
965 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000966 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000967 (OOPSLA 1996)
968
Guido van Rossum98f33732002-11-25 21:36:54 +0000969 Some notes about the rules implied by C3:
970
Tim Petersea7f75d2002-12-07 21:39:16 +0000971 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +0000972 It isn't legal to repeat a class in a list of base classes.
973
974 The next three properties are the 3 constraints in "C3".
975
Tim Petersea7f75d2002-12-07 21:39:16 +0000976 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +0000977 If A precedes B in C's MRO, then A will precede B in the MRO of all
978 subclasses of C.
979
980 Monotonicity.
981 The MRO of a class must be an extension without reordering of the
982 MRO of each of its superclasses.
983
984 Extended Precedence Graph (EPG).
985 Linearization is consistent if there is a path in the EPG from
986 each class to all its successors in the linearization. See
987 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +0000988 */
989
Tim Petersea7f75d2002-12-07 21:39:16 +0000990static int
Guido van Rossum1f121312002-11-14 19:49:16 +0000991tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000992 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +0000993 size = PyList_GET_SIZE(list);
994
995 for (j = whence+1; j < size; j++) {
996 if (PyList_GET_ITEM(list, j) == o)
997 return 1;
998 }
999 return 0;
1000}
1001
Guido van Rossum98f33732002-11-25 21:36:54 +00001002static PyObject *
1003class_name(PyObject *cls)
1004{
1005 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1006 if (name == NULL) {
1007 PyErr_Clear();
1008 Py_XDECREF(name);
1009 name = PyObject_Repr(cls);
1010 }
1011 if (name == NULL)
1012 return NULL;
1013 if (!PyString_Check(name)) {
1014 Py_DECREF(name);
1015 return NULL;
1016 }
1017 return name;
1018}
1019
1020static int
1021check_duplicates(PyObject *list)
1022{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001023 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001024 /* Let's use a quadratic time algorithm,
1025 assuming that the bases lists is short.
1026 */
1027 n = PyList_GET_SIZE(list);
1028 for (i = 0; i < n; i++) {
1029 PyObject *o = PyList_GET_ITEM(list, i);
1030 for (j = i + 1; j < n; j++) {
1031 if (PyList_GET_ITEM(list, j) == o) {
1032 o = class_name(o);
1033 PyErr_Format(PyExc_TypeError,
1034 "duplicate base class %s",
1035 o ? PyString_AS_STRING(o) : "?");
1036 Py_XDECREF(o);
1037 return -1;
1038 }
1039 }
1040 }
1041 return 0;
1042}
1043
1044/* Raise a TypeError for an MRO order disagreement.
1045
1046 It's hard to produce a good error message. In the absence of better
1047 insight into error reporting, report the classes that were candidates
Guido van Rossumd8faa362007-04-27 19:54:29 +00001048 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001049 order in which they should be put in the MRO, but it's hard to
1050 diagnose what constraint can't be satisfied.
1051*/
1052
1053static void
1054set_mro_error(PyObject *to_merge, int *remain)
1055{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001056 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001057 char buf[1000];
1058 PyObject *k, *v;
1059 PyObject *set = PyDict_New();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001060 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001061
1062 to_merge_size = PyList_GET_SIZE(to_merge);
1063 for (i = 0; i < to_merge_size; i++) {
1064 PyObject *L = PyList_GET_ITEM(to_merge, i);
1065 if (remain[i] < PyList_GET_SIZE(L)) {
1066 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001067 if (PyDict_SetItem(set, c, Py_None) < 0) {
1068 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001069 return;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001070 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001071 }
1072 }
1073 n = PyDict_Size(set);
1074
Raymond Hettingerf394df42003-04-06 19:13:41 +00001075 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1076consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001077 i = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001078 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001079 PyObject *name = class_name(k);
1080 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1081 name ? PyString_AS_STRING(name) : "?");
1082 Py_XDECREF(name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001083 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001084 buf[off++] = ',';
1085 buf[off] = '\0';
1086 }
1087 }
1088 PyErr_SetString(PyExc_TypeError, buf);
1089 Py_DECREF(set);
1090}
1091
Tim Petersea7f75d2002-12-07 21:39:16 +00001092static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001093pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001094 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001095 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001096 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001097
Guido van Rossum1f121312002-11-14 19:49:16 +00001098 to_merge_size = PyList_GET_SIZE(to_merge);
1099
Guido van Rossum98f33732002-11-25 21:36:54 +00001100 /* remain stores an index into each sublist of to_merge.
1101 remain[i] is the index of the next base in to_merge[i]
1102 that is not included in acc.
1103 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001104 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001105 if (remain == NULL)
1106 return -1;
1107 for (i = 0; i < to_merge_size; i++)
1108 remain[i] = 0;
1109
1110 again:
1111 empty_cnt = 0;
1112 for (i = 0; i < to_merge_size; i++) {
1113 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001114
Guido van Rossum1f121312002-11-14 19:49:16 +00001115 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1116
1117 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1118 empty_cnt++;
1119 continue;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001120 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001121
Guido van Rossum98f33732002-11-25 21:36:54 +00001122 /* Choose next candidate for MRO.
1123
1124 The input sequences alone can determine the choice.
1125 If not, choose the class which appears in the MRO
1126 of the earliest direct superclass of the new class.
1127 */
1128
Guido van Rossum1f121312002-11-14 19:49:16 +00001129 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1130 for (j = 0; j < to_merge_size; j++) {
1131 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001132 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001133 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001134 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001135 }
1136 ok = PyList_Append(acc, candidate);
1137 if (ok < 0) {
1138 PyMem_Free(remain);
1139 return -1;
1140 }
1141 for (j = 0; j < to_merge_size; j++) {
1142 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001143 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1144 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001145 remain[j]++;
1146 }
1147 }
1148 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001149 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001150 }
1151
Guido van Rossum98f33732002-11-25 21:36:54 +00001152 if (empty_cnt == to_merge_size) {
1153 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001154 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001155 }
1156 set_mro_error(to_merge, remain);
1157 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001158 return -1;
1159}
1160
Tim Peters6d6c1a32001-08-02 04:15:00 +00001161static PyObject *
1162mro_implementation(PyTypeObject *type)
1163{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001164 Py_ssize_t i, n;
1165 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001166 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001167 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001168
Guido van Rossum63517572002-06-18 16:44:57 +00001169 if(type->tp_dict == NULL) {
1170 if(PyType_Ready(type) < 0)
1171 return NULL;
1172 }
1173
Guido van Rossum98f33732002-11-25 21:36:54 +00001174 /* Find a superclass linearization that honors the constraints
1175 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001176 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001177
1178 to_merge is a list of lists, where each list is a superclass
1179 linearization implied by a base class. The last element of
1180 to_merge is the declared list of bases.
1181 */
1182
Tim Peters6d6c1a32001-08-02 04:15:00 +00001183 bases = type->tp_bases;
1184 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001185
1186 to_merge = PyList_New(n+1);
1187 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001188 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001189
Tim Peters6d6c1a32001-08-02 04:15:00 +00001190 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001191 PyObject *base = PyTuple_GET_ITEM(bases, i);
1192 PyObject *parentMRO;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001193 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001194 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001195 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001196 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001197 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001198
1199 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001200 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001201
1202 bases_aslist = PySequence_List(bases);
1203 if (bases_aslist == NULL) {
1204 Py_DECREF(to_merge);
1205 return NULL;
1206 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001207 /* This is just a basic sanity check. */
1208 if (check_duplicates(bases_aslist) < 0) {
1209 Py_DECREF(to_merge);
1210 Py_DECREF(bases_aslist);
1211 return NULL;
1212 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001213 PyList_SET_ITEM(to_merge, n, bases_aslist);
1214
1215 result = Py_BuildValue("[O]", (PyObject *)type);
1216 if (result == NULL) {
1217 Py_DECREF(to_merge);
1218 return NULL;
1219 }
1220
1221 ok = pmerge(result, to_merge);
1222 Py_DECREF(to_merge);
1223 if (ok < 0) {
1224 Py_DECREF(result);
1225 return NULL;
1226 }
1227
Tim Peters6d6c1a32001-08-02 04:15:00 +00001228 return result;
1229}
1230
1231static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001232mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001233{
1234 PyTypeObject *type = (PyTypeObject *)self;
1235
Tim Peters6d6c1a32001-08-02 04:15:00 +00001236 return mro_implementation(type);
1237}
1238
1239static int
1240mro_internal(PyTypeObject *type)
1241{
1242 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001243 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001244
1245 if (type->ob_type == &PyType_Type) {
1246 result = mro_implementation(type);
1247 }
1248 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001249 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001250 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001251 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001252 if (mro == NULL)
1253 return -1;
1254 result = PyObject_CallObject(mro, NULL);
1255 Py_DECREF(mro);
1256 }
1257 if (result == NULL)
1258 return -1;
1259 tuple = PySequence_Tuple(result);
1260 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001261 if (tuple == NULL)
1262 return -1;
1263 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001264 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001265 PyObject *cls;
1266 PyTypeObject *solid;
1267
1268 solid = solid_base(type);
1269
1270 len = PyTuple_GET_SIZE(tuple);
1271
1272 for (i = 0; i < len; i++) {
1273 PyTypeObject *t;
1274 cls = PyTuple_GET_ITEM(tuple, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001275 if (!PyType_Check(cls)) {
Armin Rigo037d1e02005-12-29 17:07:39 +00001276 PyErr_Format(PyExc_TypeError,
1277 "mro() returned a non-class ('%.500s')",
1278 cls->ob_type->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001279 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001280 return -1;
1281 }
1282 t = (PyTypeObject*)cls;
1283 if (!PyType_IsSubtype(solid, solid_base(t))) {
1284 PyErr_Format(PyExc_TypeError,
1285 "mro() returned base with unsuitable layout ('%.500s')",
1286 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001287 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001288 return -1;
1289 }
1290 }
1291 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001292 type->tp_mro = tuple;
1293 return 0;
1294}
1295
1296
1297/* Calculate the best base amongst multiple base classes.
1298 This is the first one that's on the path to the "solid base". */
1299
1300static PyTypeObject *
1301best_base(PyObject *bases)
1302{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001303 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001304 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001305 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306
1307 assert(PyTuple_Check(bases));
1308 n = PyTuple_GET_SIZE(bases);
1309 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001310 base = NULL;
1311 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001312 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001313 base_proto = PyTuple_GET_ITEM(bases, i);
Tim Petersa91e9642001-11-14 23:32:33 +00001314 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001315 PyErr_SetString(
1316 PyExc_TypeError,
1317 "bases must be types");
1318 return NULL;
1319 }
Tim Petersa91e9642001-11-14 23:32:33 +00001320 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001321 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001322 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001323 return NULL;
1324 }
1325 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001326 if (winner == NULL) {
1327 winner = candidate;
1328 base = base_i;
1329 }
1330 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001331 ;
1332 else if (PyType_IsSubtype(candidate, winner)) {
1333 winner = candidate;
1334 base = base_i;
1335 }
1336 else {
1337 PyErr_SetString(
1338 PyExc_TypeError,
1339 "multiple bases have "
1340 "instance lay-out conflict");
1341 return NULL;
1342 }
1343 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001344 if (base == NULL)
1345 PyErr_SetString(PyExc_TypeError,
1346 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001347 return base;
1348}
1349
1350static int
1351extra_ivars(PyTypeObject *type, PyTypeObject *base)
1352{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001353 size_t t_size = type->tp_basicsize;
1354 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001355
Guido van Rossum9676b222001-08-17 20:32:36 +00001356 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001357 if (type->tp_itemsize || base->tp_itemsize) {
1358 /* If itemsize is involved, stricter rules */
1359 return t_size != b_size ||
1360 type->tp_itemsize != base->tp_itemsize;
1361 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001362 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
Guido van Rossum360e4b82007-05-14 22:51:27 +00001363 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1364 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001365 t_size -= sizeof(PyObject *);
1366 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
Guido van Rossum360e4b82007-05-14 22:51:27 +00001367 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1368 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001369 t_size -= sizeof(PyObject *);
1370
1371 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001372}
1373
1374static PyTypeObject *
1375solid_base(PyTypeObject *type)
1376{
1377 PyTypeObject *base;
1378
1379 if (type->tp_base)
1380 base = solid_base(type->tp_base);
1381 else
1382 base = &PyBaseObject_Type;
1383 if (extra_ivars(type, base))
1384 return type;
1385 else
1386 return base;
1387}
1388
Jeremy Hylton938ace62002-07-17 16:30:39 +00001389static void object_dealloc(PyObject *);
1390static int object_init(PyObject *, PyObject *, PyObject *);
1391static int update_slot(PyTypeObject *, PyObject *);
1392static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001393
Guido van Rossum360e4b82007-05-14 22:51:27 +00001394/*
1395 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1396 * inherited from various builtin types. The builtin base usually provides
1397 * its own __dict__ descriptor, so we use that when we can.
1398 */
1399static PyTypeObject *
1400get_builtin_base_with_dict(PyTypeObject *type)
1401{
1402 while (type->tp_base != NULL) {
1403 if (type->tp_dictoffset != 0 &&
1404 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1405 return type;
1406 type = type->tp_base;
1407 }
1408 return NULL;
1409}
1410
1411static PyObject *
1412get_dict_descriptor(PyTypeObject *type)
1413{
1414 static PyObject *dict_str;
1415 PyObject *descr;
1416
1417 if (dict_str == NULL) {
1418 dict_str = PyString_InternFromString("__dict__");
1419 if (dict_str == NULL)
1420 return NULL;
1421 }
1422 descr = _PyType_Lookup(type, dict_str);
1423 if (descr == NULL || !PyDescr_IsData(descr))
1424 return NULL;
1425
1426 return descr;
1427}
1428
1429static void
1430raise_dict_descr_error(PyObject *obj)
1431{
1432 PyErr_Format(PyExc_TypeError,
1433 "this __dict__ descriptor does not support "
1434 "'%.200s' objects", obj->ob_type->tp_name);
1435}
1436
Tim Peters6d6c1a32001-08-02 04:15:00 +00001437static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001438subtype_dict(PyObject *obj, void *context)
1439{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001440 PyObject **dictptr;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001441 PyObject *dict;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001442 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001443
Guido van Rossum360e4b82007-05-14 22:51:27 +00001444 base = get_builtin_base_with_dict(obj->ob_type);
1445 if (base != NULL) {
1446 descrgetfunc func;
1447 PyObject *descr = get_dict_descriptor(base);
1448 if (descr == NULL) {
1449 raise_dict_descr_error(obj);
1450 return NULL;
1451 }
1452 func = descr->ob_type->tp_descr_get;
1453 if (func == NULL) {
1454 raise_dict_descr_error(obj);
1455 return NULL;
1456 }
1457 return func(descr, obj, (PyObject *)(obj->ob_type));
1458 }
1459
1460 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001461 if (dictptr == NULL) {
1462 PyErr_SetString(PyExc_AttributeError,
1463 "This object has no __dict__");
1464 return NULL;
1465 }
1466 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001467 if (dict == NULL)
1468 *dictptr = dict = PyDict_New();
1469 Py_XINCREF(dict);
1470 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001471}
1472
Guido van Rossum6661be32001-10-26 04:26:12 +00001473static int
1474subtype_setdict(PyObject *obj, PyObject *value, void *context)
1475{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001476 PyObject **dictptr;
Guido van Rossum6661be32001-10-26 04:26:12 +00001477 PyObject *dict;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001478 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001479
Guido van Rossum360e4b82007-05-14 22:51:27 +00001480 base = get_builtin_base_with_dict(obj->ob_type);
1481 if (base != NULL) {
1482 descrsetfunc func;
1483 PyObject *descr = get_dict_descriptor(base);
1484 if (descr == NULL) {
1485 raise_dict_descr_error(obj);
1486 return -1;
1487 }
1488 func = descr->ob_type->tp_descr_set;
1489 if (func == NULL) {
1490 raise_dict_descr_error(obj);
1491 return -1;
1492 }
1493 return func(descr, obj, value);
1494 }
1495
1496 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6661be32001-10-26 04:26:12 +00001497 if (dictptr == NULL) {
1498 PyErr_SetString(PyExc_AttributeError,
1499 "This object has no __dict__");
1500 return -1;
1501 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001502 if (value != NULL && !PyDict_Check(value)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001503 PyErr_Format(PyExc_TypeError,
1504 "__dict__ must be set to a dictionary, "
1505 "not a '%.200s'", value->ob_type->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001506 return -1;
1507 }
1508 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001509 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001510 *dictptr = value;
1511 Py_XDECREF(dict);
1512 return 0;
1513}
1514
Guido van Rossumad47da02002-08-12 19:05:44 +00001515static PyObject *
1516subtype_getweakref(PyObject *obj, void *context)
1517{
1518 PyObject **weaklistptr;
1519 PyObject *result;
1520
1521 if (obj->ob_type->tp_weaklistoffset == 0) {
1522 PyErr_SetString(PyExc_AttributeError,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001523 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001524 return NULL;
1525 }
1526 assert(obj->ob_type->tp_weaklistoffset > 0);
1527 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001528 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001529 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001530 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001531 if (*weaklistptr == NULL)
1532 result = Py_None;
1533 else
1534 result = *weaklistptr;
1535 Py_INCREF(result);
1536 return result;
1537}
1538
Guido van Rossum373c7412003-01-07 13:41:37 +00001539/* Three variants on the subtype_getsets list. */
1540
1541static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001542 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001543 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001544 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001545 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001546 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001547};
1548
Guido van Rossum373c7412003-01-07 13:41:37 +00001549static PyGetSetDef subtype_getsets_dict_only[] = {
1550 {"__dict__", subtype_dict, subtype_setdict,
1551 PyDoc_STR("dictionary for instance variables (if defined)")},
1552 {0}
1553};
1554
1555static PyGetSetDef subtype_getsets_weakref_only[] = {
1556 {"__weakref__", subtype_getweakref, NULL,
1557 PyDoc_STR("list of weak references to the object (if defined)")},
1558 {0}
1559};
1560
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001561static int
1562valid_identifier(PyObject *s)
1563{
Guido van Rossum03013a02002-07-16 14:30:28 +00001564 unsigned char *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001565 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001566
1567 if (!PyString_Check(s)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001568 PyErr_Format(PyExc_TypeError,
1569 "__slots__ items must be strings, not '%.200s'",
1570 s->ob_type->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001571 return 0;
1572 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001573 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001574 n = PyString_GET_SIZE(s);
1575 /* We must reject an empty name. As a hack, we bump the
1576 length to 1 so that the loop will balk on the trailing \0. */
1577 if (n == 0)
1578 n = 1;
1579 for (i = 0; i < n; i++, p++) {
1580 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1581 PyErr_SetString(PyExc_TypeError,
1582 "__slots__ must be identifiers");
1583 return 0;
1584 }
1585 }
1586 return 1;
1587}
1588
Martin v. Löwisd919a592002-10-14 21:07:28 +00001589/* Replace Unicode objects in slots. */
1590
1591static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001592_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001593{
Guido van Rossumd8faa362007-04-27 19:54:29 +00001594 PyObject *tmp = NULL;
1595 PyObject *slot_name, *new_name;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001596 Py_ssize_t i;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001597
Martin v. Löwisd919a592002-10-14 21:07:28 +00001598 for (i = 0; i < nslots; i++) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00001599 if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
1600 if (tmp == NULL) {
1601 tmp = PySequence_List(slots);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001602 if (tmp == NULL)
1603 return NULL;
1604 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001605 new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
1606 NULL);
1607 if (new_name == NULL) {
Martin v. Löwisd919a592002-10-14 21:07:28 +00001608 Py_DECREF(tmp);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001609 return NULL;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001610 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001611 Py_INCREF(new_name);
1612 PyList_SET_ITEM(tmp, i, new_name);
1613 Py_DECREF(slot_name);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001614 }
1615 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001616 if (tmp != NULL) {
1617 slots = PyList_AsTuple(tmp);
1618 Py_DECREF(tmp);
1619 }
1620 return slots;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001621}
Martin v. Löwisd919a592002-10-14 21:07:28 +00001622
Guido van Rossumd8faa362007-04-27 19:54:29 +00001623/* Forward */
1624static int
1625object_init(PyObject *self, PyObject *args, PyObject *kwds);
1626
1627static int
1628type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1629{
1630 int res;
1631
1632 assert(args != NULL && PyTuple_Check(args));
1633 assert(kwds == NULL || PyDict_Check(kwds));
1634
1635 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1636 PyErr_SetString(PyExc_TypeError,
1637 "type.__init__() takes no keyword arguments");
1638 return -1;
1639 }
1640
1641 if (args != NULL && PyTuple_Check(args) &&
1642 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1643 PyErr_SetString(PyExc_TypeError,
1644 "type.__init__() takes 1 or 3 arguments");
1645 return -1;
1646 }
1647
1648 /* Call object.__init__(self) now. */
1649 /* XXX Could call super(type, cls).__init__() but what's the point? */
1650 args = PyTuple_GetSlice(args, 0, 0);
1651 res = object_init(cls, args, NULL);
1652 Py_DECREF(args);
1653 return res;
1654}
1655
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001656static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001657type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1658{
1659 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001660 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001661 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001662 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001663 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001664 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001665 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001666 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001667
Tim Peters3abca122001-10-27 19:37:48 +00001668 assert(args != NULL && PyTuple_Check(args));
1669 assert(kwds == NULL || PyDict_Check(kwds));
1670
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001671 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001672 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001673 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1674 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001675
1676 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1677 PyObject *x = PyTuple_GET_ITEM(args, 0);
1678 Py_INCREF(x->ob_type);
1679 return (PyObject *) x->ob_type;
1680 }
1681
1682 /* SF bug 475327 -- if that didn't trigger, we need 3
1683 arguments. but PyArg_ParseTupleAndKeywords below may give
1684 a msg saying type() needs exactly 3. */
1685 if (nargs + nkwds != 3) {
1686 PyErr_SetString(PyExc_TypeError,
1687 "type() takes 1 or 3 arguments");
1688 return NULL;
1689 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001690 }
1691
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001692 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001693 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1694 &name,
1695 &PyTuple_Type, &bases,
1696 &PyDict_Type, &dict))
1697 return NULL;
1698
1699 /* Determine the proper metatype to deal with this,
1700 and check for metatype conflicts while we're at it.
1701 Note that if some other metatype wins to contract,
1702 it's possible that its instances are not types. */
1703 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001704 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001705 for (i = 0; i < nbases; i++) {
1706 tmp = PyTuple_GET_ITEM(bases, i);
1707 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001708 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001709 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001710 if (PyType_IsSubtype(tmptype, winner)) {
1711 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001712 continue;
1713 }
1714 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001715 "metaclass conflict: "
1716 "the metaclass of a derived class "
1717 "must be a (non-strict) subclass "
1718 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001719 return NULL;
1720 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001721 if (winner != metatype) {
1722 if (winner->tp_new != type_new) /* Pass it to the winner */
1723 return winner->tp_new(winner, args, kwds);
1724 metatype = winner;
1725 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001726
1727 /* Adjust for empty tuple bases */
1728 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001729 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001730 if (bases == NULL)
1731 return NULL;
1732 nbases = 1;
1733 }
1734 else
1735 Py_INCREF(bases);
1736
1737 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1738
1739 /* Calculate best base, and check that all bases are type objects */
1740 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001741 if (base == NULL) {
1742 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001743 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001744 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001745 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1746 PyErr_Format(PyExc_TypeError,
1747 "type '%.100s' is not an acceptable base type",
1748 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001749 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001750 return NULL;
1751 }
1752
Tim Peters6d6c1a32001-08-02 04:15:00 +00001753 /* Check for a __slots__ sequence variable in dict, and count it */
1754 slots = PyDict_GetItemString(dict, "__slots__");
1755 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001756 add_dict = 0;
1757 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001758 may_add_dict = base->tp_dictoffset == 0;
1759 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1760 if (slots == NULL) {
1761 if (may_add_dict) {
1762 add_dict++;
1763 }
1764 if (may_add_weak) {
1765 add_weak++;
1766 }
1767 }
1768 else {
1769 /* Have slots */
1770
Tim Peters6d6c1a32001-08-02 04:15:00 +00001771 /* Make it into a tuple */
Guido van Rossumd8faa362007-04-27 19:54:29 +00001772 if (PyString_Check(slots) || PyUnicode_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001773 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001774 else
1775 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001776 if (slots == NULL) {
1777 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001778 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001779 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001780 assert(PyTuple_Check(slots));
1781
1782 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001783 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001784 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001785 PyErr_Format(PyExc_TypeError,
1786 "nonempty __slots__ "
1787 "not supported for subtype of '%s'",
1788 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001789 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001790 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001791 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001792 return NULL;
1793 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001794
Martin v. Löwisd919a592002-10-14 21:07:28 +00001795 tmp = _unicode_to_string(slots, nslots);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001796 if (tmp == NULL)
1797 goto bad_slots;
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001798 if (tmp != slots) {
1799 Py_DECREF(slots);
1800 slots = tmp;
1801 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001802 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001803 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001804 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1805 char *s;
1806 if (!valid_identifier(tmp))
1807 goto bad_slots;
1808 assert(PyString_Check(tmp));
1809 s = PyString_AS_STRING(tmp);
1810 if (strcmp(s, "__dict__") == 0) {
1811 if (!may_add_dict || add_dict) {
1812 PyErr_SetString(PyExc_TypeError,
1813 "__dict__ slot disallowed: "
1814 "we already got one");
1815 goto bad_slots;
1816 }
1817 add_dict++;
1818 }
1819 if (strcmp(s, "__weakref__") == 0) {
1820 if (!may_add_weak || add_weak) {
1821 PyErr_SetString(PyExc_TypeError,
1822 "__weakref__ slot disallowed: "
1823 "either we already got one, "
1824 "or __itemsize__ != 0");
1825 goto bad_slots;
1826 }
1827 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001828 }
1829 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001830
Guido van Rossumd8faa362007-04-27 19:54:29 +00001831 /* Copy slots into a list, mangle names and sort them.
1832 Sorted names are needed for __class__ assignment.
1833 Convert them back to tuple at the end.
1834 */
1835 newslots = PyList_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001836 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001837 goto bad_slots;
1838 for (i = j = 0; i < nslots; i++) {
1839 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001840 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001841 s = PyString_AS_STRING(tmp);
1842 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1843 (add_weak && strcmp(s, "__weakref__") == 0))
1844 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001845 tmp =_Py_Mangle(name, tmp);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001846 if (!tmp)
1847 goto bad_slots;
1848 PyList_SET_ITEM(newslots, j, tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00001849 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001850 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001851 assert(j == nslots - add_dict - add_weak);
1852 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001853 Py_DECREF(slots);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001854 if (PyList_Sort(newslots) == -1) {
1855 Py_DECREF(bases);
1856 Py_DECREF(newslots);
1857 return NULL;
1858 }
1859 slots = PyList_AsTuple(newslots);
1860 Py_DECREF(newslots);
1861 if (slots == NULL) {
1862 Py_DECREF(bases);
1863 return NULL;
1864 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001865
Guido van Rossumad47da02002-08-12 19:05:44 +00001866 /* Secondary bases may provide weakrefs or dict */
1867 if (nbases > 1 &&
1868 ((may_add_dict && !add_dict) ||
1869 (may_add_weak && !add_weak))) {
1870 for (i = 0; i < nbases; i++) {
1871 tmp = PyTuple_GET_ITEM(bases, i);
1872 if (tmp == (PyObject *)base)
1873 continue; /* Skip primary base */
Guido van Rossumad47da02002-08-12 19:05:44 +00001874 assert(PyType_Check(tmp));
1875 tmptype = (PyTypeObject *)tmp;
1876 if (may_add_dict && !add_dict &&
1877 tmptype->tp_dictoffset != 0)
1878 add_dict++;
1879 if (may_add_weak && !add_weak &&
1880 tmptype->tp_weaklistoffset != 0)
1881 add_weak++;
1882 if (may_add_dict && !add_dict)
1883 continue;
1884 if (may_add_weak && !add_weak)
1885 continue;
1886 /* Nothing more to check */
1887 break;
1888 }
1889 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001890 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001891
1892 /* XXX From here until type is safely allocated,
1893 "return NULL" may leak slots! */
1894
1895 /* Allocate the type object */
1896 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001897 if (type == NULL) {
1898 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001899 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001900 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001901 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001902
1903 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001904 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001905 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00001906 et->ht_name = name;
1907 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001908
Guido van Rossumdc91b992001-08-08 22:26:22 +00001909 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001910 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1911 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001912 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1913 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001914
Guido van Rossumdc91b992001-08-08 22:26:22 +00001915 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001916 type->tp_as_number = &et->as_number;
1917 type->tp_as_sequence = &et->as_sequence;
1918 type->tp_as_mapping = &et->as_mapping;
1919 type->tp_as_buffer = &et->as_buffer;
1920 type->tp_name = PyString_AS_STRING(name);
1921
1922 /* Set tp_base and tp_bases */
1923 type->tp_bases = bases;
1924 Py_INCREF(base);
1925 type->tp_base = base;
1926
Guido van Rossum687ae002001-10-15 22:03:32 +00001927 /* Initialize tp_dict from passed-in dict */
1928 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001929 if (dict == NULL) {
1930 Py_DECREF(type);
1931 return NULL;
1932 }
1933
Guido van Rossumc3542212001-08-16 09:18:56 +00001934 /* Set __module__ in the dict */
1935 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1936 tmp = PyEval_GetGlobals();
1937 if (tmp != NULL) {
1938 tmp = PyDict_GetItemString(tmp, "__name__");
1939 if (tmp != NULL) {
1940 if (PyDict_SetItemString(dict, "__module__",
1941 tmp) < 0)
1942 return NULL;
1943 }
1944 }
1945 }
1946
Tim Peters2f93e282001-10-04 05:27:00 +00001947 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001948 and is a string. The __doc__ accessor will first look for tp_doc;
1949 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001950 */
1951 {
1952 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1953 if (doc != NULL && PyString_Check(doc)) {
1954 const size_t n = (size_t)PyString_GET_SIZE(doc);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001955 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001956 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00001957 Py_DECREF(type);
1958 return NULL;
1959 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001960 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001961 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00001962 }
1963 }
1964
Tim Peters6d6c1a32001-08-02 04:15:00 +00001965 /* Special-case __new__: if it's a plain function,
1966 make it a static function */
1967 tmp = PyDict_GetItemString(dict, "__new__");
1968 if (tmp != NULL && PyFunction_Check(tmp)) {
1969 tmp = PyStaticMethod_New(tmp);
1970 if (tmp == NULL) {
1971 Py_DECREF(type);
1972 return NULL;
1973 }
1974 PyDict_SetItemString(dict, "__new__", tmp);
1975 Py_DECREF(tmp);
1976 }
1977
1978 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001979 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001980 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001981 if (slots != NULL) {
1982 for (i = 0; i < nslots; i++, mp++) {
1983 mp->name = PyString_AS_STRING(
1984 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001985 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001986 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001987
1988 /* __dict__ and __weakref__ are already filtered out */
1989 assert(strcmp(mp->name, "__dict__") != 0);
1990 assert(strcmp(mp->name, "__weakref__") != 0);
1991
Tim Peters6d6c1a32001-08-02 04:15:00 +00001992 slotoffset += sizeof(PyObject *);
1993 }
1994 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001995 if (add_dict) {
1996 if (base->tp_itemsize)
1997 type->tp_dictoffset = -(long)sizeof(PyObject *);
1998 else
1999 type->tp_dictoffset = slotoffset;
2000 slotoffset += sizeof(PyObject *);
2001 }
2002 if (add_weak) {
2003 assert(!base->tp_itemsize);
2004 type->tp_weaklistoffset = slotoffset;
2005 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002006 }
2007 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002008 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00002009 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002010
2011 if (type->tp_weaklistoffset && type->tp_dictoffset)
2012 type->tp_getset = subtype_getsets_full;
2013 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2014 type->tp_getset = subtype_getsets_weakref_only;
2015 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2016 type->tp_getset = subtype_getsets_dict_only;
2017 else
2018 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002019
2020 /* Special case some slots */
2021 if (type->tp_dictoffset != 0 || nslots > 0) {
2022 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2023 type->tp_getattro = PyObject_GenericGetAttr;
2024 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2025 type->tp_setattro = PyObject_GenericSetAttr;
2026 }
2027 type->tp_dealloc = subtype_dealloc;
2028
Guido van Rossum9475a232001-10-05 20:51:39 +00002029 /* Enable GC unless there are really no instance variables possible */
2030 if (!(type->tp_basicsize == sizeof(PyObject) &&
2031 type->tp_itemsize == 0))
2032 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2033
Tim Peters6d6c1a32001-08-02 04:15:00 +00002034 /* Always override allocation strategy to use regular heap */
2035 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00002036 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002037 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00002038 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002039 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00002040 }
2041 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002042 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002043
2044 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002045 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002046 Py_DECREF(type);
2047 return NULL;
2048 }
2049
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002050 /* Put the proper slots in place */
2051 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002052
Tim Peters6d6c1a32001-08-02 04:15:00 +00002053 return (PyObject *)type;
2054}
2055
2056/* Internal API to look for a name through the MRO.
2057 This returns a borrowed reference, and doesn't set an exception! */
2058PyObject *
2059_PyType_Lookup(PyTypeObject *type, PyObject *name)
2060{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002061 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002062 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002063
Guido van Rossum687ae002001-10-15 22:03:32 +00002064 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002065 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002066
2067 /* If mro is NULL, the type is either not yet initialized
2068 by PyType_Ready(), or already cleared by type_clear().
2069 Either way the safest thing to do is to return NULL. */
2070 if (mro == NULL)
2071 return NULL;
2072
Tim Peters6d6c1a32001-08-02 04:15:00 +00002073 assert(PyTuple_Check(mro));
2074 n = PyTuple_GET_SIZE(mro);
2075 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002076 base = PyTuple_GET_ITEM(mro, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002077 assert(PyType_Check(base));
2078 dict = ((PyTypeObject *)base)->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002079 assert(dict && PyDict_Check(dict));
2080 res = PyDict_GetItem(dict, name);
2081 if (res != NULL)
2082 return res;
2083 }
2084 return NULL;
2085}
2086
2087/* This is similar to PyObject_GenericGetAttr(),
2088 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2089static PyObject *
2090type_getattro(PyTypeObject *type, PyObject *name)
2091{
2092 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002093 PyObject *meta_attribute, *attribute;
2094 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002095
2096 /* Initialize this type (we'll assume the metatype is initialized) */
2097 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002098 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002099 return NULL;
2100 }
2101
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002102 /* No readable descriptor found yet */
2103 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002104
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002105 /* Look for the attribute in the metatype */
2106 meta_attribute = _PyType_Lookup(metatype, name);
2107
2108 if (meta_attribute != NULL) {
2109 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002110
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002111 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2112 /* Data descriptors implement tp_descr_set to intercept
2113 * writes. Assume the attribute is not overridden in
2114 * type's tp_dict (and bases): call the descriptor now.
2115 */
2116 return meta_get(meta_attribute, (PyObject *)type,
2117 (PyObject *)metatype);
2118 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002119 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002120 }
2121
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002122 /* No data descriptor found on metatype. Look in tp_dict of this
2123 * type and its bases */
2124 attribute = _PyType_Lookup(type, name);
2125 if (attribute != NULL) {
2126 /* Implement descriptor functionality, if any */
2127 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002128
2129 Py_XDECREF(meta_attribute);
2130
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002131 if (local_get != NULL) {
2132 /* NULL 2nd argument indicates the descriptor was
2133 * found on the target object itself (or a base) */
2134 return local_get(attribute, (PyObject *)NULL,
2135 (PyObject *)type);
2136 }
Tim Peters34592512002-07-11 06:23:50 +00002137
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002138 Py_INCREF(attribute);
2139 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002140 }
2141
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002142 /* No attribute found in local __dict__ (or bases): use the
2143 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002144 if (meta_get != NULL) {
2145 PyObject *res;
2146 res = meta_get(meta_attribute, (PyObject *)type,
2147 (PyObject *)metatype);
2148 Py_DECREF(meta_attribute);
2149 return res;
2150 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002151
2152 /* If an ordinary attribute was found on the metatype, return it now */
2153 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002154 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002155 }
2156
2157 /* Give up */
2158 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002159 "type object '%.50s' has no attribute '%.400s'",
2160 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002161 return NULL;
2162}
2163
2164static int
2165type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2166{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002167 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2168 PyErr_Format(
2169 PyExc_TypeError,
2170 "can't set attributes of built-in/extension type '%s'",
2171 type->tp_name);
2172 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002173 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002174 /* XXX Example of how I expect this to be used...
2175 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2176 return -1;
2177 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002178 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2179 return -1;
2180 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002181}
2182
2183static void
2184type_dealloc(PyTypeObject *type)
2185{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002186 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002187
2188 /* Assert this is a heap-allocated type object */
2189 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002190 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002191 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002192 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002193 Py_XDECREF(type->tp_base);
2194 Py_XDECREF(type->tp_dict);
2195 Py_XDECREF(type->tp_bases);
2196 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002197 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002198 Py_XDECREF(type->tp_subclasses);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002199 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2200 * of most other objects. It's okay to cast it to char *.
2201 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002202 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002203 Py_XDECREF(et->ht_name);
2204 Py_XDECREF(et->ht_slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002205 type->ob_type->tp_free((PyObject *)type);
2206}
2207
Guido van Rossum1c450732001-10-08 15:18:27 +00002208static PyObject *
2209type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2210{
2211 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002212 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002213
2214 list = PyList_New(0);
2215 if (list == NULL)
2216 return NULL;
2217 raw = type->tp_subclasses;
2218 if (raw == NULL)
2219 return list;
2220 assert(PyList_Check(raw));
2221 n = PyList_GET_SIZE(raw);
2222 for (i = 0; i < n; i++) {
2223 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002224 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002225 ref = PyWeakref_GET_OBJECT(ref);
2226 if (ref != Py_None) {
2227 if (PyList_Append(list, ref) < 0) {
2228 Py_DECREF(list);
2229 return NULL;
2230 }
2231 }
2232 }
2233 return list;
2234}
2235
Tim Peters6d6c1a32001-08-02 04:15:00 +00002236static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002237 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002238 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002239 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002240 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002241 {0}
2242};
2243
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002244PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002245"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002246"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002247
Guido van Rossum048eb752001-10-02 21:24:57 +00002248static int
2249type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2250{
Guido van Rossuma3862092002-06-10 15:24:42 +00002251 /* Because of type_is_gc(), the collector only calls this
2252 for heaptypes. */
2253 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002254
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002255 Py_VISIT(type->tp_dict);
2256 Py_VISIT(type->tp_cache);
2257 Py_VISIT(type->tp_mro);
2258 Py_VISIT(type->tp_bases);
2259 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002260
2261 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002262 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002263 in cycles; tp_subclasses is a list of weak references,
2264 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002265
Guido van Rossum048eb752001-10-02 21:24:57 +00002266 return 0;
2267}
2268
2269static int
2270type_clear(PyTypeObject *type)
2271{
Guido van Rossuma3862092002-06-10 15:24:42 +00002272 /* Because of type_is_gc(), the collector only calls this
2273 for heaptypes. */
2274 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002275
Guido van Rossuma3862092002-06-10 15:24:42 +00002276 /* The only field we need to clear is tp_mro, which is part of a
2277 hard cycle (its first element is the class itself) that won't
2278 be broken otherwise (it's a tuple and tuples don't have a
2279 tp_clear handler). None of the other fields need to be
2280 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002281
Guido van Rossuma3862092002-06-10 15:24:42 +00002282 tp_dict:
2283 It is a dict, so the collector will call its tp_clear.
2284
2285 tp_cache:
2286 Not used; if it were, it would be a dict.
2287
2288 tp_bases, tp_base:
2289 If these are involved in a cycle, there must be at least
2290 one other, mutable object in the cycle, e.g. a base
2291 class's dict; the cycle will be broken that way.
2292
2293 tp_subclasses:
2294 A list of weak references can't be part of a cycle; and
2295 lists have their own tp_clear.
2296
Guido van Rossume5c691a2003-03-07 15:13:17 +00002297 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002298 A tuple of strings can't be part of a cycle.
2299 */
2300
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002301 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002302
2303 return 0;
2304}
2305
2306static int
2307type_is_gc(PyTypeObject *type)
2308{
2309 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2310}
2311
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002312PyTypeObject PyType_Type = {
2313 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002314 0, /* ob_size */
2315 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002316 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002317 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002318 (destructor)type_dealloc, /* tp_dealloc */
2319 0, /* tp_print */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002320 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002321 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002322 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002323 (reprfunc)type_repr, /* tp_repr */
2324 0, /* tp_as_number */
2325 0, /* tp_as_sequence */
2326 0, /* tp_as_mapping */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002327 0, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002328 (ternaryfunc)type_call, /* tp_call */
2329 0, /* tp_str */
2330 (getattrofunc)type_getattro, /* tp_getattro */
2331 (setattrofunc)type_setattro, /* tp_setattro */
2332 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002333 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Thomas Wouters27d517b2007-02-25 20:39:11 +00002334 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002335 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002336 (traverseproc)type_traverse, /* tp_traverse */
2337 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002338 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002339 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002340 0, /* tp_iter */
2341 0, /* tp_iternext */
2342 type_methods, /* tp_methods */
2343 type_members, /* tp_members */
2344 type_getsets, /* tp_getset */
2345 0, /* tp_base */
2346 0, /* tp_dict */
2347 0, /* tp_descr_get */
2348 0, /* tp_descr_set */
2349 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002350 type_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002351 0, /* tp_alloc */
2352 type_new, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002353 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002354 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002355};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002356
2357
2358/* The base type of all types (eventually)... except itself. */
2359
Guido van Rossumd8faa362007-04-27 19:54:29 +00002360/* You may wonder why object.__new__() only complains about arguments
2361 when object.__init__() is not overridden, and vice versa.
2362
2363 Consider the use cases:
2364
2365 1. When neither is overridden, we want to hear complaints about
2366 excess (i.e., any) arguments, since their presence could
2367 indicate there's a bug.
2368
2369 2. When defining an Immutable type, we are likely to override only
2370 __new__(), since __init__() is called too late to initialize an
2371 Immutable object. Since __new__() defines the signature for the
2372 type, it would be a pain to have to override __init__() just to
2373 stop it from complaining about excess arguments.
2374
2375 3. When defining a Mutable type, we are likely to override only
2376 __init__(). So here the converse reasoning applies: we don't
2377 want to have to override __new__() just to stop it from
2378 complaining.
2379
2380 4. When __init__() is overridden, and the subclass __init__() calls
2381 object.__init__(), the latter should complain about excess
2382 arguments; ditto for __new__().
2383
2384 Use cases 2 and 3 make it unattractive to unconditionally check for
2385 excess arguments. The best solution that addresses all four use
2386 cases is as follows: __init__() complains about excess arguments
2387 unless __new__() is overridden and __init__() is not overridden
2388 (IOW, if __init__() is overridden or __new__() is not overridden);
2389 symmetrically, __new__() complains about excess arguments unless
2390 __init__() is overridden and __new__() is not overridden
2391 (IOW, if __new__() is overridden or __init__() is not overridden).
2392
2393 However, for backwards compatibility, this breaks too much code.
2394 Therefore, in 2.6, we'll *warn* about excess arguments when both
2395 methods are overridden; for all other cases we'll use the above
2396 rules.
2397
2398*/
2399
2400/* Forward */
2401static PyObject *
2402object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2403
2404static int
2405excess_args(PyObject *args, PyObject *kwds)
2406{
2407 return PyTuple_GET_SIZE(args) ||
2408 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2409}
2410
Tim Peters6d6c1a32001-08-02 04:15:00 +00002411static int
2412object_init(PyObject *self, PyObject *args, PyObject *kwds)
2413{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002414 int err = 0;
2415 if (excess_args(args, kwds)) {
2416 PyTypeObject *type = self->ob_type;
2417 if (type->tp_init != object_init &&
2418 type->tp_new != object_new)
2419 {
2420 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2421 "object.__init__() takes no parameters",
2422 1);
2423 }
2424 else if (type->tp_init != object_init ||
2425 type->tp_new == object_new)
2426 {
2427 PyErr_SetString(PyExc_TypeError,
2428 "object.__init__() takes no parameters");
2429 err = -1;
2430 }
2431 }
2432 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002433}
2434
Guido van Rossum298e4212003-02-13 16:30:16 +00002435static PyObject *
2436object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2437{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002438 int err = 0;
2439 if (excess_args(args, kwds)) {
2440 if (type->tp_new != object_new &&
2441 type->tp_init != object_init)
2442 {
2443 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2444 "object.__new__() takes no parameters",
2445 1);
2446 }
2447 else if (type->tp_new != object_new ||
2448 type->tp_init == object_init)
2449 {
2450 PyErr_SetString(PyExc_TypeError,
2451 "object.__new__() takes no parameters");
2452 err = -1;
2453 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002454 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002455 if (err < 0)
2456 return NULL;
Guido van Rossum298e4212003-02-13 16:30:16 +00002457 return type->tp_alloc(type, 0);
2458}
2459
Tim Peters6d6c1a32001-08-02 04:15:00 +00002460static void
2461object_dealloc(PyObject *self)
2462{
2463 self->ob_type->tp_free(self);
2464}
2465
Guido van Rossum8e248182001-08-12 05:17:56 +00002466static PyObject *
2467object_repr(PyObject *self)
2468{
Guido van Rossum76e69632001-08-16 18:52:43 +00002469 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002470 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002471
Guido van Rossum76e69632001-08-16 18:52:43 +00002472 type = self->ob_type;
2473 mod = type_module(type, NULL);
2474 if (mod == NULL)
2475 PyErr_Clear();
2476 else if (!PyString_Check(mod)) {
2477 Py_DECREF(mod);
2478 mod = NULL;
2479 }
2480 name = type_name(type, NULL);
2481 if (name == NULL)
2482 return NULL;
2483 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002484 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002485 PyString_AS_STRING(mod),
2486 PyString_AS_STRING(name),
2487 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002488 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002489 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002490 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002491 Py_XDECREF(mod);
2492 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002493 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002494}
2495
Guido van Rossumb8f63662001-08-15 23:57:02 +00002496static PyObject *
2497object_str(PyObject *self)
2498{
2499 unaryfunc f;
2500
2501 f = self->ob_type->tp_repr;
2502 if (f == NULL)
2503 f = object_repr;
2504 return f(self);
2505}
2506
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002507static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002508object_richcompare(PyObject *self, PyObject *other, int op)
2509{
2510 PyObject *res;
2511
2512 switch (op) {
2513
2514 case Py_EQ:
2515 res = (self == other) ? Py_True : Py_False;
Guido van Rossum6b18a5b2007-03-29 20:49:57 +00002516 Py_INCREF(res);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002517 break;
2518
2519 case Py_NE:
Guido van Rossume27dc722007-03-27 22:37:34 +00002520 /* By default, != returns the opposite of ==,
2521 unless the latter returns NotImplemented. */
2522 res = PyObject_RichCompare(self, other, Py_EQ);
2523 if (res != NULL && res != Py_NotImplemented) {
2524 int ok = PyObject_IsTrue(res);
2525 Py_DECREF(res);
2526 if (ok < 0)
2527 res = NULL;
2528 else {
2529 if (ok)
2530 res = Py_False;
2531 else
2532 res = Py_True;
2533 Py_INCREF(res);
2534 }
2535 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002536 break;
2537
2538 default:
2539 res = Py_NotImplemented;
Guido van Rossum6b18a5b2007-03-29 20:49:57 +00002540 Py_INCREF(res);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002541 break;
2542 }
2543
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002544 return res;
2545}
2546
2547static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002548object_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;
Guido van Rossumd8faa362007-04-27 19:54:29 +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 *);
Guido van Rossumd8faa362007-04-27 19:54:29 +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
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002597compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002598{
2599 PyTypeObject *newbase, *oldbase;
2600
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002608 newto->tp_name,
2609 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002610 return 0;
2611 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +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 {
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002832 PyObject *items = PyObject_CallMethod(obj, "items", "");
2833 if (items == NULL)
2834 goto end;
2835 dictitems = PyObject_GetIter(items);
2836 Py_DECREF(items);
Guido van Rossum036f9992003-02-21 22:02:54 +00002837 if (dictitems == NULL)
2838 goto end;
2839 }
2840
2841 copy_reg = import_copy_reg();
2842 if (copy_reg == NULL)
2843 goto end;
2844 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2845 if (newobj == NULL)
2846 goto end;
2847
2848 n = PyTuple_GET_SIZE(args);
2849 args2 = PyTuple_New(n+1);
2850 if (args2 == NULL)
2851 goto end;
2852 PyTuple_SET_ITEM(args2, 0, cls);
2853 cls = NULL;
2854 for (i = 0; i < n; i++) {
2855 PyObject *v = PyTuple_GET_ITEM(args, i);
2856 Py_INCREF(v);
2857 PyTuple_SET_ITEM(args2, i+1, v);
2858 }
2859
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002860 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002861
2862 end:
2863 Py_XDECREF(cls);
2864 Py_XDECREF(args);
2865 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002866 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002867 Py_XDECREF(state);
2868 Py_XDECREF(names);
2869 Py_XDECREF(listitems);
2870 Py_XDECREF(dictitems);
2871 Py_XDECREF(copy_reg);
2872 Py_XDECREF(newobj);
2873 return res;
2874}
2875
Guido van Rossumd8faa362007-04-27 19:54:29 +00002876/*
2877 * There were two problems when object.__reduce__ and object.__reduce_ex__
2878 * were implemented in the same function:
2879 * - trying to pickle an object with a custom __reduce__ method that
2880 * fell back to object.__reduce__ in certain circumstances led to
2881 * infinite recursion at Python level and eventual RuntimeError.
2882 * - Pickling objects that lied about their type by overwriting the
2883 * __class__ descriptor could lead to infinite recursion at C level
2884 * and eventual segfault.
2885 *
2886 * Because of backwards compatibility, the two methods still have to
2887 * behave in the same way, even if this is not required by the pickle
2888 * protocol. This common functionality was moved to the _common_reduce
2889 * function.
2890 */
2891static PyObject *
2892_common_reduce(PyObject *self, int proto)
2893{
2894 PyObject *copy_reg, *res;
2895
2896 if (proto >= 2)
2897 return reduce_2(self);
2898
2899 copy_reg = import_copy_reg();
2900 if (!copy_reg)
2901 return NULL;
2902
2903 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
2904 Py_DECREF(copy_reg);
2905
2906 return res;
2907}
2908
2909static PyObject *
2910object_reduce(PyObject *self, PyObject *args)
2911{
2912 int proto = 0;
2913
2914 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
2915 return NULL;
2916
2917 return _common_reduce(self, proto);
2918}
2919
Guido van Rossum036f9992003-02-21 22:02:54 +00002920static PyObject *
2921object_reduce_ex(PyObject *self, PyObject *args)
2922{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002923 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00002924 int proto = 0;
2925
2926 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2927 return NULL;
2928
2929 reduce = PyObject_GetAttrString(self, "__reduce__");
2930 if (reduce == NULL)
2931 PyErr_Clear();
2932 else {
2933 PyObject *cls, *clsreduce, *objreduce;
2934 int override;
2935 cls = PyObject_GetAttrString(self, "__class__");
2936 if (cls == NULL) {
2937 Py_DECREF(reduce);
2938 return NULL;
2939 }
2940 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2941 Py_DECREF(cls);
2942 if (clsreduce == NULL) {
2943 Py_DECREF(reduce);
2944 return NULL;
2945 }
2946 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2947 "__reduce__");
2948 override = (clsreduce != objreduce);
2949 Py_DECREF(clsreduce);
2950 if (override) {
2951 res = PyObject_CallObject(reduce, NULL);
2952 Py_DECREF(reduce);
2953 return res;
2954 }
2955 else
2956 Py_DECREF(reduce);
2957 }
2958
Guido van Rossumd8faa362007-04-27 19:54:29 +00002959 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002960}
2961
2962static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002963 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2964 PyDoc_STR("helper for pickle")},
Guido van Rossumd8faa362007-04-27 19:54:29 +00002965 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002966 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002967 {0}
2968};
2969
Guido van Rossum036f9992003-02-21 22:02:54 +00002970
Tim Peters6d6c1a32001-08-02 04:15:00 +00002971PyTypeObject PyBaseObject_Type = {
2972 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002973 0, /* ob_size */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002974 "object", /* tp_name */
2975 sizeof(PyObject), /* tp_basicsize */
2976 0, /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002977 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002978 0, /* tp_print */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002979 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002980 0, /* tp_setattr */
2981 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002982 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002983 0, /* tp_as_number */
2984 0, /* tp_as_sequence */
2985 0, /* tp_as_mapping */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002986 (hashfunc)_Py_HashPointer, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002987 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002988 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002989 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002990 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002991 0, /* tp_as_buffer */
2992 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002993 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002994 0, /* tp_traverse */
2995 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002996 object_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002997 0, /* tp_weaklistoffset */
2998 0, /* tp_iter */
2999 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00003000 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003001 0, /* tp_members */
3002 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003003 0, /* tp_base */
3004 0, /* tp_dict */
3005 0, /* tp_descr_get */
3006 0, /* tp_descr_set */
3007 0, /* tp_dictoffset */
3008 object_init, /* tp_init */
3009 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00003010 object_new, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003011 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003012};
3013
3014
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003015/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003016
3017static int
3018add_methods(PyTypeObject *type, PyMethodDef *meth)
3019{
Guido van Rossum687ae002001-10-15 22:03:32 +00003020 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003021
3022 for (; meth->ml_name != NULL; meth++) {
3023 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003024 if (PyDict_GetItemString(dict, meth->ml_name) &&
3025 !(meth->ml_flags & METH_COEXIST))
3026 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00003027 if (meth->ml_flags & METH_CLASS) {
3028 if (meth->ml_flags & METH_STATIC) {
3029 PyErr_SetString(PyExc_ValueError,
3030 "method cannot be both class and static");
3031 return -1;
3032 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00003033 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00003034 }
3035 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00003036 PyObject *cfunc = PyCFunction_New(meth, NULL);
3037 if (cfunc == NULL)
3038 return -1;
3039 descr = PyStaticMethod_New(cfunc);
3040 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003041 }
3042 else {
3043 descr = PyDescr_NewMethod(type, meth);
3044 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003045 if (descr == NULL)
3046 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003047 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003048 return -1;
3049 Py_DECREF(descr);
3050 }
3051 return 0;
3052}
3053
3054static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003055add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003056{
Guido van Rossum687ae002001-10-15 22:03:32 +00003057 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003058
3059 for (; memb->name != NULL; memb++) {
3060 PyObject *descr;
3061 if (PyDict_GetItemString(dict, memb->name))
3062 continue;
3063 descr = PyDescr_NewMember(type, memb);
3064 if (descr == NULL)
3065 return -1;
3066 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3067 return -1;
3068 Py_DECREF(descr);
3069 }
3070 return 0;
3071}
3072
3073static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003074add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003075{
Guido van Rossum687ae002001-10-15 22:03:32 +00003076 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003077
3078 for (; gsp->name != NULL; gsp++) {
3079 PyObject *descr;
3080 if (PyDict_GetItemString(dict, gsp->name))
3081 continue;
3082 descr = PyDescr_NewGetSet(type, gsp);
3083
3084 if (descr == NULL)
3085 return -1;
3086 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3087 return -1;
3088 Py_DECREF(descr);
3089 }
3090 return 0;
3091}
3092
Guido van Rossum13d52f02001-08-10 21:24:08 +00003093static void
3094inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003095{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003096 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003097
Guido van Rossum13d52f02001-08-10 21:24:08 +00003098 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003099 oldsize = base->tp_basicsize;
3100 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3101 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3102 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003103 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003104 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003105 if (type->tp_traverse == NULL)
3106 type->tp_traverse = base->tp_traverse;
3107 if (type->tp_clear == NULL)
3108 type->tp_clear = base->tp_clear;
3109 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003110 {
Guido van Rossumf884b742001-12-17 17:14:22 +00003111 /* The condition below could use some explanation.
3112 It appears that tp_new is not inherited for static types
3113 whose base class is 'object'; this seems to be a precaution
3114 so that old extension types don't suddenly become
3115 callable (object.__new__ wouldn't insure the invariants
3116 that the extension type's own factory function ensures).
3117 Heap types, of course, are under our control, so they do
3118 inherit tp_new; static extension types that specify some
3119 other built-in type as the default are considered
3120 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003121 if (base != &PyBaseObject_Type ||
3122 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3123 if (type->tp_new == NULL)
3124 type->tp_new = base->tp_new;
3125 }
3126 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003127 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003128
3129 /* Copy other non-function slots */
3130
3131#undef COPYVAL
3132#define COPYVAL(SLOT) \
3133 if (type->SLOT == 0) type->SLOT = base->SLOT
3134
3135 COPYVAL(tp_itemsize);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003136 COPYVAL(tp_weaklistoffset);
3137 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003138
3139 /* Setup fast subclass flags */
3140 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3141 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3142 else if (PyType_IsSubtype(base, &PyType_Type))
3143 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3144 else if (PyType_IsSubtype(base, &PyLong_Type))
3145 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3146 else if (PyType_IsSubtype(base, &PyString_Type))
3147 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
3148 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3149 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3150 else if (PyType_IsSubtype(base, &PyTuple_Type))
3151 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3152 else if (PyType_IsSubtype(base, &PyList_Type))
3153 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3154 else if (PyType_IsSubtype(base, &PyDict_Type))
3155 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003156}
3157
Guido van Rossum38938152006-08-21 23:36:26 +00003158/* Map rich comparison operators to their __xx__ namesakes */
3159static char *name_op[] = {
3160 "__lt__",
3161 "__le__",
3162 "__eq__",
3163 "__ne__",
3164 "__gt__",
3165 "__ge__",
3166 /* These are only for overrides_cmp_or_hash(): */
3167 "__cmp__",
3168 "__hash__",
3169};
3170
3171static int
3172overrides_cmp_or_hash(PyTypeObject *type)
3173{
3174 int i;
3175 PyObject *dict = type->tp_dict;
3176
3177 assert(dict != NULL);
3178 for (i = 0; i < 8; i++) {
3179 if (PyDict_GetItemString(dict, name_op[i]) != NULL)
3180 return 1;
3181 }
3182 return 0;
3183}
3184
Guido van Rossum13d52f02001-08-10 21:24:08 +00003185static void
3186inherit_slots(PyTypeObject *type, PyTypeObject *base)
3187{
3188 PyTypeObject *basebase;
3189
3190#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003191#undef COPYSLOT
3192#undef COPYNUM
3193#undef COPYSEQ
3194#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003195#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003196
3197#define SLOTDEFINED(SLOT) \
3198 (base->SLOT != 0 && \
3199 (basebase == NULL || base->SLOT != basebase->SLOT))
3200
Tim Peters6d6c1a32001-08-02 04:15:00 +00003201#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003202 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003203
3204#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3205#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3206#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003207#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003208
Guido van Rossum13d52f02001-08-10 21:24:08 +00003209 /* This won't inherit indirect slots (from tp_as_number etc.)
3210 if type doesn't provide the space. */
3211
3212 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3213 basebase = base->tp_base;
3214 if (basebase->tp_as_number == NULL)
3215 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003216 COPYNUM(nb_add);
3217 COPYNUM(nb_subtract);
3218 COPYNUM(nb_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003219 COPYNUM(nb_remainder);
3220 COPYNUM(nb_divmod);
3221 COPYNUM(nb_power);
3222 COPYNUM(nb_negative);
3223 COPYNUM(nb_positive);
3224 COPYNUM(nb_absolute);
Jack Diederich4dafcc42006-11-28 19:15:13 +00003225 COPYNUM(nb_bool);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003226 COPYNUM(nb_invert);
3227 COPYNUM(nb_lshift);
3228 COPYNUM(nb_rshift);
3229 COPYNUM(nb_and);
3230 COPYNUM(nb_xor);
3231 COPYNUM(nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003232 COPYNUM(nb_int);
3233 COPYNUM(nb_long);
3234 COPYNUM(nb_float);
3235 COPYNUM(nb_oct);
3236 COPYNUM(nb_hex);
3237 COPYNUM(nb_inplace_add);
3238 COPYNUM(nb_inplace_subtract);
3239 COPYNUM(nb_inplace_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003240 COPYNUM(nb_inplace_remainder);
3241 COPYNUM(nb_inplace_power);
3242 COPYNUM(nb_inplace_lshift);
3243 COPYNUM(nb_inplace_rshift);
3244 COPYNUM(nb_inplace_and);
3245 COPYNUM(nb_inplace_xor);
3246 COPYNUM(nb_inplace_or);
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003247 COPYNUM(nb_true_divide);
3248 COPYNUM(nb_floor_divide);
3249 COPYNUM(nb_inplace_true_divide);
3250 COPYNUM(nb_inplace_floor_divide);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003251 COPYNUM(nb_index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003252 }
3253
Guido van Rossum13d52f02001-08-10 21:24:08 +00003254 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3255 basebase = base->tp_base;
3256 if (basebase->tp_as_sequence == NULL)
3257 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003258 COPYSEQ(sq_length);
3259 COPYSEQ(sq_concat);
3260 COPYSEQ(sq_repeat);
3261 COPYSEQ(sq_item);
3262 COPYSEQ(sq_slice);
3263 COPYSEQ(sq_ass_item);
3264 COPYSEQ(sq_ass_slice);
3265 COPYSEQ(sq_contains);
3266 COPYSEQ(sq_inplace_concat);
3267 COPYSEQ(sq_inplace_repeat);
3268 }
3269
Guido van Rossum13d52f02001-08-10 21:24:08 +00003270 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3271 basebase = base->tp_base;
3272 if (basebase->tp_as_mapping == NULL)
3273 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003274 COPYMAP(mp_length);
3275 COPYMAP(mp_subscript);
3276 COPYMAP(mp_ass_subscript);
3277 }
3278
Tim Petersfc57ccb2001-10-12 02:38:24 +00003279 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3280 basebase = base->tp_base;
3281 if (basebase->tp_as_buffer == NULL)
3282 basebase = NULL;
3283 COPYBUF(bf_getreadbuffer);
3284 COPYBUF(bf_getwritebuffer);
3285 COPYBUF(bf_getsegcount);
3286 COPYBUF(bf_getcharbuffer);
3287 }
3288
Guido van Rossum13d52f02001-08-10 21:24:08 +00003289 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003290
Tim Peters6d6c1a32001-08-02 04:15:00 +00003291 COPYSLOT(tp_dealloc);
3292 COPYSLOT(tp_print);
3293 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3294 type->tp_getattr = base->tp_getattr;
3295 type->tp_getattro = base->tp_getattro;
3296 }
3297 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3298 type->tp_setattr = base->tp_setattr;
3299 type->tp_setattro = base->tp_setattro;
3300 }
3301 /* tp_compare see tp_richcompare */
3302 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003303 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003304 COPYSLOT(tp_call);
3305 COPYSLOT(tp_str);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003306 {
Guido van Rossum38938152006-08-21 23:36:26 +00003307 /* Copy comparison-related slots only when
3308 not overriding them anywhere */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003309 if (type->tp_compare == NULL &&
3310 type->tp_richcompare == NULL &&
Guido van Rossum38938152006-08-21 23:36:26 +00003311 type->tp_hash == NULL &&
3312 !overrides_cmp_or_hash(type))
Guido van Rossumb8f63662001-08-15 23:57:02 +00003313 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003314 type->tp_compare = base->tp_compare;
3315 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003316 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003317 }
3318 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003319 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003320 COPYSLOT(tp_iter);
3321 COPYSLOT(tp_iternext);
3322 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003323 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003324 COPYSLOT(tp_descr_get);
3325 COPYSLOT(tp_descr_set);
3326 COPYSLOT(tp_dictoffset);
3327 COPYSLOT(tp_init);
3328 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003329 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003330 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3331 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3332 /* They agree about gc. */
3333 COPYSLOT(tp_free);
3334 }
3335 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3336 type->tp_free == NULL &&
3337 base->tp_free == _PyObject_Del) {
3338 /* A bit of magic to plug in the correct default
3339 * tp_free function when a derived class adds gc,
3340 * didn't define tp_free, and the base uses the
3341 * default non-gc tp_free.
3342 */
3343 type->tp_free = PyObject_GC_Del;
3344 }
3345 /* else they didn't agree about gc, and there isn't something
3346 * obvious to be done -- the type is on its own.
3347 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003348 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003349}
3350
Jeremy Hylton938ace62002-07-17 16:30:39 +00003351static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003352
Tim Peters6d6c1a32001-08-02 04:15:00 +00003353int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003354PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003355{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003356 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003357 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003358 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003359
Guido van Rossumcab05802002-06-10 15:29:03 +00003360 if (type->tp_flags & Py_TPFLAGS_READY) {
3361 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003362 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003363 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003364 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003365
3366 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003367
Tim Peters36eb4df2003-03-23 03:33:13 +00003368#ifdef Py_TRACE_REFS
3369 /* PyType_Ready is the closest thing we have to a choke point
3370 * for type objects, so is the best place I can think of to try
3371 * to get type objects into the doubly-linked list of all objects.
3372 * Still, not all type objects go thru PyType_Ready.
3373 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003374 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003375#endif
3376
Tim Peters6d6c1a32001-08-02 04:15:00 +00003377 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3378 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003379 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003380 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003381 Py_INCREF(base);
3382 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003383
Guido van Rossumd8faa362007-04-27 19:54:29 +00003384 /* Now the only way base can still be NULL is if type is
3385 * &PyBaseObject_Type.
3386 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003387
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003388 /* Initialize the base class */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003389 if (base != NULL && base->tp_dict == NULL) {
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003390 if (PyType_Ready(base) < 0)
3391 goto error;
3392 }
3393
Guido van Rossumd8faa362007-04-27 19:54:29 +00003394 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003395 compilable separately on Windows can call PyType_Ready() instead of
3396 initializing the ob_type field of their type objects. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003397 /* The test for base != NULL is really unnecessary, since base is only
3398 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3399 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3400 know that. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003401 if (type->ob_type == NULL && base != NULL)
Guido van Rossum0986d822002-04-08 01:38:42 +00003402 type->ob_type = base->ob_type;
3403
Tim Peters6d6c1a32001-08-02 04:15:00 +00003404 /* Initialize tp_bases */
3405 bases = type->tp_bases;
3406 if (bases == NULL) {
3407 if (base == NULL)
3408 bases = PyTuple_New(0);
3409 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003410 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003411 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003412 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003413 type->tp_bases = bases;
3414 }
3415
Guido van Rossum687ae002001-10-15 22:03:32 +00003416 /* Initialize tp_dict */
3417 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003418 if (dict == NULL) {
3419 dict = PyDict_New();
3420 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003421 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003422 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003423 }
3424
Guido van Rossum687ae002001-10-15 22:03:32 +00003425 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003426 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003427 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003428 if (type->tp_methods != NULL) {
3429 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003430 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003431 }
3432 if (type->tp_members != NULL) {
3433 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003434 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003435 }
3436 if (type->tp_getset != NULL) {
3437 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003438 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003439 }
3440
Tim Peters6d6c1a32001-08-02 04:15:00 +00003441 /* Calculate method resolution order */
3442 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003443 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003444 }
3445
Guido van Rossum13d52f02001-08-10 21:24:08 +00003446 /* Inherit special flags from dominant base */
3447 if (type->tp_base != NULL)
3448 inherit_special(type, type->tp_base);
3449
Tim Peters6d6c1a32001-08-02 04:15:00 +00003450 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003451 bases = type->tp_mro;
3452 assert(bases != NULL);
3453 assert(PyTuple_Check(bases));
3454 n = PyTuple_GET_SIZE(bases);
3455 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003456 PyObject *b = PyTuple_GET_ITEM(bases, i);
3457 if (PyType_Check(b))
3458 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003459 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003460
Tim Peters3cfe7542003-05-21 21:29:48 +00003461 /* Sanity check for tp_free. */
3462 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3463 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003464 /* This base class needs to call tp_free, but doesn't have
3465 * one, or its tp_free is for non-gc'ed objects.
3466 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003467 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3468 "gc and is a base type but has inappropriate "
3469 "tp_free slot",
3470 type->tp_name);
3471 goto error;
3472 }
3473
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003474 /* if the type dictionary doesn't contain a __doc__, set it from
3475 the tp_doc slot.
3476 */
3477 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3478 if (type->tp_doc != NULL) {
3479 PyObject *doc = PyString_FromString(type->tp_doc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003480 if (doc == NULL)
3481 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003482 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3483 Py_DECREF(doc);
3484 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003485 PyDict_SetItemString(type->tp_dict,
3486 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003487 }
3488 }
3489
Guido van Rossum38938152006-08-21 23:36:26 +00003490 /* Hack for tp_hash and __hash__.
3491 If after all that, tp_hash is still NULL, and __hash__ is not in
3492 tp_dict, set tp_dict['__hash__'] equal to None.
3493 This signals that __hash__ is not inherited.
3494 */
3495 if (type->tp_hash == NULL) {
3496 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
3497 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3498 goto error;
3499 }
3500 }
3501
Guido van Rossum13d52f02001-08-10 21:24:08 +00003502 /* Some more special stuff */
3503 base = type->tp_base;
3504 if (base != NULL) {
3505 if (type->tp_as_number == NULL)
3506 type->tp_as_number = base->tp_as_number;
3507 if (type->tp_as_sequence == NULL)
3508 type->tp_as_sequence = base->tp_as_sequence;
3509 if (type->tp_as_mapping == NULL)
3510 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003511 if (type->tp_as_buffer == NULL)
3512 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003513 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003514
Guido van Rossum1c450732001-10-08 15:18:27 +00003515 /* Link into each base class's list of subclasses */
3516 bases = type->tp_bases;
3517 n = PyTuple_GET_SIZE(bases);
3518 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003519 PyObject *b = PyTuple_GET_ITEM(bases, i);
3520 if (PyType_Check(b) &&
3521 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003522 goto error;
3523 }
3524
Guido van Rossum13d52f02001-08-10 21:24:08 +00003525 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003526 assert(type->tp_dict != NULL);
3527 type->tp_flags =
3528 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003529 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003530
3531 error:
3532 type->tp_flags &= ~Py_TPFLAGS_READYING;
3533 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003534}
3535
Guido van Rossum1c450732001-10-08 15:18:27 +00003536static int
3537add_subclass(PyTypeObject *base, PyTypeObject *type)
3538{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003539 Py_ssize_t i;
3540 int result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003541 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003542
3543 list = base->tp_subclasses;
3544 if (list == NULL) {
3545 base->tp_subclasses = list = PyList_New(0);
3546 if (list == NULL)
3547 return -1;
3548 }
3549 assert(PyList_Check(list));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003550 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003551 i = PyList_GET_SIZE(list);
3552 while (--i >= 0) {
3553 ref = PyList_GET_ITEM(list, i);
3554 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003555 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003556 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003557 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003558 result = PyList_Append(list, newobj);
3559 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003560 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003561}
3562
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003563static void
3564remove_subclass(PyTypeObject *base, PyTypeObject *type)
3565{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003566 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003567 PyObject *list, *ref;
3568
3569 list = base->tp_subclasses;
3570 if (list == NULL) {
3571 return;
3572 }
3573 assert(PyList_Check(list));
3574 i = PyList_GET_SIZE(list);
3575 while (--i >= 0) {
3576 ref = PyList_GET_ITEM(list, i);
3577 assert(PyWeakref_CheckRef(ref));
3578 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3579 /* this can't fail, right? */
3580 PySequence_DelItem(list, i);
3581 return;
3582 }
3583 }
3584}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003585
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003586static int
3587check_num_args(PyObject *ob, int n)
3588{
3589 if (!PyTuple_CheckExact(ob)) {
3590 PyErr_SetString(PyExc_SystemError,
3591 "PyArg_UnpackTuple() argument list is not a tuple");
3592 return 0;
3593 }
3594 if (n == PyTuple_GET_SIZE(ob))
3595 return 1;
3596 PyErr_Format(
3597 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003598 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003599 return 0;
3600}
3601
Tim Peters6d6c1a32001-08-02 04:15:00 +00003602/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3603
3604/* There's a wrapper *function* for each distinct function typedef used
Guido van Rossumd8faa362007-04-27 19:54:29 +00003605 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00003606 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3607 Most tables have only one entry; the tables for binary operators have two
3608 entries, one regular and one with reversed arguments. */
3609
3610static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003611wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003612{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003613 lenfunc func = (lenfunc)wrapped;
3614 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003615
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003616 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003617 return NULL;
3618 res = (*func)(self);
3619 if (res == -1 && PyErr_Occurred())
3620 return NULL;
3621 return PyInt_FromLong((long)res);
3622}
3623
Tim Peters6d6c1a32001-08-02 04:15:00 +00003624static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003625wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3626{
3627 inquiry func = (inquiry)wrapped;
3628 int res;
3629
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003630 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003631 return NULL;
3632 res = (*func)(self);
3633 if (res == -1 && PyErr_Occurred())
3634 return NULL;
3635 return PyBool_FromLong((long)res);
3636}
3637
3638static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003639wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3640{
3641 binaryfunc func = (binaryfunc)wrapped;
3642 PyObject *other;
3643
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003644 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003645 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003646 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003647 return (*func)(self, other);
3648}
3649
3650static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003651wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3652{
3653 binaryfunc func = (binaryfunc)wrapped;
3654 PyObject *other;
3655
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003656 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003657 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003658 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003659 return (*func)(self, other);
3660}
3661
3662static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003663wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3664{
3665 binaryfunc func = (binaryfunc)wrapped;
3666 PyObject *other;
3667
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003668 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003669 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003670 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003671 if (!PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003672 Py_INCREF(Py_NotImplemented);
3673 return Py_NotImplemented;
3674 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003675 return (*func)(other, self);
3676}
3677
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003678static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003679wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3680{
3681 ternaryfunc func = (ternaryfunc)wrapped;
3682 PyObject *other;
3683 PyObject *third = Py_None;
3684
3685 /* Note: This wrapper only works for __pow__() */
3686
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003687 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003688 return NULL;
3689 return (*func)(self, other, third);
3690}
3691
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003692static PyObject *
3693wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3694{
3695 ternaryfunc func = (ternaryfunc)wrapped;
3696 PyObject *other;
3697 PyObject *third = Py_None;
3698
3699 /* Note: This wrapper only works for __pow__() */
3700
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003701 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003702 return NULL;
3703 return (*func)(other, self, third);
3704}
3705
Tim Peters6d6c1a32001-08-02 04:15:00 +00003706static PyObject *
3707wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3708{
3709 unaryfunc func = (unaryfunc)wrapped;
3710
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003711 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003712 return NULL;
3713 return (*func)(self);
3714}
3715
Tim Peters6d6c1a32001-08-02 04:15:00 +00003716static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003717wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003718{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003719 ssizeargfunc func = (ssizeargfunc)wrapped;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003720 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003721 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003722
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003723 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
3724 return NULL;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003725 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003726 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003727 return NULL;
3728 return (*func)(self, i);
3729}
3730
Martin v. Löwis18e16552006-02-15 17:27:45 +00003731static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00003732getindex(PyObject *self, PyObject *arg)
3733{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003734 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003735
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003736 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003737 if (i == -1 && PyErr_Occurred())
3738 return -1;
3739 if (i < 0) {
3740 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3741 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003742 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003743 if (n < 0)
3744 return -1;
3745 i += n;
3746 }
3747 }
3748 return i;
3749}
3750
3751static PyObject *
3752wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3753{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003754 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003755 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003756 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003757
Guido van Rossumf4593e02001-10-03 12:09:30 +00003758 if (PyTuple_GET_SIZE(args) == 1) {
3759 arg = PyTuple_GET_ITEM(args, 0);
3760 i = getindex(self, arg);
3761 if (i == -1 && PyErr_Occurred())
3762 return NULL;
3763 return (*func)(self, i);
3764 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003765 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003766 assert(PyErr_Occurred());
3767 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003768}
3769
Tim Peters6d6c1a32001-08-02 04:15:00 +00003770static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003771wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003772{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003773 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
3774 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003775
Martin v. Löwis18e16552006-02-15 17:27:45 +00003776 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003777 return NULL;
3778 return (*func)(self, i, j);
3779}
3780
Tim Peters6d6c1a32001-08-02 04:15:00 +00003781static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003782wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003783{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003784 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3785 Py_ssize_t i;
3786 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003787 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003788
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003789 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003790 return NULL;
3791 i = getindex(self, arg);
3792 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003793 return NULL;
3794 res = (*func)(self, i, value);
3795 if (res == -1 && PyErr_Occurred())
3796 return NULL;
3797 Py_INCREF(Py_None);
3798 return Py_None;
3799}
3800
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003801static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003802wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003803{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003804 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3805 Py_ssize_t i;
3806 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003807 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003808
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003809 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003810 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003811 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003812 i = getindex(self, arg);
3813 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003814 return NULL;
3815 res = (*func)(self, i, NULL);
3816 if (res == -1 && PyErr_Occurred())
3817 return NULL;
3818 Py_INCREF(Py_None);
3819 return Py_None;
3820}
3821
Tim Peters6d6c1a32001-08-02 04:15:00 +00003822static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003823wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003824{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003825 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3826 Py_ssize_t i, j;
3827 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003828 PyObject *value;
3829
Martin v. Löwis18e16552006-02-15 17:27:45 +00003830 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003831 return NULL;
3832 res = (*func)(self, i, j, value);
3833 if (res == -1 && PyErr_Occurred())
3834 return NULL;
3835 Py_INCREF(Py_None);
3836 return Py_None;
3837}
3838
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003839static PyObject *
3840wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3841{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003842 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3843 Py_ssize_t i, j;
3844 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003845
Martin v. Löwis18e16552006-02-15 17:27:45 +00003846 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003847 return NULL;
3848 res = (*func)(self, i, j, NULL);
3849 if (res == -1 && PyErr_Occurred())
3850 return NULL;
3851 Py_INCREF(Py_None);
3852 return Py_None;
3853}
3854
Tim Peters6d6c1a32001-08-02 04:15:00 +00003855/* XXX objobjproc is a misnomer; should be objargpred */
3856static PyObject *
3857wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3858{
3859 objobjproc func = (objobjproc)wrapped;
3860 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003861 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003862
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003863 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003864 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003865 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003866 res = (*func)(self, value);
3867 if (res == -1 && PyErr_Occurred())
3868 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003869 else
3870 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003871}
3872
Tim Peters6d6c1a32001-08-02 04:15:00 +00003873static PyObject *
3874wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3875{
3876 objobjargproc func = (objobjargproc)wrapped;
3877 int res;
3878 PyObject *key, *value;
3879
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003880 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003881 return NULL;
3882 res = (*func)(self, key, value);
3883 if (res == -1 && PyErr_Occurred())
3884 return NULL;
3885 Py_INCREF(Py_None);
3886 return Py_None;
3887}
3888
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003889static PyObject *
3890wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3891{
3892 objobjargproc func = (objobjargproc)wrapped;
3893 int res;
3894 PyObject *key;
3895
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003896 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003897 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003898 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003899 res = (*func)(self, key, NULL);
3900 if (res == -1 && PyErr_Occurred())
3901 return NULL;
3902 Py_INCREF(Py_None);
3903 return Py_None;
3904}
3905
Tim Peters6d6c1a32001-08-02 04:15:00 +00003906static PyObject *
3907wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3908{
3909 cmpfunc func = (cmpfunc)wrapped;
3910 int res;
3911 PyObject *other;
3912
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003913 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003914 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003915 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003916 if (other->ob_type->tp_compare != func &&
3917 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003918 PyErr_Format(
3919 PyExc_TypeError,
3920 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3921 self->ob_type->tp_name,
3922 self->ob_type->tp_name,
3923 other->ob_type->tp_name);
3924 return NULL;
3925 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003926 res = (*func)(self, other);
3927 if (PyErr_Occurred())
3928 return NULL;
3929 return PyInt_FromLong((long)res);
3930}
3931
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003932/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003933 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003934static int
3935hackcheck(PyObject *self, setattrofunc func, char *what)
3936{
3937 PyTypeObject *type = self->ob_type;
3938 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3939 type = type->tp_base;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003940 /* If type is NULL now, this is a really weird type.
3941 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003942 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003943 PyErr_Format(PyExc_TypeError,
3944 "can't apply this %s to %s object",
3945 what,
3946 type->tp_name);
3947 return 0;
3948 }
3949 return 1;
3950}
3951
Tim Peters6d6c1a32001-08-02 04:15:00 +00003952static PyObject *
3953wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3954{
3955 setattrofunc func = (setattrofunc)wrapped;
3956 int res;
3957 PyObject *name, *value;
3958
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003959 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003960 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003961 if (!hackcheck(self, func, "__setattr__"))
3962 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003963 res = (*func)(self, name, value);
3964 if (res < 0)
3965 return NULL;
3966 Py_INCREF(Py_None);
3967 return Py_None;
3968}
3969
3970static PyObject *
3971wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3972{
3973 setattrofunc func = (setattrofunc)wrapped;
3974 int res;
3975 PyObject *name;
3976
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003977 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003978 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003979 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003980 if (!hackcheck(self, func, "__delattr__"))
3981 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003982 res = (*func)(self, name, NULL);
3983 if (res < 0)
3984 return NULL;
3985 Py_INCREF(Py_None);
3986 return Py_None;
3987}
3988
Tim Peters6d6c1a32001-08-02 04:15:00 +00003989static PyObject *
3990wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3991{
3992 hashfunc func = (hashfunc)wrapped;
3993 long res;
3994
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003995 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003996 return NULL;
3997 res = (*func)(self);
3998 if (res == -1 && PyErr_Occurred())
3999 return NULL;
4000 return PyInt_FromLong(res);
4001}
4002
Tim Peters6d6c1a32001-08-02 04:15:00 +00004003static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004004wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004005{
4006 ternaryfunc func = (ternaryfunc)wrapped;
4007
Guido van Rossumc8e56452001-10-22 00:43:43 +00004008 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004009}
4010
Tim Peters6d6c1a32001-08-02 04:15:00 +00004011static PyObject *
4012wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4013{
4014 richcmpfunc func = (richcmpfunc)wrapped;
4015 PyObject *other;
4016
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004017 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004018 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004019 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004020 return (*func)(self, other, op);
4021}
4022
4023#undef RICHCMP_WRAPPER
4024#define RICHCMP_WRAPPER(NAME, OP) \
4025static PyObject * \
4026richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4027{ \
4028 return wrap_richcmpfunc(self, args, wrapped, OP); \
4029}
4030
Jack Jansen8e938b42001-08-08 15:29:49 +00004031RICHCMP_WRAPPER(lt, Py_LT)
4032RICHCMP_WRAPPER(le, Py_LE)
4033RICHCMP_WRAPPER(eq, Py_EQ)
4034RICHCMP_WRAPPER(ne, Py_NE)
4035RICHCMP_WRAPPER(gt, Py_GT)
4036RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004037
Tim Peters6d6c1a32001-08-02 04:15:00 +00004038static PyObject *
4039wrap_next(PyObject *self, PyObject *args, void *wrapped)
4040{
4041 unaryfunc func = (unaryfunc)wrapped;
4042 PyObject *res;
4043
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004044 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004045 return NULL;
4046 res = (*func)(self);
4047 if (res == NULL && !PyErr_Occurred())
4048 PyErr_SetNone(PyExc_StopIteration);
4049 return res;
4050}
4051
Tim Peters6d6c1a32001-08-02 04:15:00 +00004052static PyObject *
4053wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4054{
4055 descrgetfunc func = (descrgetfunc)wrapped;
4056 PyObject *obj;
4057 PyObject *type = NULL;
4058
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004059 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004060 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004061 if (obj == Py_None)
4062 obj = NULL;
4063 if (type == Py_None)
4064 type = NULL;
4065 if (type == NULL &&obj == NULL) {
4066 PyErr_SetString(PyExc_TypeError,
4067 "__get__(None, None) is invalid");
4068 return NULL;
4069 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004070 return (*func)(self, obj, type);
4071}
4072
Tim Peters6d6c1a32001-08-02 04:15:00 +00004073static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004074wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004075{
4076 descrsetfunc func = (descrsetfunc)wrapped;
4077 PyObject *obj, *value;
4078 int ret;
4079
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004080 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004081 return NULL;
4082 ret = (*func)(self, obj, value);
4083 if (ret < 0)
4084 return NULL;
4085 Py_INCREF(Py_None);
4086 return Py_None;
4087}
Guido van Rossum22b13872002-08-06 21:41:44 +00004088
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004089static PyObject *
4090wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4091{
4092 descrsetfunc func = (descrsetfunc)wrapped;
4093 PyObject *obj;
4094 int ret;
4095
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004096 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004097 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004098 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004099 ret = (*func)(self, obj, NULL);
4100 if (ret < 0)
4101 return NULL;
4102 Py_INCREF(Py_None);
4103 return Py_None;
4104}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004105
Tim Peters6d6c1a32001-08-02 04:15:00 +00004106static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004107wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004108{
4109 initproc func = (initproc)wrapped;
4110
Guido van Rossumc8e56452001-10-22 00:43:43 +00004111 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004112 return NULL;
4113 Py_INCREF(Py_None);
4114 return Py_None;
4115}
4116
Tim Peters6d6c1a32001-08-02 04:15:00 +00004117static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004118tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004119{
Barry Warsaw60f01882001-08-22 19:24:42 +00004120 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004121 PyObject *arg0, *res;
4122
4123 if (self == NULL || !PyType_Check(self))
4124 Py_FatalError("__new__() called with non-type 'self'");
4125 type = (PyTypeObject *)self;
4126 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004127 PyErr_Format(PyExc_TypeError,
4128 "%s.__new__(): not enough arguments",
4129 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004130 return NULL;
4131 }
4132 arg0 = PyTuple_GET_ITEM(args, 0);
4133 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004134 PyErr_Format(PyExc_TypeError,
4135 "%s.__new__(X): X is not a type object (%s)",
4136 type->tp_name,
4137 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004138 return NULL;
4139 }
4140 subtype = (PyTypeObject *)arg0;
4141 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004142 PyErr_Format(PyExc_TypeError,
4143 "%s.__new__(%s): %s is not a subtype of %s",
4144 type->tp_name,
4145 subtype->tp_name,
4146 subtype->tp_name,
4147 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004148 return NULL;
4149 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004150
4151 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004152 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004153 most derived base that's not a heap type is this type. */
4154 staticbase = subtype;
4155 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4156 staticbase = staticbase->tp_base;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004157 /* If staticbase is NULL now, it is a really weird type.
4158 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004159 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004160 PyErr_Format(PyExc_TypeError,
4161 "%s.__new__(%s) is not safe, use %s.__new__()",
4162 type->tp_name,
4163 subtype->tp_name,
4164 staticbase == NULL ? "?" : staticbase->tp_name);
4165 return NULL;
4166 }
4167
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004168 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4169 if (args == NULL)
4170 return NULL;
4171 res = type->tp_new(subtype, args, kwds);
4172 Py_DECREF(args);
4173 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004174}
4175
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004176static struct PyMethodDef tp_new_methoddef[] = {
4177 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004178 PyDoc_STR("T.__new__(S, ...) -> "
Guido van Rossumd8faa362007-04-27 19:54:29 +00004179 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004180 {0}
4181};
4182
4183static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004184add_tp_new_wrapper(PyTypeObject *type)
4185{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004186 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004187
Guido van Rossum687ae002001-10-15 22:03:32 +00004188 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004189 return 0;
4190 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004191 if (func == NULL)
4192 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004193 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004194 Py_DECREF(func);
4195 return -1;
4196 }
4197 Py_DECREF(func);
4198 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004199}
4200
Guido van Rossumf040ede2001-08-07 16:40:56 +00004201/* Slot wrappers that call the corresponding __foo__ slot. See comments
4202 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004203
Guido van Rossumdc91b992001-08-08 22:26:22 +00004204#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004205static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004206FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004207{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004208 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004209 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004210}
4211
Guido van Rossumdc91b992001-08-08 22:26:22 +00004212#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004213static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004214FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004215{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004216 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004217 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004218}
4219
Guido van Rossumcd118802003-01-06 22:57:47 +00004220/* Boolean helper for SLOT1BINFULL().
4221 right.__class__ is a nontrivial subclass of left.__class__. */
4222static int
4223method_is_overloaded(PyObject *left, PyObject *right, char *name)
4224{
4225 PyObject *a, *b;
4226 int ok;
4227
4228 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
4229 if (b == NULL) {
4230 PyErr_Clear();
4231 /* If right doesn't have it, it's not overloaded */
4232 return 0;
4233 }
4234
4235 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
4236 if (a == NULL) {
4237 PyErr_Clear();
4238 Py_DECREF(b);
4239 /* If right has it but left doesn't, it's overloaded */
4240 return 1;
4241 }
4242
4243 ok = PyObject_RichCompareBool(a, b, Py_NE);
4244 Py_DECREF(a);
4245 Py_DECREF(b);
4246 if (ok < 0) {
4247 PyErr_Clear();
4248 return 0;
4249 }
4250
4251 return ok;
4252}
4253
Guido van Rossumdc91b992001-08-08 22:26:22 +00004254
4255#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004256static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004257FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004258{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004259 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004260 int do_other = self->ob_type != other->ob_type && \
4261 other->ob_type->tp_as_number != NULL && \
4262 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004263 if (self->ob_type->tp_as_number != NULL && \
4264 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
4265 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004266 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004267 PyType_IsSubtype(other->ob_type, self->ob_type) && \
4268 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004269 r = call_maybe( \
4270 other, ROPSTR, &rcache_str, "(O)", self); \
4271 if (r != Py_NotImplemented) \
4272 return r; \
4273 Py_DECREF(r); \
4274 do_other = 0; \
4275 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004276 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004277 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004278 if (r != Py_NotImplemented || \
4279 other->ob_type == self->ob_type) \
4280 return r; \
4281 Py_DECREF(r); \
4282 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004283 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004284 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004285 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004286 } \
4287 Py_INCREF(Py_NotImplemented); \
4288 return Py_NotImplemented; \
4289}
4290
4291#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4292 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4293
4294#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4295static PyObject * \
4296FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4297{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004298 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004299 return call_method(self, OPSTR, &cache_str, \
4300 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004301}
4302
Martin v. Löwis18e16552006-02-15 17:27:45 +00004303static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004304slot_sq_length(PyObject *self)
4305{
Guido van Rossum2730b132001-08-28 18:22:14 +00004306 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004307 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004308 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004309
4310 if (res == NULL)
4311 return -1;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004312 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004313 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004314 if (len < 0) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00004315 if (!PyErr_Occurred())
4316 PyErr_SetString(PyExc_ValueError,
4317 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004318 return -1;
4319 }
Guido van Rossum26111622001-10-01 16:42:49 +00004320 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004321}
4322
Guido van Rossumf4593e02001-10-03 12:09:30 +00004323/* Super-optimized version of slot_sq_item.
4324 Other slots could do the same... */
4325static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004326slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004327{
4328 static PyObject *getitem_str;
4329 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4330 descrgetfunc f;
4331
4332 if (getitem_str == NULL) {
4333 getitem_str = PyString_InternFromString("__getitem__");
4334 if (getitem_str == NULL)
4335 return NULL;
4336 }
4337 func = _PyType_Lookup(self->ob_type, getitem_str);
4338 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004339 if ((f = func->ob_type->tp_descr_get) == NULL)
4340 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004341 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004342 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004343 if (func == NULL) {
4344 return NULL;
4345 }
4346 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004347 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004348 if (ival != NULL) {
4349 args = PyTuple_New(1);
4350 if (args != NULL) {
4351 PyTuple_SET_ITEM(args, 0, ival);
4352 retval = PyObject_Call(func, args, NULL);
4353 Py_XDECREF(args);
4354 Py_XDECREF(func);
4355 return retval;
4356 }
4357 }
4358 }
4359 else {
4360 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4361 }
4362 Py_XDECREF(args);
4363 Py_XDECREF(ival);
4364 Py_XDECREF(func);
4365 return NULL;
4366}
4367
Martin v. Löwis18e16552006-02-15 17:27:45 +00004368SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004369
4370static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004371slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004372{
4373 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004374 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004375
4376 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004377 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004378 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004379 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004380 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004381 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004382 if (res == NULL)
4383 return -1;
4384 Py_DECREF(res);
4385 return 0;
4386}
4387
4388static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004389slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004390{
4391 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004392 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004393
4394 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004395 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004396 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004397 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004398 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004399 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004400 if (res == NULL)
4401 return -1;
4402 Py_DECREF(res);
4403 return 0;
4404}
4405
4406static int
4407slot_sq_contains(PyObject *self, PyObject *value)
4408{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004409 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004410 int result = -1;
4411
Guido van Rossum60718732001-08-28 17:47:51 +00004412 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004413
Guido van Rossum55f20992001-10-01 17:18:22 +00004414 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004415 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004416 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004417 if (args == NULL)
4418 res = NULL;
4419 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004420 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004421 Py_DECREF(args);
4422 }
4423 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004424 if (res != NULL) {
4425 result = PyObject_IsTrue(res);
4426 Py_DECREF(res);
4427 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004428 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004429 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004430 /* Possible results: -1 and 1 */
4431 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004432 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004433 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004434 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004435}
4436
Tim Peters6d6c1a32001-08-02 04:15:00 +00004437#define slot_mp_length slot_sq_length
4438
Guido van Rossumdc91b992001-08-08 22:26:22 +00004439SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004440
4441static int
4442slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4443{
4444 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004445 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004446
4447 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004448 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004449 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004450 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004451 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004452 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004453 if (res == NULL)
4454 return -1;
4455 Py_DECREF(res);
4456 return 0;
4457}
4458
Guido van Rossumdc91b992001-08-08 22:26:22 +00004459SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4460SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4461SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004462SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4463SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4464
Jeremy Hylton938ace62002-07-17 16:30:39 +00004465static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004466
4467SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4468 nb_power, "__pow__", "__rpow__")
4469
4470static PyObject *
4471slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4472{
Guido van Rossum2730b132001-08-28 18:22:14 +00004473 static PyObject *pow_str;
4474
Guido van Rossumdc91b992001-08-08 22:26:22 +00004475 if (modulus == Py_None)
4476 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004477 /* Three-arg power doesn't use __rpow__. But ternary_op
4478 can call this when the second argument's type uses
4479 slot_nb_power, so check before calling self.__pow__. */
4480 if (self->ob_type->tp_as_number != NULL &&
4481 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4482 return call_method(self, "__pow__", &pow_str,
4483 "(OO)", other, modulus);
4484 }
4485 Py_INCREF(Py_NotImplemented);
4486 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004487}
4488
4489SLOT0(slot_nb_negative, "__neg__")
4490SLOT0(slot_nb_positive, "__pos__")
4491SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004492
4493static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004494slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004495{
Tim Petersea7f75d2002-12-07 21:39:16 +00004496 PyObject *func, *args;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004497 static PyObject *bool_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004498 int result = -1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004499 int from_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004500
Jack Diederich4dafcc42006-11-28 19:15:13 +00004501 func = lookup_maybe(self, "__bool__", &bool_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004502 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004503 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004504 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004505 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004506 if (func == NULL)
4507 return PyErr_Occurred() ? -1 : 1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004508 from_len = 1;
Tim Petersea7f75d2002-12-07 21:39:16 +00004509 }
4510 args = PyTuple_New(0);
4511 if (args != NULL) {
4512 PyObject *temp = PyObject_Call(func, args, NULL);
4513 Py_DECREF(args);
4514 if (temp != NULL) {
Jack Diederich4dafcc42006-11-28 19:15:13 +00004515 if (from_len) {
4516 /* enforced by slot_nb_len */
Jeremy Hylton090a3492003-06-27 16:46:45 +00004517 result = PyObject_IsTrue(temp);
Jack Diederich4dafcc42006-11-28 19:15:13 +00004518 }
4519 else if (PyBool_Check(temp)) {
4520 result = PyObject_IsTrue(temp);
4521 }
Jeremy Hylton090a3492003-06-27 16:46:45 +00004522 else {
4523 PyErr_Format(PyExc_TypeError,
Jack Diederich4dafcc42006-11-28 19:15:13 +00004524 "__bool__ should return "
4525 "bool, returned %s",
4526 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004527 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004528 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004529 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004530 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004531 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004532 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004533 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004534}
4535
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004536
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004537static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004538slot_nb_index(PyObject *self)
4539{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004540 static PyObject *index_str;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004541 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004542}
4543
4544
Guido van Rossumdc91b992001-08-08 22:26:22 +00004545SLOT0(slot_nb_invert, "__invert__")
4546SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4547SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4548SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4549SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4550SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004551
Guido van Rossumdc91b992001-08-08 22:26:22 +00004552SLOT0(slot_nb_int, "__int__")
4553SLOT0(slot_nb_long, "__long__")
4554SLOT0(slot_nb_float, "__float__")
4555SLOT0(slot_nb_oct, "__oct__")
4556SLOT0(slot_nb_hex, "__hex__")
4557SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4558SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4559SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004560SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00004561/* Can't use SLOT1 here, because nb_inplace_power is ternary */
4562static PyObject *
4563slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4564{
4565 static PyObject *cache_str;
4566 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
4567}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004568SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4569SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4570SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4571SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4572SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4573SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4574 "__floordiv__", "__rfloordiv__")
4575SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4576SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4577SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004578
4579static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004580half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004581{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004582 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004583 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004584 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004585
Guido van Rossum60718732001-08-28 17:47:51 +00004586 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004587 if (func == NULL) {
4588 PyErr_Clear();
4589 }
4590 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004591 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004592 if (args == NULL)
4593 res = NULL;
4594 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004595 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004596 Py_DECREF(args);
4597 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004598 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004599 if (res != Py_NotImplemented) {
4600 if (res == NULL)
4601 return -2;
4602 c = PyInt_AsLong(res);
4603 Py_DECREF(res);
4604 if (c == -1 && PyErr_Occurred())
4605 return -2;
4606 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4607 }
4608 Py_DECREF(res);
4609 }
4610 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004611}
4612
Guido van Rossumab3b0342001-09-18 20:38:53 +00004613/* This slot is published for the benefit of try_3way_compare in object.c */
4614int
4615_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004616{
4617 int c;
4618
Guido van Rossumab3b0342001-09-18 20:38:53 +00004619 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004620 c = half_compare(self, other);
4621 if (c <= 1)
4622 return c;
4623 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004624 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004625 c = half_compare(other, self);
4626 if (c < -1)
4627 return -2;
4628 if (c <= 1)
4629 return -c;
4630 }
4631 return (void *)self < (void *)other ? -1 :
4632 (void *)self > (void *)other ? 1 : 0;
4633}
4634
4635static PyObject *
4636slot_tp_repr(PyObject *self)
4637{
4638 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004639 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004640
Guido van Rossum60718732001-08-28 17:47:51 +00004641 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004642 if (func != NULL) {
4643 res = PyEval_CallObject(func, NULL);
4644 Py_DECREF(func);
4645 return res;
4646 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004647 PyErr_Clear();
4648 return PyString_FromFormat("<%s object at %p>",
4649 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004650}
4651
4652static PyObject *
4653slot_tp_str(PyObject *self)
4654{
4655 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004656 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004657
Guido van Rossum60718732001-08-28 17:47:51 +00004658 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004659 if (func != NULL) {
4660 res = PyEval_CallObject(func, NULL);
4661 Py_DECREF(func);
4662 return res;
4663 }
4664 else {
4665 PyErr_Clear();
4666 return slot_tp_repr(self);
4667 }
4668}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004669
4670static long
4671slot_tp_hash(PyObject *self)
4672{
Guido van Rossum4011a242006-08-17 23:09:57 +00004673 PyObject *func, *res;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004674 static PyObject *hash_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004675 long h;
4676
Guido van Rossum60718732001-08-28 17:47:51 +00004677 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004678
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004679 if (func == Py_None) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004680 Py_DECREF(func);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004681 func = NULL;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004682 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004683
4684 if (func == NULL) {
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004685 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
4686 self->ob_type->tp_name);
4687 return -1;
4688 }
4689
Guido van Rossum4011a242006-08-17 23:09:57 +00004690 res = PyEval_CallObject(func, NULL);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004691 Py_DECREF(func);
4692 if (res == NULL)
4693 return -1;
4694 if (PyLong_Check(res))
4695 h = PyLong_Type.tp_hash(res);
4696 else
4697 h = PyInt_AsLong(res);
4698 Py_DECREF(res);
4699 if (h == -1 && !PyErr_Occurred())
4700 h = -2;
4701 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004702}
4703
4704static PyObject *
4705slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4706{
Guido van Rossum60718732001-08-28 17:47:51 +00004707 static PyObject *call_str;
4708 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004709 PyObject *res;
4710
4711 if (meth == NULL)
4712 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004713
4714 /* PyObject_Call() will end up calling slot_tp_call() again if
4715 the object returned for __call__ has __call__ itself defined
4716 upon it. This can be an infinite recursion if you set
4717 __call__ in a class to an instance of it. */
4718 if (Py_EnterRecursiveCall(" in __call__")) {
4719 Py_DECREF(meth);
4720 return NULL;
4721 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004722 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004723 Py_LeaveRecursiveCall();
4724
Tim Peters6d6c1a32001-08-02 04:15:00 +00004725 Py_DECREF(meth);
4726 return res;
4727}
4728
Guido van Rossum14a6f832001-10-17 13:59:09 +00004729/* There are two slot dispatch functions for tp_getattro.
4730
4731 - slot_tp_getattro() is used when __getattribute__ is overridden
4732 but no __getattr__ hook is present;
4733
4734 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4735
Guido van Rossumc334df52002-04-04 23:44:47 +00004736 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4737 detects the absence of __getattr__ and then installs the simpler slot if
4738 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004739
Tim Peters6d6c1a32001-08-02 04:15:00 +00004740static PyObject *
4741slot_tp_getattro(PyObject *self, PyObject *name)
4742{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004743 static PyObject *getattribute_str = NULL;
4744 return call_method(self, "__getattribute__", &getattribute_str,
4745 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004746}
4747
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004748static PyObject *
4749slot_tp_getattr_hook(PyObject *self, PyObject *name)
4750{
4751 PyTypeObject *tp = self->ob_type;
4752 PyObject *getattr, *getattribute, *res;
4753 static PyObject *getattribute_str = NULL;
4754 static PyObject *getattr_str = NULL;
4755
4756 if (getattr_str == NULL) {
4757 getattr_str = PyString_InternFromString("__getattr__");
4758 if (getattr_str == NULL)
4759 return NULL;
4760 }
4761 if (getattribute_str == NULL) {
4762 getattribute_str =
4763 PyString_InternFromString("__getattribute__");
4764 if (getattribute_str == NULL)
4765 return NULL;
4766 }
4767 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004768 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004769 /* No __getattr__ hook: use a simpler dispatcher */
4770 tp->tp_getattro = slot_tp_getattro;
4771 return slot_tp_getattro(self, name);
4772 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004773 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004774 if (getattribute == NULL ||
4775 (getattribute->ob_type == &PyWrapperDescr_Type &&
4776 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4777 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004778 res = PyObject_GenericGetAttr(self, name);
4779 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00004780 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004781 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004782 PyErr_Clear();
Thomas Wouters477c8d52006-05-27 19:21:47 +00004783 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004784 }
4785 return res;
4786}
4787
Tim Peters6d6c1a32001-08-02 04:15:00 +00004788static int
4789slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4790{
4791 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004792 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004793
4794 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004795 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004796 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004797 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004798 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004799 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004800 if (res == NULL)
4801 return -1;
4802 Py_DECREF(res);
4803 return 0;
4804}
4805
Tim Peters6d6c1a32001-08-02 04:15:00 +00004806static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004807half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004808{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004809 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004810 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004811
Guido van Rossum60718732001-08-28 17:47:51 +00004812 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004813 if (func == NULL) {
4814 PyErr_Clear();
4815 Py_INCREF(Py_NotImplemented);
4816 return Py_NotImplemented;
4817 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004818 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004819 if (args == NULL)
4820 res = NULL;
4821 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004822 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004823 Py_DECREF(args);
4824 }
4825 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004826 return res;
4827}
4828
Guido van Rossumb8f63662001-08-15 23:57:02 +00004829static PyObject *
4830slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4831{
4832 PyObject *res;
4833
4834 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4835 res = half_richcompare(self, other, op);
4836 if (res != Py_NotImplemented)
4837 return res;
4838 Py_DECREF(res);
4839 }
4840 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004841 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004842 if (res != Py_NotImplemented) {
4843 return res;
4844 }
4845 Py_DECREF(res);
4846 }
4847 Py_INCREF(Py_NotImplemented);
4848 return Py_NotImplemented;
4849}
4850
4851static PyObject *
4852slot_tp_iter(PyObject *self)
4853{
4854 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004855 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004856
Guido van Rossum60718732001-08-28 17:47:51 +00004857 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004858 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004859 PyObject *args;
4860 args = res = PyTuple_New(0);
4861 if (args != NULL) {
4862 res = PyObject_Call(func, args, NULL);
4863 Py_DECREF(args);
4864 }
4865 Py_DECREF(func);
4866 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004867 }
4868 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004869 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004870 if (func == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004871 PyErr_Format(PyExc_TypeError,
4872 "'%.200s' object is not iterable",
4873 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004874 return NULL;
4875 }
4876 Py_DECREF(func);
4877 return PySeqIter_New(self);
4878}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004879
4880static PyObject *
4881slot_tp_iternext(PyObject *self)
4882{
Guido van Rossum2730b132001-08-28 18:22:14 +00004883 static PyObject *next_str;
Georg Brandla18af4e2007-04-21 15:47:16 +00004884 return call_method(self, "__next__", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004885}
4886
Guido van Rossum1a493502001-08-17 16:47:50 +00004887static PyObject *
4888slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4889{
4890 PyTypeObject *tp = self->ob_type;
4891 PyObject *get;
4892 static PyObject *get_str = NULL;
4893
4894 if (get_str == NULL) {
4895 get_str = PyString_InternFromString("__get__");
4896 if (get_str == NULL)
4897 return NULL;
4898 }
4899 get = _PyType_Lookup(tp, get_str);
4900 if (get == NULL) {
4901 /* Avoid further slowdowns */
4902 if (tp->tp_descr_get == slot_tp_descr_get)
4903 tp->tp_descr_get = NULL;
4904 Py_INCREF(self);
4905 return self;
4906 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004907 if (obj == NULL)
4908 obj = Py_None;
4909 if (type == NULL)
4910 type = Py_None;
Thomas Wouters477c8d52006-05-27 19:21:47 +00004911 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00004912}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004913
4914static int
4915slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4916{
Guido van Rossum2c252392001-08-24 10:13:31 +00004917 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004918 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004919
4920 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004921 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004922 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004923 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004924 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004925 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004926 if (res == NULL)
4927 return -1;
4928 Py_DECREF(res);
4929 return 0;
4930}
4931
4932static int
4933slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4934{
Guido van Rossum60718732001-08-28 17:47:51 +00004935 static PyObject *init_str;
4936 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004937 PyObject *res;
4938
4939 if (meth == NULL)
4940 return -1;
4941 res = PyObject_Call(meth, args, kwds);
4942 Py_DECREF(meth);
4943 if (res == NULL)
4944 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004945 if (res != Py_None) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004946 PyErr_Format(PyExc_TypeError,
4947 "__init__() should return None, not '%.200s'",
4948 res->ob_type->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004949 Py_DECREF(res);
4950 return -1;
4951 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004952 Py_DECREF(res);
4953 return 0;
4954}
4955
4956static PyObject *
4957slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4958{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004959 static PyObject *new_str;
4960 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004961 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004962 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004963
Guido van Rossum7bed2132002-08-08 21:57:53 +00004964 if (new_str == NULL) {
4965 new_str = PyString_InternFromString("__new__");
4966 if (new_str == NULL)
4967 return NULL;
4968 }
4969 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004970 if (func == NULL)
4971 return NULL;
4972 assert(PyTuple_Check(args));
4973 n = PyTuple_GET_SIZE(args);
4974 newargs = PyTuple_New(n+1);
4975 if (newargs == NULL)
4976 return NULL;
4977 Py_INCREF(type);
4978 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4979 for (i = 0; i < n; i++) {
4980 x = PyTuple_GET_ITEM(args, i);
4981 Py_INCREF(x);
4982 PyTuple_SET_ITEM(newargs, i+1, x);
4983 }
4984 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004985 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004986 Py_DECREF(func);
4987 return x;
4988}
4989
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004990static void
4991slot_tp_del(PyObject *self)
4992{
4993 static PyObject *del_str = NULL;
4994 PyObject *del, *res;
4995 PyObject *error_type, *error_value, *error_traceback;
4996
4997 /* Temporarily resurrect the object. */
4998 assert(self->ob_refcnt == 0);
4999 self->ob_refcnt = 1;
5000
5001 /* Save the current exception, if any. */
5002 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5003
5004 /* Execute __del__ method, if any. */
5005 del = lookup_maybe(self, "__del__", &del_str);
5006 if (del != NULL) {
5007 res = PyEval_CallObject(del, NULL);
5008 if (res == NULL)
5009 PyErr_WriteUnraisable(del);
5010 else
5011 Py_DECREF(res);
5012 Py_DECREF(del);
5013 }
5014
5015 /* Restore the saved exception. */
5016 PyErr_Restore(error_type, error_value, error_traceback);
5017
5018 /* Undo the temporary resurrection; can't use DECREF here, it would
5019 * cause a recursive call.
5020 */
5021 assert(self->ob_refcnt > 0);
5022 if (--self->ob_refcnt == 0)
5023 return; /* this is the normal path out */
5024
5025 /* __del__ resurrected it! Make it look like the original Py_DECREF
5026 * never happened.
5027 */
5028 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005029 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005030 _Py_NewReference(self);
5031 self->ob_refcnt = refcnt;
5032 }
5033 assert(!PyType_IS_GC(self->ob_type) ||
5034 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00005035 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5036 * we need to undo that. */
5037 _Py_DEC_REFTOTAL;
5038 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5039 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005040 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5041 * _Py_NewReference bumped tp_allocs: both of those need to be
5042 * undone.
5043 */
5044#ifdef COUNT_ALLOCS
5045 --self->ob_type->tp_frees;
5046 --self->ob_type->tp_allocs;
5047#endif
5048}
5049
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005050
5051/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005052 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005053 structure, which incorporates the additional structures used for numbers,
5054 sequences and mappings.
5055 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005056 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005057 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5058 terminated with an all-zero entry. (This table is further initialized and
5059 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005060
Guido van Rossum6d204072001-10-21 00:44:31 +00005061typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005062
5063#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005064#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005065#undef ETSLOT
5066#undef SQSLOT
5067#undef MPSLOT
5068#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005069#undef UNSLOT
5070#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005071#undef BINSLOT
5072#undef RBINSLOT
5073
Guido van Rossum6d204072001-10-21 00:44:31 +00005074#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005075 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5076 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005077#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5078 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005079 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005080#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005081 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005082 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005083#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5084 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5085#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5086 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5087#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5088 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5089#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5090 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5091 "x." NAME "() <==> " DOC)
5092#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5093 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5094 "x." NAME "(y) <==> x" DOC "y")
5095#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5096 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5097 "x." NAME "(y) <==> x" DOC "y")
5098#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5099 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5100 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005101#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5102 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5103 "x." NAME "(y) <==> " DOC)
5104#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5105 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5106 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005107
5108static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005109 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005110 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005111 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5112 The logic in abstract.c always falls back to nb_add/nb_multiply in
5113 this case. Defining both the nb_* and the sq_* slots to call the
5114 user-defined methods has unexpected side-effects, as shown by
5115 test_descr.notimplemented() */
5116 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005117 "x.__add__(y) <==> x+y"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005118 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005119 "x.__mul__(n) <==> x*n"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005120 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005121 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005122 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5123 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005124 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005125 "x.__getslice__(i, j) <==> x[i:j]\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00005126 \n\
5127 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005128 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005129 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005130 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005131 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005132 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005133 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005134 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00005135 \n\
5136 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005137 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005138 "x.__delslice__(i, j) <==> del x[i:j]\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00005139 \n\
5140 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005141 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5142 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005143 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005144 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005145 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005146 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005147
Martin v. Löwis18e16552006-02-15 17:27:45 +00005148 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005149 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005150 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005151 wrap_binaryfunc,
5152 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005153 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005154 wrap_objobjargproc,
5155 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005156 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005157 wrap_delitem,
5158 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005159
Guido van Rossum6d204072001-10-21 00:44:31 +00005160 BINSLOT("__add__", nb_add, slot_nb_add,
5161 "+"),
5162 RBINSLOT("__radd__", nb_add, slot_nb_add,
5163 "+"),
5164 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5165 "-"),
5166 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5167 "-"),
5168 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5169 "*"),
5170 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5171 "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005172 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5173 "%"),
5174 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5175 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005176 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005177 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005178 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005179 "divmod(y, x)"),
5180 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5181 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5182 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5183 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5184 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5185 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5186 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5187 "abs(x)"),
Jack Diederich4dafcc42006-11-28 19:15:13 +00005188 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005189 "x != 0"),
5190 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5191 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5192 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5193 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5194 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5195 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5196 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5197 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5198 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5199 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5200 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005201 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5202 "int(x)"),
5203 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5204 "long(x)"),
5205 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5206 "float(x)"),
5207 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5208 "oct(x)"),
5209 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5210 "hex(x)"),
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005211 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005212 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005213 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5214 wrap_binaryfunc, "+"),
5215 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5216 wrap_binaryfunc, "-"),
5217 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5218 wrap_binaryfunc, "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005219 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5220 wrap_binaryfunc, "%"),
5221 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005222 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005223 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5224 wrap_binaryfunc, "<<"),
5225 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5226 wrap_binaryfunc, ">>"),
5227 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5228 wrap_binaryfunc, "&"),
5229 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5230 wrap_binaryfunc, "^"),
5231 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5232 wrap_binaryfunc, "|"),
5233 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5234 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5235 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5236 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5237 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5238 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5239 IBSLOT("__itruediv__", nb_inplace_true_divide,
5240 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005241
Guido van Rossum6d204072001-10-21 00:44:31 +00005242 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5243 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005244 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005245 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5246 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005247 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005248 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5249 "x.__cmp__(y) <==> cmp(x,y)"),
5250 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5251 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005252 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5253 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005254 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005255 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5256 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5257 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5258 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5259 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5260 "x.__setattr__('name', value) <==> x.name = value"),
5261 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5262 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5263 "x.__delattr__('name') <==> del x.name"),
5264 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5265 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5266 "x.__lt__(y) <==> x<y"),
5267 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5268 "x.__le__(y) <==> x<=y"),
5269 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5270 "x.__eq__(y) <==> x==y"),
5271 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5272 "x.__ne__(y) <==> x!=y"),
5273 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5274 "x.__gt__(y) <==> x>y"),
5275 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5276 "x.__ge__(y) <==> x>=y"),
5277 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5278 "x.__iter__() <==> iter(x)"),
Georg Brandla18af4e2007-04-21 15:47:16 +00005279 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5280 "x.__next__() <==> next(x)"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005281 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5282 "descr.__get__(obj[, type]) -> value"),
5283 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5284 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005285 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5286 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005287 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005288 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005289 "see x.__class__.__doc__ for signature",
5290 PyWrapperFlag_KEYWORDS),
5291 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005292 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005293 {NULL}
5294};
5295
Guido van Rossumc334df52002-04-04 23:44:47 +00005296/* Given a type pointer and an offset gotten from a slotdef entry, return a
Guido van Rossumd8faa362007-04-27 19:54:29 +00005297 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005298 the offset to the type pointer, since it takes care to indirect through the
5299 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5300 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005301static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005302slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005303{
5304 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005305 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005306
Guido van Rossume5c691a2003-03-07 15:13:17 +00005307 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005308 assert(offset >= 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005309 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5310 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5311 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005312 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005313 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005314 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5315 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005316 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005317 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005318 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5319 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005320 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005321 }
5322 else {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005323 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005324 }
5325 if (ptr != NULL)
5326 ptr += offset;
5327 return (void **)ptr;
5328}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005329
Guido van Rossumc334df52002-04-04 23:44:47 +00005330/* Length of array of slotdef pointers used to store slots with the
5331 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5332 the same __name__, for any __name__. Since that's a static property, it is
5333 appropriate to declare fixed-size arrays for this. */
5334#define MAX_EQUIV 10
5335
5336/* Return a slot pointer for a given name, but ONLY if the attribute has
5337 exactly one slot function. The name must be an interned string. */
5338static void **
5339resolve_slotdups(PyTypeObject *type, PyObject *name)
5340{
5341 /* XXX Maybe this could be optimized more -- but is it worth it? */
5342
5343 /* pname and ptrs act as a little cache */
5344 static PyObject *pname;
5345 static slotdef *ptrs[MAX_EQUIV];
5346 slotdef *p, **pp;
5347 void **res, **ptr;
5348
5349 if (pname != name) {
5350 /* Collect all slotdefs that match name into ptrs. */
5351 pname = name;
5352 pp = ptrs;
5353 for (p = slotdefs; p->name_strobj; p++) {
5354 if (p->name_strobj == name)
5355 *pp++ = p;
5356 }
5357 *pp = NULL;
5358 }
5359
5360 /* Look in all matching slots of the type; if exactly one of these has
Guido van Rossumd8faa362007-04-27 19:54:29 +00005361 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005362 res = NULL;
5363 for (pp = ptrs; *pp; pp++) {
5364 ptr = slotptr(type, (*pp)->offset);
5365 if (ptr == NULL || *ptr == NULL)
5366 continue;
5367 if (res != NULL)
5368 return NULL;
5369 res = ptr;
5370 }
5371 return res;
5372}
5373
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005374/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005375 does some incredibly complex thinking and then sticks something into the
5376 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5377 interests, and then stores a generic wrapper or a specific function into
5378 the slot.) Return a pointer to the next slotdef with a different offset,
5379 because that's convenient for fixup_slot_dispatchers(). */
5380static slotdef *
5381update_one_slot(PyTypeObject *type, slotdef *p)
5382{
5383 PyObject *descr;
5384 PyWrapperDescrObject *d;
5385 void *generic = NULL, *specific = NULL;
5386 int use_generic = 0;
5387 int offset = p->offset;
5388 void **ptr = slotptr(type, offset);
5389
5390 if (ptr == NULL) {
5391 do {
5392 ++p;
5393 } while (p->offset == offset);
5394 return p;
5395 }
5396 do {
5397 descr = _PyType_Lookup(type, p->name_strobj);
5398 if (descr == NULL)
5399 continue;
5400 if (descr->ob_type == &PyWrapperDescr_Type) {
5401 void **tptr = resolve_slotdups(type, p->name_strobj);
5402 if (tptr == NULL || tptr == ptr)
5403 generic = p->function;
5404 d = (PyWrapperDescrObject *)descr;
5405 if (d->d_base->wrapper == p->wrapper &&
5406 PyType_IsSubtype(type, d->d_type))
5407 {
5408 if (specific == NULL ||
5409 specific == d->d_wrapped)
5410 specific = d->d_wrapped;
5411 else
5412 use_generic = 1;
5413 }
5414 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005415 else if (descr->ob_type == &PyCFunction_Type &&
5416 PyCFunction_GET_FUNCTION(descr) ==
5417 (PyCFunction)tp_new_wrapper &&
5418 strcmp(p->name, "__new__") == 0)
5419 {
5420 /* The __new__ wrapper is not a wrapper descriptor,
5421 so must be special-cased differently.
5422 If we don't do this, creating an instance will
5423 always use slot_tp_new which will look up
5424 __new__ in the MRO which will call tp_new_wrapper
5425 which will look through the base classes looking
5426 for a static base and call its tp_new (usually
5427 PyType_GenericNew), after performing various
5428 sanity checks and constructing a new argument
5429 list. Cut all that nonsense short -- this speeds
5430 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005431 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005432 /* XXX I'm not 100% sure that there isn't a hole
5433 in this reasoning that requires additional
5434 sanity checks. I'll buy the first person to
5435 point out a bug in this reasoning a beer. */
5436 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005437 else {
5438 use_generic = 1;
5439 generic = p->function;
5440 }
5441 } while ((++p)->offset == offset);
5442 if (specific && !use_generic)
5443 *ptr = specific;
5444 else
5445 *ptr = generic;
5446 return p;
5447}
5448
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005449/* In the type, update the slots whose slotdefs are gathered in the pp array.
5450 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005451static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005452update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005453{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005454 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005455
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005456 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005457 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005458 return 0;
5459}
5460
Guido van Rossumc334df52002-04-04 23:44:47 +00005461/* Comparison function for qsort() to compare slotdefs by their offset, and
5462 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005463static int
5464slotdef_cmp(const void *aa, const void *bb)
5465{
5466 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5467 int c = a->offset - b->offset;
5468 if (c != 0)
5469 return c;
5470 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005471 /* Cannot use a-b, as this gives off_t,
5472 which may lose precision when converted to int. */
5473 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005474}
5475
Guido van Rossumc334df52002-04-04 23:44:47 +00005476/* Initialize the slotdefs table by adding interned string objects for the
5477 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005478static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005479init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005480{
5481 slotdef *p;
5482 static int initialized = 0;
5483
5484 if (initialized)
5485 return;
5486 for (p = slotdefs; p->name; p++) {
5487 p->name_strobj = PyString_InternFromString(p->name);
5488 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005489 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005490 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005491 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5492 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005493 initialized = 1;
5494}
5495
Guido van Rossumc334df52002-04-04 23:44:47 +00005496/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005497static int
5498update_slot(PyTypeObject *type, PyObject *name)
5499{
Guido van Rossumc334df52002-04-04 23:44:47 +00005500 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005501 slotdef *p;
5502 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005503 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005504
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005505 init_slotdefs();
5506 pp = ptrs;
5507 for (p = slotdefs; p->name; p++) {
5508 /* XXX assume name is interned! */
5509 if (p->name_strobj == name)
5510 *pp++ = p;
5511 }
5512 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005513 for (pp = ptrs; *pp; pp++) {
5514 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005515 offset = p->offset;
5516 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005517 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005518 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005519 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005520 if (ptrs[0] == NULL)
5521 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005522 return update_subclasses(type, name,
5523 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005524}
5525
Guido van Rossumc334df52002-04-04 23:44:47 +00005526/* Store the proper functions in the slot dispatches at class (type)
5527 definition time, based upon which operations the class overrides in its
5528 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005529static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005530fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005531{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005532 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005533
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005534 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005535 for (p = slotdefs; p->name; )
5536 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005537}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005538
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005539static void
5540update_all_slots(PyTypeObject* type)
5541{
5542 slotdef *p;
5543
5544 init_slotdefs();
5545 for (p = slotdefs; p->name; p++) {
5546 /* update_slot returns int but can't actually fail */
5547 update_slot(type, p->name_strobj);
5548 }
5549}
5550
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005551/* recurse_down_subclasses() and update_subclasses() are mutually
5552 recursive functions to call a callback for all subclasses,
5553 but refraining from recursing into subclasses that define 'name'. */
5554
5555static int
5556update_subclasses(PyTypeObject *type, PyObject *name,
5557 update_callback callback, void *data)
5558{
5559 if (callback(type, data) < 0)
5560 return -1;
5561 return recurse_down_subclasses(type, name, callback, data);
5562}
5563
5564static int
5565recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5566 update_callback callback, void *data)
5567{
5568 PyTypeObject *subclass;
5569 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005570 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005571
5572 subclasses = type->tp_subclasses;
5573 if (subclasses == NULL)
5574 return 0;
5575 assert(PyList_Check(subclasses));
5576 n = PyList_GET_SIZE(subclasses);
5577 for (i = 0; i < n; i++) {
5578 ref = PyList_GET_ITEM(subclasses, i);
5579 assert(PyWeakref_CheckRef(ref));
5580 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5581 assert(subclass != NULL);
5582 if ((PyObject *)subclass == Py_None)
5583 continue;
5584 assert(PyType_Check(subclass));
5585 /* Avoid recursing down into unaffected classes */
5586 dict = subclass->tp_dict;
5587 if (dict != NULL && PyDict_Check(dict) &&
5588 PyDict_GetItem(dict, name) != NULL)
5589 continue;
5590 if (update_subclasses(subclass, name, callback, data) < 0)
5591 return -1;
5592 }
5593 return 0;
5594}
5595
Guido van Rossum6d204072001-10-21 00:44:31 +00005596/* This function is called by PyType_Ready() to populate the type's
5597 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005598 function slot (like tp_repr) that's defined in the type, one or more
5599 corresponding descriptors are added in the type's tp_dict dictionary
Guido van Rossumd8faa362007-04-27 19:54:29 +00005600 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005601 cause more than one descriptor to be added (for example, the nb_add
5602 slot adds both __add__ and __radd__ descriptors) and some function
5603 slots compete for the same descriptor (for example both sq_item and
5604 mp_subscript generate a __getitem__ descriptor).
5605
Guido van Rossumd8faa362007-04-27 19:54:29 +00005606 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005607 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005608 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005609 between competing slots: the members of PyHeapTypeObject are listed
5610 from most general to least general, so the most general slot is
5611 preferred. In particular, because as_mapping comes before as_sequence,
5612 for a type that defines both mp_subscript and sq_item, mp_subscript
5613 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005614
5615 This only adds new descriptors and doesn't overwrite entries in
5616 tp_dict that were previously defined. The descriptors contain a
5617 reference to the C function they must call, so that it's safe if they
5618 are copied into a subtype's __dict__ and the subtype has a different
5619 C function in its slot -- calling the method defined by the
5620 descriptor will call the C function that was used to create it,
5621 rather than the C function present in the slot when it is called.
5622 (This is important because a subtype may have a C function in the
5623 slot that calls the method from the dictionary, and we want to avoid
5624 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005625
5626static int
5627add_operators(PyTypeObject *type)
5628{
5629 PyObject *dict = type->tp_dict;
5630 slotdef *p;
5631 PyObject *descr;
5632 void **ptr;
5633
5634 init_slotdefs();
5635 for (p = slotdefs; p->name; p++) {
5636 if (p->wrapper == NULL)
5637 continue;
5638 ptr = slotptr(type, p->offset);
5639 if (!ptr || !*ptr)
5640 continue;
5641 if (PyDict_GetItem(dict, p->name_strobj))
5642 continue;
5643 descr = PyDescr_NewWrapper(type, p, *ptr);
5644 if (descr == NULL)
5645 return -1;
5646 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5647 return -1;
5648 Py_DECREF(descr);
5649 }
5650 if (type->tp_new != NULL) {
5651 if (add_tp_new_wrapper(type) < 0)
5652 return -1;
5653 }
5654 return 0;
5655}
5656
Guido van Rossum705f0f52001-08-24 16:47:00 +00005657
5658/* Cooperative 'super' */
5659
5660typedef struct {
5661 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005662 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005663 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005664 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005665} superobject;
5666
Guido van Rossum6f799372001-09-20 20:46:19 +00005667static PyMemberDef super_members[] = {
5668 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5669 "the class invoking super()"},
5670 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5671 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005672 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005673 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005674 {0}
5675};
5676
Guido van Rossum705f0f52001-08-24 16:47:00 +00005677static void
5678super_dealloc(PyObject *self)
5679{
5680 superobject *su = (superobject *)self;
5681
Guido van Rossum048eb752001-10-02 21:24:57 +00005682 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005683 Py_XDECREF(su->obj);
5684 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005685 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005686 self->ob_type->tp_free(self);
5687}
5688
5689static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005690super_repr(PyObject *self)
5691{
5692 superobject *su = (superobject *)self;
5693
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005694 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005695 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005696 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005697 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005698 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005699 else
5700 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005701 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005702 su->type ? su->type->tp_name : "NULL");
5703}
5704
5705static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005706super_getattro(PyObject *self, PyObject *name)
5707{
5708 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005709 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005710
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005711 if (!skip) {
5712 /* We want __class__ to return the class of the super object
5713 (i.e. super, or a subclass), not the class of su->obj. */
5714 skip = (PyString_Check(name) &&
5715 PyString_GET_SIZE(name) == 9 &&
5716 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5717 }
5718
5719 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005720 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005721 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005722 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005723 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005724
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005725 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005726 mro = starttype->tp_mro;
5727
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005728 if (mro == NULL)
5729 n = 0;
5730 else {
5731 assert(PyTuple_Check(mro));
5732 n = PyTuple_GET_SIZE(mro);
5733 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005734 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005735 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005736 break;
5737 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005738 i++;
5739 res = NULL;
5740 for (; i < n; i++) {
5741 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005742 if (PyType_Check(tmp))
5743 dict = ((PyTypeObject *)tmp)->tp_dict;
Tim Petersa91e9642001-11-14 23:32:33 +00005744 else
5745 continue;
5746 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005747 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005748 Py_INCREF(res);
5749 f = res->ob_type->tp_descr_get;
5750 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005751 tmp = f(res,
5752 /* Only pass 'obj' param if
5753 this is instance-mode super
5754 (See SF ID #743627)
5755 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005756 (su->obj == (PyObject *)
5757 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005758 ? (PyObject *)NULL
5759 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005760 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005761 Py_DECREF(res);
5762 res = tmp;
5763 }
5764 return res;
5765 }
5766 }
5767 }
5768 return PyObject_GenericGetAttr(self, name);
5769}
5770
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005771static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005772supercheck(PyTypeObject *type, PyObject *obj)
5773{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005774 /* Check that a super() call makes sense. Return a type object.
5775
5776 obj can be a new-style class, or an instance of one:
5777
Guido van Rossumd8faa362007-04-27 19:54:29 +00005778 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005779 used for class methods; the return value is obj.
5780
5781 - If it is an instance, it must be an instance of 'type'. This is
5782 the normal case; the return value is obj.__class__.
5783
5784 But... when obj is an instance, we want to allow for the case where
5785 obj->ob_type is not a subclass of type, but obj.__class__ is!
5786 This will allow using super() with a proxy for obj.
5787 */
5788
Guido van Rossum8e80a722003-02-18 19:22:22 +00005789 /* Check for first bullet above (special case) */
5790 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5791 Py_INCREF(obj);
5792 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005793 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005794
5795 /* Normal case */
5796 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005797 Py_INCREF(obj->ob_type);
5798 return obj->ob_type;
5799 }
5800 else {
5801 /* Try the slow way */
5802 static PyObject *class_str = NULL;
5803 PyObject *class_attr;
5804
5805 if (class_str == NULL) {
5806 class_str = PyString_FromString("__class__");
5807 if (class_str == NULL)
5808 return NULL;
5809 }
5810
5811 class_attr = PyObject_GetAttr(obj, class_str);
5812
5813 if (class_attr != NULL &&
5814 PyType_Check(class_attr) &&
5815 (PyTypeObject *)class_attr != obj->ob_type)
5816 {
5817 int ok = PyType_IsSubtype(
5818 (PyTypeObject *)class_attr, type);
5819 if (ok)
5820 return (PyTypeObject *)class_attr;
5821 }
5822
5823 if (class_attr == NULL)
5824 PyErr_Clear();
5825 else
5826 Py_DECREF(class_attr);
5827 }
5828
Guido van Rossumd8faa362007-04-27 19:54:29 +00005829 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005830 "super(type, obj): "
5831 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005832 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005833}
5834
Guido van Rossum705f0f52001-08-24 16:47:00 +00005835static PyObject *
5836super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5837{
5838 superobject *su = (superobject *)self;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005839 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005840
5841 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5842 /* Not binding to an object, or already bound */
5843 Py_INCREF(self);
5844 return self;
5845 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005846 if (su->ob_type != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005847 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005848 call its type */
Thomas Wouters477c8d52006-05-27 19:21:47 +00005849 return PyObject_CallFunctionObjArgs((PyObject *)su->ob_type,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005850 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005851 else {
5852 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005853 PyTypeObject *obj_type = supercheck(su->type, obj);
5854 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005855 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005856 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005857 NULL, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005858 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005859 return NULL;
5860 Py_INCREF(su->type);
5861 Py_INCREF(obj);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005862 newobj->type = su->type;
5863 newobj->obj = obj;
5864 newobj->obj_type = obj_type;
5865 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005866 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005867}
5868
5869static int
5870super_init(PyObject *self, PyObject *args, PyObject *kwds)
5871{
5872 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005873 PyTypeObject *type;
5874 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005875 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005876
Thomas Wouters89f507f2006-12-13 04:49:30 +00005877 if (!_PyArg_NoKeywords("super", kwds))
5878 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005879 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5880 return -1;
5881 if (obj == Py_None)
5882 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005883 if (obj != NULL) {
5884 obj_type = supercheck(type, obj);
5885 if (obj_type == NULL)
5886 return -1;
5887 Py_INCREF(obj);
5888 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005889 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005890 su->type = type;
5891 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005892 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005893 return 0;
5894}
5895
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005896PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005897"super(type) -> unbound super object\n"
5898"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005899"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005900"Typical use to call a cooperative superclass method:\n"
5901"class C(B):\n"
5902" def meth(self, arg):\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +00005903" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005904
Guido van Rossum048eb752001-10-02 21:24:57 +00005905static int
5906super_traverse(PyObject *self, visitproc visit, void *arg)
5907{
5908 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00005909
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005910 Py_VISIT(su->obj);
5911 Py_VISIT(su->type);
5912 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005913
5914 return 0;
5915}
5916
Guido van Rossum705f0f52001-08-24 16:47:00 +00005917PyTypeObject PySuper_Type = {
5918 PyObject_HEAD_INIT(&PyType_Type)
5919 0, /* ob_size */
5920 "super", /* tp_name */
5921 sizeof(superobject), /* tp_basicsize */
5922 0, /* tp_itemsize */
5923 /* methods */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005924 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005925 0, /* tp_print */
5926 0, /* tp_getattr */
5927 0, /* tp_setattr */
5928 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005929 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005930 0, /* tp_as_number */
5931 0, /* tp_as_sequence */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005932 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005933 0, /* tp_hash */
5934 0, /* tp_call */
5935 0, /* tp_str */
5936 super_getattro, /* tp_getattro */
5937 0, /* tp_setattro */
5938 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005939 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5940 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005941 super_doc, /* tp_doc */
5942 super_traverse, /* tp_traverse */
5943 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005944 0, /* tp_richcompare */
5945 0, /* tp_weaklistoffset */
5946 0, /* tp_iter */
5947 0, /* tp_iternext */
5948 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005949 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005950 0, /* tp_getset */
5951 0, /* tp_base */
5952 0, /* tp_dict */
5953 super_descr_get, /* tp_descr_get */
5954 0, /* tp_descr_set */
5955 0, /* tp_dictoffset */
5956 super_init, /* tp_init */
5957 PyType_GenericAlloc, /* tp_alloc */
5958 PyType_GenericNew, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005959 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005960};