blob: a3b1476a8d50c416d5b59e447ab9bebceac8baf4 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
Guido van Rossum6f799372001-09-20 20:46:19 +00008static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00009 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
10 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
11 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000017 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
18 {0}
19};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000020
Guido van Rossumc0b618a1997-05-02 03:12:38 +000021static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000022type_name(PyTypeObject *type, void *context)
23{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +000024 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +000025
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000026 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +000027 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +000028
Georg Brandlc255c7b2006-02-20 22:27:28 +000029 Py_INCREF(et->ht_name);
30 return et->ht_name;
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000031 }
32 else {
33 s = strrchr(type->tp_name, '.');
34 if (s == NULL)
35 s = type->tp_name;
36 else
37 s++;
38 return PyString_FromString(s);
39 }
Guido van Rossumc3542212001-08-16 09:18:56 +000040}
41
Michael W. Hudson98bbc492002-11-26 14:47:27 +000042static int
43type_set_name(PyTypeObject *type, PyObject *value, void *context)
44{
Guido van Rossume5c691a2003-03-07 15:13:17 +000045 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000046
47 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
48 PyErr_Format(PyExc_TypeError,
49 "can't set %s.__name__", type->tp_name);
50 return -1;
51 }
52 if (!value) {
53 PyErr_Format(PyExc_TypeError,
54 "can't delete %s.__name__", type->tp_name);
55 return -1;
56 }
57 if (!PyString_Check(value)) {
58 PyErr_Format(PyExc_TypeError,
59 "can only assign string to %s.__name__, not '%s'",
60 type->tp_name, value->ob_type->tp_name);
61 return -1;
62 }
Tim Petersea7f75d2002-12-07 21:39:16 +000063 if (strlen(PyString_AS_STRING(value))
Michael W. Hudson98bbc492002-11-26 14:47:27 +000064 != (size_t)PyString_GET_SIZE(value)) {
65 PyErr_Format(PyExc_ValueError,
66 "__name__ must not contain null bytes");
67 return -1;
68 }
69
Guido van Rossume5c691a2003-03-07 15:13:17 +000070 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000071
72 Py_INCREF(value);
73
Georg Brandlc255c7b2006-02-20 22:27:28 +000074 Py_DECREF(et->ht_name);
75 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000076
77 type->tp_name = PyString_AS_STRING(value);
78
79 return 0;
80}
81
Guido van Rossumc3542212001-08-16 09:18:56 +000082static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000083type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000084{
Guido van Rossumc3542212001-08-16 09:18:56 +000085 PyObject *mod;
86 char *s;
87
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000088 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
89 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Anthony Baxter3ecdb252004-06-11 14:41:18 +000090 if (!mod) {
91 PyErr_Format(PyExc_AttributeError, "__module__");
92 return 0;
93 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000094 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +000095 return mod;
96 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000097 else {
98 s = strrchr(type->tp_name, '.');
99 if (s != NULL)
100 return PyString_FromStringAndSize(
Armin Rigo7ccbca92006-10-04 12:17:45 +0000101 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000102 return PyString_FromString("__builtin__");
103 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000104}
105
Guido van Rossum3926a632001-09-25 16:25:58 +0000106static int
107type_set_module(PyTypeObject *type, PyObject *value, void *context)
108{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000109 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000110 PyErr_Format(PyExc_TypeError,
111 "can't set %s.__module__", type->tp_name);
112 return -1;
113 }
114 if (!value) {
115 PyErr_Format(PyExc_TypeError,
116 "can't delete %s.__module__", type->tp_name);
117 return -1;
118 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000119
Guido van Rossum3926a632001-09-25 16:25:58 +0000120 return PyDict_SetItemString(type->tp_dict, "__module__", value);
121}
122
Tim Peters6d6c1a32001-08-02 04:15:00 +0000123static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000124type_get_bases(PyTypeObject *type, void *context)
125{
126 Py_INCREF(type->tp_bases);
127 return type->tp_bases;
128}
129
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;
Armin Rigoc0ba52d2007-04-19 14:44:48 +0000190 PyTypeObject *new_base, *old_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000191 PyObject *old_bases, *old_mro;
192
193 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
194 PyErr_Format(PyExc_TypeError,
195 "can't set %s.__bases__", type->tp_name);
196 return -1;
197 }
198 if (!value) {
199 PyErr_Format(PyExc_TypeError,
200 "can't delete %s.__bases__", type->tp_name);
201 return -1;
202 }
203 if (!PyTuple_Check(value)) {
204 PyErr_Format(PyExc_TypeError,
205 "can only assign tuple to %s.__bases__, not %s",
206 type->tp_name, value->ob_type->tp_name);
207 return -1;
208 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000209 if (PyTuple_GET_SIZE(value) == 0) {
210 PyErr_Format(PyExc_TypeError,
211 "can only assign non-empty tuple to %s.__bases__, not ()",
212 type->tp_name);
213 return -1;
214 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000215 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
216 ob = PyTuple_GET_ITEM(value, i);
217 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
218 PyErr_Format(
219 PyExc_TypeError,
220 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
221 type->tp_name, ob->ob_type->tp_name);
222 return -1;
223 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000224 if (PyType_Check(ob)) {
225 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
226 PyErr_SetString(PyExc_TypeError,
227 "a __bases__ item causes an inheritance cycle");
228 return -1;
229 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000230 }
231 }
232
233 new_base = best_base(value);
234
235 if (!new_base) {
236 return -1;
237 }
238
239 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
240 return -1;
241
242 Py_INCREF(new_base);
243 Py_INCREF(value);
244
245 old_bases = type->tp_bases;
246 old_base = type->tp_base;
247 old_mro = type->tp_mro;
248
249 type->tp_bases = value;
250 type->tp_base = new_base;
251
252 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000253 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000254 }
255
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000256 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000257 if (!temp)
258 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000259
260 r = mro_subclasses(type, temp);
261
262 if (r < 0) {
263 for (i = 0; i < PyList_Size(temp); i++) {
264 PyTypeObject* cls;
265 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000266 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
267 "", 2, 2, &cls, &mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000268 Py_DECREF(cls->tp_mro);
269 cls->tp_mro = mro;
270 Py_INCREF(cls->tp_mro);
271 }
272 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000273 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000274 }
275
276 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000277
278 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000279 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000280 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000281 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000282
283 /* for now, sod that: just remove from all old_bases,
284 add to all new_bases */
285
286 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
287 ob = PyTuple_GET_ITEM(old_bases, i);
288 if (PyType_Check(ob)) {
289 remove_subclass(
290 (PyTypeObject*)ob, type);
291 }
292 }
293
294 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
295 ob = PyTuple_GET_ITEM(value, i);
296 if (PyType_Check(ob)) {
297 if (add_subclass((PyTypeObject*)ob, type) < 0)
298 r = -1;
299 }
300 }
301
302 update_all_slots(type);
303
304 Py_DECREF(old_bases);
305 Py_DECREF(old_base);
306 Py_DECREF(old_mro);
307
308 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000309
310 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000311 Py_DECREF(type->tp_bases);
312 Py_DECREF(type->tp_base);
313 if (type->tp_mro != old_mro) {
314 Py_DECREF(type->tp_mro);
315 }
316
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000317 type->tp_bases = old_bases;
318 type->tp_base = old_base;
319 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000320
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000321 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000322}
323
324static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000325type_dict(PyTypeObject *type, void *context)
326{
327 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000328 Py_INCREF(Py_None);
329 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000330 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000331 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000332}
333
Tim Peters24008312002-03-17 18:56:20 +0000334static PyObject *
335type_get_doc(PyTypeObject *type, void *context)
336{
337 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000338 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000339 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000340 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000341 if (result == NULL) {
342 result = Py_None;
343 Py_INCREF(result);
344 }
345 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000346 result = result->ob_type->tp_descr_get(result, NULL,
347 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000348 }
349 else {
350 Py_INCREF(result);
351 }
Tim Peters24008312002-03-17 18:56:20 +0000352 return result;
353}
354
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000355static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000356 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
357 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000358 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000359 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000360 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000361 {0}
362};
363
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000364static int
365type_compare(PyObject *v, PyObject *w)
366{
367 /* This is called with type objects only. So we
368 can just compare the addresses. */
369 Py_uintptr_t vv = (Py_uintptr_t)v;
370 Py_uintptr_t ww = (Py_uintptr_t)w;
371 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
372}
373
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000374static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000375type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000376{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000377 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000378 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000379
380 mod = type_module(type, NULL);
381 if (mod == NULL)
382 PyErr_Clear();
383 else if (!PyString_Check(mod)) {
384 Py_DECREF(mod);
385 mod = NULL;
386 }
387 name = type_name(type, NULL);
388 if (name == NULL)
389 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000390
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000391 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
392 kind = "class";
393 else
394 kind = "type";
395
Barry Warsaw7ce36942001-08-24 18:34:26 +0000396 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000397 rtn = PyString_FromFormat("<%s '%s.%s'>",
398 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000399 PyString_AS_STRING(mod),
400 PyString_AS_STRING(name));
401 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000402 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000403 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000404
Guido van Rossumc3542212001-08-16 09:18:56 +0000405 Py_XDECREF(mod);
406 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000407 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000408}
409
Tim Peters6d6c1a32001-08-02 04:15:00 +0000410static PyObject *
411type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
412{
413 PyObject *obj;
414
415 if (type->tp_new == NULL) {
416 PyErr_Format(PyExc_TypeError,
417 "cannot create '%.100s' instances",
418 type->tp_name);
419 return NULL;
420 }
421
Tim Peters3f996e72001-09-13 19:18:27 +0000422 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000423 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000424 /* Ugly exception: when the call was type(something),
425 don't call tp_init on the result. */
426 if (type == &PyType_Type &&
427 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
428 (kwds == NULL ||
429 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
430 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000431 /* If the returned object is not an instance of type,
432 it won't be initialized. */
433 if (!PyType_IsSubtype(obj->ob_type, type))
434 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000435 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000436 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
437 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000438 type->tp_init(obj, args, kwds) < 0) {
439 Py_DECREF(obj);
440 obj = NULL;
441 }
442 }
443 return obj;
444}
445
446PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000447PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000448{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000449 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000450 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
451 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000452
453 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000454 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000455 else
Anthony Baxtera6286212006-04-11 07:42:36 +0000456 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000457
Neil Schemenauerc806c882001-08-29 23:54:54 +0000458 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000459 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000460
Neil Schemenauerc806c882001-08-29 23:54:54 +0000461 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000462
Tim Peters6d6c1a32001-08-02 04:15:00 +0000463 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
464 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000465
Tim Peters6d6c1a32001-08-02 04:15:00 +0000466 if (type->tp_itemsize == 0)
467 PyObject_INIT(obj, type);
468 else
469 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000470
Tim Peters6d6c1a32001-08-02 04:15:00 +0000471 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000472 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000473 return obj;
474}
475
476PyObject *
477PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
478{
479 return type->tp_alloc(type, 0);
480}
481
Guido van Rossum9475a232001-10-05 20:51:39 +0000482/* Helpers for subtyping */
483
484static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000485traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
486{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000487 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000488 PyMemberDef *mp;
489
490 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000491 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000492 for (i = 0; i < n; i++, mp++) {
493 if (mp->type == T_OBJECT_EX) {
494 char *addr = (char *)self + mp->offset;
495 PyObject *obj = *(PyObject **)addr;
496 if (obj != NULL) {
497 int err = visit(obj, arg);
498 if (err)
499 return err;
500 }
501 }
502 }
503 return 0;
504}
505
506static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000507subtype_traverse(PyObject *self, visitproc visit, void *arg)
508{
509 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000510 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000511
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000512 /* Find the nearest base with a different tp_traverse,
513 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000514 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000515 base = type;
516 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
517 if (base->ob_size) {
518 int err = traverse_slots(base, self, visit, arg);
519 if (err)
520 return err;
521 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000522 base = base->tp_base;
523 assert(base);
524 }
525
526 if (type->tp_dictoffset != base->tp_dictoffset) {
527 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Woutersc6e55062006-04-15 21:47:09 +0000528 if (dictptr && *dictptr)
529 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000530 }
531
Thomas Woutersc6e55062006-04-15 21:47:09 +0000532 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000533 /* For a heaptype, the instances count as references
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000534 to the type. Traverse the type so the collector
Guido van Rossuma3862092002-06-10 15:24:42 +0000535 can find cycles involving this link. */
Thomas Woutersc6e55062006-04-15 21:47:09 +0000536 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000537
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000538 if (basetraverse)
539 return basetraverse(self, visit, arg);
540 return 0;
541}
542
543static void
544clear_slots(PyTypeObject *type, PyObject *self)
545{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000546 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000547 PyMemberDef *mp;
548
549 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000550 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000551 for (i = 0; i < n; i++, mp++) {
552 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
553 char *addr = (char *)self + mp->offset;
554 PyObject *obj = *(PyObject **)addr;
555 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000556 *(PyObject **)addr = NULL;
Thomas Woutersedf17d82006-04-15 17:28:34 +0000557 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000558 }
559 }
560 }
561}
562
563static int
564subtype_clear(PyObject *self)
565{
566 PyTypeObject *type, *base;
567 inquiry baseclear;
568
569 /* Find the nearest base with a different tp_clear
570 and clear slots while we're at it */
571 type = self->ob_type;
572 base = type;
573 while ((baseclear = base->tp_clear) == subtype_clear) {
574 if (base->ob_size)
575 clear_slots(base, self);
576 base = base->tp_base;
577 assert(base);
578 }
579
Guido van Rossuma3862092002-06-10 15:24:42 +0000580 /* There's no need to clear the instance dict (if any);
581 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000582
583 if (baseclear)
584 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000585 return 0;
586}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000587
588static void
589subtype_dealloc(PyObject *self)
590{
Guido van Rossum14227b42001-12-06 02:35:58 +0000591 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000592 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000593
Guido van Rossum22b13872002-08-06 21:41:44 +0000594 /* Extract the type; we expect it to be a heap type */
595 type = self->ob_type;
596 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000597
Guido van Rossum22b13872002-08-06 21:41:44 +0000598 /* Test whether the type has GC exactly once */
599
600 if (!PyType_IS_GC(type)) {
601 /* It's really rare to find a dynamic type that doesn't have
602 GC; it can only happen when deriving from 'object' and not
603 adding any slots or instance variables. This allows
604 certain simplifications: there's no need to call
605 clear_slots(), or DECREF the dict, or clear weakrefs. */
606
607 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000608 if (type->tp_del) {
609 type->tp_del(self);
610 if (self->ob_refcnt > 0)
611 return;
612 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000613
614 /* Find the nearest base with a different tp_dealloc */
615 base = type;
616 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
617 assert(base->ob_size == 0);
618 base = base->tp_base;
619 assert(base);
620 }
621
622 /* Call the base tp_dealloc() */
623 assert(basedealloc);
624 basedealloc(self);
625
626 /* Can't reference self beyond this point */
627 Py_DECREF(type);
628
629 /* Done */
630 return;
631 }
632
633 /* We get here only if the type has GC */
634
635 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000636 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000637 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000638 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000639 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000640 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000641 /* DO NOT restore GC tracking at this point. weakref callbacks
642 * (if any, and whether directly here or indirectly in something we
643 * call) may trigger GC, and if self is tracked at that point, it
644 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000645 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000646
Guido van Rossum59195fd2003-06-13 20:54:40 +0000647 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000648 base = type;
649 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000650 base = base->tp_base;
651 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000652 }
653
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000654 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000655 the finalizer (__del__), clearing slots, or clearing the instance
656 dict. */
657
Guido van Rossum1987c662003-05-29 14:29:23 +0000658 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
659 PyObject_ClearWeakRefs(self);
660
661 /* Maybe call finalizer; exit early if resurrected */
662 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000663 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000664 type->tp_del(self);
665 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000666 goto endlabel; /* resurrected */
667 else
668 _PyObject_GC_UNTRACK(self);
Brett Cannonf5bee302007-01-23 23:21:22 +0000669 /* New weakrefs could be created during the finalizer call.
670 If this occurs, clear them out without calling their
671 finalizers since they might rely on part of the object
672 being finalized that has already been destroyed. */
673 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
674 /* Modeled after GET_WEAKREFS_LISTPTR() */
675 PyWeakReference **list = (PyWeakReference **) \
676 PyObject_GET_WEAKREFS_LISTPTR(self);
677 while (*list)
678 _PyWeakref_ClearRef(*list);
679 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000680 }
681
Guido van Rossum59195fd2003-06-13 20:54:40 +0000682 /* Clear slots up to the nearest base with a different tp_dealloc */
683 base = type;
684 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
685 if (base->ob_size)
686 clear_slots(base, self);
687 base = base->tp_base;
688 assert(base);
689 }
690
Tim Peters6d6c1a32001-08-02 04:15:00 +0000691 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000692 if (type->tp_dictoffset && !base->tp_dictoffset) {
693 PyObject **dictptr = _PyObject_GetDictPtr(self);
694 if (dictptr != NULL) {
695 PyObject *dict = *dictptr;
696 if (dict != NULL) {
697 Py_DECREF(dict);
698 *dictptr = NULL;
699 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000700 }
701 }
702
Tim Peters0bd743c2003-11-13 22:50:00 +0000703 /* Call the base tp_dealloc(); first retrack self if
704 * basedealloc knows about gc.
705 */
706 if (PyType_IS_GC(base))
707 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000708 assert(basedealloc);
709 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000710
711 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000712 Py_DECREF(type);
713
Guido van Rossum0906e072002-08-07 20:42:09 +0000714 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000715 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000716 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000717 --_PyTrash_delete_nesting;
718
719 /* Explanation of the weirdness around the trashcan macros:
720
721 Q. What do the trashcan macros do?
722
723 A. Read the comment titled "Trashcan mechanism" in object.h.
724 For one, this explains why there must be a call to GC-untrack
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000725 before the trashcan begin macro. Without understanding the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000726 trashcan code, the answers to the following questions don't make
727 sense.
728
729 Q. Why do we GC-untrack before the trashcan and then immediately
730 GC-track again afterward?
731
732 A. In the case that the base class is GC-aware, the base class
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000733 probably GC-untracks the object. If it does that using the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000734 UNTRACK macro, this will crash when the object is already
735 untracked. Because we don't know what the base class does, the
736 only safe thing is to make sure the object is tracked when we
737 call the base class dealloc. But... The trashcan begin macro
738 requires that the object is *untracked* before it is called. So
739 the dance becomes:
740
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000741 GC untrack
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000742 trashcan begin
743 GC track
744
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000745 Q. Why did the last question say "immediately GC-track again"?
746 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +0000747
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000748 A. Because the code *used* to re-track immediately. Bad Idea.
749 self has a refcount of 0, and if gc ever gets its hands on it
750 (which can happen if any weakref callback gets invoked), it
751 looks like trash to gc too, and gc also tries to delete self
752 then. But we're already deleting self. Double dealloction is
753 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +0000754
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000755 Q. Why the bizarre (net-zero) manipulation of
756 _PyTrash_delete_nesting around the trashcan macros?
757
758 A. Some base classes (e.g. list) also use the trashcan mechanism.
759 The following scenario used to be possible:
760
761 - suppose the trashcan level is one below the trashcan limit
762
763 - subtype_dealloc() is called
764
765 - the trashcan limit is not yet reached, so the trashcan level
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000766 is incremented and the code between trashcan begin and end is
767 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000768
769 - this destroys much of the object's contents, including its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000770 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000771
772 - basedealloc() is called; this is really list_dealloc(), or
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000773 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000774
775 - the trashcan limit is now reached, so the object is put on the
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000776 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000777
778 - basedealloc() returns
779
780 - subtype_dealloc() decrefs the object's type
781
782 - subtype_dealloc() returns
783
784 - later, the trashcan code starts deleting the objects from its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000785 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000786
787 - subtype_dealloc() is called *AGAIN* for the same object
788
789 - at the very least (if the destroyed slots and __dict__ don't
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000790 cause problems) the object's type gets decref'ed a second
791 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000792
793 The remedy is to make sure that if the code between trashcan
794 begin and end in subtype_dealloc() is called, the code between
795 trashcan begin and end in basedealloc() will also be called.
796 This is done by decrementing the level after passing into the
797 trashcan block, and incrementing it just before leaving the
798 block.
799
800 But now it's possible that a chain of objects consisting solely
801 of objects whose deallocator is subtype_dealloc() will defeat
802 the trashcan mechanism completely: the decremented level means
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000803 that the effective level never reaches the limit. Therefore, we
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000804 *increment* the level *before* entering the trashcan block, and
805 matchingly decrement it after leaving. This means the trashcan
806 code will trigger a little early, but that's no big deal.
807
808 Q. Are there any live examples of code in need of all this
809 complexity?
810
811 A. Yes. See SF bug 668433 for code that crashed (when Python was
812 compiled in debug mode) before the trashcan level manipulations
813 were added. For more discussion, see SF patches 581742, 575073
814 and bug 574207.
815 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000816}
817
Jeremy Hylton938ace62002-07-17 16:30:39 +0000818static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000819
Tim Peters6d6c1a32001-08-02 04:15:00 +0000820/* type test with subclassing support */
821
822int
823PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
824{
825 PyObject *mro;
826
Guido van Rossum9478d072001-09-07 18:52:13 +0000827 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
828 return b == a || b == &PyBaseObject_Type;
829
Tim Peters6d6c1a32001-08-02 04:15:00 +0000830 mro = a->tp_mro;
831 if (mro != NULL) {
832 /* Deal with multiple inheritance without recursion
833 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000834 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000835 assert(PyTuple_Check(mro));
836 n = PyTuple_GET_SIZE(mro);
837 for (i = 0; i < n; i++) {
838 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
839 return 1;
840 }
841 return 0;
842 }
843 else {
844 /* a is not completely initilized yet; follow tp_base */
845 do {
846 if (a == b)
847 return 1;
848 a = a->tp_base;
849 } while (a != NULL);
850 return b == &PyBaseObject_Type;
851 }
852}
853
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000854/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000855 without looking in the instance dictionary
856 (so we can't use PyObject_GetAttr) but still binding
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000857 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +0000858 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000859 static variable used to cache the interned Python string.
860
861 Two variants:
862
863 - lookup_maybe() returns NULL without raising an exception
864 when the _PyType_Lookup() call fails;
865
866 - lookup_method() always raises an exception upon errors.
867*/
Guido van Rossum60718732001-08-28 17:47:51 +0000868
869static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000870lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000871{
872 PyObject *res;
873
874 if (*attrobj == NULL) {
875 *attrobj = PyString_InternFromString(attrstr);
876 if (*attrobj == NULL)
877 return NULL;
878 }
879 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000880 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000881 descrgetfunc f;
882 if ((f = res->ob_type->tp_descr_get) == NULL)
883 Py_INCREF(res);
884 else
885 res = f(res, self, (PyObject *)(self->ob_type));
886 }
887 return res;
888}
889
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000890static PyObject *
891lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
892{
893 PyObject *res = lookup_maybe(self, attrstr, attrobj);
894 if (res == NULL && !PyErr_Occurred())
895 PyErr_SetObject(PyExc_AttributeError, *attrobj);
896 return res;
897}
898
Guido van Rossum2730b132001-08-28 18:22:14 +0000899/* A variation of PyObject_CallMethod that uses lookup_method()
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000900 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +0000901 as lookup_method to cache the interned name string object. */
902
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000903static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000904call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
905{
906 va_list va;
907 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000908 va_start(va, format);
909
Guido van Rossumda21c012001-10-03 00:50:18 +0000910 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000911 if (func == NULL) {
912 va_end(va);
913 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000914 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000915 return NULL;
916 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000917
918 if (format && *format)
919 args = Py_VaBuildValue(format, va);
920 else
921 args = PyTuple_New(0);
922
923 va_end(va);
924
925 if (args == NULL)
926 return NULL;
927
928 assert(PyTuple_Check(args));
929 retval = PyObject_Call(func, args, NULL);
930
931 Py_DECREF(args);
932 Py_DECREF(func);
933
934 return retval;
935}
936
937/* Clone of call_method() that returns NotImplemented when the lookup fails. */
938
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000939static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000940call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
941{
942 va_list va;
943 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000944 va_start(va, format);
945
Guido van Rossumda21c012001-10-03 00:50:18 +0000946 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000947 if (func == NULL) {
948 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000949 if (!PyErr_Occurred()) {
950 Py_INCREF(Py_NotImplemented);
951 return Py_NotImplemented;
952 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000953 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000954 }
955
956 if (format && *format)
957 args = Py_VaBuildValue(format, va);
958 else
959 args = PyTuple_New(0);
960
961 va_end(va);
962
Guido van Rossum717ce002001-09-14 16:58:08 +0000963 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000964 return NULL;
965
Guido van Rossum717ce002001-09-14 16:58:08 +0000966 assert(PyTuple_Check(args));
967 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000968
969 Py_DECREF(args);
970 Py_DECREF(func);
971
972 return retval;
973}
974
Tim Petersa91e9642001-11-14 23:32:33 +0000975static int
976fill_classic_mro(PyObject *mro, PyObject *cls)
977{
978 PyObject *bases, *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000979 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +0000980
981 assert(PyList_Check(mro));
982 assert(PyClass_Check(cls));
983 i = PySequence_Contains(mro, cls);
984 if (i < 0)
985 return -1;
986 if (!i) {
987 if (PyList_Append(mro, cls) < 0)
988 return -1;
989 }
990 bases = ((PyClassObject *)cls)->cl_bases;
991 assert(bases && PyTuple_Check(bases));
992 n = PyTuple_GET_SIZE(bases);
993 for (i = 0; i < n; i++) {
994 base = PyTuple_GET_ITEM(bases, i);
995 if (fill_classic_mro(mro, base) < 0)
996 return -1;
997 }
998 return 0;
999}
1000
1001static PyObject *
1002classic_mro(PyObject *cls)
1003{
1004 PyObject *mro;
1005
1006 assert(PyClass_Check(cls));
1007 mro = PyList_New(0);
1008 if (mro != NULL) {
1009 if (fill_classic_mro(mro, cls) == 0)
1010 return mro;
1011 Py_DECREF(mro);
1012 }
1013 return NULL;
1014}
1015
Tim Petersea7f75d2002-12-07 21:39:16 +00001016/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001017 Method resolution order algorithm C3 described in
1018 "A Monotonic Superclass Linearization for Dylan",
1019 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001020 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001021 (OOPSLA 1996)
1022
Guido van Rossum98f33732002-11-25 21:36:54 +00001023 Some notes about the rules implied by C3:
1024
Tim Petersea7f75d2002-12-07 21:39:16 +00001025 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001026 It isn't legal to repeat a class in a list of base classes.
1027
1028 The next three properties are the 3 constraints in "C3".
1029
Tim Petersea7f75d2002-12-07 21:39:16 +00001030 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001031 If A precedes B in C's MRO, then A will precede B in the MRO of all
1032 subclasses of C.
1033
1034 Monotonicity.
1035 The MRO of a class must be an extension without reordering of the
1036 MRO of each of its superclasses.
1037
1038 Extended Precedence Graph (EPG).
1039 Linearization is consistent if there is a path in the EPG from
1040 each class to all its successors in the linearization. See
1041 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001042 */
1043
Tim Petersea7f75d2002-12-07 21:39:16 +00001044static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001045tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001046 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +00001047 size = PyList_GET_SIZE(list);
1048
1049 for (j = whence+1; j < size; j++) {
1050 if (PyList_GET_ITEM(list, j) == o)
1051 return 1;
1052 }
1053 return 0;
1054}
1055
Guido van Rossum98f33732002-11-25 21:36:54 +00001056static PyObject *
1057class_name(PyObject *cls)
1058{
1059 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1060 if (name == NULL) {
1061 PyErr_Clear();
1062 Py_XDECREF(name);
1063 name = PyObject_Repr(cls);
1064 }
1065 if (name == NULL)
1066 return NULL;
1067 if (!PyString_Check(name)) {
1068 Py_DECREF(name);
1069 return NULL;
1070 }
1071 return name;
1072}
1073
1074static int
1075check_duplicates(PyObject *list)
1076{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001077 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001078 /* Let's use a quadratic time algorithm,
1079 assuming that the bases lists is short.
1080 */
1081 n = PyList_GET_SIZE(list);
1082 for (i = 0; i < n; i++) {
1083 PyObject *o = PyList_GET_ITEM(list, i);
1084 for (j = i + 1; j < n; j++) {
1085 if (PyList_GET_ITEM(list, j) == o) {
1086 o = class_name(o);
1087 PyErr_Format(PyExc_TypeError,
1088 "duplicate base class %s",
1089 o ? PyString_AS_STRING(o) : "?");
1090 Py_XDECREF(o);
1091 return -1;
1092 }
1093 }
1094 }
1095 return 0;
1096}
1097
1098/* Raise a TypeError for an MRO order disagreement.
1099
1100 It's hard to produce a good error message. In the absence of better
1101 insight into error reporting, report the classes that were candidates
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001102 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001103 order in which they should be put in the MRO, but it's hard to
1104 diagnose what constraint can't be satisfied.
1105*/
1106
1107static void
1108set_mro_error(PyObject *to_merge, int *remain)
1109{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001110 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001111 char buf[1000];
1112 PyObject *k, *v;
1113 PyObject *set = PyDict_New();
Georg Brandl5c170fd2006-03-17 19:03:25 +00001114 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001115
1116 to_merge_size = PyList_GET_SIZE(to_merge);
1117 for (i = 0; i < to_merge_size; i++) {
1118 PyObject *L = PyList_GET_ITEM(to_merge, i);
1119 if (remain[i] < PyList_GET_SIZE(L)) {
1120 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Georg Brandl5c170fd2006-03-17 19:03:25 +00001121 if (PyDict_SetItem(set, c, Py_None) < 0) {
1122 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001123 return;
Georg Brandl5c170fd2006-03-17 19:03:25 +00001124 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001125 }
1126 }
1127 n = PyDict_Size(set);
1128
Raymond Hettingerf394df42003-04-06 19:13:41 +00001129 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1130consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001131 i = 0;
Skip Montanaro429433b2006-04-18 00:35:43 +00001132 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001133 PyObject *name = class_name(k);
1134 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1135 name ? PyString_AS_STRING(name) : "?");
1136 Py_XDECREF(name);
Skip Montanaro429433b2006-04-18 00:35:43 +00001137 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001138 buf[off++] = ',';
1139 buf[off] = '\0';
1140 }
1141 }
1142 PyErr_SetString(PyExc_TypeError, buf);
1143 Py_DECREF(set);
1144}
1145
Tim Petersea7f75d2002-12-07 21:39:16 +00001146static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001147pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001148 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001149 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001150 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001151
Guido van Rossum1f121312002-11-14 19:49:16 +00001152 to_merge_size = PyList_GET_SIZE(to_merge);
1153
Guido van Rossum98f33732002-11-25 21:36:54 +00001154 /* remain stores an index into each sublist of to_merge.
1155 remain[i] is the index of the next base in to_merge[i]
1156 that is not included in acc.
1157 */
Anthony Baxtera6286212006-04-11 07:42:36 +00001158 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001159 if (remain == NULL)
1160 return -1;
1161 for (i = 0; i < to_merge_size; i++)
1162 remain[i] = 0;
1163
1164 again:
1165 empty_cnt = 0;
1166 for (i = 0; i < to_merge_size; i++) {
1167 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001168
Guido van Rossum1f121312002-11-14 19:49:16 +00001169 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1170
1171 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1172 empty_cnt++;
1173 continue;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001174 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001175
Guido van Rossum98f33732002-11-25 21:36:54 +00001176 /* Choose next candidate for MRO.
1177
1178 The input sequences alone can determine the choice.
1179 If not, choose the class which appears in the MRO
1180 of the earliest direct superclass of the new class.
1181 */
1182
Guido van Rossum1f121312002-11-14 19:49:16 +00001183 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1184 for (j = 0; j < to_merge_size; j++) {
1185 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001186 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001187 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001188 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001189 }
1190 ok = PyList_Append(acc, candidate);
1191 if (ok < 0) {
1192 PyMem_Free(remain);
1193 return -1;
1194 }
1195 for (j = 0; j < to_merge_size; j++) {
1196 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001197 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1198 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001199 remain[j]++;
1200 }
1201 }
1202 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001203 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001204 }
1205
Guido van Rossum98f33732002-11-25 21:36:54 +00001206 if (empty_cnt == to_merge_size) {
1207 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001208 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001209 }
1210 set_mro_error(to_merge, remain);
1211 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001212 return -1;
1213}
1214
Tim Peters6d6c1a32001-08-02 04:15:00 +00001215static PyObject *
1216mro_implementation(PyTypeObject *type)
1217{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001218 Py_ssize_t i, n;
1219 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001220 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001221 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001222
Guido van Rossum63517572002-06-18 16:44:57 +00001223 if(type->tp_dict == NULL) {
1224 if(PyType_Ready(type) < 0)
1225 return NULL;
1226 }
1227
Guido van Rossum98f33732002-11-25 21:36:54 +00001228 /* Find a superclass linearization that honors the constraints
1229 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001230 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001231
1232 to_merge is a list of lists, where each list is a superclass
1233 linearization implied by a base class. The last element of
1234 to_merge is the declared list of bases.
1235 */
1236
Tim Peters6d6c1a32001-08-02 04:15:00 +00001237 bases = type->tp_bases;
1238 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001239
1240 to_merge = PyList_New(n+1);
1241 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001242 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001243
Tim Peters6d6c1a32001-08-02 04:15:00 +00001244 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001245 PyObject *base = PyTuple_GET_ITEM(bases, i);
1246 PyObject *parentMRO;
1247 if (PyType_Check(base))
1248 parentMRO = PySequence_List(
1249 ((PyTypeObject*)base)->tp_mro);
1250 else
1251 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001252 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001253 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001254 return NULL;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001255 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001256
1257 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001258 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001259
1260 bases_aslist = PySequence_List(bases);
1261 if (bases_aslist == NULL) {
1262 Py_DECREF(to_merge);
1263 return NULL;
1264 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001265 /* This is just a basic sanity check. */
1266 if (check_duplicates(bases_aslist) < 0) {
1267 Py_DECREF(to_merge);
1268 Py_DECREF(bases_aslist);
1269 return NULL;
1270 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001271 PyList_SET_ITEM(to_merge, n, bases_aslist);
1272
1273 result = Py_BuildValue("[O]", (PyObject *)type);
1274 if (result == NULL) {
1275 Py_DECREF(to_merge);
1276 return NULL;
1277 }
1278
1279 ok = pmerge(result, to_merge);
1280 Py_DECREF(to_merge);
1281 if (ok < 0) {
1282 Py_DECREF(result);
1283 return NULL;
1284 }
1285
Tim Peters6d6c1a32001-08-02 04:15:00 +00001286 return result;
1287}
1288
1289static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001290mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001291{
1292 PyTypeObject *type = (PyTypeObject *)self;
1293
Tim Peters6d6c1a32001-08-02 04:15:00 +00001294 return mro_implementation(type);
1295}
1296
1297static int
1298mro_internal(PyTypeObject *type)
1299{
1300 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001301 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001302
1303 if (type->ob_type == &PyType_Type) {
1304 result = mro_implementation(type);
1305 }
1306 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001307 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001308 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001309 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001310 if (mro == NULL)
1311 return -1;
1312 result = PyObject_CallObject(mro, NULL);
1313 Py_DECREF(mro);
1314 }
1315 if (result == NULL)
1316 return -1;
1317 tuple = PySequence_Tuple(result);
1318 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001319 if (tuple == NULL)
1320 return -1;
1321 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001322 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001323 PyObject *cls;
1324 PyTypeObject *solid;
1325
1326 solid = solid_base(type);
1327
1328 len = PyTuple_GET_SIZE(tuple);
1329
1330 for (i = 0; i < len; i++) {
1331 PyTypeObject *t;
1332 cls = PyTuple_GET_ITEM(tuple, i);
1333 if (PyClass_Check(cls))
1334 continue;
1335 else if (!PyType_Check(cls)) {
1336 PyErr_Format(PyExc_TypeError,
1337 "mro() returned a non-class ('%.500s')",
1338 cls->ob_type->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001339 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001340 return -1;
1341 }
1342 t = (PyTypeObject*)cls;
1343 if (!PyType_IsSubtype(solid, solid_base(t))) {
1344 PyErr_Format(PyExc_TypeError,
1345 "mro() returned base with unsuitable layout ('%.500s')",
1346 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001347 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001348 return -1;
1349 }
1350 }
1351 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001352 type->tp_mro = tuple;
1353 return 0;
1354}
1355
1356
1357/* Calculate the best base amongst multiple base classes.
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001358 This is the first one that's on the path to the "solid base". */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001359
1360static PyTypeObject *
1361best_base(PyObject *bases)
1362{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001363 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001364 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001365 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001366
1367 assert(PyTuple_Check(bases));
1368 n = PyTuple_GET_SIZE(bases);
1369 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001370 base = NULL;
1371 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001372 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001373 base_proto = PyTuple_GET_ITEM(bases, i);
1374 if (PyClass_Check(base_proto))
1375 continue;
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001376 if (!PyType_Check(base_proto)) {
1377 PyErr_SetString(
1378 PyExc_TypeError,
1379 "bases must be types");
1380 return NULL;
1381 }
Tim Petersa91e9642001-11-14 23:32:33 +00001382 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001383 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001384 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001385 return NULL;
1386 }
1387 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001388 if (winner == NULL) {
1389 winner = candidate;
1390 base = base_i;
1391 }
1392 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001393 ;
1394 else if (PyType_IsSubtype(candidate, winner)) {
1395 winner = candidate;
1396 base = base_i;
1397 }
1398 else {
1399 PyErr_SetString(
1400 PyExc_TypeError,
1401 "multiple bases have "
1402 "instance lay-out conflict");
1403 return NULL;
1404 }
1405 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001406 if (base == NULL)
1407 PyErr_SetString(PyExc_TypeError,
1408 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001409 return base;
1410}
1411
1412static int
1413extra_ivars(PyTypeObject *type, PyTypeObject *base)
1414{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001415 size_t t_size = type->tp_basicsize;
1416 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001417
Guido van Rossum9676b222001-08-17 20:32:36 +00001418 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001419 if (type->tp_itemsize || base->tp_itemsize) {
1420 /* If itemsize is involved, stricter rules */
1421 return t_size != b_size ||
1422 type->tp_itemsize != base->tp_itemsize;
1423 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001424 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1425 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1426 t_size -= sizeof(PyObject *);
1427 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1428 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1429 t_size -= sizeof(PyObject *);
1430
1431 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001432}
1433
1434static PyTypeObject *
1435solid_base(PyTypeObject *type)
1436{
1437 PyTypeObject *base;
1438
1439 if (type->tp_base)
1440 base = solid_base(type->tp_base);
1441 else
1442 base = &PyBaseObject_Type;
1443 if (extra_ivars(type, base))
1444 return type;
1445 else
1446 return base;
1447}
1448
Jeremy Hylton938ace62002-07-17 16:30:39 +00001449static void object_dealloc(PyObject *);
1450static int object_init(PyObject *, PyObject *, PyObject *);
1451static int update_slot(PyTypeObject *, PyObject *);
1452static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001453
1454static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001455subtype_dict(PyObject *obj, void *context)
1456{
1457 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1458 PyObject *dict;
1459
1460 if (dictptr == NULL) {
1461 PyErr_SetString(PyExc_AttributeError,
1462 "This object has no __dict__");
1463 return NULL;
1464 }
1465 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001466 if (dict == NULL)
1467 *dictptr = dict = PyDict_New();
1468 Py_XINCREF(dict);
1469 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001470}
1471
Guido van Rossum6661be32001-10-26 04:26:12 +00001472static int
1473subtype_setdict(PyObject *obj, PyObject *value, void *context)
1474{
1475 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1476 PyObject *dict;
1477
1478 if (dictptr == NULL) {
1479 PyErr_SetString(PyExc_AttributeError,
1480 "This object has no __dict__");
1481 return -1;
1482 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001483 if (value != NULL && !PyDict_Check(value)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001484 PyErr_Format(PyExc_TypeError,
1485 "__dict__ must be set to a dictionary, "
1486 "not a '%.200s'", value->ob_type->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001487 return -1;
1488 }
1489 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001490 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001491 *dictptr = value;
1492 Py_XDECREF(dict);
1493 return 0;
1494}
1495
Guido van Rossumad47da02002-08-12 19:05:44 +00001496static PyObject *
1497subtype_getweakref(PyObject *obj, void *context)
1498{
1499 PyObject **weaklistptr;
1500 PyObject *result;
1501
1502 if (obj->ob_type->tp_weaklistoffset == 0) {
1503 PyErr_SetString(PyExc_AttributeError,
Fred Drake7a36f5f2006-08-04 05:17:21 +00001504 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001505 return NULL;
1506 }
1507 assert(obj->ob_type->tp_weaklistoffset > 0);
1508 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001509 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001510 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001511 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001512 if (*weaklistptr == NULL)
1513 result = Py_None;
1514 else
1515 result = *weaklistptr;
1516 Py_INCREF(result);
1517 return result;
1518}
1519
Guido van Rossum373c7412003-01-07 13:41:37 +00001520/* Three variants on the subtype_getsets list. */
1521
1522static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001523 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001524 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001525 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001526 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001527 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001528};
1529
Guido van Rossum373c7412003-01-07 13:41:37 +00001530static PyGetSetDef subtype_getsets_dict_only[] = {
1531 {"__dict__", subtype_dict, subtype_setdict,
1532 PyDoc_STR("dictionary for instance variables (if defined)")},
1533 {0}
1534};
1535
1536static PyGetSetDef subtype_getsets_weakref_only[] = {
1537 {"__weakref__", subtype_getweakref, NULL,
1538 PyDoc_STR("list of weak references to the object (if defined)")},
1539 {0}
1540};
1541
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001542static int
1543valid_identifier(PyObject *s)
1544{
Guido van Rossum03013a02002-07-16 14:30:28 +00001545 unsigned char *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001546 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001547
1548 if (!PyString_Check(s)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001549 PyErr_Format(PyExc_TypeError,
1550 "__slots__ items must be strings, not '%.200s'",
1551 s->ob_type->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001552 return 0;
1553 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001554 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001555 n = PyString_GET_SIZE(s);
1556 /* We must reject an empty name. As a hack, we bump the
1557 length to 1 so that the loop will balk on the trailing \0. */
1558 if (n == 0)
1559 n = 1;
1560 for (i = 0; i < n; i++, p++) {
1561 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1562 PyErr_SetString(PyExc_TypeError,
1563 "__slots__ must be identifiers");
1564 return 0;
1565 }
1566 }
1567 return 1;
1568}
1569
Martin v. Löwisd919a592002-10-14 21:07:28 +00001570#ifdef Py_USING_UNICODE
1571/* Replace Unicode objects in slots. */
1572
1573static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001574_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001575{
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001576 PyObject *tmp = NULL;
1577 PyObject *slot_name, *new_name;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001578 Py_ssize_t i;
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001579
Martin v. Löwisd919a592002-10-14 21:07:28 +00001580 for (i = 0; i < nslots; i++) {
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001581 if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
1582 if (tmp == NULL) {
1583 tmp = PySequence_List(slots);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001584 if (tmp == NULL)
1585 return NULL;
1586 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001587 new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
1588 NULL);
1589 if (new_name == NULL) {
Martin v. Löwisd919a592002-10-14 21:07:28 +00001590 Py_DECREF(tmp);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001591 return NULL;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001592 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001593 Py_INCREF(new_name);
1594 PyList_SET_ITEM(tmp, i, new_name);
1595 Py_DECREF(slot_name);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001596 }
1597 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001598 if (tmp != NULL) {
1599 slots = PyList_AsTuple(tmp);
1600 Py_DECREF(tmp);
1601 }
1602 return slots;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001603}
1604#endif
1605
Guido van Rossumf102e242007-03-23 18:53:03 +00001606/* Forward */
1607static int
1608object_init(PyObject *self, PyObject *args, PyObject *kwds);
1609
1610static int
1611type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1612{
1613 int res;
1614
1615 assert(args != NULL && PyTuple_Check(args));
1616 assert(kwds == NULL || PyDict_Check(kwds));
1617
1618 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1619 PyErr_SetString(PyExc_TypeError,
1620 "type.__init__() takes no keyword arguments");
1621 return -1;
1622 }
1623
1624 if (args != NULL && PyTuple_Check(args) &&
1625 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1626 PyErr_SetString(PyExc_TypeError,
1627 "type.__init__() takes 1 or 3 arguments");
1628 return -1;
1629 }
1630
1631 /* Call object.__init__(self) now. */
1632 /* XXX Could call super(type, cls).__init__() but what's the point? */
1633 args = PyTuple_GetSlice(args, 0, 0);
1634 res = object_init(cls, args, NULL);
1635 Py_DECREF(args);
1636 return res;
1637}
1638
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001639static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001640type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1641{
1642 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001643 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001644 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001645 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001646 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001647 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001648 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001649 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001650
Tim Peters3abca122001-10-27 19:37:48 +00001651 assert(args != NULL && PyTuple_Check(args));
1652 assert(kwds == NULL || PyDict_Check(kwds));
1653
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001654 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001655 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001656 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1657 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001658
1659 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1660 PyObject *x = PyTuple_GET_ITEM(args, 0);
1661 Py_INCREF(x->ob_type);
1662 return (PyObject *) x->ob_type;
1663 }
1664
1665 /* SF bug 475327 -- if that didn't trigger, we need 3
1666 arguments. but PyArg_ParseTupleAndKeywords below may give
1667 a msg saying type() needs exactly 3. */
1668 if (nargs + nkwds != 3) {
1669 PyErr_SetString(PyExc_TypeError,
1670 "type() takes 1 or 3 arguments");
1671 return NULL;
1672 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001673 }
1674
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001675 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001676 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1677 &name,
1678 &PyTuple_Type, &bases,
1679 &PyDict_Type, &dict))
1680 return NULL;
1681
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001682 /* Determine the proper metatype to deal with this,
1683 and check for metatype conflicts while we're at it.
1684 Note that if some other metatype wins to contract,
1685 it's possible that its instances are not types. */
1686 nbases = PyTuple_GET_SIZE(bases);
1687 winner = metatype;
1688 for (i = 0; i < nbases; i++) {
1689 tmp = PyTuple_GET_ITEM(bases, i);
1690 tmptype = tmp->ob_type;
1691 if (tmptype == &PyClass_Type)
1692 continue; /* Special case classic classes */
1693 if (PyType_IsSubtype(winner, tmptype))
1694 continue;
1695 if (PyType_IsSubtype(tmptype, winner)) {
1696 winner = tmptype;
1697 continue;
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001698 }
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001699 PyErr_SetString(PyExc_TypeError,
1700 "metaclass conflict: "
1701 "the metaclass of a derived class "
1702 "must be a (non-strict) subclass "
1703 "of the metaclasses of all its bases");
1704 return NULL;
1705 }
1706 if (winner != metatype) {
1707 if (winner->tp_new != type_new) /* Pass it to the winner */
1708 return winner->tp_new(winner, args, kwds);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001709 metatype = winner;
1710 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001711
1712 /* Adjust for empty tuple bases */
1713 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001714 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001715 if (bases == NULL)
1716 return NULL;
1717 nbases = 1;
1718 }
1719 else
1720 Py_INCREF(bases);
1721
1722 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1723
1724 /* Calculate best base, and check that all bases are type objects */
1725 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001726 if (base == NULL) {
1727 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001728 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001729 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001730 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1731 PyErr_Format(PyExc_TypeError,
1732 "type '%.100s' is not an acceptable base type",
1733 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001734 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001735 return NULL;
1736 }
1737
Tim Peters6d6c1a32001-08-02 04:15:00 +00001738 /* Check for a __slots__ sequence variable in dict, and count it */
1739 slots = PyDict_GetItemString(dict, "__slots__");
1740 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001741 add_dict = 0;
1742 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001743 may_add_dict = base->tp_dictoffset == 0;
1744 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1745 if (slots == NULL) {
1746 if (may_add_dict) {
1747 add_dict++;
1748 }
1749 if (may_add_weak) {
1750 add_weak++;
1751 }
1752 }
1753 else {
1754 /* Have slots */
1755
Tim Peters6d6c1a32001-08-02 04:15:00 +00001756 /* Make it into a tuple */
Neal Norwitzcbd9ee62007-04-14 05:25:50 +00001757 if (PyString_Check(slots) || PyUnicode_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001758 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001759 else
1760 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001761 if (slots == NULL) {
1762 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001763 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001764 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001765 assert(PyTuple_Check(slots));
1766
1767 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001768 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001769 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001770 PyErr_Format(PyExc_TypeError,
1771 "nonempty __slots__ "
1772 "not supported for subtype of '%s'",
1773 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001774 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001775 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001776 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001777 return NULL;
1778 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001779
Martin v. Löwisd919a592002-10-14 21:07:28 +00001780#ifdef Py_USING_UNICODE
1781 tmp = _unicode_to_string(slots, nslots);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001782 if (tmp == NULL)
1783 goto bad_slots;
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001784 if (tmp != slots) {
1785 Py_DECREF(slots);
1786 slots = tmp;
1787 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001788#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001789 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001790 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001791 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1792 char *s;
1793 if (!valid_identifier(tmp))
1794 goto bad_slots;
1795 assert(PyString_Check(tmp));
1796 s = PyString_AS_STRING(tmp);
1797 if (strcmp(s, "__dict__") == 0) {
1798 if (!may_add_dict || add_dict) {
1799 PyErr_SetString(PyExc_TypeError,
1800 "__dict__ slot disallowed: "
1801 "we already got one");
1802 goto bad_slots;
1803 }
1804 add_dict++;
1805 }
1806 if (strcmp(s, "__weakref__") == 0) {
1807 if (!may_add_weak || add_weak) {
1808 PyErr_SetString(PyExc_TypeError,
1809 "__weakref__ slot disallowed: "
1810 "either we already got one, "
1811 "or __itemsize__ != 0");
1812 goto bad_slots;
1813 }
1814 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001815 }
1816 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001817
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00001818 /* Copy slots into a list, mangle names and sort them.
1819 Sorted names are needed for __class__ assignment.
1820 Convert them back to tuple at the end.
1821 */
1822 newslots = PyList_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001823 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001824 goto bad_slots;
1825 for (i = j = 0; i < nslots; i++) {
1826 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001827 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001828 s = PyString_AS_STRING(tmp);
1829 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1830 (add_weak && strcmp(s, "__weakref__") == 0))
1831 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001832 tmp =_Py_Mangle(name, tmp);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001833 if (!tmp)
1834 goto bad_slots;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00001835 PyList_SET_ITEM(newslots, j, tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00001836 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001837 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001838 assert(j == nslots - add_dict - add_weak);
1839 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001840 Py_DECREF(slots);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00001841 if (PyList_Sort(newslots) == -1) {
1842 Py_DECREF(bases);
1843 Py_DECREF(newslots);
1844 return NULL;
1845 }
1846 slots = PyList_AsTuple(newslots);
1847 Py_DECREF(newslots);
1848 if (slots == NULL) {
1849 Py_DECREF(bases);
1850 return NULL;
1851 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001852
Guido van Rossumad47da02002-08-12 19:05:44 +00001853 /* Secondary bases may provide weakrefs or dict */
1854 if (nbases > 1 &&
1855 ((may_add_dict && !add_dict) ||
1856 (may_add_weak && !add_weak))) {
1857 for (i = 0; i < nbases; i++) {
1858 tmp = PyTuple_GET_ITEM(bases, i);
1859 if (tmp == (PyObject *)base)
1860 continue; /* Skip primary base */
1861 if (PyClass_Check(tmp)) {
1862 /* Classic base class provides both */
1863 if (may_add_dict && !add_dict)
1864 add_dict++;
1865 if (may_add_weak && !add_weak)
1866 add_weak++;
1867 break;
1868 }
1869 assert(PyType_Check(tmp));
1870 tmptype = (PyTypeObject *)tmp;
1871 if (may_add_dict && !add_dict &&
1872 tmptype->tp_dictoffset != 0)
1873 add_dict++;
1874 if (may_add_weak && !add_weak &&
1875 tmptype->tp_weaklistoffset != 0)
1876 add_weak++;
1877 if (may_add_dict && !add_dict)
1878 continue;
1879 if (may_add_weak && !add_weak)
1880 continue;
1881 /* Nothing more to check */
1882 break;
1883 }
1884 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001885 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001886
1887 /* XXX From here until type is safely allocated,
1888 "return NULL" may leak slots! */
1889
1890 /* Allocate the type object */
1891 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001892 if (type == NULL) {
1893 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001894 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001895 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001896 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001897
1898 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001899 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001900 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00001901 et->ht_name = name;
1902 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001903
Guido van Rossumdc91b992001-08-08 22:26:22 +00001904 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001905 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1906 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001907 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1908 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001909
1910 /* It's a new-style number unless it specifically inherits any
1911 old-style numeric behavior */
1912 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1913 (base->tp_as_number == NULL))
1914 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1915
1916 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001917 type->tp_as_number = &et->as_number;
1918 type->tp_as_sequence = &et->as_sequence;
1919 type->tp_as_mapping = &et->as_mapping;
1920 type->tp_as_buffer = &et->as_buffer;
1921 type->tp_name = PyString_AS_STRING(name);
1922
1923 /* Set tp_base and tp_bases */
1924 type->tp_bases = bases;
1925 Py_INCREF(base);
1926 type->tp_base = base;
1927
Guido van Rossum687ae002001-10-15 22:03:32 +00001928 /* Initialize tp_dict from passed-in dict */
1929 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001930 if (dict == NULL) {
1931 Py_DECREF(type);
1932 return NULL;
1933 }
1934
Guido van Rossumc3542212001-08-16 09:18:56 +00001935 /* Set __module__ in the dict */
1936 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1937 tmp = PyEval_GetGlobals();
1938 if (tmp != NULL) {
1939 tmp = PyDict_GetItemString(tmp, "__name__");
1940 if (tmp != NULL) {
1941 if (PyDict_SetItemString(dict, "__module__",
1942 tmp) < 0)
1943 return NULL;
1944 }
1945 }
1946 }
1947
Tim Peters2f93e282001-10-04 05:27:00 +00001948 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001949 and is a string. The __doc__ accessor will first look for tp_doc;
1950 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001951 */
1952 {
1953 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1954 if (doc != NULL && PyString_Check(doc)) {
1955 const size_t n = (size_t)PyString_GET_SIZE(doc);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001956 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001957 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00001958 Py_DECREF(type);
1959 return NULL;
1960 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001961 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001962 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00001963 }
1964 }
1965
Tim Peters6d6c1a32001-08-02 04:15:00 +00001966 /* Special-case __new__: if it's a plain function,
1967 make it a static function */
1968 tmp = PyDict_GetItemString(dict, "__new__");
1969 if (tmp != NULL && PyFunction_Check(tmp)) {
1970 tmp = PyStaticMethod_New(tmp);
1971 if (tmp == NULL) {
1972 Py_DECREF(type);
1973 return NULL;
1974 }
1975 PyDict_SetItemString(dict, "__new__", tmp);
1976 Py_DECREF(tmp);
1977 }
1978
1979 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001980 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001981 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001982 if (slots != NULL) {
1983 for (i = 0; i < nslots; i++, mp++) {
1984 mp->name = PyString_AS_STRING(
1985 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001986 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001987 mp->offset = slotoffset;
Žiga Seilnacht89032082007-03-11 15:54:54 +00001988
1989 /* __dict__ and __weakref__ are already filtered out */
1990 assert(strcmp(mp->name, "__dict__") != 0);
1991 assert(strcmp(mp->name, "__weakref__") != 0);
1992
Tim Peters6d6c1a32001-08-02 04:15:00 +00001993 slotoffset += sizeof(PyObject *);
1994 }
1995 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001996 if (add_dict) {
1997 if (base->tp_itemsize)
1998 type->tp_dictoffset = -(long)sizeof(PyObject *);
1999 else
2000 type->tp_dictoffset = slotoffset;
2001 slotoffset += sizeof(PyObject *);
2002 }
2003 if (add_weak) {
2004 assert(!base->tp_itemsize);
2005 type->tp_weaklistoffset = slotoffset;
2006 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002007 }
2008 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002009 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00002010 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002011
2012 if (type->tp_weaklistoffset && type->tp_dictoffset)
2013 type->tp_getset = subtype_getsets_full;
2014 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2015 type->tp_getset = subtype_getsets_weakref_only;
2016 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2017 type->tp_getset = subtype_getsets_dict_only;
2018 else
2019 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002020
2021 /* Special case some slots */
2022 if (type->tp_dictoffset != 0 || nslots > 0) {
2023 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2024 type->tp_getattro = PyObject_GenericGetAttr;
2025 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2026 type->tp_setattro = PyObject_GenericSetAttr;
2027 }
2028 type->tp_dealloc = subtype_dealloc;
2029
Guido van Rossum9475a232001-10-05 20:51:39 +00002030 /* Enable GC unless there are really no instance variables possible */
2031 if (!(type->tp_basicsize == sizeof(PyObject) &&
2032 type->tp_itemsize == 0))
2033 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2034
Tim Peters6d6c1a32001-08-02 04:15:00 +00002035 /* Always override allocation strategy to use regular heap */
2036 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00002037 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002038 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00002039 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002040 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00002041 }
2042 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002043 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002044
2045 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002046 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002047 Py_DECREF(type);
2048 return NULL;
2049 }
2050
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002051 /* Put the proper slots in place */
2052 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002053
Tim Peters6d6c1a32001-08-02 04:15:00 +00002054 return (PyObject *)type;
2055}
2056
2057/* Internal API to look for a name through the MRO.
2058 This returns a borrowed reference, and doesn't set an exception! */
2059PyObject *
2060_PyType_Lookup(PyTypeObject *type, PyObject *name)
2061{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002062 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002063 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002064
Guido van Rossum687ae002001-10-15 22:03:32 +00002065 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002066 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002067
2068 /* If mro is NULL, the type is either not yet initialized
2069 by PyType_Ready(), or already cleared by type_clear().
2070 Either way the safest thing to do is to return NULL. */
2071 if (mro == NULL)
2072 return NULL;
2073
Tim Peters6d6c1a32001-08-02 04:15:00 +00002074 assert(PyTuple_Check(mro));
2075 n = PyTuple_GET_SIZE(mro);
2076 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002077 base = PyTuple_GET_ITEM(mro, i);
2078 if (PyClass_Check(base))
2079 dict = ((PyClassObject *)base)->cl_dict;
2080 else {
2081 assert(PyType_Check(base));
2082 dict = ((PyTypeObject *)base)->tp_dict;
2083 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002084 assert(dict && PyDict_Check(dict));
2085 res = PyDict_GetItem(dict, name);
2086 if (res != NULL)
2087 return res;
2088 }
2089 return NULL;
2090}
2091
2092/* This is similar to PyObject_GenericGetAttr(),
2093 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2094static PyObject *
2095type_getattro(PyTypeObject *type, PyObject *name)
2096{
2097 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002098 PyObject *meta_attribute, *attribute;
2099 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002100
2101 /* Initialize this type (we'll assume the metatype is initialized) */
2102 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002103 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002104 return NULL;
2105 }
2106
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002107 /* No readable descriptor found yet */
2108 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002109
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002110 /* Look for the attribute in the metatype */
2111 meta_attribute = _PyType_Lookup(metatype, name);
2112
2113 if (meta_attribute != NULL) {
2114 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002115
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002116 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2117 /* Data descriptors implement tp_descr_set to intercept
2118 * writes. Assume the attribute is not overridden in
2119 * type's tp_dict (and bases): call the descriptor now.
2120 */
2121 return meta_get(meta_attribute, (PyObject *)type,
2122 (PyObject *)metatype);
2123 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002124 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002125 }
2126
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002127 /* No data descriptor found on metatype. Look in tp_dict of this
2128 * type and its bases */
2129 attribute = _PyType_Lookup(type, name);
2130 if (attribute != NULL) {
2131 /* Implement descriptor functionality, if any */
2132 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002133
2134 Py_XDECREF(meta_attribute);
2135
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002136 if (local_get != NULL) {
2137 /* NULL 2nd argument indicates the descriptor was
2138 * found on the target object itself (or a base) */
2139 return local_get(attribute, (PyObject *)NULL,
2140 (PyObject *)type);
2141 }
Tim Peters34592512002-07-11 06:23:50 +00002142
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002143 Py_INCREF(attribute);
2144 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002145 }
2146
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002147 /* No attribute found in local __dict__ (or bases): use the
2148 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002149 if (meta_get != NULL) {
2150 PyObject *res;
2151 res = meta_get(meta_attribute, (PyObject *)type,
2152 (PyObject *)metatype);
2153 Py_DECREF(meta_attribute);
2154 return res;
2155 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002156
2157 /* If an ordinary attribute was found on the metatype, return it now */
2158 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002159 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002160 }
2161
2162 /* Give up */
2163 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002164 "type object '%.50s' has no attribute '%.400s'",
2165 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002166 return NULL;
2167}
2168
2169static int
2170type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2171{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002172 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2173 PyErr_Format(
2174 PyExc_TypeError,
2175 "can't set attributes of built-in/extension type '%s'",
2176 type->tp_name);
2177 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002178 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002179 /* XXX Example of how I expect this to be used...
2180 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2181 return -1;
2182 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002183 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2184 return -1;
2185 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002186}
2187
2188static void
2189type_dealloc(PyTypeObject *type)
2190{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002191 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002192
2193 /* Assert this is a heap-allocated type object */
2194 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002195 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002196 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002197 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002198 Py_XDECREF(type->tp_base);
2199 Py_XDECREF(type->tp_dict);
2200 Py_XDECREF(type->tp_bases);
2201 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002202 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002203 Py_XDECREF(type->tp_subclasses);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002204 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2205 * of most other objects. It's okay to cast it to char *.
2206 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002207 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002208 Py_XDECREF(et->ht_name);
2209 Py_XDECREF(et->ht_slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002210 type->ob_type->tp_free((PyObject *)type);
2211}
2212
Guido van Rossum1c450732001-10-08 15:18:27 +00002213static PyObject *
2214type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2215{
2216 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002217 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002218
2219 list = PyList_New(0);
2220 if (list == NULL)
2221 return NULL;
2222 raw = type->tp_subclasses;
2223 if (raw == NULL)
2224 return list;
2225 assert(PyList_Check(raw));
2226 n = PyList_GET_SIZE(raw);
2227 for (i = 0; i < n; i++) {
2228 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002229 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002230 ref = PyWeakref_GET_OBJECT(ref);
2231 if (ref != Py_None) {
2232 if (PyList_Append(list, ref) < 0) {
2233 Py_DECREF(list);
2234 return NULL;
2235 }
2236 }
2237 }
2238 return list;
2239}
2240
Tim Peters6d6c1a32001-08-02 04:15:00 +00002241static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002242 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002243 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002244 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002245 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002246 {0}
2247};
2248
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002249PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002250"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002251"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002252
Guido van Rossum048eb752001-10-02 21:24:57 +00002253static int
2254type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2255{
Guido van Rossuma3862092002-06-10 15:24:42 +00002256 /* Because of type_is_gc(), the collector only calls this
2257 for heaptypes. */
2258 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002259
Thomas Woutersc6e55062006-04-15 21:47:09 +00002260 Py_VISIT(type->tp_dict);
2261 Py_VISIT(type->tp_cache);
2262 Py_VISIT(type->tp_mro);
2263 Py_VISIT(type->tp_bases);
2264 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002265
2266 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002267 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002268 in cycles; tp_subclasses is a list of weak references,
2269 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002270
Guido van Rossum048eb752001-10-02 21:24:57 +00002271 return 0;
2272}
2273
2274static int
2275type_clear(PyTypeObject *type)
2276{
Guido van Rossuma3862092002-06-10 15:24:42 +00002277 /* Because of type_is_gc(), the collector only calls this
2278 for heaptypes. */
2279 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002280
Guido van Rossuma3862092002-06-10 15:24:42 +00002281 /* The only field we need to clear is tp_mro, which is part of a
2282 hard cycle (its first element is the class itself) that won't
2283 be broken otherwise (it's a tuple and tuples don't have a
2284 tp_clear handler). None of the other fields need to be
2285 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002286
Guido van Rossuma3862092002-06-10 15:24:42 +00002287 tp_dict:
2288 It is a dict, so the collector will call its tp_clear.
2289
2290 tp_cache:
2291 Not used; if it were, it would be a dict.
2292
2293 tp_bases, tp_base:
2294 If these are involved in a cycle, there must be at least
2295 one other, mutable object in the cycle, e.g. a base
2296 class's dict; the cycle will be broken that way.
2297
2298 tp_subclasses:
2299 A list of weak references can't be part of a cycle; and
2300 lists have their own tp_clear.
2301
Guido van Rossume5c691a2003-03-07 15:13:17 +00002302 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002303 A tuple of strings can't be part of a cycle.
2304 */
2305
Thomas Woutersedf17d82006-04-15 17:28:34 +00002306 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002307
2308 return 0;
2309}
2310
2311static int
2312type_is_gc(PyTypeObject *type)
2313{
2314 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2315}
2316
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002317PyTypeObject PyType_Type = {
2318 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002319 0, /* ob_size */
2320 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002321 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002322 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002323 (destructor)type_dealloc, /* tp_dealloc */
2324 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002325 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002326 0, /* tp_setattr */
2327 type_compare, /* tp_compare */
2328 (reprfunc)type_repr, /* tp_repr */
2329 0, /* tp_as_number */
2330 0, /* tp_as_sequence */
2331 0, /* tp_as_mapping */
2332 (hashfunc)_Py_HashPointer, /* tp_hash */
2333 (ternaryfunc)type_call, /* tp_call */
2334 0, /* tp_str */
2335 (getattrofunc)type_getattro, /* tp_getattro */
2336 (setattrofunc)type_setattro, /* tp_setattro */
2337 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002338 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002339 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002340 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002341 (traverseproc)type_traverse, /* tp_traverse */
2342 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002343 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002344 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002345 0, /* tp_iter */
2346 0, /* tp_iternext */
2347 type_methods, /* tp_methods */
2348 type_members, /* tp_members */
2349 type_getsets, /* tp_getset */
2350 0, /* tp_base */
2351 0, /* tp_dict */
2352 0, /* tp_descr_get */
2353 0, /* tp_descr_set */
2354 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
Guido van Rossumf102e242007-03-23 18:53:03 +00002355 type_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002356 0, /* tp_alloc */
2357 type_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002358 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002359 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002360};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002361
2362
2363/* The base type of all types (eventually)... except itself. */
2364
Guido van Rossum143b5642007-03-23 04:58:42 +00002365/* You may wonder why object.__new__() only complains about arguments
2366 when object.__init__() is not overridden, and vice versa.
2367
2368 Consider the use cases:
2369
2370 1. When neither is overridden, we want to hear complaints about
2371 excess (i.e., any) arguments, since their presence could
2372 indicate there's a bug.
2373
2374 2. When defining an Immutable type, we are likely to override only
2375 __new__(), since __init__() is called too late to initialize an
2376 Immutable object. Since __new__() defines the signature for the
2377 type, it would be a pain to have to override __init__() just to
2378 stop it from complaining about excess arguments.
2379
2380 3. When defining a Mutable type, we are likely to override only
2381 __init__(). So here the converse reasoning applies: we don't
2382 want to have to override __new__() just to stop it from
2383 complaining.
2384
2385 4. When __init__() is overridden, and the subclass __init__() calls
2386 object.__init__(), the latter should complain about excess
2387 arguments; ditto for __new__().
2388
2389 Use cases 2 and 3 make it unattractive to unconditionally check for
2390 excess arguments. The best solution that addresses all four use
2391 cases is as follows: __init__() complains about excess arguments
2392 unless __new__() is overridden and __init__() is not overridden
2393 (IOW, if __init__() is overridden or __new__() is not overridden);
2394 symmetrically, __new__() complains about excess arguments unless
2395 __init__() is overridden and __new__() is not overridden
2396 (IOW, if __new__() is overridden or __init__() is not overridden).
2397
2398 However, for backwards compatibility, this breaks too much code.
2399 Therefore, in 2.6, we'll *warn* about excess arguments when both
2400 methods are overridden; for all other cases we'll use the above
2401 rules.
2402
2403*/
2404
2405/* Forward */
2406static PyObject *
2407object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2408
2409static int
2410excess_args(PyObject *args, PyObject *kwds)
2411{
2412 return PyTuple_GET_SIZE(args) ||
2413 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2414}
2415
Tim Peters6d6c1a32001-08-02 04:15:00 +00002416static int
2417object_init(PyObject *self, PyObject *args, PyObject *kwds)
2418{
Guido van Rossum143b5642007-03-23 04:58:42 +00002419 int err = 0;
2420 if (excess_args(args, kwds)) {
2421 PyTypeObject *type = self->ob_type;
2422 if (type->tp_init != object_init &&
2423 type->tp_new != object_new)
2424 {
2425 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2426 "object.__init__() takes no parameters",
2427 1);
2428 }
2429 else if (type->tp_init != object_init ||
2430 type->tp_new == object_new)
2431 {
2432 PyErr_SetString(PyExc_TypeError,
2433 "object.__init__() takes no parameters");
2434 err = -1;
2435 }
2436 }
2437 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002438}
2439
Guido van Rossum298e4212003-02-13 16:30:16 +00002440static PyObject *
2441object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2442{
Guido van Rossum143b5642007-03-23 04:58:42 +00002443 int err = 0;
2444 if (excess_args(args, kwds)) {
2445 if (type->tp_new != object_new &&
2446 type->tp_init != object_init)
2447 {
2448 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2449 "object.__new__() takes no parameters",
2450 1);
2451 }
2452 else if (type->tp_new != object_new ||
2453 type->tp_init == object_init)
2454 {
2455 PyErr_SetString(PyExc_TypeError,
2456 "object.__new__() takes no parameters");
2457 err = -1;
2458 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002459 }
Guido van Rossum143b5642007-03-23 04:58:42 +00002460 if (err < 0)
2461 return NULL;
Guido van Rossum298e4212003-02-13 16:30:16 +00002462 return type->tp_alloc(type, 0);
2463}
2464
Tim Peters6d6c1a32001-08-02 04:15:00 +00002465static void
2466object_dealloc(PyObject *self)
2467{
2468 self->ob_type->tp_free(self);
2469}
2470
Guido van Rossum8e248182001-08-12 05:17:56 +00002471static PyObject *
2472object_repr(PyObject *self)
2473{
Guido van Rossum76e69632001-08-16 18:52:43 +00002474 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002475 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002476
Guido van Rossum76e69632001-08-16 18:52:43 +00002477 type = self->ob_type;
2478 mod = type_module(type, NULL);
2479 if (mod == NULL)
2480 PyErr_Clear();
2481 else if (!PyString_Check(mod)) {
2482 Py_DECREF(mod);
2483 mod = NULL;
2484 }
2485 name = type_name(type, NULL);
2486 if (name == NULL)
2487 return NULL;
2488 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002489 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002490 PyString_AS_STRING(mod),
2491 PyString_AS_STRING(name),
2492 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002493 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002494 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002495 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002496 Py_XDECREF(mod);
2497 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002498 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002499}
2500
Guido van Rossumb8f63662001-08-15 23:57:02 +00002501static PyObject *
2502object_str(PyObject *self)
2503{
2504 unaryfunc f;
2505
2506 f = self->ob_type->tp_repr;
2507 if (f == NULL)
2508 f = object_repr;
2509 return f(self);
2510}
2511
Guido van Rossum8e248182001-08-12 05:17:56 +00002512static long
2513object_hash(PyObject *self)
2514{
2515 return _Py_HashPointer(self);
2516}
Guido van Rossum8e248182001-08-12 05:17:56 +00002517
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002518static PyObject *
2519object_get_class(PyObject *self, void *closure)
2520{
2521 Py_INCREF(self->ob_type);
2522 return (PyObject *)(self->ob_type);
2523}
2524
2525static int
2526equiv_structs(PyTypeObject *a, PyTypeObject *b)
2527{
2528 return a == b ||
2529 (a != NULL &&
2530 b != NULL &&
2531 a->tp_basicsize == b->tp_basicsize &&
2532 a->tp_itemsize == b->tp_itemsize &&
2533 a->tp_dictoffset == b->tp_dictoffset &&
2534 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2535 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2536 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2537}
2538
2539static int
2540same_slots_added(PyTypeObject *a, PyTypeObject *b)
2541{
2542 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002543 Py_ssize_t size;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002544 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002545
2546 if (base != b->tp_base)
2547 return 0;
2548 if (equiv_structs(a, base) && equiv_structs(b, base))
2549 return 1;
2550 size = base->tp_basicsize;
2551 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2552 size += sizeof(PyObject *);
2553 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2554 size += sizeof(PyObject *);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002555
2556 /* Check slots compliance */
2557 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2558 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2559 if (slots_a && slots_b) {
2560 if (PyObject_Compare(slots_a, slots_b) != 0)
2561 return 0;
2562 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2563 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002564 return size == a->tp_basicsize && size == b->tp_basicsize;
2565}
2566
2567static int
Anthony Baxtera6286212006-04-11 07:42:36 +00002568compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002569{
2570 PyTypeObject *newbase, *oldbase;
2571
Anthony Baxtera6286212006-04-11 07:42:36 +00002572 if (newto->tp_dealloc != oldto->tp_dealloc ||
2573 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002574 {
2575 PyErr_Format(PyExc_TypeError,
2576 "%s assignment: "
2577 "'%s' deallocator differs from '%s'",
2578 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002579 newto->tp_name,
2580 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002581 return 0;
2582 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002583 newbase = newto;
2584 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002585 while (equiv_structs(newbase, newbase->tp_base))
2586 newbase = newbase->tp_base;
2587 while (equiv_structs(oldbase, oldbase->tp_base))
2588 oldbase = oldbase->tp_base;
2589 if (newbase != oldbase &&
2590 (newbase->tp_base != oldbase->tp_base ||
2591 !same_slots_added(newbase, oldbase))) {
2592 PyErr_Format(PyExc_TypeError,
2593 "%s assignment: "
2594 "'%s' object layout differs from '%s'",
2595 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002596 newto->tp_name,
2597 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002598 return 0;
2599 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002600
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002601 return 1;
2602}
2603
2604static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002605object_set_class(PyObject *self, PyObject *value, void *closure)
2606{
Anthony Baxtera6286212006-04-11 07:42:36 +00002607 PyTypeObject *oldto = self->ob_type;
2608 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002609
Guido van Rossumb6b89422002-04-15 01:03:30 +00002610 if (value == NULL) {
2611 PyErr_SetString(PyExc_TypeError,
2612 "can't delete __class__ attribute");
2613 return -1;
2614 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002615 if (!PyType_Check(value)) {
2616 PyErr_Format(PyExc_TypeError,
2617 "__class__ must be set to new-style class, not '%s' object",
2618 value->ob_type->tp_name);
2619 return -1;
2620 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002621 newto = (PyTypeObject *)value;
2622 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2623 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002624 {
2625 PyErr_Format(PyExc_TypeError,
2626 "__class__ assignment: only for heap types");
2627 return -1;
2628 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002629 if (compatible_for_assignment(newto, oldto, "__class__")) {
2630 Py_INCREF(newto);
2631 self->ob_type = newto;
2632 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002633 return 0;
2634 }
2635 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002636 return -1;
2637 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002638}
2639
2640static PyGetSetDef object_getsets[] = {
2641 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002642 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002643 {0}
2644};
2645
Guido van Rossumc53f0092003-02-18 22:05:12 +00002646
Guido van Rossum036f9992003-02-21 22:02:54 +00002647/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2648 We fall back to helpers in copy_reg for:
2649 - pickle protocols < 2
2650 - calculating the list of slot names (done only once per class)
2651 - the __newobj__ function (which is used as a token but never called)
2652*/
2653
2654static PyObject *
2655import_copy_reg(void)
2656{
2657 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002658
2659 if (!copy_reg_str) {
2660 copy_reg_str = PyString_InternFromString("copy_reg");
2661 if (copy_reg_str == NULL)
2662 return NULL;
2663 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002664
2665 return PyImport_Import(copy_reg_str);
2666}
2667
2668static PyObject *
2669slotnames(PyObject *cls)
2670{
2671 PyObject *clsdict;
2672 PyObject *copy_reg;
2673 PyObject *slotnames;
2674
2675 if (!PyType_Check(cls)) {
2676 Py_INCREF(Py_None);
2677 return Py_None;
2678 }
2679
2680 clsdict = ((PyTypeObject *)cls)->tp_dict;
2681 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002682 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002683 Py_INCREF(slotnames);
2684 return slotnames;
2685 }
2686
2687 copy_reg = import_copy_reg();
2688 if (copy_reg == NULL)
2689 return NULL;
2690
2691 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2692 Py_DECREF(copy_reg);
2693 if (slotnames != NULL &&
2694 slotnames != Py_None &&
2695 !PyList_Check(slotnames))
2696 {
2697 PyErr_SetString(PyExc_TypeError,
2698 "copy_reg._slotnames didn't return a list or None");
2699 Py_DECREF(slotnames);
2700 slotnames = NULL;
2701 }
2702
2703 return slotnames;
2704}
2705
2706static PyObject *
2707reduce_2(PyObject *obj)
2708{
2709 PyObject *cls, *getnewargs;
2710 PyObject *args = NULL, *args2 = NULL;
2711 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2712 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2713 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002714 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00002715
2716 cls = PyObject_GetAttrString(obj, "__class__");
2717 if (cls == NULL)
2718 return NULL;
2719
2720 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2721 if (getnewargs != NULL) {
2722 args = PyObject_CallObject(getnewargs, NULL);
2723 Py_DECREF(getnewargs);
2724 if (args != NULL && !PyTuple_Check(args)) {
Georg Brandlccff7852006-06-18 22:17:29 +00002725 PyErr_Format(PyExc_TypeError,
2726 "__getnewargs__ should return a tuple, "
2727 "not '%.200s'", args->ob_type->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00002728 goto end;
2729 }
2730 }
2731 else {
2732 PyErr_Clear();
2733 args = PyTuple_New(0);
2734 }
2735 if (args == NULL)
2736 goto end;
2737
2738 getstate = PyObject_GetAttrString(obj, "__getstate__");
2739 if (getstate != NULL) {
2740 state = PyObject_CallObject(getstate, NULL);
2741 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002742 if (state == NULL)
2743 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002744 }
2745 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002746 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002747 state = PyObject_GetAttrString(obj, "__dict__");
2748 if (state == NULL) {
2749 PyErr_Clear();
2750 state = Py_None;
2751 Py_INCREF(state);
2752 }
2753 names = slotnames(cls);
2754 if (names == NULL)
2755 goto end;
2756 if (names != Py_None) {
2757 assert(PyList_Check(names));
2758 slots = PyDict_New();
2759 if (slots == NULL)
2760 goto end;
2761 n = 0;
2762 /* Can't pre-compute the list size; the list
2763 is stored on the class so accessible to other
2764 threads, which may be run by DECREF */
2765 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2766 PyObject *name, *value;
2767 name = PyList_GET_ITEM(names, i);
2768 value = PyObject_GetAttr(obj, name);
2769 if (value == NULL)
2770 PyErr_Clear();
2771 else {
2772 int err = PyDict_SetItem(slots, name,
2773 value);
2774 Py_DECREF(value);
2775 if (err)
2776 goto end;
2777 n++;
2778 }
2779 }
2780 if (n) {
2781 state = Py_BuildValue("(NO)", state, slots);
2782 if (state == NULL)
2783 goto end;
2784 }
2785 }
2786 }
2787
2788 if (!PyList_Check(obj)) {
2789 listitems = Py_None;
2790 Py_INCREF(listitems);
2791 }
2792 else {
2793 listitems = PyObject_GetIter(obj);
2794 if (listitems == NULL)
2795 goto end;
2796 }
2797
2798 if (!PyDict_Check(obj)) {
2799 dictitems = Py_None;
2800 Py_INCREF(dictitems);
2801 }
2802 else {
2803 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2804 if (dictitems == NULL)
2805 goto end;
2806 }
2807
2808 copy_reg = import_copy_reg();
2809 if (copy_reg == NULL)
2810 goto end;
2811 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2812 if (newobj == NULL)
2813 goto end;
2814
2815 n = PyTuple_GET_SIZE(args);
2816 args2 = PyTuple_New(n+1);
2817 if (args2 == NULL)
2818 goto end;
2819 PyTuple_SET_ITEM(args2, 0, cls);
2820 cls = NULL;
2821 for (i = 0; i < n; i++) {
2822 PyObject *v = PyTuple_GET_ITEM(args, i);
2823 Py_INCREF(v);
2824 PyTuple_SET_ITEM(args2, i+1, v);
2825 }
2826
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002827 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002828
2829 end:
2830 Py_XDECREF(cls);
2831 Py_XDECREF(args);
2832 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002833 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002834 Py_XDECREF(state);
2835 Py_XDECREF(names);
2836 Py_XDECREF(listitems);
2837 Py_XDECREF(dictitems);
2838 Py_XDECREF(copy_reg);
2839 Py_XDECREF(newobj);
2840 return res;
2841}
2842
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00002843/*
2844 * There were two problems when object.__reduce__ and object.__reduce_ex__
2845 * were implemented in the same function:
2846 * - trying to pickle an object with a custom __reduce__ method that
2847 * fell back to object.__reduce__ in certain circumstances led to
2848 * infinite recursion at Python level and eventual RuntimeError.
2849 * - Pickling objects that lied about their type by overwriting the
2850 * __class__ descriptor could lead to infinite recursion at C level
2851 * and eventual segfault.
2852 *
2853 * Because of backwards compatibility, the two methods still have to
2854 * behave in the same way, even if this is not required by the pickle
2855 * protocol. This common functionality was moved to the _common_reduce
2856 * function.
2857 */
2858static PyObject *
2859_common_reduce(PyObject *self, int proto)
2860{
2861 PyObject *copy_reg, *res;
2862
2863 if (proto >= 2)
2864 return reduce_2(self);
2865
2866 copy_reg = import_copy_reg();
2867 if (!copy_reg)
2868 return NULL;
2869
2870 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
2871 Py_DECREF(copy_reg);
2872
2873 return res;
2874}
2875
2876static PyObject *
2877object_reduce(PyObject *self, PyObject *args)
2878{
2879 int proto = 0;
2880
2881 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
2882 return NULL;
2883
2884 return _common_reduce(self, proto);
2885}
2886
Guido van Rossum036f9992003-02-21 22:02:54 +00002887static PyObject *
2888object_reduce_ex(PyObject *self, PyObject *args)
2889{
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00002890 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00002891 int proto = 0;
2892
2893 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2894 return NULL;
2895
2896 reduce = PyObject_GetAttrString(self, "__reduce__");
2897 if (reduce == NULL)
2898 PyErr_Clear();
2899 else {
2900 PyObject *cls, *clsreduce, *objreduce;
2901 int override;
2902 cls = PyObject_GetAttrString(self, "__class__");
2903 if (cls == NULL) {
2904 Py_DECREF(reduce);
2905 return NULL;
2906 }
2907 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2908 Py_DECREF(cls);
2909 if (clsreduce == NULL) {
2910 Py_DECREF(reduce);
2911 return NULL;
2912 }
2913 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2914 "__reduce__");
2915 override = (clsreduce != objreduce);
2916 Py_DECREF(clsreduce);
2917 if (override) {
2918 res = PyObject_CallObject(reduce, NULL);
2919 Py_DECREF(reduce);
2920 return res;
2921 }
2922 else
2923 Py_DECREF(reduce);
2924 }
2925
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00002926 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002927}
2928
2929static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002930 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2931 PyDoc_STR("helper for pickle")},
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00002932 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002933 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002934 {0}
2935};
2936
Guido van Rossum036f9992003-02-21 22:02:54 +00002937
Tim Peters6d6c1a32001-08-02 04:15:00 +00002938PyTypeObject PyBaseObject_Type = {
2939 PyObject_HEAD_INIT(&PyType_Type)
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002940 0, /* ob_size */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002941 "object", /* tp_name */
2942 sizeof(PyObject), /* tp_basicsize */
2943 0, /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00002944 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002945 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002946 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002947 0, /* tp_setattr */
2948 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002949 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002950 0, /* tp_as_number */
2951 0, /* tp_as_sequence */
2952 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002953 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002954 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002955 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002956 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002957 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002958 0, /* tp_as_buffer */
2959 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002960 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002961 0, /* tp_traverse */
2962 0, /* tp_clear */
2963 0, /* tp_richcompare */
2964 0, /* tp_weaklistoffset */
2965 0, /* tp_iter */
2966 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002967 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002968 0, /* tp_members */
2969 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002970 0, /* tp_base */
2971 0, /* tp_dict */
2972 0, /* tp_descr_get */
2973 0, /* tp_descr_set */
2974 0, /* tp_dictoffset */
2975 object_init, /* tp_init */
2976 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002977 object_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002978 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002979};
2980
2981
2982/* Initialize the __dict__ in a type object */
2983
2984static int
2985add_methods(PyTypeObject *type, PyMethodDef *meth)
2986{
Guido van Rossum687ae002001-10-15 22:03:32 +00002987 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002988
2989 for (; meth->ml_name != NULL; meth++) {
2990 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002991 if (PyDict_GetItemString(dict, meth->ml_name) &&
2992 !(meth->ml_flags & METH_COEXIST))
2993 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002994 if (meth->ml_flags & METH_CLASS) {
2995 if (meth->ml_flags & METH_STATIC) {
2996 PyErr_SetString(PyExc_ValueError,
2997 "method cannot be both class and static");
2998 return -1;
2999 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00003000 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00003001 }
3002 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00003003 PyObject *cfunc = PyCFunction_New(meth, NULL);
3004 if (cfunc == NULL)
3005 return -1;
3006 descr = PyStaticMethod_New(cfunc);
3007 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003008 }
3009 else {
3010 descr = PyDescr_NewMethod(type, meth);
3011 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003012 if (descr == NULL)
3013 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003014 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003015 return -1;
3016 Py_DECREF(descr);
3017 }
3018 return 0;
3019}
3020
3021static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003022add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003023{
Guido van Rossum687ae002001-10-15 22:03:32 +00003024 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003025
3026 for (; memb->name != NULL; memb++) {
3027 PyObject *descr;
3028 if (PyDict_GetItemString(dict, memb->name))
3029 continue;
3030 descr = PyDescr_NewMember(type, memb);
3031 if (descr == NULL)
3032 return -1;
3033 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3034 return -1;
3035 Py_DECREF(descr);
3036 }
3037 return 0;
3038}
3039
3040static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003041add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003042{
Guido van Rossum687ae002001-10-15 22:03:32 +00003043 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003044
3045 for (; gsp->name != NULL; gsp++) {
3046 PyObject *descr;
3047 if (PyDict_GetItemString(dict, gsp->name))
3048 continue;
3049 descr = PyDescr_NewGetSet(type, gsp);
3050
3051 if (descr == NULL)
3052 return -1;
3053 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3054 return -1;
3055 Py_DECREF(descr);
3056 }
3057 return 0;
3058}
3059
Guido van Rossum13d52f02001-08-10 21:24:08 +00003060static void
3061inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003062{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003063 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003064
Guido van Rossum13d52f02001-08-10 21:24:08 +00003065 /* Special flag magic */
3066 if (!type->tp_as_buffer && base->tp_as_buffer) {
3067 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
3068 type->tp_flags |=
3069 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
3070 }
3071 if (!type->tp_as_sequence && base->tp_as_sequence) {
3072 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
3073 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
3074 }
3075 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
3076 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
3077 if ((!type->tp_as_number && base->tp_as_number) ||
3078 (!type->tp_as_sequence && base->tp_as_sequence)) {
3079 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
3080 if (!type->tp_as_number && !type->tp_as_sequence) {
3081 type->tp_flags |= base->tp_flags &
3082 Py_TPFLAGS_HAVE_INPLACEOPS;
3083 }
3084 }
3085 /* Wow */
3086 }
3087 if (!type->tp_as_number && base->tp_as_number) {
3088 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
3089 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
3090 }
3091
3092 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003093 oldsize = base->tp_basicsize;
3094 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3095 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3096 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003097 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
3098 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003099 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003100 if (type->tp_traverse == NULL)
3101 type->tp_traverse = base->tp_traverse;
3102 if (type->tp_clear == NULL)
3103 type->tp_clear = base->tp_clear;
3104 }
3105 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00003106 /* The condition below could use some explanation.
3107 It appears that tp_new is not inherited for static types
3108 whose base class is 'object'; this seems to be a precaution
3109 so that old extension types don't suddenly become
3110 callable (object.__new__ wouldn't insure the invariants
3111 that the extension type's own factory function ensures).
3112 Heap types, of course, are under our control, so they do
3113 inherit tp_new; static extension types that specify some
3114 other built-in type as the default are considered
3115 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003116 if (base != &PyBaseObject_Type ||
3117 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3118 if (type->tp_new == NULL)
3119 type->tp_new = base->tp_new;
3120 }
3121 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003122 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003123
3124 /* Copy other non-function slots */
3125
3126#undef COPYVAL
3127#define COPYVAL(SLOT) \
3128 if (type->SLOT == 0) type->SLOT = base->SLOT
3129
3130 COPYVAL(tp_itemsize);
3131 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
3132 COPYVAL(tp_weaklistoffset);
3133 }
3134 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3135 COPYVAL(tp_dictoffset);
3136 }
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003137
3138 /* Setup fast subclass flags */
3139 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3140 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3141 else if (PyType_IsSubtype(base, &PyType_Type))
3142 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3143 else if (PyType_IsSubtype(base, &PyInt_Type))
3144 type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS;
3145 else if (PyType_IsSubtype(base, &PyLong_Type))
3146 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3147 else if (PyType_IsSubtype(base, &PyString_Type))
3148 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
3149 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3150 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3151 else if (PyType_IsSubtype(base, &PyTuple_Type))
3152 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3153 else if (PyType_IsSubtype(base, &PyList_Type))
3154 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3155 else if (PyType_IsSubtype(base, &PyDict_Type))
3156 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003157}
3158
3159static void
3160inherit_slots(PyTypeObject *type, PyTypeObject *base)
3161{
3162 PyTypeObject *basebase;
3163
3164#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003165#undef COPYSLOT
3166#undef COPYNUM
3167#undef COPYSEQ
3168#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003169#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003170
3171#define SLOTDEFINED(SLOT) \
3172 (base->SLOT != 0 && \
3173 (basebase == NULL || base->SLOT != basebase->SLOT))
3174
Tim Peters6d6c1a32001-08-02 04:15:00 +00003175#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003176 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003177
3178#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3179#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3180#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003181#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003182
Guido van Rossum13d52f02001-08-10 21:24:08 +00003183 /* This won't inherit indirect slots (from tp_as_number etc.)
3184 if type doesn't provide the space. */
3185
3186 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3187 basebase = base->tp_base;
3188 if (basebase->tp_as_number == NULL)
3189 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003190 COPYNUM(nb_add);
3191 COPYNUM(nb_subtract);
3192 COPYNUM(nb_multiply);
3193 COPYNUM(nb_divide);
3194 COPYNUM(nb_remainder);
3195 COPYNUM(nb_divmod);
3196 COPYNUM(nb_power);
3197 COPYNUM(nb_negative);
3198 COPYNUM(nb_positive);
3199 COPYNUM(nb_absolute);
3200 COPYNUM(nb_nonzero);
3201 COPYNUM(nb_invert);
3202 COPYNUM(nb_lshift);
3203 COPYNUM(nb_rshift);
3204 COPYNUM(nb_and);
3205 COPYNUM(nb_xor);
3206 COPYNUM(nb_or);
3207 COPYNUM(nb_coerce);
3208 COPYNUM(nb_int);
3209 COPYNUM(nb_long);
3210 COPYNUM(nb_float);
3211 COPYNUM(nb_oct);
3212 COPYNUM(nb_hex);
3213 COPYNUM(nb_inplace_add);
3214 COPYNUM(nb_inplace_subtract);
3215 COPYNUM(nb_inplace_multiply);
3216 COPYNUM(nb_inplace_divide);
3217 COPYNUM(nb_inplace_remainder);
3218 COPYNUM(nb_inplace_power);
3219 COPYNUM(nb_inplace_lshift);
3220 COPYNUM(nb_inplace_rshift);
3221 COPYNUM(nb_inplace_and);
3222 COPYNUM(nb_inplace_xor);
3223 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003224 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3225 COPYNUM(nb_true_divide);
3226 COPYNUM(nb_floor_divide);
3227 COPYNUM(nb_inplace_true_divide);
3228 COPYNUM(nb_inplace_floor_divide);
3229 }
Guido van Rossum38fff8c2006-03-07 18:50:55 +00003230 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3231 COPYNUM(nb_index);
3232 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003233 }
3234
Guido van Rossum13d52f02001-08-10 21:24:08 +00003235 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3236 basebase = base->tp_base;
3237 if (basebase->tp_as_sequence == NULL)
3238 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003239 COPYSEQ(sq_length);
3240 COPYSEQ(sq_concat);
3241 COPYSEQ(sq_repeat);
3242 COPYSEQ(sq_item);
3243 COPYSEQ(sq_slice);
3244 COPYSEQ(sq_ass_item);
3245 COPYSEQ(sq_ass_slice);
3246 COPYSEQ(sq_contains);
3247 COPYSEQ(sq_inplace_concat);
3248 COPYSEQ(sq_inplace_repeat);
3249 }
3250
Guido van Rossum13d52f02001-08-10 21:24:08 +00003251 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3252 basebase = base->tp_base;
3253 if (basebase->tp_as_mapping == NULL)
3254 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003255 COPYMAP(mp_length);
3256 COPYMAP(mp_subscript);
3257 COPYMAP(mp_ass_subscript);
3258 }
3259
Tim Petersfc57ccb2001-10-12 02:38:24 +00003260 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3261 basebase = base->tp_base;
3262 if (basebase->tp_as_buffer == NULL)
3263 basebase = NULL;
3264 COPYBUF(bf_getreadbuffer);
3265 COPYBUF(bf_getwritebuffer);
3266 COPYBUF(bf_getsegcount);
3267 COPYBUF(bf_getcharbuffer);
3268 }
3269
Guido van Rossum13d52f02001-08-10 21:24:08 +00003270 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003271
Tim Peters6d6c1a32001-08-02 04:15:00 +00003272 COPYSLOT(tp_dealloc);
3273 COPYSLOT(tp_print);
3274 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3275 type->tp_getattr = base->tp_getattr;
3276 type->tp_getattro = base->tp_getattro;
3277 }
3278 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3279 type->tp_setattr = base->tp_setattr;
3280 type->tp_setattro = base->tp_setattro;
3281 }
3282 /* tp_compare see tp_richcompare */
3283 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003284 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003285 COPYSLOT(tp_call);
3286 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003287 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003288 if (type->tp_compare == NULL &&
3289 type->tp_richcompare == NULL &&
3290 type->tp_hash == NULL)
3291 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003292 type->tp_compare = base->tp_compare;
3293 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003294 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003295 }
3296 }
3297 else {
3298 COPYSLOT(tp_compare);
3299 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003300 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3301 COPYSLOT(tp_iter);
3302 COPYSLOT(tp_iternext);
3303 }
3304 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3305 COPYSLOT(tp_descr_get);
3306 COPYSLOT(tp_descr_set);
3307 COPYSLOT(tp_dictoffset);
3308 COPYSLOT(tp_init);
3309 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003310 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003311 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3312 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3313 /* They agree about gc. */
3314 COPYSLOT(tp_free);
3315 }
3316 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3317 type->tp_free == NULL &&
3318 base->tp_free == _PyObject_Del) {
3319 /* A bit of magic to plug in the correct default
3320 * tp_free function when a derived class adds gc,
3321 * didn't define tp_free, and the base uses the
3322 * default non-gc tp_free.
3323 */
3324 type->tp_free = PyObject_GC_Del;
3325 }
3326 /* else they didn't agree about gc, and there isn't something
3327 * obvious to be done -- the type is on its own.
3328 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003329 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003330}
3331
Jeremy Hylton938ace62002-07-17 16:30:39 +00003332static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003333
Tim Peters6d6c1a32001-08-02 04:15:00 +00003334int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003335PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003336{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003337 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003338 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003339 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003340
Guido van Rossumcab05802002-06-10 15:29:03 +00003341 if (type->tp_flags & Py_TPFLAGS_READY) {
3342 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003343 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003344 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003345 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003346
3347 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003348
Tim Peters36eb4df2003-03-23 03:33:13 +00003349#ifdef Py_TRACE_REFS
3350 /* PyType_Ready is the closest thing we have to a choke point
3351 * for type objects, so is the best place I can think of to try
3352 * to get type objects into the doubly-linked list of all objects.
3353 * Still, not all type objects go thru PyType_Ready.
3354 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003355 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003356#endif
3357
Tim Peters6d6c1a32001-08-02 04:15:00 +00003358 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3359 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003360 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003361 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003362 Py_INCREF(base);
3363 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003364
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003365 /* Now the only way base can still be NULL is if type is
3366 * &PyBaseObject_Type.
3367 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003368
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003369 /* Initialize the base class */
3370 if (base && base->tp_dict == NULL) {
3371 if (PyType_Ready(base) < 0)
3372 goto error;
3373 }
3374
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003375 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003376 compilable separately on Windows can call PyType_Ready() instead of
3377 initializing the ob_type field of their type objects. */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003378 /* The test for base != NULL is really unnecessary, since base is only
3379 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3380 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3381 know that. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003382 if (type->ob_type == NULL && base != NULL)
Guido van Rossum0986d822002-04-08 01:38:42 +00003383 type->ob_type = base->ob_type;
3384
Tim Peters6d6c1a32001-08-02 04:15:00 +00003385 /* Initialize tp_bases */
3386 bases = type->tp_bases;
3387 if (bases == NULL) {
3388 if (base == NULL)
3389 bases = PyTuple_New(0);
3390 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003391 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003392 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003393 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003394 type->tp_bases = bases;
3395 }
3396
Guido van Rossum687ae002001-10-15 22:03:32 +00003397 /* Initialize tp_dict */
3398 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003399 if (dict == NULL) {
3400 dict = PyDict_New();
3401 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003402 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003403 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003404 }
3405
Guido van Rossum687ae002001-10-15 22:03:32 +00003406 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003407 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003408 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003409 if (type->tp_methods != NULL) {
3410 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003411 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003412 }
3413 if (type->tp_members != NULL) {
3414 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003415 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003416 }
3417 if (type->tp_getset != NULL) {
3418 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003419 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003420 }
3421
Tim Peters6d6c1a32001-08-02 04:15:00 +00003422 /* Calculate method resolution order */
3423 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003424 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003425 }
3426
Guido van Rossum13d52f02001-08-10 21:24:08 +00003427 /* Inherit special flags from dominant base */
3428 if (type->tp_base != NULL)
3429 inherit_special(type, type->tp_base);
3430
Tim Peters6d6c1a32001-08-02 04:15:00 +00003431 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003432 bases = type->tp_mro;
3433 assert(bases != NULL);
3434 assert(PyTuple_Check(bases));
3435 n = PyTuple_GET_SIZE(bases);
3436 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003437 PyObject *b = PyTuple_GET_ITEM(bases, i);
3438 if (PyType_Check(b))
3439 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003440 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003441
Tim Peters3cfe7542003-05-21 21:29:48 +00003442 /* Sanity check for tp_free. */
3443 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3444 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003445 /* This base class needs to call tp_free, but doesn't have
3446 * one, or its tp_free is for non-gc'ed objects.
3447 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003448 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3449 "gc and is a base type but has inappropriate "
3450 "tp_free slot",
3451 type->tp_name);
3452 goto error;
3453 }
3454
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003455 /* if the type dictionary doesn't contain a __doc__, set it from
3456 the tp_doc slot.
3457 */
3458 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3459 if (type->tp_doc != NULL) {
3460 PyObject *doc = PyString_FromString(type->tp_doc);
Neal Norwitze1fdb322006-07-21 05:32:28 +00003461 if (doc == NULL)
3462 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003463 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3464 Py_DECREF(doc);
3465 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003466 PyDict_SetItemString(type->tp_dict,
3467 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003468 }
3469 }
3470
Guido van Rossum13d52f02001-08-10 21:24:08 +00003471 /* Some more special stuff */
3472 base = type->tp_base;
3473 if (base != NULL) {
3474 if (type->tp_as_number == NULL)
3475 type->tp_as_number = base->tp_as_number;
3476 if (type->tp_as_sequence == NULL)
3477 type->tp_as_sequence = base->tp_as_sequence;
3478 if (type->tp_as_mapping == NULL)
3479 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003480 if (type->tp_as_buffer == NULL)
3481 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003482 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003483
Guido van Rossum1c450732001-10-08 15:18:27 +00003484 /* Link into each base class's list of subclasses */
3485 bases = type->tp_bases;
3486 n = PyTuple_GET_SIZE(bases);
3487 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003488 PyObject *b = PyTuple_GET_ITEM(bases, i);
3489 if (PyType_Check(b) &&
3490 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003491 goto error;
3492 }
3493
Guido van Rossum13d52f02001-08-10 21:24:08 +00003494 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003495 assert(type->tp_dict != NULL);
3496 type->tp_flags =
3497 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003498 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003499
3500 error:
3501 type->tp_flags &= ~Py_TPFLAGS_READYING;
3502 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003503}
3504
Guido van Rossum1c450732001-10-08 15:18:27 +00003505static int
3506add_subclass(PyTypeObject *base, PyTypeObject *type)
3507{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003508 Py_ssize_t i;
3509 int result;
Anthony Baxtera6286212006-04-11 07:42:36 +00003510 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003511
3512 list = base->tp_subclasses;
3513 if (list == NULL) {
3514 base->tp_subclasses = list = PyList_New(0);
3515 if (list == NULL)
3516 return -1;
3517 }
3518 assert(PyList_Check(list));
Anthony Baxtera6286212006-04-11 07:42:36 +00003519 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003520 i = PyList_GET_SIZE(list);
3521 while (--i >= 0) {
3522 ref = PyList_GET_ITEM(list, i);
3523 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003524 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Anthony Baxtera6286212006-04-11 07:42:36 +00003525 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003526 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003527 result = PyList_Append(list, newobj);
3528 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003529 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003530}
3531
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003532static void
3533remove_subclass(PyTypeObject *base, PyTypeObject *type)
3534{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003535 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003536 PyObject *list, *ref;
3537
3538 list = base->tp_subclasses;
3539 if (list == NULL) {
3540 return;
3541 }
3542 assert(PyList_Check(list));
3543 i = PyList_GET_SIZE(list);
3544 while (--i >= 0) {
3545 ref = PyList_GET_ITEM(list, i);
3546 assert(PyWeakref_CheckRef(ref));
3547 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3548 /* this can't fail, right? */
3549 PySequence_DelItem(list, i);
3550 return;
3551 }
3552 }
3553}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003554
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003555static int
3556check_num_args(PyObject *ob, int n)
3557{
3558 if (!PyTuple_CheckExact(ob)) {
3559 PyErr_SetString(PyExc_SystemError,
3560 "PyArg_UnpackTuple() argument list is not a tuple");
3561 return 0;
3562 }
3563 if (n == PyTuple_GET_SIZE(ob))
3564 return 1;
3565 PyErr_Format(
3566 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003567 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003568 return 0;
3569}
3570
Tim Peters6d6c1a32001-08-02 04:15:00 +00003571/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3572
3573/* There's a wrapper *function* for each distinct function typedef used
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003574 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00003575 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3576 Most tables have only one entry; the tables for binary operators have two
3577 entries, one regular and one with reversed arguments. */
3578
3579static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003580wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003581{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003582 lenfunc func = (lenfunc)wrapped;
3583 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003584
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003585 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003586 return NULL;
3587 res = (*func)(self);
3588 if (res == -1 && PyErr_Occurred())
3589 return NULL;
3590 return PyInt_FromLong((long)res);
3591}
3592
Tim Peters6d6c1a32001-08-02 04:15:00 +00003593static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003594wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3595{
3596 inquiry func = (inquiry)wrapped;
3597 int res;
3598
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003599 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003600 return NULL;
3601 res = (*func)(self);
3602 if (res == -1 && PyErr_Occurred())
3603 return NULL;
3604 return PyBool_FromLong((long)res);
3605}
3606
3607static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003608wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3609{
3610 binaryfunc func = (binaryfunc)wrapped;
3611 PyObject *other;
3612
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003613 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003614 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003615 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003616 return (*func)(self, other);
3617}
3618
3619static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003620wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3621{
3622 binaryfunc func = (binaryfunc)wrapped;
3623 PyObject *other;
3624
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003625 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003626 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003627 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003628 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003629 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003630 Py_INCREF(Py_NotImplemented);
3631 return Py_NotImplemented;
3632 }
3633 return (*func)(self, other);
3634}
3635
3636static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003637wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3638{
3639 binaryfunc func = (binaryfunc)wrapped;
3640 PyObject *other;
3641
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003642 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003643 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003644 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003645 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003646 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003647 Py_INCREF(Py_NotImplemented);
3648 return Py_NotImplemented;
3649 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003650 return (*func)(other, self);
3651}
3652
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003653static PyObject *
3654wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3655{
3656 coercion func = (coercion)wrapped;
3657 PyObject *other, *res;
3658 int ok;
3659
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003660 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003661 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003662 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003663 ok = func(&self, &other);
3664 if (ok < 0)
3665 return NULL;
3666 if (ok > 0) {
3667 Py_INCREF(Py_NotImplemented);
3668 return Py_NotImplemented;
3669 }
3670 res = PyTuple_New(2);
3671 if (res == NULL) {
3672 Py_DECREF(self);
3673 Py_DECREF(other);
3674 return NULL;
3675 }
3676 PyTuple_SET_ITEM(res, 0, self);
3677 PyTuple_SET_ITEM(res, 1, other);
3678 return res;
3679}
3680
Tim Peters6d6c1a32001-08-02 04:15:00 +00003681static PyObject *
3682wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3683{
3684 ternaryfunc func = (ternaryfunc)wrapped;
3685 PyObject *other;
3686 PyObject *third = Py_None;
3687
3688 /* Note: This wrapper only works for __pow__() */
3689
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003690 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003691 return NULL;
3692 return (*func)(self, other, third);
3693}
3694
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003695static PyObject *
3696wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3697{
3698 ternaryfunc func = (ternaryfunc)wrapped;
3699 PyObject *other;
3700 PyObject *third = Py_None;
3701
3702 /* Note: This wrapper only works for __pow__() */
3703
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003704 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003705 return NULL;
3706 return (*func)(other, self, third);
3707}
3708
Tim Peters6d6c1a32001-08-02 04:15:00 +00003709static PyObject *
3710wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3711{
3712 unaryfunc func = (unaryfunc)wrapped;
3713
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003714 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003715 return NULL;
3716 return (*func)(self);
3717}
3718
Tim Peters6d6c1a32001-08-02 04:15:00 +00003719static PyObject *
Armin Rigo314861c2006-03-30 14:04:02 +00003720wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003721{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003722 ssizeargfunc func = (ssizeargfunc)wrapped;
Armin Rigo314861c2006-03-30 14:04:02 +00003723 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003724 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003725
Armin Rigo314861c2006-03-30 14:04:02 +00003726 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
3727 return NULL;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00003728 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Armin Rigo314861c2006-03-30 14:04:02 +00003729 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003730 return NULL;
3731 return (*func)(self, i);
3732}
3733
Martin v. Löwis18e16552006-02-15 17:27:45 +00003734static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00003735getindex(PyObject *self, PyObject *arg)
3736{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003737 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003738
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00003739 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003740 if (i == -1 && PyErr_Occurred())
3741 return -1;
3742 if (i < 0) {
3743 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3744 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003745 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003746 if (n < 0)
3747 return -1;
3748 i += n;
3749 }
3750 }
3751 return i;
3752}
3753
3754static PyObject *
3755wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3756{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003757 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003758 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003759 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003760
Guido van Rossumf4593e02001-10-03 12:09:30 +00003761 if (PyTuple_GET_SIZE(args) == 1) {
3762 arg = PyTuple_GET_ITEM(args, 0);
3763 i = getindex(self, arg);
3764 if (i == -1 && PyErr_Occurred())
3765 return NULL;
3766 return (*func)(self, i);
3767 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003768 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003769 assert(PyErr_Occurred());
3770 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003771}
3772
Tim Peters6d6c1a32001-08-02 04:15:00 +00003773static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003774wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003775{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003776 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
3777 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003778
Martin v. Löwis18e16552006-02-15 17:27:45 +00003779 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003780 return NULL;
3781 return (*func)(self, i, j);
3782}
3783
Tim Peters6d6c1a32001-08-02 04:15:00 +00003784static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003785wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003786{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003787 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3788 Py_ssize_t i;
3789 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003790 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003791
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003792 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003793 return NULL;
3794 i = getindex(self, arg);
3795 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003796 return NULL;
3797 res = (*func)(self, i, value);
3798 if (res == -1 && PyErr_Occurred())
3799 return NULL;
3800 Py_INCREF(Py_None);
3801 return Py_None;
3802}
3803
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003804static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003805wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003806{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003807 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3808 Py_ssize_t i;
3809 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003810 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003811
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003812 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003813 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003814 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003815 i = getindex(self, arg);
3816 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003817 return NULL;
3818 res = (*func)(self, i, NULL);
3819 if (res == -1 && PyErr_Occurred())
3820 return NULL;
3821 Py_INCREF(Py_None);
3822 return Py_None;
3823}
3824
Tim Peters6d6c1a32001-08-02 04:15:00 +00003825static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003826wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003827{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003828 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3829 Py_ssize_t i, j;
3830 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003831 PyObject *value;
3832
Martin v. Löwis18e16552006-02-15 17:27:45 +00003833 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003834 return NULL;
3835 res = (*func)(self, i, j, value);
3836 if (res == -1 && PyErr_Occurred())
3837 return NULL;
3838 Py_INCREF(Py_None);
3839 return Py_None;
3840}
3841
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003842static PyObject *
3843wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3844{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003845 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3846 Py_ssize_t i, j;
3847 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003848
Martin v. Löwis18e16552006-02-15 17:27:45 +00003849 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003850 return NULL;
3851 res = (*func)(self, i, j, NULL);
3852 if (res == -1 && PyErr_Occurred())
3853 return NULL;
3854 Py_INCREF(Py_None);
3855 return Py_None;
3856}
3857
Tim Peters6d6c1a32001-08-02 04:15:00 +00003858/* XXX objobjproc is a misnomer; should be objargpred */
3859static PyObject *
3860wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3861{
3862 objobjproc func = (objobjproc)wrapped;
3863 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003864 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003865
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003866 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003867 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003868 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003869 res = (*func)(self, value);
3870 if (res == -1 && PyErr_Occurred())
3871 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003872 else
3873 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003874}
3875
Tim Peters6d6c1a32001-08-02 04:15:00 +00003876static PyObject *
3877wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3878{
3879 objobjargproc func = (objobjargproc)wrapped;
3880 int res;
3881 PyObject *key, *value;
3882
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003883 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003884 return NULL;
3885 res = (*func)(self, key, value);
3886 if (res == -1 && PyErr_Occurred())
3887 return NULL;
3888 Py_INCREF(Py_None);
3889 return Py_None;
3890}
3891
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003892static PyObject *
3893wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3894{
3895 objobjargproc func = (objobjargproc)wrapped;
3896 int res;
3897 PyObject *key;
3898
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003899 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003900 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003901 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003902 res = (*func)(self, key, NULL);
3903 if (res == -1 && PyErr_Occurred())
3904 return NULL;
3905 Py_INCREF(Py_None);
3906 return Py_None;
3907}
3908
Tim Peters6d6c1a32001-08-02 04:15:00 +00003909static PyObject *
3910wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3911{
3912 cmpfunc func = (cmpfunc)wrapped;
3913 int res;
3914 PyObject *other;
3915
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003916 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003917 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003918 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003919 if (other->ob_type->tp_compare != func &&
3920 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003921 PyErr_Format(
3922 PyExc_TypeError,
3923 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3924 self->ob_type->tp_name,
3925 self->ob_type->tp_name,
3926 other->ob_type->tp_name);
3927 return NULL;
3928 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003929 res = (*func)(self, other);
3930 if (PyErr_Occurred())
3931 return NULL;
3932 return PyInt_FromLong((long)res);
3933}
3934
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003935/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003936 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003937static int
3938hackcheck(PyObject *self, setattrofunc func, char *what)
3939{
3940 PyTypeObject *type = self->ob_type;
3941 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3942 type = type->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003943 /* If type is NULL now, this is a really weird type.
3944 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003945 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003946 PyErr_Format(PyExc_TypeError,
3947 "can't apply this %s to %s object",
3948 what,
3949 type->tp_name);
3950 return 0;
3951 }
3952 return 1;
3953}
3954
Tim Peters6d6c1a32001-08-02 04:15:00 +00003955static PyObject *
3956wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3957{
3958 setattrofunc func = (setattrofunc)wrapped;
3959 int res;
3960 PyObject *name, *value;
3961
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003962 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003963 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003964 if (!hackcheck(self, func, "__setattr__"))
3965 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003966 res = (*func)(self, name, value);
3967 if (res < 0)
3968 return NULL;
3969 Py_INCREF(Py_None);
3970 return Py_None;
3971}
3972
3973static PyObject *
3974wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3975{
3976 setattrofunc func = (setattrofunc)wrapped;
3977 int res;
3978 PyObject *name;
3979
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003980 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003981 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003982 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003983 if (!hackcheck(self, func, "__delattr__"))
3984 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003985 res = (*func)(self, name, NULL);
3986 if (res < 0)
3987 return NULL;
3988 Py_INCREF(Py_None);
3989 return Py_None;
3990}
3991
Tim Peters6d6c1a32001-08-02 04:15:00 +00003992static PyObject *
3993wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3994{
3995 hashfunc func = (hashfunc)wrapped;
3996 long res;
3997
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003998 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003999 return NULL;
4000 res = (*func)(self);
4001 if (res == -1 && PyErr_Occurred())
4002 return NULL;
4003 return PyInt_FromLong(res);
4004}
4005
Tim Peters6d6c1a32001-08-02 04:15:00 +00004006static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004007wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004008{
4009 ternaryfunc func = (ternaryfunc)wrapped;
4010
Guido van Rossumc8e56452001-10-22 00:43:43 +00004011 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004012}
4013
Tim Peters6d6c1a32001-08-02 04:15:00 +00004014static PyObject *
4015wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4016{
4017 richcmpfunc func = (richcmpfunc)wrapped;
4018 PyObject *other;
4019
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004020 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004021 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004022 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004023 return (*func)(self, other, op);
4024}
4025
4026#undef RICHCMP_WRAPPER
4027#define RICHCMP_WRAPPER(NAME, OP) \
4028static PyObject * \
4029richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4030{ \
4031 return wrap_richcmpfunc(self, args, wrapped, OP); \
4032}
4033
Jack Jansen8e938b42001-08-08 15:29:49 +00004034RICHCMP_WRAPPER(lt, Py_LT)
4035RICHCMP_WRAPPER(le, Py_LE)
4036RICHCMP_WRAPPER(eq, Py_EQ)
4037RICHCMP_WRAPPER(ne, Py_NE)
4038RICHCMP_WRAPPER(gt, Py_GT)
4039RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004040
Tim Peters6d6c1a32001-08-02 04:15:00 +00004041static PyObject *
4042wrap_next(PyObject *self, PyObject *args, void *wrapped)
4043{
4044 unaryfunc func = (unaryfunc)wrapped;
4045 PyObject *res;
4046
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004047 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004048 return NULL;
4049 res = (*func)(self);
4050 if (res == NULL && !PyErr_Occurred())
4051 PyErr_SetNone(PyExc_StopIteration);
4052 return res;
4053}
4054
Tim Peters6d6c1a32001-08-02 04:15:00 +00004055static PyObject *
4056wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4057{
4058 descrgetfunc func = (descrgetfunc)wrapped;
4059 PyObject *obj;
4060 PyObject *type = NULL;
4061
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004062 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004063 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004064 if (obj == Py_None)
4065 obj = NULL;
4066 if (type == Py_None)
4067 type = NULL;
4068 if (type == NULL &&obj == NULL) {
4069 PyErr_SetString(PyExc_TypeError,
4070 "__get__(None, None) is invalid");
4071 return NULL;
4072 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004073 return (*func)(self, obj, type);
4074}
4075
Tim Peters6d6c1a32001-08-02 04:15:00 +00004076static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004077wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004078{
4079 descrsetfunc func = (descrsetfunc)wrapped;
4080 PyObject *obj, *value;
4081 int ret;
4082
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004083 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004084 return NULL;
4085 ret = (*func)(self, obj, value);
4086 if (ret < 0)
4087 return NULL;
4088 Py_INCREF(Py_None);
4089 return Py_None;
4090}
Guido van Rossum22b13872002-08-06 21:41:44 +00004091
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004092static PyObject *
4093wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4094{
4095 descrsetfunc func = (descrsetfunc)wrapped;
4096 PyObject *obj;
4097 int ret;
4098
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004099 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004100 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004101 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004102 ret = (*func)(self, obj, NULL);
4103 if (ret < 0)
4104 return NULL;
4105 Py_INCREF(Py_None);
4106 return Py_None;
4107}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004108
Tim Peters6d6c1a32001-08-02 04:15:00 +00004109static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004110wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004111{
4112 initproc func = (initproc)wrapped;
4113
Guido van Rossumc8e56452001-10-22 00:43:43 +00004114 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004115 return NULL;
4116 Py_INCREF(Py_None);
4117 return Py_None;
4118}
4119
Tim Peters6d6c1a32001-08-02 04:15:00 +00004120static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004121tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004122{
Barry Warsaw60f01882001-08-22 19:24:42 +00004123 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004124 PyObject *arg0, *res;
4125
4126 if (self == NULL || !PyType_Check(self))
4127 Py_FatalError("__new__() called with non-type 'self'");
4128 type = (PyTypeObject *)self;
4129 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004130 PyErr_Format(PyExc_TypeError,
4131 "%s.__new__(): not enough arguments",
4132 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004133 return NULL;
4134 }
4135 arg0 = PyTuple_GET_ITEM(args, 0);
4136 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004137 PyErr_Format(PyExc_TypeError,
4138 "%s.__new__(X): X is not a type object (%s)",
4139 type->tp_name,
4140 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004141 return NULL;
4142 }
4143 subtype = (PyTypeObject *)arg0;
4144 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004145 PyErr_Format(PyExc_TypeError,
4146 "%s.__new__(%s): %s is not a subtype of %s",
4147 type->tp_name,
4148 subtype->tp_name,
4149 subtype->tp_name,
4150 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004151 return NULL;
4152 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004153
4154 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004155 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004156 most derived base that's not a heap type is this type. */
4157 staticbase = subtype;
4158 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4159 staticbase = staticbase->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004160 /* If staticbase is NULL now, it is a really weird type.
4161 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004162 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004163 PyErr_Format(PyExc_TypeError,
4164 "%s.__new__(%s) is not safe, use %s.__new__()",
4165 type->tp_name,
4166 subtype->tp_name,
4167 staticbase == NULL ? "?" : staticbase->tp_name);
4168 return NULL;
4169 }
4170
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004171 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4172 if (args == NULL)
4173 return NULL;
4174 res = type->tp_new(subtype, args, kwds);
4175 Py_DECREF(args);
4176 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004177}
4178
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004179static struct PyMethodDef tp_new_methoddef[] = {
4180 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004181 PyDoc_STR("T.__new__(S, ...) -> "
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004182 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004183 {0}
4184};
4185
4186static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004187add_tp_new_wrapper(PyTypeObject *type)
4188{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004189 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004190
Guido van Rossum687ae002001-10-15 22:03:32 +00004191 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004192 return 0;
4193 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004194 if (func == NULL)
4195 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004196 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004197 Py_DECREF(func);
4198 return -1;
4199 }
4200 Py_DECREF(func);
4201 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004202}
4203
Guido van Rossumf040ede2001-08-07 16:40:56 +00004204/* Slot wrappers that call the corresponding __foo__ slot. See comments
4205 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004206
Guido van Rossumdc91b992001-08-08 22:26:22 +00004207#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004208static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004209FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004210{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004211 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004212 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004213}
4214
Guido van Rossumdc91b992001-08-08 22:26:22 +00004215#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004216static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004217FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004218{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004219 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004220 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004221}
4222
Guido van Rossumcd118802003-01-06 22:57:47 +00004223/* Boolean helper for SLOT1BINFULL().
4224 right.__class__ is a nontrivial subclass of left.__class__. */
4225static int
4226method_is_overloaded(PyObject *left, PyObject *right, char *name)
4227{
4228 PyObject *a, *b;
4229 int ok;
4230
4231 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
4232 if (b == NULL) {
4233 PyErr_Clear();
4234 /* If right doesn't have it, it's not overloaded */
4235 return 0;
4236 }
4237
4238 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
4239 if (a == NULL) {
4240 PyErr_Clear();
4241 Py_DECREF(b);
4242 /* If right has it but left doesn't, it's overloaded */
4243 return 1;
4244 }
4245
4246 ok = PyObject_RichCompareBool(a, b, Py_NE);
4247 Py_DECREF(a);
4248 Py_DECREF(b);
4249 if (ok < 0) {
4250 PyErr_Clear();
4251 return 0;
4252 }
4253
4254 return ok;
4255}
4256
Guido van Rossumdc91b992001-08-08 22:26:22 +00004257
4258#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004259static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004260FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004261{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004262 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004263 int do_other = self->ob_type != other->ob_type && \
4264 other->ob_type->tp_as_number != NULL && \
4265 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004266 if (self->ob_type->tp_as_number != NULL && \
4267 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
4268 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004269 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004270 PyType_IsSubtype(other->ob_type, self->ob_type) && \
4271 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004272 r = call_maybe( \
4273 other, ROPSTR, &rcache_str, "(O)", self); \
4274 if (r != Py_NotImplemented) \
4275 return r; \
4276 Py_DECREF(r); \
4277 do_other = 0; \
4278 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004279 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004280 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004281 if (r != Py_NotImplemented || \
4282 other->ob_type == self->ob_type) \
4283 return r; \
4284 Py_DECREF(r); \
4285 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004286 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004287 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004288 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004289 } \
4290 Py_INCREF(Py_NotImplemented); \
4291 return Py_NotImplemented; \
4292}
4293
4294#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4295 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4296
4297#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4298static PyObject * \
4299FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4300{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004301 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004302 return call_method(self, OPSTR, &cache_str, \
4303 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004304}
4305
Martin v. Löwis18e16552006-02-15 17:27:45 +00004306static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004307slot_sq_length(PyObject *self)
4308{
Guido van Rossum2730b132001-08-28 18:22:14 +00004309 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004310 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004311 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004312
4313 if (res == NULL)
4314 return -1;
Neal Norwitz1872b1c2006-08-12 18:44:06 +00004315 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004316 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004317 if (len < 0) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00004318 if (!PyErr_Occurred())
4319 PyErr_SetString(PyExc_ValueError,
4320 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004321 return -1;
4322 }
Guido van Rossum26111622001-10-01 16:42:49 +00004323 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004324}
4325
Guido van Rossumf4593e02001-10-03 12:09:30 +00004326/* Super-optimized version of slot_sq_item.
4327 Other slots could do the same... */
4328static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004329slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004330{
4331 static PyObject *getitem_str;
4332 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4333 descrgetfunc f;
4334
4335 if (getitem_str == NULL) {
4336 getitem_str = PyString_InternFromString("__getitem__");
4337 if (getitem_str == NULL)
4338 return NULL;
4339 }
4340 func = _PyType_Lookup(self->ob_type, getitem_str);
4341 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004342 if ((f = func->ob_type->tp_descr_get) == NULL)
4343 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004344 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004345 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004346 if (func == NULL) {
4347 return NULL;
4348 }
4349 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004350 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004351 if (ival != NULL) {
4352 args = PyTuple_New(1);
4353 if (args != NULL) {
4354 PyTuple_SET_ITEM(args, 0, ival);
4355 retval = PyObject_Call(func, args, NULL);
4356 Py_XDECREF(args);
4357 Py_XDECREF(func);
4358 return retval;
4359 }
4360 }
4361 }
4362 else {
4363 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4364 }
4365 Py_XDECREF(args);
4366 Py_XDECREF(ival);
4367 Py_XDECREF(func);
4368 return NULL;
4369}
4370
Martin v. Löwis18e16552006-02-15 17:27:45 +00004371SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004372
4373static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004374slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004375{
4376 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004377 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004378
4379 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004380 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004381 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004382 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004383 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004384 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004385 if (res == NULL)
4386 return -1;
4387 Py_DECREF(res);
4388 return 0;
4389}
4390
4391static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004392slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004393{
4394 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004395 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004396
4397 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004398 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004399 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004400 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004401 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004402 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004403 if (res == NULL)
4404 return -1;
4405 Py_DECREF(res);
4406 return 0;
4407}
4408
4409static int
4410slot_sq_contains(PyObject *self, PyObject *value)
4411{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004412 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004413 int result = -1;
4414
Guido van Rossum60718732001-08-28 17:47:51 +00004415 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004416
Guido van Rossum55f20992001-10-01 17:18:22 +00004417 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004418 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004419 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004420 if (args == NULL)
4421 res = NULL;
4422 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004423 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004424 Py_DECREF(args);
4425 }
4426 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004427 if (res != NULL) {
4428 result = PyObject_IsTrue(res);
4429 Py_DECREF(res);
4430 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004431 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004432 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004433 /* Possible results: -1 and 1 */
4434 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004435 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004436 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004437 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004438}
4439
Tim Peters6d6c1a32001-08-02 04:15:00 +00004440#define slot_mp_length slot_sq_length
4441
Guido van Rossumdc91b992001-08-08 22:26:22 +00004442SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004443
4444static int
4445slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4446{
4447 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004448 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004449
4450 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004451 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004452 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004453 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004454 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004455 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004456 if (res == NULL)
4457 return -1;
4458 Py_DECREF(res);
4459 return 0;
4460}
4461
Guido van Rossumdc91b992001-08-08 22:26:22 +00004462SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4463SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4464SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4465SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4466SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4467SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4468
Jeremy Hylton938ace62002-07-17 16:30:39 +00004469static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004470
4471SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4472 nb_power, "__pow__", "__rpow__")
4473
4474static PyObject *
4475slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4476{
Guido van Rossum2730b132001-08-28 18:22:14 +00004477 static PyObject *pow_str;
4478
Guido van Rossumdc91b992001-08-08 22:26:22 +00004479 if (modulus == Py_None)
4480 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004481 /* Three-arg power doesn't use __rpow__. But ternary_op
4482 can call this when the second argument's type uses
4483 slot_nb_power, so check before calling self.__pow__. */
4484 if (self->ob_type->tp_as_number != NULL &&
4485 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4486 return call_method(self, "__pow__", &pow_str,
4487 "(OO)", other, modulus);
4488 }
4489 Py_INCREF(Py_NotImplemented);
4490 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004491}
4492
4493SLOT0(slot_nb_negative, "__neg__")
4494SLOT0(slot_nb_positive, "__pos__")
4495SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004496
4497static int
4498slot_nb_nonzero(PyObject *self)
4499{
Tim Petersea7f75d2002-12-07 21:39:16 +00004500 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004501 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004502 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004503
Guido van Rossum55f20992001-10-01 17:18:22 +00004504 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004505 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004506 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004507 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004508 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004509 if (func == NULL)
4510 return PyErr_Occurred() ? -1 : 1;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004511 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004512 args = PyTuple_New(0);
4513 if (args != NULL) {
4514 PyObject *temp = PyObject_Call(func, args, NULL);
4515 Py_DECREF(args);
4516 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004517 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004518 result = PyObject_IsTrue(temp);
4519 else {
4520 PyErr_Format(PyExc_TypeError,
4521 "__nonzero__ should return "
4522 "bool or int, returned %s",
4523 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004524 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004525 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004526 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004527 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004528 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004529 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004530 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004531}
4532
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004533
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004534static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004535slot_nb_index(PyObject *self)
4536{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004537 static PyObject *index_str;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004538 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004539}
4540
4541
Guido van Rossumdc91b992001-08-08 22:26:22 +00004542SLOT0(slot_nb_invert, "__invert__")
4543SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4544SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4545SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4546SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4547SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004548
4549static int
4550slot_nb_coerce(PyObject **a, PyObject **b)
4551{
4552 static PyObject *coerce_str;
4553 PyObject *self = *a, *other = *b;
4554
4555 if (self->ob_type->tp_as_number != NULL &&
4556 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4557 PyObject *r;
4558 r = call_maybe(
4559 self, "__coerce__", &coerce_str, "(O)", other);
4560 if (r == NULL)
4561 return -1;
4562 if (r == Py_NotImplemented) {
4563 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004564 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004565 else {
4566 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4567 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004568 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004569 Py_DECREF(r);
4570 return -1;
4571 }
4572 *a = PyTuple_GET_ITEM(r, 0);
4573 Py_INCREF(*a);
4574 *b = PyTuple_GET_ITEM(r, 1);
4575 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004576 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004577 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004578 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004579 }
4580 if (other->ob_type->tp_as_number != NULL &&
4581 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4582 PyObject *r;
4583 r = call_maybe(
4584 other, "__coerce__", &coerce_str, "(O)", self);
4585 if (r == NULL)
4586 return -1;
4587 if (r == Py_NotImplemented) {
4588 Py_DECREF(r);
4589 return 1;
4590 }
4591 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4592 PyErr_SetString(PyExc_TypeError,
4593 "__coerce__ didn't return a 2-tuple");
4594 Py_DECREF(r);
4595 return -1;
4596 }
4597 *a = PyTuple_GET_ITEM(r, 1);
4598 Py_INCREF(*a);
4599 *b = PyTuple_GET_ITEM(r, 0);
4600 Py_INCREF(*b);
4601 Py_DECREF(r);
4602 return 0;
4603 }
4604 return 1;
4605}
4606
Guido van Rossumdc91b992001-08-08 22:26:22 +00004607SLOT0(slot_nb_int, "__int__")
4608SLOT0(slot_nb_long, "__long__")
4609SLOT0(slot_nb_float, "__float__")
4610SLOT0(slot_nb_oct, "__oct__")
4611SLOT0(slot_nb_hex, "__hex__")
4612SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4613SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4614SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4615SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4616SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Martin v. Löwisfd963262007-02-09 12:19:32 +00004617/* Can't use SLOT1 here, because nb_inplace_power is ternary */
4618static PyObject *
4619slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4620{
4621 static PyObject *cache_str;
4622 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
4623}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004624SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4625SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4626SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4627SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4628SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4629SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4630 "__floordiv__", "__rfloordiv__")
4631SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4632SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4633SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004634
4635static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004636half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004637{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004638 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004639 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004640 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004641
Guido van Rossum60718732001-08-28 17:47:51 +00004642 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004643 if (func == NULL) {
4644 PyErr_Clear();
4645 }
4646 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004647 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004648 if (args == NULL)
4649 res = NULL;
4650 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004651 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004652 Py_DECREF(args);
4653 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004654 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004655 if (res != Py_NotImplemented) {
4656 if (res == NULL)
4657 return -2;
4658 c = PyInt_AsLong(res);
4659 Py_DECREF(res);
4660 if (c == -1 && PyErr_Occurred())
4661 return -2;
4662 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4663 }
4664 Py_DECREF(res);
4665 }
4666 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004667}
4668
Guido van Rossumab3b0342001-09-18 20:38:53 +00004669/* This slot is published for the benefit of try_3way_compare in object.c */
4670int
4671_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004672{
4673 int c;
4674
Guido van Rossumab3b0342001-09-18 20:38:53 +00004675 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004676 c = half_compare(self, other);
4677 if (c <= 1)
4678 return c;
4679 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004680 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004681 c = half_compare(other, self);
4682 if (c < -1)
4683 return -2;
4684 if (c <= 1)
4685 return -c;
4686 }
4687 return (void *)self < (void *)other ? -1 :
4688 (void *)self > (void *)other ? 1 : 0;
4689}
4690
4691static PyObject *
4692slot_tp_repr(PyObject *self)
4693{
4694 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004695 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004696
Guido van Rossum60718732001-08-28 17:47:51 +00004697 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004698 if (func != NULL) {
4699 res = PyEval_CallObject(func, NULL);
4700 Py_DECREF(func);
4701 return res;
4702 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004703 PyErr_Clear();
4704 return PyString_FromFormat("<%s object at %p>",
4705 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004706}
4707
4708static PyObject *
4709slot_tp_str(PyObject *self)
4710{
4711 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004712 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004713
Guido van Rossum60718732001-08-28 17:47:51 +00004714 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004715 if (func != NULL) {
4716 res = PyEval_CallObject(func, NULL);
4717 Py_DECREF(func);
4718 return res;
4719 }
4720 else {
4721 PyErr_Clear();
4722 return slot_tp_repr(self);
4723 }
4724}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004725
4726static long
4727slot_tp_hash(PyObject *self)
4728{
Tim Peters61ce0a92002-12-06 23:38:02 +00004729 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004730 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004731 long h;
4732
Guido van Rossum60718732001-08-28 17:47:51 +00004733 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004734
4735 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004736 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004737 Py_DECREF(func);
4738 if (res == NULL)
4739 return -1;
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00004740 if (PyLong_Check(res))
Armin Rigo51fc8c42006-08-09 14:55:26 +00004741 h = PyLong_Type.tp_hash(res);
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00004742 else
4743 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004744 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004745 }
4746 else {
4747 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004748 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004749 if (func == NULL) {
4750 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004751 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004752 }
4753 if (func != NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00004754 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
4755 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004756 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004757 return -1;
4758 }
4759 PyErr_Clear();
4760 h = _Py_HashPointer((void *)self);
4761 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004762 if (h == -1 && !PyErr_Occurred())
4763 h = -2;
4764 return h;
4765}
4766
4767static PyObject *
4768slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4769{
Guido van Rossum60718732001-08-28 17:47:51 +00004770 static PyObject *call_str;
4771 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004772 PyObject *res;
4773
4774 if (meth == NULL)
4775 return NULL;
Armin Rigo53c1692f2006-06-21 21:58:50 +00004776
4777 /* PyObject_Call() will end up calling slot_tp_call() again if
4778 the object returned for __call__ has __call__ itself defined
4779 upon it. This can be an infinite recursion if you set
4780 __call__ in a class to an instance of it. */
Neal Norwitzb1149842006-06-23 03:32:44 +00004781 if (Py_EnterRecursiveCall(" in __call__")) {
4782 Py_DECREF(meth);
Armin Rigo53c1692f2006-06-21 21:58:50 +00004783 return NULL;
Neal Norwitzb1149842006-06-23 03:32:44 +00004784 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004785 res = PyObject_Call(meth, args, kwds);
Armin Rigo53c1692f2006-06-21 21:58:50 +00004786 Py_LeaveRecursiveCall();
4787
Tim Peters6d6c1a32001-08-02 04:15:00 +00004788 Py_DECREF(meth);
4789 return res;
4790}
4791
Guido van Rossum14a6f832001-10-17 13:59:09 +00004792/* There are two slot dispatch functions for tp_getattro.
4793
4794 - slot_tp_getattro() is used when __getattribute__ is overridden
4795 but no __getattr__ hook is present;
4796
4797 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4798
Guido van Rossumc334df52002-04-04 23:44:47 +00004799 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4800 detects the absence of __getattr__ and then installs the simpler slot if
4801 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004802
Tim Peters6d6c1a32001-08-02 04:15:00 +00004803static PyObject *
4804slot_tp_getattro(PyObject *self, PyObject *name)
4805{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004806 static PyObject *getattribute_str = NULL;
4807 return call_method(self, "__getattribute__", &getattribute_str,
4808 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004809}
4810
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004811static PyObject *
4812slot_tp_getattr_hook(PyObject *self, PyObject *name)
4813{
4814 PyTypeObject *tp = self->ob_type;
4815 PyObject *getattr, *getattribute, *res;
4816 static PyObject *getattribute_str = NULL;
4817 static PyObject *getattr_str = NULL;
4818
4819 if (getattr_str == NULL) {
4820 getattr_str = PyString_InternFromString("__getattr__");
4821 if (getattr_str == NULL)
4822 return NULL;
4823 }
4824 if (getattribute_str == NULL) {
4825 getattribute_str =
4826 PyString_InternFromString("__getattribute__");
4827 if (getattribute_str == NULL)
4828 return NULL;
4829 }
4830 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004831 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004832 /* No __getattr__ hook: use a simpler dispatcher */
4833 tp->tp_getattro = slot_tp_getattro;
4834 return slot_tp_getattro(self, name);
4835 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004836 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004837 if (getattribute == NULL ||
4838 (getattribute->ob_type == &PyWrapperDescr_Type &&
4839 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4840 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004841 res = PyObject_GenericGetAttr(self, name);
4842 else
Georg Brandl684fd0c2006-05-25 19:15:31 +00004843 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004844 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004845 PyErr_Clear();
Georg Brandl684fd0c2006-05-25 19:15:31 +00004846 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004847 }
4848 return res;
4849}
4850
Tim Peters6d6c1a32001-08-02 04:15:00 +00004851static int
4852slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4853{
4854 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004855 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004856
4857 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004858 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004859 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004860 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004861 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004862 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004863 if (res == NULL)
4864 return -1;
4865 Py_DECREF(res);
4866 return 0;
4867}
4868
4869/* Map rich comparison operators to their __xx__ namesakes */
4870static char *name_op[] = {
4871 "__lt__",
4872 "__le__",
4873 "__eq__",
4874 "__ne__",
4875 "__gt__",
4876 "__ge__",
4877};
4878
4879static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004880half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004881{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004882 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004883 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004884
Guido van Rossum60718732001-08-28 17:47:51 +00004885 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004886 if (func == NULL) {
4887 PyErr_Clear();
4888 Py_INCREF(Py_NotImplemented);
4889 return Py_NotImplemented;
4890 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004891 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004892 if (args == NULL)
4893 res = NULL;
4894 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004895 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004896 Py_DECREF(args);
4897 }
4898 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004899 return res;
4900}
4901
Guido van Rossumb8f63662001-08-15 23:57:02 +00004902static PyObject *
4903slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4904{
4905 PyObject *res;
4906
4907 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4908 res = half_richcompare(self, other, op);
4909 if (res != Py_NotImplemented)
4910 return res;
4911 Py_DECREF(res);
4912 }
4913 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004914 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004915 if (res != Py_NotImplemented) {
4916 return res;
4917 }
4918 Py_DECREF(res);
4919 }
4920 Py_INCREF(Py_NotImplemented);
4921 return Py_NotImplemented;
4922}
4923
4924static PyObject *
4925slot_tp_iter(PyObject *self)
4926{
4927 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004928 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004929
Guido van Rossum60718732001-08-28 17:47:51 +00004930 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004931 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004932 PyObject *args;
4933 args = res = PyTuple_New(0);
4934 if (args != NULL) {
4935 res = PyObject_Call(func, args, NULL);
4936 Py_DECREF(args);
4937 }
4938 Py_DECREF(func);
4939 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004940 }
4941 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004942 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004943 if (func == NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00004944 PyErr_Format(PyExc_TypeError,
4945 "'%.200s' object is not iterable",
4946 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004947 return NULL;
4948 }
4949 Py_DECREF(func);
4950 return PySeqIter_New(self);
4951}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004952
4953static PyObject *
4954slot_tp_iternext(PyObject *self)
4955{
Guido van Rossum2730b132001-08-28 18:22:14 +00004956 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004957 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004958}
4959
Guido van Rossum1a493502001-08-17 16:47:50 +00004960static PyObject *
4961slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4962{
4963 PyTypeObject *tp = self->ob_type;
4964 PyObject *get;
4965 static PyObject *get_str = NULL;
4966
4967 if (get_str == NULL) {
4968 get_str = PyString_InternFromString("__get__");
4969 if (get_str == NULL)
4970 return NULL;
4971 }
4972 get = _PyType_Lookup(tp, get_str);
4973 if (get == NULL) {
4974 /* Avoid further slowdowns */
4975 if (tp->tp_descr_get == slot_tp_descr_get)
4976 tp->tp_descr_get = NULL;
4977 Py_INCREF(self);
4978 return self;
4979 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004980 if (obj == NULL)
4981 obj = Py_None;
4982 if (type == NULL)
4983 type = Py_None;
Georg Brandl684fd0c2006-05-25 19:15:31 +00004984 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00004985}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004986
4987static int
4988slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4989{
Guido van Rossum2c252392001-08-24 10:13:31 +00004990 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004991 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004992
4993 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004994 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004995 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004996 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004997 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004998 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004999 if (res == NULL)
5000 return -1;
5001 Py_DECREF(res);
5002 return 0;
5003}
5004
5005static int
5006slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5007{
Guido van Rossum60718732001-08-28 17:47:51 +00005008 static PyObject *init_str;
5009 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005010 PyObject *res;
5011
5012 if (meth == NULL)
5013 return -1;
5014 res = PyObject_Call(meth, args, kwds);
5015 Py_DECREF(meth);
5016 if (res == NULL)
5017 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005018 if (res != Py_None) {
Georg Brandlccff7852006-06-18 22:17:29 +00005019 PyErr_Format(PyExc_TypeError,
5020 "__init__() should return None, not '%.200s'",
5021 res->ob_type->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005022 Py_DECREF(res);
5023 return -1;
5024 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005025 Py_DECREF(res);
5026 return 0;
5027}
5028
5029static PyObject *
5030slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5031{
Guido van Rossum7bed2132002-08-08 21:57:53 +00005032 static PyObject *new_str;
5033 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005034 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005035 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005036
Guido van Rossum7bed2132002-08-08 21:57:53 +00005037 if (new_str == NULL) {
5038 new_str = PyString_InternFromString("__new__");
5039 if (new_str == NULL)
5040 return NULL;
5041 }
5042 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005043 if (func == NULL)
5044 return NULL;
5045 assert(PyTuple_Check(args));
5046 n = PyTuple_GET_SIZE(args);
5047 newargs = PyTuple_New(n+1);
5048 if (newargs == NULL)
5049 return NULL;
5050 Py_INCREF(type);
5051 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5052 for (i = 0; i < n; i++) {
5053 x = PyTuple_GET_ITEM(args, i);
5054 Py_INCREF(x);
5055 PyTuple_SET_ITEM(newargs, i+1, x);
5056 }
5057 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00005058 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005059 Py_DECREF(func);
5060 return x;
5061}
5062
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005063static void
5064slot_tp_del(PyObject *self)
5065{
5066 static PyObject *del_str = NULL;
5067 PyObject *del, *res;
5068 PyObject *error_type, *error_value, *error_traceback;
5069
5070 /* Temporarily resurrect the object. */
5071 assert(self->ob_refcnt == 0);
5072 self->ob_refcnt = 1;
5073
5074 /* Save the current exception, if any. */
5075 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5076
5077 /* Execute __del__ method, if any. */
5078 del = lookup_maybe(self, "__del__", &del_str);
5079 if (del != NULL) {
5080 res = PyEval_CallObject(del, NULL);
5081 if (res == NULL)
5082 PyErr_WriteUnraisable(del);
5083 else
5084 Py_DECREF(res);
5085 Py_DECREF(del);
5086 }
5087
5088 /* Restore the saved exception. */
5089 PyErr_Restore(error_type, error_value, error_traceback);
5090
5091 /* Undo the temporary resurrection; can't use DECREF here, it would
5092 * cause a recursive call.
5093 */
5094 assert(self->ob_refcnt > 0);
5095 if (--self->ob_refcnt == 0)
5096 return; /* this is the normal path out */
5097
5098 /* __del__ resurrected it! Make it look like the original Py_DECREF
5099 * never happened.
5100 */
5101 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005102 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005103 _Py_NewReference(self);
5104 self->ob_refcnt = refcnt;
5105 }
5106 assert(!PyType_IS_GC(self->ob_type) ||
5107 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00005108 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5109 * we need to undo that. */
5110 _Py_DEC_REFTOTAL;
5111 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5112 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005113 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5114 * _Py_NewReference bumped tp_allocs: both of those need to be
5115 * undone.
5116 */
5117#ifdef COUNT_ALLOCS
5118 --self->ob_type->tp_frees;
5119 --self->ob_type->tp_allocs;
5120#endif
5121}
5122
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005123
5124/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005125 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005126 structure, which incorporates the additional structures used for numbers,
5127 sequences and mappings.
5128 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005129 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005130 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5131 terminated with an all-zero entry. (This table is further initialized and
5132 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005133
Guido van Rossum6d204072001-10-21 00:44:31 +00005134typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005135
5136#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005137#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005138#undef ETSLOT
5139#undef SQSLOT
5140#undef MPSLOT
5141#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005142#undef UNSLOT
5143#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005144#undef BINSLOT
5145#undef RBINSLOT
5146
Guido van Rossum6d204072001-10-21 00:44:31 +00005147#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005148 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5149 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005150#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5151 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005152 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005153#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005154 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005155 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005156#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5157 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5158#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5159 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5160#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5161 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5162#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5163 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5164 "x." NAME "() <==> " DOC)
5165#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5166 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5167 "x." NAME "(y) <==> x" DOC "y")
5168#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5169 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5170 "x." NAME "(y) <==> x" DOC "y")
5171#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5172 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5173 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005174#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5175 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5176 "x." NAME "(y) <==> " DOC)
5177#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5178 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5179 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005180
5181static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005182 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005183 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005184 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5185 The logic in abstract.c always falls back to nb_add/nb_multiply in
5186 this case. Defining both the nb_* and the sq_* slots to call the
5187 user-defined methods has unexpected side-effects, as shown by
5188 test_descr.notimplemented() */
5189 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005190 "x.__add__(y) <==> x+y"),
Armin Rigo314861c2006-03-30 14:04:02 +00005191 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005192 "x.__mul__(n) <==> x*n"),
Armin Rigo314861c2006-03-30 14:04:02 +00005193 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005194 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005195 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5196 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005197 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005198 "x.__getslice__(i, j) <==> x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005199 \n\
5200 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005201 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005202 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005203 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005204 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005205 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005206 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005207 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005208 \n\
5209 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005210 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005211 "x.__delslice__(i, j) <==> del x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005212 \n\
5213 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005214 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5215 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005216 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005217 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005218 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005219 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005220
Martin v. Löwis18e16552006-02-15 17:27:45 +00005221 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005222 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005223 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005224 wrap_binaryfunc,
5225 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005226 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005227 wrap_objobjargproc,
5228 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005229 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005230 wrap_delitem,
5231 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005232
Guido van Rossum6d204072001-10-21 00:44:31 +00005233 BINSLOT("__add__", nb_add, slot_nb_add,
5234 "+"),
5235 RBINSLOT("__radd__", nb_add, slot_nb_add,
5236 "+"),
5237 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5238 "-"),
5239 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5240 "-"),
5241 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5242 "*"),
5243 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5244 "*"),
5245 BINSLOT("__div__", nb_divide, slot_nb_divide,
5246 "/"),
5247 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5248 "/"),
5249 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5250 "%"),
5251 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5252 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005253 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005254 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005255 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005256 "divmod(y, x)"),
5257 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5258 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5259 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5260 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5261 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5262 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5263 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5264 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005265 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005266 "x != 0"),
5267 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5268 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5269 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5270 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5271 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5272 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5273 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5274 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5275 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5276 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5277 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5278 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5279 "x.__coerce__(y) <==> coerce(x, y)"),
5280 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5281 "int(x)"),
5282 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5283 "long(x)"),
5284 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5285 "float(x)"),
5286 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5287 "oct(x)"),
5288 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5289 "hex(x)"),
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005290 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005291 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005292 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5293 wrap_binaryfunc, "+"),
5294 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5295 wrap_binaryfunc, "-"),
5296 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5297 wrap_binaryfunc, "*"),
5298 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5299 wrap_binaryfunc, "/"),
5300 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5301 wrap_binaryfunc, "%"),
5302 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005303 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005304 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5305 wrap_binaryfunc, "<<"),
5306 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5307 wrap_binaryfunc, ">>"),
5308 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5309 wrap_binaryfunc, "&"),
5310 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5311 wrap_binaryfunc, "^"),
5312 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5313 wrap_binaryfunc, "|"),
5314 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5315 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5316 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5317 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5318 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5319 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5320 IBSLOT("__itruediv__", nb_inplace_true_divide,
5321 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005322
Guido van Rossum6d204072001-10-21 00:44:31 +00005323 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5324 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005325 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005326 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5327 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005328 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005329 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5330 "x.__cmp__(y) <==> cmp(x,y)"),
5331 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5332 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005333 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5334 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005335 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005336 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5337 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5338 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5339 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5340 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5341 "x.__setattr__('name', value) <==> x.name = value"),
5342 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5343 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5344 "x.__delattr__('name') <==> del x.name"),
5345 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5346 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5347 "x.__lt__(y) <==> x<y"),
5348 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5349 "x.__le__(y) <==> x<=y"),
5350 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5351 "x.__eq__(y) <==> x==y"),
5352 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5353 "x.__ne__(y) <==> x!=y"),
5354 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5355 "x.__gt__(y) <==> x>y"),
5356 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5357 "x.__ge__(y) <==> x>=y"),
5358 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5359 "x.__iter__() <==> iter(x)"),
5360 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5361 "x.next() -> the next value, or raise StopIteration"),
5362 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5363 "descr.__get__(obj[, type]) -> value"),
5364 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5365 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005366 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5367 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005368 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005369 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005370 "see x.__class__.__doc__ for signature",
5371 PyWrapperFlag_KEYWORDS),
5372 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005373 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005374 {NULL}
5375};
5376
Guido van Rossumc334df52002-04-04 23:44:47 +00005377/* Given a type pointer and an offset gotten from a slotdef entry, return a
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005378 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005379 the offset to the type pointer, since it takes care to indirect through the
5380 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5381 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005382static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005383slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005384{
5385 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005386 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005387
Guido van Rossume5c691a2003-03-07 15:13:17 +00005388 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005389 assert(offset >= 0);
Skip Montanaro429433b2006-04-18 00:35:43 +00005390 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5391 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005392 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005393 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005394 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005395 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005396 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005397 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005398 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005399 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005400 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005401 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005402 }
5403 else {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005404 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005405 }
5406 if (ptr != NULL)
5407 ptr += offset;
5408 return (void **)ptr;
5409}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005410
Guido van Rossumc334df52002-04-04 23:44:47 +00005411/* Length of array of slotdef pointers used to store slots with the
5412 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5413 the same __name__, for any __name__. Since that's a static property, it is
5414 appropriate to declare fixed-size arrays for this. */
5415#define MAX_EQUIV 10
5416
5417/* Return a slot pointer for a given name, but ONLY if the attribute has
5418 exactly one slot function. The name must be an interned string. */
5419static void **
5420resolve_slotdups(PyTypeObject *type, PyObject *name)
5421{
5422 /* XXX Maybe this could be optimized more -- but is it worth it? */
5423
5424 /* pname and ptrs act as a little cache */
5425 static PyObject *pname;
5426 static slotdef *ptrs[MAX_EQUIV];
5427 slotdef *p, **pp;
5428 void **res, **ptr;
5429
5430 if (pname != name) {
5431 /* Collect all slotdefs that match name into ptrs. */
5432 pname = name;
5433 pp = ptrs;
5434 for (p = slotdefs; p->name_strobj; p++) {
5435 if (p->name_strobj == name)
5436 *pp++ = p;
5437 }
5438 *pp = NULL;
5439 }
5440
5441 /* Look in all matching slots of the type; if exactly one of these has
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005442 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005443 res = NULL;
5444 for (pp = ptrs; *pp; pp++) {
5445 ptr = slotptr(type, (*pp)->offset);
5446 if (ptr == NULL || *ptr == NULL)
5447 continue;
5448 if (res != NULL)
5449 return NULL;
5450 res = ptr;
5451 }
5452 return res;
5453}
5454
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005455/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005456 does some incredibly complex thinking and then sticks something into the
5457 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5458 interests, and then stores a generic wrapper or a specific function into
5459 the slot.) Return a pointer to the next slotdef with a different offset,
5460 because that's convenient for fixup_slot_dispatchers(). */
5461static slotdef *
5462update_one_slot(PyTypeObject *type, slotdef *p)
5463{
5464 PyObject *descr;
5465 PyWrapperDescrObject *d;
5466 void *generic = NULL, *specific = NULL;
5467 int use_generic = 0;
5468 int offset = p->offset;
5469 void **ptr = slotptr(type, offset);
5470
5471 if (ptr == NULL) {
5472 do {
5473 ++p;
5474 } while (p->offset == offset);
5475 return p;
5476 }
5477 do {
5478 descr = _PyType_Lookup(type, p->name_strobj);
5479 if (descr == NULL)
5480 continue;
5481 if (descr->ob_type == &PyWrapperDescr_Type) {
5482 void **tptr = resolve_slotdups(type, p->name_strobj);
5483 if (tptr == NULL || tptr == ptr)
5484 generic = p->function;
5485 d = (PyWrapperDescrObject *)descr;
5486 if (d->d_base->wrapper == p->wrapper &&
5487 PyType_IsSubtype(type, d->d_type))
5488 {
5489 if (specific == NULL ||
5490 specific == d->d_wrapped)
5491 specific = d->d_wrapped;
5492 else
5493 use_generic = 1;
5494 }
5495 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005496 else if (descr->ob_type == &PyCFunction_Type &&
5497 PyCFunction_GET_FUNCTION(descr) ==
5498 (PyCFunction)tp_new_wrapper &&
5499 strcmp(p->name, "__new__") == 0)
5500 {
5501 /* The __new__ wrapper is not a wrapper descriptor,
5502 so must be special-cased differently.
5503 If we don't do this, creating an instance will
5504 always use slot_tp_new which will look up
5505 __new__ in the MRO which will call tp_new_wrapper
5506 which will look through the base classes looking
5507 for a static base and call its tp_new (usually
5508 PyType_GenericNew), after performing various
5509 sanity checks and constructing a new argument
5510 list. Cut all that nonsense short -- this speeds
5511 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005512 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005513 /* XXX I'm not 100% sure that there isn't a hole
5514 in this reasoning that requires additional
5515 sanity checks. I'll buy the first person to
5516 point out a bug in this reasoning a beer. */
5517 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005518 else {
5519 use_generic = 1;
5520 generic = p->function;
5521 }
5522 } while ((++p)->offset == offset);
5523 if (specific && !use_generic)
5524 *ptr = specific;
5525 else
5526 *ptr = generic;
5527 return p;
5528}
5529
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005530/* In the type, update the slots whose slotdefs are gathered in the pp array.
5531 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005532static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005533update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005534{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005535 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005536
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005537 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005538 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005539 return 0;
5540}
5541
Guido van Rossumc334df52002-04-04 23:44:47 +00005542/* Comparison function for qsort() to compare slotdefs by their offset, and
5543 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005544static int
5545slotdef_cmp(const void *aa, const void *bb)
5546{
5547 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5548 int c = a->offset - b->offset;
5549 if (c != 0)
5550 return c;
5551 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005552 /* Cannot use a-b, as this gives off_t,
5553 which may lose precision when converted to int. */
5554 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005555}
5556
Guido van Rossumc334df52002-04-04 23:44:47 +00005557/* Initialize the slotdefs table by adding interned string objects for the
5558 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005559static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005560init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005561{
5562 slotdef *p;
5563 static int initialized = 0;
5564
5565 if (initialized)
5566 return;
5567 for (p = slotdefs; p->name; p++) {
5568 p->name_strobj = PyString_InternFromString(p->name);
5569 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005570 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005571 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005572 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5573 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005574 initialized = 1;
5575}
5576
Guido van Rossumc334df52002-04-04 23:44:47 +00005577/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005578static int
5579update_slot(PyTypeObject *type, PyObject *name)
5580{
Guido van Rossumc334df52002-04-04 23:44:47 +00005581 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005582 slotdef *p;
5583 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005584 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005585
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005586 init_slotdefs();
5587 pp = ptrs;
5588 for (p = slotdefs; p->name; p++) {
5589 /* XXX assume name is interned! */
5590 if (p->name_strobj == name)
5591 *pp++ = p;
5592 }
5593 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005594 for (pp = ptrs; *pp; pp++) {
5595 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005596 offset = p->offset;
5597 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005598 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005599 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005600 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005601 if (ptrs[0] == NULL)
5602 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005603 return update_subclasses(type, name,
5604 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005605}
5606
Guido van Rossumc334df52002-04-04 23:44:47 +00005607/* Store the proper functions in the slot dispatches at class (type)
5608 definition time, based upon which operations the class overrides in its
5609 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005610static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005611fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005612{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005613 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005614
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005615 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005616 for (p = slotdefs; p->name; )
5617 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005618}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005619
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005620static void
5621update_all_slots(PyTypeObject* type)
5622{
5623 slotdef *p;
5624
5625 init_slotdefs();
5626 for (p = slotdefs; p->name; p++) {
5627 /* update_slot returns int but can't actually fail */
5628 update_slot(type, p->name_strobj);
5629 }
5630}
5631
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005632/* recurse_down_subclasses() and update_subclasses() are mutually
5633 recursive functions to call a callback for all subclasses,
5634 but refraining from recursing into subclasses that define 'name'. */
5635
5636static int
5637update_subclasses(PyTypeObject *type, PyObject *name,
5638 update_callback callback, void *data)
5639{
5640 if (callback(type, data) < 0)
5641 return -1;
5642 return recurse_down_subclasses(type, name, callback, data);
5643}
5644
5645static int
5646recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5647 update_callback callback, void *data)
5648{
5649 PyTypeObject *subclass;
5650 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005651 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005652
5653 subclasses = type->tp_subclasses;
5654 if (subclasses == NULL)
5655 return 0;
5656 assert(PyList_Check(subclasses));
5657 n = PyList_GET_SIZE(subclasses);
5658 for (i = 0; i < n; i++) {
5659 ref = PyList_GET_ITEM(subclasses, i);
5660 assert(PyWeakref_CheckRef(ref));
5661 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5662 assert(subclass != NULL);
5663 if ((PyObject *)subclass == Py_None)
5664 continue;
5665 assert(PyType_Check(subclass));
5666 /* Avoid recursing down into unaffected classes */
5667 dict = subclass->tp_dict;
5668 if (dict != NULL && PyDict_Check(dict) &&
5669 PyDict_GetItem(dict, name) != NULL)
5670 continue;
5671 if (update_subclasses(subclass, name, callback, data) < 0)
5672 return -1;
5673 }
5674 return 0;
5675}
5676
Guido van Rossum6d204072001-10-21 00:44:31 +00005677/* This function is called by PyType_Ready() to populate the type's
5678 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005679 function slot (like tp_repr) that's defined in the type, one or more
5680 corresponding descriptors are added in the type's tp_dict dictionary
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005681 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005682 cause more than one descriptor to be added (for example, the nb_add
5683 slot adds both __add__ and __radd__ descriptors) and some function
5684 slots compete for the same descriptor (for example both sq_item and
5685 mp_subscript generate a __getitem__ descriptor).
5686
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005687 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005688 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005689 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005690 between competing slots: the members of PyHeapTypeObject are listed
5691 from most general to least general, so the most general slot is
5692 preferred. In particular, because as_mapping comes before as_sequence,
5693 for a type that defines both mp_subscript and sq_item, mp_subscript
5694 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005695
5696 This only adds new descriptors and doesn't overwrite entries in
5697 tp_dict that were previously defined. The descriptors contain a
5698 reference to the C function they must call, so that it's safe if they
5699 are copied into a subtype's __dict__ and the subtype has a different
5700 C function in its slot -- calling the method defined by the
5701 descriptor will call the C function that was used to create it,
5702 rather than the C function present in the slot when it is called.
5703 (This is important because a subtype may have a C function in the
5704 slot that calls the method from the dictionary, and we want to avoid
5705 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005706
5707static int
5708add_operators(PyTypeObject *type)
5709{
5710 PyObject *dict = type->tp_dict;
5711 slotdef *p;
5712 PyObject *descr;
5713 void **ptr;
5714
5715 init_slotdefs();
5716 for (p = slotdefs; p->name; p++) {
5717 if (p->wrapper == NULL)
5718 continue;
5719 ptr = slotptr(type, p->offset);
5720 if (!ptr || !*ptr)
5721 continue;
5722 if (PyDict_GetItem(dict, p->name_strobj))
5723 continue;
5724 descr = PyDescr_NewWrapper(type, p, *ptr);
5725 if (descr == NULL)
5726 return -1;
5727 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5728 return -1;
5729 Py_DECREF(descr);
5730 }
5731 if (type->tp_new != NULL) {
5732 if (add_tp_new_wrapper(type) < 0)
5733 return -1;
5734 }
5735 return 0;
5736}
5737
Guido van Rossum705f0f52001-08-24 16:47:00 +00005738
5739/* Cooperative 'super' */
5740
5741typedef struct {
5742 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005743 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005744 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005745 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005746} superobject;
5747
Guido van Rossum6f799372001-09-20 20:46:19 +00005748static PyMemberDef super_members[] = {
5749 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5750 "the class invoking super()"},
5751 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5752 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005753 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005754 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005755 {0}
5756};
5757
Guido van Rossum705f0f52001-08-24 16:47:00 +00005758static void
5759super_dealloc(PyObject *self)
5760{
5761 superobject *su = (superobject *)self;
5762
Guido van Rossum048eb752001-10-02 21:24:57 +00005763 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005764 Py_XDECREF(su->obj);
5765 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005766 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005767 self->ob_type->tp_free(self);
5768}
5769
5770static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005771super_repr(PyObject *self)
5772{
5773 superobject *su = (superobject *)self;
5774
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005775 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005776 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005777 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005778 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005779 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005780 else
5781 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005782 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005783 su->type ? su->type->tp_name : "NULL");
5784}
5785
5786static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005787super_getattro(PyObject *self, PyObject *name)
5788{
5789 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005790 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005791
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005792 if (!skip) {
5793 /* We want __class__ to return the class of the super object
5794 (i.e. super, or a subclass), not the class of su->obj. */
5795 skip = (PyString_Check(name) &&
5796 PyString_GET_SIZE(name) == 9 &&
5797 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5798 }
5799
5800 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005801 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005802 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005803 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005804 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005805
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005806 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005807 mro = starttype->tp_mro;
5808
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005809 if (mro == NULL)
5810 n = 0;
5811 else {
5812 assert(PyTuple_Check(mro));
5813 n = PyTuple_GET_SIZE(mro);
5814 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005815 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005816 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005817 break;
5818 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005819 i++;
5820 res = NULL;
5821 for (; i < n; i++) {
5822 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005823 if (PyType_Check(tmp))
5824 dict = ((PyTypeObject *)tmp)->tp_dict;
5825 else if (PyClass_Check(tmp))
5826 dict = ((PyClassObject *)tmp)->cl_dict;
5827 else
5828 continue;
5829 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005830 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005831 Py_INCREF(res);
5832 f = res->ob_type->tp_descr_get;
5833 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005834 tmp = f(res,
5835 /* Only pass 'obj' param if
5836 this is instance-mode super
5837 (See SF ID #743627)
5838 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005839 (su->obj == (PyObject *)
5840 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005841 ? (PyObject *)NULL
5842 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005843 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005844 Py_DECREF(res);
5845 res = tmp;
5846 }
5847 return res;
5848 }
5849 }
5850 }
5851 return PyObject_GenericGetAttr(self, name);
5852}
5853
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005854static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005855supercheck(PyTypeObject *type, PyObject *obj)
5856{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005857 /* Check that a super() call makes sense. Return a type object.
5858
5859 obj can be a new-style class, or an instance of one:
5860
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005861 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005862 used for class methods; the return value is obj.
5863
5864 - If it is an instance, it must be an instance of 'type'. This is
5865 the normal case; the return value is obj.__class__.
5866
5867 But... when obj is an instance, we want to allow for the case where
5868 obj->ob_type is not a subclass of type, but obj.__class__ is!
5869 This will allow using super() with a proxy for obj.
5870 */
5871
Guido van Rossum8e80a722003-02-18 19:22:22 +00005872 /* Check for first bullet above (special case) */
5873 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5874 Py_INCREF(obj);
5875 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005876 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005877
5878 /* Normal case */
5879 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005880 Py_INCREF(obj->ob_type);
5881 return obj->ob_type;
5882 }
5883 else {
5884 /* Try the slow way */
5885 static PyObject *class_str = NULL;
5886 PyObject *class_attr;
5887
5888 if (class_str == NULL) {
5889 class_str = PyString_FromString("__class__");
5890 if (class_str == NULL)
5891 return NULL;
5892 }
5893
5894 class_attr = PyObject_GetAttr(obj, class_str);
5895
5896 if (class_attr != NULL &&
5897 PyType_Check(class_attr) &&
5898 (PyTypeObject *)class_attr != obj->ob_type)
5899 {
5900 int ok = PyType_IsSubtype(
5901 (PyTypeObject *)class_attr, type);
5902 if (ok)
5903 return (PyTypeObject *)class_attr;
5904 }
5905
5906 if (class_attr == NULL)
5907 PyErr_Clear();
5908 else
5909 Py_DECREF(class_attr);
5910 }
5911
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005912 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005913 "super(type, obj): "
5914 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005915 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005916}
5917
Guido van Rossum705f0f52001-08-24 16:47:00 +00005918static PyObject *
5919super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5920{
5921 superobject *su = (superobject *)self;
Anthony Baxtera6286212006-04-11 07:42:36 +00005922 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005923
5924 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5925 /* Not binding to an object, or already bound */
5926 Py_INCREF(self);
5927 return self;
5928 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005929 if (su->ob_type != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005930 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005931 call its type */
Georg Brandl684fd0c2006-05-25 19:15:31 +00005932 return PyObject_CallFunctionObjArgs((PyObject *)su->ob_type,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005933 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005934 else {
5935 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005936 PyTypeObject *obj_type = supercheck(su->type, obj);
5937 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005938 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00005939 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005940 NULL, NULL);
Anthony Baxtera6286212006-04-11 07:42:36 +00005941 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005942 return NULL;
5943 Py_INCREF(su->type);
5944 Py_INCREF(obj);
Anthony Baxtera6286212006-04-11 07:42:36 +00005945 newobj->type = su->type;
5946 newobj->obj = obj;
5947 newobj->obj_type = obj_type;
5948 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005949 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005950}
5951
5952static int
5953super_init(PyObject *self, PyObject *args, PyObject *kwds)
5954{
5955 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005956 PyTypeObject *type;
5957 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005958 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005959
Georg Brandl5d59c092006-09-30 08:43:30 +00005960 if (!_PyArg_NoKeywords("super", kwds))
5961 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005962 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5963 return -1;
5964 if (obj == Py_None)
5965 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005966 if (obj != NULL) {
5967 obj_type = supercheck(type, obj);
5968 if (obj_type == NULL)
5969 return -1;
5970 Py_INCREF(obj);
5971 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005972 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005973 su->type = type;
5974 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005975 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005976 return 0;
5977}
5978
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005979PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005980"super(type) -> unbound super object\n"
5981"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005982"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005983"Typical use to call a cooperative superclass method:\n"
5984"class C(B):\n"
5985" def meth(self, arg):\n"
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005986" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005987
Guido van Rossum048eb752001-10-02 21:24:57 +00005988static int
5989super_traverse(PyObject *self, visitproc visit, void *arg)
5990{
5991 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00005992
Thomas Woutersc6e55062006-04-15 21:47:09 +00005993 Py_VISIT(su->obj);
5994 Py_VISIT(su->type);
5995 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005996
5997 return 0;
5998}
5999
Guido van Rossum705f0f52001-08-24 16:47:00 +00006000PyTypeObject PySuper_Type = {
6001 PyObject_HEAD_INIT(&PyType_Type)
6002 0, /* ob_size */
6003 "super", /* tp_name */
6004 sizeof(superobject), /* tp_basicsize */
6005 0, /* tp_itemsize */
6006 /* methods */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006007 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006008 0, /* tp_print */
6009 0, /* tp_getattr */
6010 0, /* tp_setattr */
6011 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006012 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006013 0, /* tp_as_number */
6014 0, /* tp_as_sequence */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006015 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006016 0, /* tp_hash */
6017 0, /* tp_call */
6018 0, /* tp_str */
6019 super_getattro, /* tp_getattro */
6020 0, /* tp_setattro */
6021 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00006022 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6023 Py_TPFLAGS_BASETYPE, /* tp_flags */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006024 super_doc, /* tp_doc */
6025 super_traverse, /* tp_traverse */
6026 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006027 0, /* tp_richcompare */
6028 0, /* tp_weaklistoffset */
6029 0, /* tp_iter */
6030 0, /* tp_iternext */
6031 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006032 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006033 0, /* tp_getset */
6034 0, /* tp_base */
6035 0, /* tp_dict */
6036 super_descr_get, /* tp_descr_get */
6037 0, /* tp_descr_set */
6038 0, /* tp_dictoffset */
6039 super_init, /* tp_init */
6040 PyType_GenericAlloc, /* tp_alloc */
6041 PyType_GenericNew, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006042 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006043};