blob: 4b0816e02aeedc753bad40ce732d1c0460bd8a19 [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;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000190 PyTypeObject *new_base, *old_base;
191 PyObject *old_bases, *old_mro;
192
193 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
194 PyErr_Format(PyExc_TypeError,
195 "can't set %s.__bases__", type->tp_name);
196 return -1;
197 }
198 if (!value) {
199 PyErr_Format(PyExc_TypeError,
200 "can't delete %s.__bases__", type->tp_name);
201 return -1;
202 }
203 if (!PyTuple_Check(value)) {
204 PyErr_Format(PyExc_TypeError,
205 "can only assign tuple to %s.__bases__, not %s",
206 type->tp_name, value->ob_type->tp_name);
207 return -1;
208 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000209 if (PyTuple_GET_SIZE(value) == 0) {
210 PyErr_Format(PyExc_TypeError,
211 "can only assign non-empty tuple to %s.__bases__, not ()",
212 type->tp_name);
213 return -1;
214 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000215 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
216 ob = PyTuple_GET_ITEM(value, i);
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
534 to the type. Traverse the type so the collector
535 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
Guido van Rossum1987c662003-05-29 14:29:23 +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
725 before the trashcan begin macro. Without understanding the
726 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
733 probably GC-untracks the object. If it does that using the
734 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
741 GC untrack
742 trashcan begin
743 GC track
744
Tim Petersf7f9e992003-11-13 21:59:32 +0000745 Q. Why did the last question say "immediately GC-track again"?
746 It's nowhere near immediately.
747
748 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.
754
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
766 is incremented and the code between trashcan begin and end is
767 executed
768
769 - this destroys much of the object's contents, including its
770 slots and __dict__
771
772 - basedealloc() is called; this is really list_dealloc(), or
773 some other type which also uses the trashcan macros
774
775 - the trashcan limit is now reached, so the object is put on the
776 trashcan's to-be-deleted-later list
777
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
785 to-be-deleted-later list
786
787 - subtype_dealloc() is called *AGAIN* for the same object
788
789 - at the very least (if the destroyed slots and __dict__ don't
790 cause problems) the object's type gets decref'ed a second
791 time, which is *BAD*!!!
792
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
803 that the effective level never reaches the limit. Therefore, we
804 *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
857 it to the instance. The arguments are the object,
858 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()
900 instead of PyObject_GetAttrString(). This uses the same convention
901 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
1102 to be put next into the MRO. There is some conflict between the
1103 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;
1174 }
1175
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;
Guido van Rossum1f121312002-11-14 19:49:16 +00001255 }
1256
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.
1358 This is the first one that's on the path to the "solid base". */
1359
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;
1376 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001377 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{
1576 PyObject *tmp = slots;
1577 PyObject *o, *o1;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001578 Py_ssize_t i;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001579 ssizessizeargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001580 for (i = 0; i < nslots; i++) {
1581 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1582 if (tmp == slots) {
1583 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1584 if (tmp == NULL)
1585 return NULL;
1586 }
1587 o1 = _PyUnicode_AsDefaultEncodedString
1588 (o, NULL);
1589 if (o1 == NULL) {
1590 Py_DECREF(tmp);
1591 return 0;
1592 }
1593 Py_INCREF(o1);
1594 Py_DECREF(o);
1595 PyTuple_SET_ITEM(tmp, i, o1);
1596 }
1597 }
1598 return tmp;
1599}
1600#endif
1601
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001602static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001603type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1604{
1605 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001606 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001607 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001608 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001609 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001610 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001611 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001612 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001613
Tim Peters3abca122001-10-27 19:37:48 +00001614 assert(args != NULL && PyTuple_Check(args));
1615 assert(kwds == NULL || PyDict_Check(kwds));
1616
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001617 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001618 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001619 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1620 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001621
1622 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1623 PyObject *x = PyTuple_GET_ITEM(args, 0);
1624 Py_INCREF(x->ob_type);
1625 return (PyObject *) x->ob_type;
1626 }
1627
1628 /* SF bug 475327 -- if that didn't trigger, we need 3
1629 arguments. but PyArg_ParseTupleAndKeywords below may give
1630 a msg saying type() needs exactly 3. */
1631 if (nargs + nkwds != 3) {
1632 PyErr_SetString(PyExc_TypeError,
1633 "type() takes 1 or 3 arguments");
1634 return NULL;
1635 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001636 }
1637
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001638 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001639 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1640 &name,
1641 &PyTuple_Type, &bases,
1642 &PyDict_Type, &dict))
1643 return NULL;
1644
1645 /* Determine the proper metatype to deal with this,
1646 and check for metatype conflicts while we're at it.
1647 Note that if some other metatype wins to contract,
1648 it's possible that its instances are not types. */
1649 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001650 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001651 for (i = 0; i < nbases; i++) {
1652 tmp = PyTuple_GET_ITEM(bases, i);
1653 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001654 if (tmptype == &PyClass_Type)
1655 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001656 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001657 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001658 if (PyType_IsSubtype(tmptype, winner)) {
1659 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001660 continue;
1661 }
1662 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001663 "metaclass conflict: "
1664 "the metaclass of a derived class "
1665 "must be a (non-strict) subclass "
1666 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001667 return NULL;
1668 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001669 if (winner != metatype) {
1670 if (winner->tp_new != type_new) /* Pass it to the winner */
1671 return winner->tp_new(winner, args, kwds);
1672 metatype = winner;
1673 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001674
1675 /* Adjust for empty tuple bases */
1676 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001677 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001678 if (bases == NULL)
1679 return NULL;
1680 nbases = 1;
1681 }
1682 else
1683 Py_INCREF(bases);
1684
1685 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1686
1687 /* Calculate best base, and check that all bases are type objects */
1688 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001689 if (base == NULL) {
1690 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001691 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001692 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001693 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1694 PyErr_Format(PyExc_TypeError,
1695 "type '%.100s' is not an acceptable base type",
1696 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001697 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001698 return NULL;
1699 }
1700
Tim Peters6d6c1a32001-08-02 04:15:00 +00001701 /* Check for a __slots__ sequence variable in dict, and count it */
1702 slots = PyDict_GetItemString(dict, "__slots__");
1703 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001704 add_dict = 0;
1705 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001706 may_add_dict = base->tp_dictoffset == 0;
1707 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1708 if (slots == NULL) {
1709 if (may_add_dict) {
1710 add_dict++;
1711 }
1712 if (may_add_weak) {
1713 add_weak++;
1714 }
1715 }
1716 else {
1717 /* Have slots */
1718
Tim Peters6d6c1a32001-08-02 04:15:00 +00001719 /* Make it into a tuple */
1720 if (PyString_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001721 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001722 else
1723 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001724 if (slots == NULL) {
1725 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001726 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001727 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001728 assert(PyTuple_Check(slots));
1729
1730 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001731 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001732 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001733 PyErr_Format(PyExc_TypeError,
1734 "nonempty __slots__ "
1735 "not supported for subtype of '%s'",
1736 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001737 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001738 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001739 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001740 return NULL;
1741 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001742
Martin v. Löwisd919a592002-10-14 21:07:28 +00001743#ifdef Py_USING_UNICODE
1744 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001745 if (tmp != slots) {
1746 Py_DECREF(slots);
1747 slots = tmp;
1748 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001749 if (!tmp)
1750 return NULL;
1751#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001752 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001753 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001754 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1755 char *s;
1756 if (!valid_identifier(tmp))
1757 goto bad_slots;
1758 assert(PyString_Check(tmp));
1759 s = PyString_AS_STRING(tmp);
1760 if (strcmp(s, "__dict__") == 0) {
1761 if (!may_add_dict || add_dict) {
1762 PyErr_SetString(PyExc_TypeError,
1763 "__dict__ slot disallowed: "
1764 "we already got one");
1765 goto bad_slots;
1766 }
1767 add_dict++;
1768 }
1769 if (strcmp(s, "__weakref__") == 0) {
1770 if (!may_add_weak || add_weak) {
1771 PyErr_SetString(PyExc_TypeError,
1772 "__weakref__ slot disallowed: "
1773 "either we already got one, "
1774 "or __itemsize__ != 0");
1775 goto bad_slots;
1776 }
1777 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001778 }
1779 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001780
Guido van Rossumad47da02002-08-12 19:05:44 +00001781 /* Copy slots into yet another tuple, demangling names */
1782 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001783 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001784 goto bad_slots;
1785 for (i = j = 0; i < nslots; i++) {
1786 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001787 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001788 s = PyString_AS_STRING(tmp);
1789 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1790 (add_weak && strcmp(s, "__weakref__") == 0))
1791 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001792 tmp =_Py_Mangle(name, tmp);
1793 if (!tmp)
1794 goto bad_slots;
Guido van Rossumad47da02002-08-12 19:05:44 +00001795 PyTuple_SET_ITEM(newslots, j, tmp);
1796 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001797 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001798 assert(j == nslots - add_dict - add_weak);
1799 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001800 Py_DECREF(slots);
1801 slots = newslots;
1802
Guido van Rossumad47da02002-08-12 19:05:44 +00001803 /* Secondary bases may provide weakrefs or dict */
1804 if (nbases > 1 &&
1805 ((may_add_dict && !add_dict) ||
1806 (may_add_weak && !add_weak))) {
1807 for (i = 0; i < nbases; i++) {
1808 tmp = PyTuple_GET_ITEM(bases, i);
1809 if (tmp == (PyObject *)base)
1810 continue; /* Skip primary base */
1811 if (PyClass_Check(tmp)) {
1812 /* Classic base class provides both */
1813 if (may_add_dict && !add_dict)
1814 add_dict++;
1815 if (may_add_weak && !add_weak)
1816 add_weak++;
1817 break;
1818 }
1819 assert(PyType_Check(tmp));
1820 tmptype = (PyTypeObject *)tmp;
1821 if (may_add_dict && !add_dict &&
1822 tmptype->tp_dictoffset != 0)
1823 add_dict++;
1824 if (may_add_weak && !add_weak &&
1825 tmptype->tp_weaklistoffset != 0)
1826 add_weak++;
1827 if (may_add_dict && !add_dict)
1828 continue;
1829 if (may_add_weak && !add_weak)
1830 continue;
1831 /* Nothing more to check */
1832 break;
1833 }
1834 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001835 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001836
1837 /* XXX From here until type is safely allocated,
1838 "return NULL" may leak slots! */
1839
1840 /* Allocate the type object */
1841 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001842 if (type == NULL) {
1843 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001844 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001845 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001846 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001847
1848 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001849 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001850 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00001851 et->ht_name = name;
1852 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001853
Guido van Rossumdc91b992001-08-08 22:26:22 +00001854 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001855 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1856 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001857 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1858 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001859
1860 /* It's a new-style number unless it specifically inherits any
1861 old-style numeric behavior */
1862 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1863 (base->tp_as_number == NULL))
1864 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1865
1866 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001867 type->tp_as_number = &et->as_number;
1868 type->tp_as_sequence = &et->as_sequence;
1869 type->tp_as_mapping = &et->as_mapping;
1870 type->tp_as_buffer = &et->as_buffer;
1871 type->tp_name = PyString_AS_STRING(name);
1872
1873 /* Set tp_base and tp_bases */
1874 type->tp_bases = bases;
1875 Py_INCREF(base);
1876 type->tp_base = base;
1877
Guido van Rossum687ae002001-10-15 22:03:32 +00001878 /* Initialize tp_dict from passed-in dict */
1879 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001880 if (dict == NULL) {
1881 Py_DECREF(type);
1882 return NULL;
1883 }
1884
Guido van Rossumc3542212001-08-16 09:18:56 +00001885 /* Set __module__ in the dict */
1886 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1887 tmp = PyEval_GetGlobals();
1888 if (tmp != NULL) {
1889 tmp = PyDict_GetItemString(tmp, "__name__");
1890 if (tmp != NULL) {
1891 if (PyDict_SetItemString(dict, "__module__",
1892 tmp) < 0)
1893 return NULL;
1894 }
1895 }
1896 }
1897
Tim Peters2f93e282001-10-04 05:27:00 +00001898 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001899 and is a string. The __doc__ accessor will first look for tp_doc;
1900 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001901 */
1902 {
1903 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1904 if (doc != NULL && PyString_Check(doc)) {
1905 const size_t n = (size_t)PyString_GET_SIZE(doc);
Anthony Baxtera6286212006-04-11 07:42:36 +00001906 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001907 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00001908 Py_DECREF(type);
1909 return NULL;
1910 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001911 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
1912 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00001913 }
1914 }
1915
Tim Peters6d6c1a32001-08-02 04:15:00 +00001916 /* Special-case __new__: if it's a plain function,
1917 make it a static function */
1918 tmp = PyDict_GetItemString(dict, "__new__");
1919 if (tmp != NULL && PyFunction_Check(tmp)) {
1920 tmp = PyStaticMethod_New(tmp);
1921 if (tmp == NULL) {
1922 Py_DECREF(type);
1923 return NULL;
1924 }
1925 PyDict_SetItemString(dict, "__new__", tmp);
1926 Py_DECREF(tmp);
1927 }
1928
1929 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001930 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001931 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001932 if (slots != NULL) {
1933 for (i = 0; i < nslots; i++, mp++) {
1934 mp->name = PyString_AS_STRING(
1935 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001936 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001937 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001938 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001939 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001940 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001941 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001942 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001943 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001944 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001945 slotoffset += sizeof(PyObject *);
1946 }
1947 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001948 if (add_dict) {
1949 if (base->tp_itemsize)
1950 type->tp_dictoffset = -(long)sizeof(PyObject *);
1951 else
1952 type->tp_dictoffset = slotoffset;
1953 slotoffset += sizeof(PyObject *);
1954 }
1955 if (add_weak) {
1956 assert(!base->tp_itemsize);
1957 type->tp_weaklistoffset = slotoffset;
1958 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001959 }
1960 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001961 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001962 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001963
1964 if (type->tp_weaklistoffset && type->tp_dictoffset)
1965 type->tp_getset = subtype_getsets_full;
1966 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1967 type->tp_getset = subtype_getsets_weakref_only;
1968 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1969 type->tp_getset = subtype_getsets_dict_only;
1970 else
1971 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001972
1973 /* Special case some slots */
1974 if (type->tp_dictoffset != 0 || nslots > 0) {
1975 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1976 type->tp_getattro = PyObject_GenericGetAttr;
1977 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1978 type->tp_setattro = PyObject_GenericSetAttr;
1979 }
1980 type->tp_dealloc = subtype_dealloc;
1981
Guido van Rossum9475a232001-10-05 20:51:39 +00001982 /* Enable GC unless there are really no instance variables possible */
1983 if (!(type->tp_basicsize == sizeof(PyObject) &&
1984 type->tp_itemsize == 0))
1985 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1986
Tim Peters6d6c1a32001-08-02 04:15:00 +00001987 /* Always override allocation strategy to use regular heap */
1988 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001989 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001990 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001991 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001992 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001993 }
1994 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001995 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001996
1997 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001998 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001999 Py_DECREF(type);
2000 return NULL;
2001 }
2002
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002003 /* Put the proper slots in place */
2004 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002005
Tim Peters6d6c1a32001-08-02 04:15:00 +00002006 return (PyObject *)type;
2007}
2008
2009/* Internal API to look for a name through the MRO.
2010 This returns a borrowed reference, and doesn't set an exception! */
2011PyObject *
2012_PyType_Lookup(PyTypeObject *type, PyObject *name)
2013{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002014 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002015 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002016
Guido van Rossum687ae002001-10-15 22:03:32 +00002017 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002018 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002019
2020 /* If mro is NULL, the type is either not yet initialized
2021 by PyType_Ready(), or already cleared by type_clear().
2022 Either way the safest thing to do is to return NULL. */
2023 if (mro == NULL)
2024 return NULL;
2025
Tim Peters6d6c1a32001-08-02 04:15:00 +00002026 assert(PyTuple_Check(mro));
2027 n = PyTuple_GET_SIZE(mro);
2028 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002029 base = PyTuple_GET_ITEM(mro, i);
2030 if (PyClass_Check(base))
2031 dict = ((PyClassObject *)base)->cl_dict;
2032 else {
2033 assert(PyType_Check(base));
2034 dict = ((PyTypeObject *)base)->tp_dict;
2035 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002036 assert(dict && PyDict_Check(dict));
2037 res = PyDict_GetItem(dict, name);
2038 if (res != NULL)
2039 return res;
2040 }
2041 return NULL;
2042}
2043
2044/* This is similar to PyObject_GenericGetAttr(),
2045 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2046static PyObject *
2047type_getattro(PyTypeObject *type, PyObject *name)
2048{
2049 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002050 PyObject *meta_attribute, *attribute;
2051 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002052
2053 /* Initialize this type (we'll assume the metatype is initialized) */
2054 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002055 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002056 return NULL;
2057 }
2058
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002059 /* No readable descriptor found yet */
2060 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002061
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002062 /* Look for the attribute in the metatype */
2063 meta_attribute = _PyType_Lookup(metatype, name);
2064
2065 if (meta_attribute != NULL) {
2066 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002067
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002068 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2069 /* Data descriptors implement tp_descr_set to intercept
2070 * writes. Assume the attribute is not overridden in
2071 * type's tp_dict (and bases): call the descriptor now.
2072 */
2073 return meta_get(meta_attribute, (PyObject *)type,
2074 (PyObject *)metatype);
2075 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002076 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002077 }
2078
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002079 /* No data descriptor found on metatype. Look in tp_dict of this
2080 * type and its bases */
2081 attribute = _PyType_Lookup(type, name);
2082 if (attribute != NULL) {
2083 /* Implement descriptor functionality, if any */
2084 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002085
2086 Py_XDECREF(meta_attribute);
2087
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002088 if (local_get != NULL) {
2089 /* NULL 2nd argument indicates the descriptor was
2090 * found on the target object itself (or a base) */
2091 return local_get(attribute, (PyObject *)NULL,
2092 (PyObject *)type);
2093 }
Tim Peters34592512002-07-11 06:23:50 +00002094
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002095 Py_INCREF(attribute);
2096 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002097 }
2098
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002099 /* No attribute found in local __dict__ (or bases): use the
2100 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002101 if (meta_get != NULL) {
2102 PyObject *res;
2103 res = meta_get(meta_attribute, (PyObject *)type,
2104 (PyObject *)metatype);
2105 Py_DECREF(meta_attribute);
2106 return res;
2107 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002108
2109 /* If an ordinary attribute was found on the metatype, return it now */
2110 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002111 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002112 }
2113
2114 /* Give up */
2115 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002116 "type object '%.50s' has no attribute '%.400s'",
2117 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002118 return NULL;
2119}
2120
2121static int
2122type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2123{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002124 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2125 PyErr_Format(
2126 PyExc_TypeError,
2127 "can't set attributes of built-in/extension type '%s'",
2128 type->tp_name);
2129 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002130 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002131 /* XXX Example of how I expect this to be used...
2132 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2133 return -1;
2134 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002135 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2136 return -1;
2137 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002138}
2139
2140static void
2141type_dealloc(PyTypeObject *type)
2142{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002143 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002144
2145 /* Assert this is a heap-allocated type object */
2146 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002147 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002148 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002149 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002150 Py_XDECREF(type->tp_base);
2151 Py_XDECREF(type->tp_dict);
2152 Py_XDECREF(type->tp_bases);
2153 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002154 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002155 Py_XDECREF(type->tp_subclasses);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002156 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2157 * of most other objects. It's okay to cast it to char *.
2158 */
2159 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002160 Py_XDECREF(et->ht_name);
2161 Py_XDECREF(et->ht_slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002162 type->ob_type->tp_free((PyObject *)type);
2163}
2164
Guido van Rossum1c450732001-10-08 15:18:27 +00002165static PyObject *
2166type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2167{
2168 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002169 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002170
2171 list = PyList_New(0);
2172 if (list == NULL)
2173 return NULL;
2174 raw = type->tp_subclasses;
2175 if (raw == NULL)
2176 return list;
2177 assert(PyList_Check(raw));
2178 n = PyList_GET_SIZE(raw);
2179 for (i = 0; i < n; i++) {
2180 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002181 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002182 ref = PyWeakref_GET_OBJECT(ref);
2183 if (ref != Py_None) {
2184 if (PyList_Append(list, ref) < 0) {
2185 Py_DECREF(list);
2186 return NULL;
2187 }
2188 }
2189 }
2190 return list;
2191}
2192
Tim Peters6d6c1a32001-08-02 04:15:00 +00002193static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002194 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002195 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002196 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002197 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002198 {0}
2199};
2200
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002201PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002202"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002203"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002204
Guido van Rossum048eb752001-10-02 21:24:57 +00002205static int
2206type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2207{
Guido van Rossuma3862092002-06-10 15:24:42 +00002208 /* Because of type_is_gc(), the collector only calls this
2209 for heaptypes. */
2210 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002211
Thomas Woutersc6e55062006-04-15 21:47:09 +00002212 Py_VISIT(type->tp_dict);
2213 Py_VISIT(type->tp_cache);
2214 Py_VISIT(type->tp_mro);
2215 Py_VISIT(type->tp_bases);
2216 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002217
2218 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002219 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002220 in cycles; tp_subclasses is a list of weak references,
2221 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002222
Guido van Rossum048eb752001-10-02 21:24:57 +00002223 return 0;
2224}
2225
2226static int
2227type_clear(PyTypeObject *type)
2228{
Guido van Rossuma3862092002-06-10 15:24:42 +00002229 /* Because of type_is_gc(), the collector only calls this
2230 for heaptypes. */
2231 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002232
Guido van Rossuma3862092002-06-10 15:24:42 +00002233 /* The only field we need to clear is tp_mro, which is part of a
2234 hard cycle (its first element is the class itself) that won't
2235 be broken otherwise (it's a tuple and tuples don't have a
2236 tp_clear handler). None of the other fields need to be
2237 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002238
Guido van Rossuma3862092002-06-10 15:24:42 +00002239 tp_dict:
2240 It is a dict, so the collector will call its tp_clear.
2241
2242 tp_cache:
2243 Not used; if it were, it would be a dict.
2244
2245 tp_bases, tp_base:
2246 If these are involved in a cycle, there must be at least
2247 one other, mutable object in the cycle, e.g. a base
2248 class's dict; the cycle will be broken that way.
2249
2250 tp_subclasses:
2251 A list of weak references can't be part of a cycle; and
2252 lists have their own tp_clear.
2253
Guido van Rossume5c691a2003-03-07 15:13:17 +00002254 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002255 A tuple of strings can't be part of a cycle.
2256 */
2257
Thomas Woutersedf17d82006-04-15 17:28:34 +00002258 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002259
2260 return 0;
2261}
2262
2263static int
2264type_is_gc(PyTypeObject *type)
2265{
2266 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2267}
2268
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002269PyTypeObject PyType_Type = {
2270 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002271 0, /* ob_size */
2272 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002273 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002274 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002275 (destructor)type_dealloc, /* tp_dealloc */
2276 0, /* tp_print */
2277 0, /* tp_getattr */
2278 0, /* tp_setattr */
2279 type_compare, /* tp_compare */
2280 (reprfunc)type_repr, /* tp_repr */
2281 0, /* tp_as_number */
2282 0, /* tp_as_sequence */
2283 0, /* tp_as_mapping */
2284 (hashfunc)_Py_HashPointer, /* tp_hash */
2285 (ternaryfunc)type_call, /* tp_call */
2286 0, /* tp_str */
2287 (getattrofunc)type_getattro, /* tp_getattro */
2288 (setattrofunc)type_setattro, /* tp_setattro */
2289 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002290 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002291 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002292 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002293 (traverseproc)type_traverse, /* tp_traverse */
2294 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002295 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002296 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002297 0, /* tp_iter */
2298 0, /* tp_iternext */
2299 type_methods, /* tp_methods */
2300 type_members, /* tp_members */
2301 type_getsets, /* tp_getset */
2302 0, /* tp_base */
2303 0, /* tp_dict */
2304 0, /* tp_descr_get */
2305 0, /* tp_descr_set */
2306 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2307 0, /* tp_init */
2308 0, /* tp_alloc */
2309 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002310 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002311 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002312};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002313
2314
2315/* The base type of all types (eventually)... except itself. */
2316
2317static int
2318object_init(PyObject *self, PyObject *args, PyObject *kwds)
2319{
2320 return 0;
2321}
2322
Guido van Rossum298e4212003-02-13 16:30:16 +00002323/* If we don't have a tp_new for a new-style class, new will use this one.
2324 Therefore this should take no arguments/keywords. However, this new may
2325 also be inherited by objects that define a tp_init but no tp_new. These
2326 objects WILL pass argumets to tp_new, because it gets the same args as
2327 tp_init. So only allow arguments if we aren't using the default init, in
2328 which case we expect init to handle argument parsing. */
2329static PyObject *
2330object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2331{
2332 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2333 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2334 PyErr_SetString(PyExc_TypeError,
2335 "default __new__ takes no parameters");
2336 return NULL;
2337 }
2338 return type->tp_alloc(type, 0);
2339}
2340
Tim Peters6d6c1a32001-08-02 04:15:00 +00002341static void
2342object_dealloc(PyObject *self)
2343{
2344 self->ob_type->tp_free(self);
2345}
2346
Guido van Rossum8e248182001-08-12 05:17:56 +00002347static PyObject *
2348object_repr(PyObject *self)
2349{
Guido van Rossum76e69632001-08-16 18:52:43 +00002350 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002351 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002352
Guido van Rossum76e69632001-08-16 18:52:43 +00002353 type = self->ob_type;
2354 mod = type_module(type, NULL);
2355 if (mod == NULL)
2356 PyErr_Clear();
2357 else if (!PyString_Check(mod)) {
2358 Py_DECREF(mod);
2359 mod = NULL;
2360 }
2361 name = type_name(type, NULL);
2362 if (name == NULL)
2363 return NULL;
2364 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002365 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002366 PyString_AS_STRING(mod),
2367 PyString_AS_STRING(name),
2368 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002369 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002370 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002371 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002372 Py_XDECREF(mod);
2373 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002374 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002375}
2376
Guido van Rossumb8f63662001-08-15 23:57:02 +00002377static PyObject *
2378object_str(PyObject *self)
2379{
2380 unaryfunc f;
2381
2382 f = self->ob_type->tp_repr;
2383 if (f == NULL)
2384 f = object_repr;
2385 return f(self);
2386}
2387
Guido van Rossum8e248182001-08-12 05:17:56 +00002388static long
2389object_hash(PyObject *self)
2390{
2391 return _Py_HashPointer(self);
2392}
Guido van Rossum8e248182001-08-12 05:17:56 +00002393
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002394static PyObject *
2395object_get_class(PyObject *self, void *closure)
2396{
2397 Py_INCREF(self->ob_type);
2398 return (PyObject *)(self->ob_type);
2399}
2400
2401static int
2402equiv_structs(PyTypeObject *a, PyTypeObject *b)
2403{
2404 return a == b ||
2405 (a != NULL &&
2406 b != NULL &&
2407 a->tp_basicsize == b->tp_basicsize &&
2408 a->tp_itemsize == b->tp_itemsize &&
2409 a->tp_dictoffset == b->tp_dictoffset &&
2410 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2411 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2412 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2413}
2414
2415static int
2416same_slots_added(PyTypeObject *a, PyTypeObject *b)
2417{
2418 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002419 Py_ssize_t size;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002420
2421 if (base != b->tp_base)
2422 return 0;
2423 if (equiv_structs(a, base) && equiv_structs(b, base))
2424 return 1;
2425 size = base->tp_basicsize;
2426 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2427 size += sizeof(PyObject *);
2428 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2429 size += sizeof(PyObject *);
2430 return size == a->tp_basicsize && size == b->tp_basicsize;
2431}
2432
2433static int
Anthony Baxtera6286212006-04-11 07:42:36 +00002434compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002435{
2436 PyTypeObject *newbase, *oldbase;
2437
Anthony Baxtera6286212006-04-11 07:42:36 +00002438 if (newto->tp_dealloc != oldto->tp_dealloc ||
2439 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002440 {
2441 PyErr_Format(PyExc_TypeError,
2442 "%s assignment: "
2443 "'%s' deallocator differs from '%s'",
2444 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002445 newto->tp_name,
2446 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002447 return 0;
2448 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002449 newbase = newto;
2450 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002451 while (equiv_structs(newbase, newbase->tp_base))
2452 newbase = newbase->tp_base;
2453 while (equiv_structs(oldbase, oldbase->tp_base))
2454 oldbase = oldbase->tp_base;
2455 if (newbase != oldbase &&
2456 (newbase->tp_base != oldbase->tp_base ||
2457 !same_slots_added(newbase, oldbase))) {
2458 PyErr_Format(PyExc_TypeError,
2459 "%s assignment: "
2460 "'%s' object layout differs from '%s'",
2461 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002462 newto->tp_name,
2463 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002464 return 0;
2465 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002466
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002467 return 1;
2468}
2469
2470static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002471object_set_class(PyObject *self, PyObject *value, void *closure)
2472{
Anthony Baxtera6286212006-04-11 07:42:36 +00002473 PyTypeObject *oldto = self->ob_type;
2474 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002475
Guido van Rossumb6b89422002-04-15 01:03:30 +00002476 if (value == NULL) {
2477 PyErr_SetString(PyExc_TypeError,
2478 "can't delete __class__ attribute");
2479 return -1;
2480 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002481 if (!PyType_Check(value)) {
2482 PyErr_Format(PyExc_TypeError,
2483 "__class__ must be set to new-style class, not '%s' object",
2484 value->ob_type->tp_name);
2485 return -1;
2486 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002487 newto = (PyTypeObject *)value;
2488 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2489 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002490 {
2491 PyErr_Format(PyExc_TypeError,
2492 "__class__ assignment: only for heap types");
2493 return -1;
2494 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002495 if (compatible_for_assignment(newto, oldto, "__class__")) {
2496 Py_INCREF(newto);
2497 self->ob_type = newto;
2498 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002499 return 0;
2500 }
2501 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002502 return -1;
2503 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002504}
2505
2506static PyGetSetDef object_getsets[] = {
2507 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002508 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002509 {0}
2510};
2511
Guido van Rossumc53f0092003-02-18 22:05:12 +00002512
Guido van Rossum036f9992003-02-21 22:02:54 +00002513/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2514 We fall back to helpers in copy_reg for:
2515 - pickle protocols < 2
2516 - calculating the list of slot names (done only once per class)
2517 - the __newobj__ function (which is used as a token but never called)
2518*/
2519
2520static PyObject *
2521import_copy_reg(void)
2522{
2523 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002524
2525 if (!copy_reg_str) {
2526 copy_reg_str = PyString_InternFromString("copy_reg");
2527 if (copy_reg_str == NULL)
2528 return NULL;
2529 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002530
2531 return PyImport_Import(copy_reg_str);
2532}
2533
2534static PyObject *
2535slotnames(PyObject *cls)
2536{
2537 PyObject *clsdict;
2538 PyObject *copy_reg;
2539 PyObject *slotnames;
2540
2541 if (!PyType_Check(cls)) {
2542 Py_INCREF(Py_None);
2543 return Py_None;
2544 }
2545
2546 clsdict = ((PyTypeObject *)cls)->tp_dict;
2547 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002548 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002549 Py_INCREF(slotnames);
2550 return slotnames;
2551 }
2552
2553 copy_reg = import_copy_reg();
2554 if (copy_reg == NULL)
2555 return NULL;
2556
2557 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2558 Py_DECREF(copy_reg);
2559 if (slotnames != NULL &&
2560 slotnames != Py_None &&
2561 !PyList_Check(slotnames))
2562 {
2563 PyErr_SetString(PyExc_TypeError,
2564 "copy_reg._slotnames didn't return a list or None");
2565 Py_DECREF(slotnames);
2566 slotnames = NULL;
2567 }
2568
2569 return slotnames;
2570}
2571
2572static PyObject *
2573reduce_2(PyObject *obj)
2574{
2575 PyObject *cls, *getnewargs;
2576 PyObject *args = NULL, *args2 = NULL;
2577 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2578 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2579 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002580 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00002581
2582 cls = PyObject_GetAttrString(obj, "__class__");
2583 if (cls == NULL)
2584 return NULL;
2585
2586 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2587 if (getnewargs != NULL) {
2588 args = PyObject_CallObject(getnewargs, NULL);
2589 Py_DECREF(getnewargs);
2590 if (args != NULL && !PyTuple_Check(args)) {
Georg Brandlccff7852006-06-18 22:17:29 +00002591 PyErr_Format(PyExc_TypeError,
2592 "__getnewargs__ should return a tuple, "
2593 "not '%.200s'", args->ob_type->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00002594 goto end;
2595 }
2596 }
2597 else {
2598 PyErr_Clear();
2599 args = PyTuple_New(0);
2600 }
2601 if (args == NULL)
2602 goto end;
2603
2604 getstate = PyObject_GetAttrString(obj, "__getstate__");
2605 if (getstate != NULL) {
2606 state = PyObject_CallObject(getstate, NULL);
2607 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002608 if (state == NULL)
2609 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002610 }
2611 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002612 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002613 state = PyObject_GetAttrString(obj, "__dict__");
2614 if (state == NULL) {
2615 PyErr_Clear();
2616 state = Py_None;
2617 Py_INCREF(state);
2618 }
2619 names = slotnames(cls);
2620 if (names == NULL)
2621 goto end;
2622 if (names != Py_None) {
2623 assert(PyList_Check(names));
2624 slots = PyDict_New();
2625 if (slots == NULL)
2626 goto end;
2627 n = 0;
2628 /* Can't pre-compute the list size; the list
2629 is stored on the class so accessible to other
2630 threads, which may be run by DECREF */
2631 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2632 PyObject *name, *value;
2633 name = PyList_GET_ITEM(names, i);
2634 value = PyObject_GetAttr(obj, name);
2635 if (value == NULL)
2636 PyErr_Clear();
2637 else {
2638 int err = PyDict_SetItem(slots, name,
2639 value);
2640 Py_DECREF(value);
2641 if (err)
2642 goto end;
2643 n++;
2644 }
2645 }
2646 if (n) {
2647 state = Py_BuildValue("(NO)", state, slots);
2648 if (state == NULL)
2649 goto end;
2650 }
2651 }
2652 }
2653
2654 if (!PyList_Check(obj)) {
2655 listitems = Py_None;
2656 Py_INCREF(listitems);
2657 }
2658 else {
2659 listitems = PyObject_GetIter(obj);
2660 if (listitems == NULL)
2661 goto end;
2662 }
2663
2664 if (!PyDict_Check(obj)) {
2665 dictitems = Py_None;
2666 Py_INCREF(dictitems);
2667 }
2668 else {
2669 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2670 if (dictitems == NULL)
2671 goto end;
2672 }
2673
2674 copy_reg = import_copy_reg();
2675 if (copy_reg == NULL)
2676 goto end;
2677 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2678 if (newobj == NULL)
2679 goto end;
2680
2681 n = PyTuple_GET_SIZE(args);
2682 args2 = PyTuple_New(n+1);
2683 if (args2 == NULL)
2684 goto end;
2685 PyTuple_SET_ITEM(args2, 0, cls);
2686 cls = NULL;
2687 for (i = 0; i < n; i++) {
2688 PyObject *v = PyTuple_GET_ITEM(args, i);
2689 Py_INCREF(v);
2690 PyTuple_SET_ITEM(args2, i+1, v);
2691 }
2692
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002693 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002694
2695 end:
2696 Py_XDECREF(cls);
2697 Py_XDECREF(args);
2698 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002699 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002700 Py_XDECREF(state);
2701 Py_XDECREF(names);
2702 Py_XDECREF(listitems);
2703 Py_XDECREF(dictitems);
2704 Py_XDECREF(copy_reg);
2705 Py_XDECREF(newobj);
2706 return res;
2707}
2708
2709static PyObject *
2710object_reduce_ex(PyObject *self, PyObject *args)
2711{
2712 /* Call copy_reg._reduce_ex(self, proto) */
2713 PyObject *reduce, *copy_reg, *res;
2714 int proto = 0;
2715
2716 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2717 return NULL;
2718
2719 reduce = PyObject_GetAttrString(self, "__reduce__");
2720 if (reduce == NULL)
2721 PyErr_Clear();
2722 else {
2723 PyObject *cls, *clsreduce, *objreduce;
2724 int override;
2725 cls = PyObject_GetAttrString(self, "__class__");
2726 if (cls == NULL) {
2727 Py_DECREF(reduce);
2728 return NULL;
2729 }
2730 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2731 Py_DECREF(cls);
2732 if (clsreduce == NULL) {
2733 Py_DECREF(reduce);
2734 return NULL;
2735 }
2736 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2737 "__reduce__");
2738 override = (clsreduce != objreduce);
2739 Py_DECREF(clsreduce);
2740 if (override) {
2741 res = PyObject_CallObject(reduce, NULL);
2742 Py_DECREF(reduce);
2743 return res;
2744 }
2745 else
2746 Py_DECREF(reduce);
2747 }
2748
2749 if (proto >= 2)
2750 return reduce_2(self);
2751
2752 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002753 if (!copy_reg)
2754 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002755
Guido van Rossumc53f0092003-02-18 22:05:12 +00002756 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002757 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002758
Guido van Rossum3926a632001-09-25 16:25:58 +00002759 return res;
2760}
2761
2762static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002763 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2764 PyDoc_STR("helper for pickle")},
2765 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002766 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002767 {0}
2768};
2769
Guido van Rossum036f9992003-02-21 22:02:54 +00002770
Tim Peters6d6c1a32001-08-02 04:15:00 +00002771PyTypeObject PyBaseObject_Type = {
2772 PyObject_HEAD_INIT(&PyType_Type)
2773 0, /* ob_size */
2774 "object", /* tp_name */
2775 sizeof(PyObject), /* tp_basicsize */
2776 0, /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00002777 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002778 0, /* tp_print */
2779 0, /* tp_getattr */
2780 0, /* tp_setattr */
2781 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002782 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002783 0, /* tp_as_number */
2784 0, /* tp_as_sequence */
2785 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002786 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002787 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002788 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002789 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002790 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002791 0, /* tp_as_buffer */
2792 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002793 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002794 0, /* tp_traverse */
2795 0, /* tp_clear */
2796 0, /* tp_richcompare */
2797 0, /* tp_weaklistoffset */
2798 0, /* tp_iter */
2799 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002800 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002801 0, /* tp_members */
2802 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002803 0, /* tp_base */
2804 0, /* tp_dict */
2805 0, /* tp_descr_get */
2806 0, /* tp_descr_set */
2807 0, /* tp_dictoffset */
2808 object_init, /* tp_init */
2809 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002810 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002811 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002812};
2813
2814
2815/* Initialize the __dict__ in a type object */
2816
2817static int
2818add_methods(PyTypeObject *type, PyMethodDef *meth)
2819{
Guido van Rossum687ae002001-10-15 22:03:32 +00002820 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002821
2822 for (; meth->ml_name != NULL; meth++) {
2823 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002824 if (PyDict_GetItemString(dict, meth->ml_name) &&
2825 !(meth->ml_flags & METH_COEXIST))
2826 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002827 if (meth->ml_flags & METH_CLASS) {
2828 if (meth->ml_flags & METH_STATIC) {
2829 PyErr_SetString(PyExc_ValueError,
2830 "method cannot be both class and static");
2831 return -1;
2832 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002833 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002834 }
2835 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002836 PyObject *cfunc = PyCFunction_New(meth, NULL);
2837 if (cfunc == NULL)
2838 return -1;
2839 descr = PyStaticMethod_New(cfunc);
2840 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002841 }
2842 else {
2843 descr = PyDescr_NewMethod(type, meth);
2844 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002845 if (descr == NULL)
2846 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002847 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002848 return -1;
2849 Py_DECREF(descr);
2850 }
2851 return 0;
2852}
2853
2854static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002855add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002856{
Guido van Rossum687ae002001-10-15 22:03:32 +00002857 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002858
2859 for (; memb->name != NULL; memb++) {
2860 PyObject *descr;
2861 if (PyDict_GetItemString(dict, memb->name))
2862 continue;
2863 descr = PyDescr_NewMember(type, memb);
2864 if (descr == NULL)
2865 return -1;
2866 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2867 return -1;
2868 Py_DECREF(descr);
2869 }
2870 return 0;
2871}
2872
2873static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002874add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002875{
Guido van Rossum687ae002001-10-15 22:03:32 +00002876 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002877
2878 for (; gsp->name != NULL; gsp++) {
2879 PyObject *descr;
2880 if (PyDict_GetItemString(dict, gsp->name))
2881 continue;
2882 descr = PyDescr_NewGetSet(type, gsp);
2883
2884 if (descr == NULL)
2885 return -1;
2886 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2887 return -1;
2888 Py_DECREF(descr);
2889 }
2890 return 0;
2891}
2892
Guido van Rossum13d52f02001-08-10 21:24:08 +00002893static void
2894inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002895{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002896 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002897
Guido van Rossum13d52f02001-08-10 21:24:08 +00002898 /* Special flag magic */
2899 if (!type->tp_as_buffer && base->tp_as_buffer) {
2900 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2901 type->tp_flags |=
2902 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2903 }
2904 if (!type->tp_as_sequence && base->tp_as_sequence) {
2905 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2906 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2907 }
2908 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2909 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2910 if ((!type->tp_as_number && base->tp_as_number) ||
2911 (!type->tp_as_sequence && base->tp_as_sequence)) {
2912 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2913 if (!type->tp_as_number && !type->tp_as_sequence) {
2914 type->tp_flags |= base->tp_flags &
2915 Py_TPFLAGS_HAVE_INPLACEOPS;
2916 }
2917 }
2918 /* Wow */
2919 }
2920 if (!type->tp_as_number && base->tp_as_number) {
2921 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2922 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2923 }
2924
2925 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002926 oldsize = base->tp_basicsize;
2927 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2928 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2929 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002930 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2931 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002932 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002933 if (type->tp_traverse == NULL)
2934 type->tp_traverse = base->tp_traverse;
2935 if (type->tp_clear == NULL)
2936 type->tp_clear = base->tp_clear;
2937 }
2938 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002939 /* The condition below could use some explanation.
2940 It appears that tp_new is not inherited for static types
2941 whose base class is 'object'; this seems to be a precaution
2942 so that old extension types don't suddenly become
2943 callable (object.__new__ wouldn't insure the invariants
2944 that the extension type's own factory function ensures).
2945 Heap types, of course, are under our control, so they do
2946 inherit tp_new; static extension types that specify some
2947 other built-in type as the default are considered
2948 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002949 if (base != &PyBaseObject_Type ||
2950 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2951 if (type->tp_new == NULL)
2952 type->tp_new = base->tp_new;
2953 }
2954 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002955 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002956
2957 /* Copy other non-function slots */
2958
2959#undef COPYVAL
2960#define COPYVAL(SLOT) \
2961 if (type->SLOT == 0) type->SLOT = base->SLOT
2962
2963 COPYVAL(tp_itemsize);
2964 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2965 COPYVAL(tp_weaklistoffset);
2966 }
2967 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2968 COPYVAL(tp_dictoffset);
2969 }
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002970
2971 /* Setup fast subclass flags */
2972 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
2973 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
2974 else if (PyType_IsSubtype(base, &PyType_Type))
2975 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
2976 else if (PyType_IsSubtype(base, &PyInt_Type))
2977 type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS;
2978 else if (PyType_IsSubtype(base, &PyLong_Type))
2979 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
2980 else if (PyType_IsSubtype(base, &PyString_Type))
2981 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
2982 else if (PyType_IsSubtype(base, &PyUnicode_Type))
2983 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
2984 else if (PyType_IsSubtype(base, &PyTuple_Type))
2985 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
2986 else if (PyType_IsSubtype(base, &PyList_Type))
2987 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
2988 else if (PyType_IsSubtype(base, &PyDict_Type))
2989 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002990}
2991
2992static void
2993inherit_slots(PyTypeObject *type, PyTypeObject *base)
2994{
2995 PyTypeObject *basebase;
2996
2997#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002998#undef COPYSLOT
2999#undef COPYNUM
3000#undef COPYSEQ
3001#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003002#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003003
3004#define SLOTDEFINED(SLOT) \
3005 (base->SLOT != 0 && \
3006 (basebase == NULL || base->SLOT != basebase->SLOT))
3007
Tim Peters6d6c1a32001-08-02 04:15:00 +00003008#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003009 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003010
3011#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3012#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3013#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003014#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003015
Guido van Rossum13d52f02001-08-10 21:24:08 +00003016 /* This won't inherit indirect slots (from tp_as_number etc.)
3017 if type doesn't provide the space. */
3018
3019 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3020 basebase = base->tp_base;
3021 if (basebase->tp_as_number == NULL)
3022 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003023 COPYNUM(nb_add);
3024 COPYNUM(nb_subtract);
3025 COPYNUM(nb_multiply);
3026 COPYNUM(nb_divide);
3027 COPYNUM(nb_remainder);
3028 COPYNUM(nb_divmod);
3029 COPYNUM(nb_power);
3030 COPYNUM(nb_negative);
3031 COPYNUM(nb_positive);
3032 COPYNUM(nb_absolute);
3033 COPYNUM(nb_nonzero);
3034 COPYNUM(nb_invert);
3035 COPYNUM(nb_lshift);
3036 COPYNUM(nb_rshift);
3037 COPYNUM(nb_and);
3038 COPYNUM(nb_xor);
3039 COPYNUM(nb_or);
3040 COPYNUM(nb_coerce);
3041 COPYNUM(nb_int);
3042 COPYNUM(nb_long);
3043 COPYNUM(nb_float);
3044 COPYNUM(nb_oct);
3045 COPYNUM(nb_hex);
3046 COPYNUM(nb_inplace_add);
3047 COPYNUM(nb_inplace_subtract);
3048 COPYNUM(nb_inplace_multiply);
3049 COPYNUM(nb_inplace_divide);
3050 COPYNUM(nb_inplace_remainder);
3051 COPYNUM(nb_inplace_power);
3052 COPYNUM(nb_inplace_lshift);
3053 COPYNUM(nb_inplace_rshift);
3054 COPYNUM(nb_inplace_and);
3055 COPYNUM(nb_inplace_xor);
3056 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003057 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3058 COPYNUM(nb_true_divide);
3059 COPYNUM(nb_floor_divide);
3060 COPYNUM(nb_inplace_true_divide);
3061 COPYNUM(nb_inplace_floor_divide);
3062 }
Guido van Rossum38fff8c2006-03-07 18:50:55 +00003063 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3064 COPYNUM(nb_index);
3065 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003066 }
3067
Guido van Rossum13d52f02001-08-10 21:24:08 +00003068 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3069 basebase = base->tp_base;
3070 if (basebase->tp_as_sequence == NULL)
3071 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003072 COPYSEQ(sq_length);
3073 COPYSEQ(sq_concat);
3074 COPYSEQ(sq_repeat);
3075 COPYSEQ(sq_item);
3076 COPYSEQ(sq_slice);
3077 COPYSEQ(sq_ass_item);
3078 COPYSEQ(sq_ass_slice);
3079 COPYSEQ(sq_contains);
3080 COPYSEQ(sq_inplace_concat);
3081 COPYSEQ(sq_inplace_repeat);
3082 }
3083
Guido van Rossum13d52f02001-08-10 21:24:08 +00003084 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3085 basebase = base->tp_base;
3086 if (basebase->tp_as_mapping == NULL)
3087 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003088 COPYMAP(mp_length);
3089 COPYMAP(mp_subscript);
3090 COPYMAP(mp_ass_subscript);
3091 }
3092
Tim Petersfc57ccb2001-10-12 02:38:24 +00003093 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3094 basebase = base->tp_base;
3095 if (basebase->tp_as_buffer == NULL)
3096 basebase = NULL;
3097 COPYBUF(bf_getreadbuffer);
3098 COPYBUF(bf_getwritebuffer);
3099 COPYBUF(bf_getsegcount);
3100 COPYBUF(bf_getcharbuffer);
3101 }
3102
Guido van Rossum13d52f02001-08-10 21:24:08 +00003103 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003104
Tim Peters6d6c1a32001-08-02 04:15:00 +00003105 COPYSLOT(tp_dealloc);
3106 COPYSLOT(tp_print);
3107 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3108 type->tp_getattr = base->tp_getattr;
3109 type->tp_getattro = base->tp_getattro;
3110 }
3111 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3112 type->tp_setattr = base->tp_setattr;
3113 type->tp_setattro = base->tp_setattro;
3114 }
3115 /* tp_compare see tp_richcompare */
3116 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003117 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003118 COPYSLOT(tp_call);
3119 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003120 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003121 if (type->tp_compare == NULL &&
3122 type->tp_richcompare == NULL &&
3123 type->tp_hash == NULL)
3124 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003125 type->tp_compare = base->tp_compare;
3126 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003127 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003128 }
3129 }
3130 else {
3131 COPYSLOT(tp_compare);
3132 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003133 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3134 COPYSLOT(tp_iter);
3135 COPYSLOT(tp_iternext);
3136 }
3137 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3138 COPYSLOT(tp_descr_get);
3139 COPYSLOT(tp_descr_set);
3140 COPYSLOT(tp_dictoffset);
3141 COPYSLOT(tp_init);
3142 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003143 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003144 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3145 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3146 /* They agree about gc. */
3147 COPYSLOT(tp_free);
3148 }
3149 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3150 type->tp_free == NULL &&
3151 base->tp_free == _PyObject_Del) {
3152 /* A bit of magic to plug in the correct default
3153 * tp_free function when a derived class adds gc,
3154 * didn't define tp_free, and the base uses the
3155 * default non-gc tp_free.
3156 */
3157 type->tp_free = PyObject_GC_Del;
3158 }
3159 /* else they didn't agree about gc, and there isn't something
3160 * obvious to be done -- the type is on its own.
3161 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003162 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003163}
3164
Jeremy Hylton938ace62002-07-17 16:30:39 +00003165static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003166
Tim Peters6d6c1a32001-08-02 04:15:00 +00003167int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003168PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003169{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003170 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003171 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003172 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003173
Guido van Rossumcab05802002-06-10 15:29:03 +00003174 if (type->tp_flags & Py_TPFLAGS_READY) {
3175 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003176 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003177 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003178 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003179
3180 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003181
Tim Peters36eb4df2003-03-23 03:33:13 +00003182#ifdef Py_TRACE_REFS
3183 /* PyType_Ready is the closest thing we have to a choke point
3184 * for type objects, so is the best place I can think of to try
3185 * to get type objects into the doubly-linked list of all objects.
3186 * Still, not all type objects go thru PyType_Ready.
3187 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003188 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003189#endif
3190
Tim Peters6d6c1a32001-08-02 04:15:00 +00003191 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3192 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003193 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003194 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003195 Py_INCREF(base);
3196 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003197
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003198 /* Now the only way base can still be NULL is if type is
3199 * &PyBaseObject_Type.
3200 */
3201
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003202 /* Initialize the base class */
3203 if (base && base->tp_dict == NULL) {
3204 if (PyType_Ready(base) < 0)
3205 goto error;
3206 }
3207
Guido van Rossum0986d822002-04-08 01:38:42 +00003208 /* Initialize ob_type if NULL. This means extensions that want to be
3209 compilable separately on Windows can call PyType_Ready() instead of
3210 initializing the ob_type field of their type objects. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003211 /* The test for base != NULL is really unnecessary, since base is only
3212 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3213 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3214 know that. */
3215 if (type->ob_type == NULL && base != NULL)
Guido van Rossum0986d822002-04-08 01:38:42 +00003216 type->ob_type = base->ob_type;
3217
Tim Peters6d6c1a32001-08-02 04:15:00 +00003218 /* Initialize tp_bases */
3219 bases = type->tp_bases;
3220 if (bases == NULL) {
3221 if (base == NULL)
3222 bases = PyTuple_New(0);
3223 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003224 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003225 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003226 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003227 type->tp_bases = bases;
3228 }
3229
Guido van Rossum687ae002001-10-15 22:03:32 +00003230 /* Initialize tp_dict */
3231 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003232 if (dict == NULL) {
3233 dict = PyDict_New();
3234 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003235 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003236 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003237 }
3238
Guido van Rossum687ae002001-10-15 22:03:32 +00003239 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003240 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003241 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003242 if (type->tp_methods != NULL) {
3243 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003244 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003245 }
3246 if (type->tp_members != NULL) {
3247 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003248 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003249 }
3250 if (type->tp_getset != NULL) {
3251 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003252 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003253 }
3254
Tim Peters6d6c1a32001-08-02 04:15:00 +00003255 /* Calculate method resolution order */
3256 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003257 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003258 }
3259
Guido van Rossum13d52f02001-08-10 21:24:08 +00003260 /* Inherit special flags from dominant base */
3261 if (type->tp_base != NULL)
3262 inherit_special(type, type->tp_base);
3263
Tim Peters6d6c1a32001-08-02 04:15:00 +00003264 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003265 bases = type->tp_mro;
3266 assert(bases != NULL);
3267 assert(PyTuple_Check(bases));
3268 n = PyTuple_GET_SIZE(bases);
3269 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003270 PyObject *b = PyTuple_GET_ITEM(bases, i);
3271 if (PyType_Check(b))
3272 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003273 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003274
Tim Peters3cfe7542003-05-21 21:29:48 +00003275 /* Sanity check for tp_free. */
3276 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3277 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3278 /* This base class needs to call tp_free, but doesn't have
3279 * one, or its tp_free is for non-gc'ed objects.
3280 */
3281 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3282 "gc and is a base type but has inappropriate "
3283 "tp_free slot",
3284 type->tp_name);
3285 goto error;
3286 }
3287
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003288 /* if the type dictionary doesn't contain a __doc__, set it from
3289 the tp_doc slot.
3290 */
3291 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3292 if (type->tp_doc != NULL) {
3293 PyObject *doc = PyString_FromString(type->tp_doc);
Neal Norwitze1fdb322006-07-21 05:32:28 +00003294 if (doc == NULL)
3295 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003296 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3297 Py_DECREF(doc);
3298 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003299 PyDict_SetItemString(type->tp_dict,
3300 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003301 }
3302 }
3303
Guido van Rossum13d52f02001-08-10 21:24:08 +00003304 /* Some more special stuff */
3305 base = type->tp_base;
3306 if (base != NULL) {
3307 if (type->tp_as_number == NULL)
3308 type->tp_as_number = base->tp_as_number;
3309 if (type->tp_as_sequence == NULL)
3310 type->tp_as_sequence = base->tp_as_sequence;
3311 if (type->tp_as_mapping == NULL)
3312 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003313 if (type->tp_as_buffer == NULL)
3314 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003315 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003316
Guido van Rossum1c450732001-10-08 15:18:27 +00003317 /* Link into each base class's list of subclasses */
3318 bases = type->tp_bases;
3319 n = PyTuple_GET_SIZE(bases);
3320 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003321 PyObject *b = PyTuple_GET_ITEM(bases, i);
3322 if (PyType_Check(b) &&
3323 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003324 goto error;
3325 }
3326
Guido van Rossum13d52f02001-08-10 21:24:08 +00003327 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003328 assert(type->tp_dict != NULL);
3329 type->tp_flags =
3330 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003331 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003332
3333 error:
3334 type->tp_flags &= ~Py_TPFLAGS_READYING;
3335 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003336}
3337
Guido van Rossum1c450732001-10-08 15:18:27 +00003338static int
3339add_subclass(PyTypeObject *base, PyTypeObject *type)
3340{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003341 Py_ssize_t i;
3342 int result;
Anthony Baxtera6286212006-04-11 07:42:36 +00003343 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003344
3345 list = base->tp_subclasses;
3346 if (list == NULL) {
3347 base->tp_subclasses = list = PyList_New(0);
3348 if (list == NULL)
3349 return -1;
3350 }
3351 assert(PyList_Check(list));
Anthony Baxtera6286212006-04-11 07:42:36 +00003352 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003353 i = PyList_GET_SIZE(list);
3354 while (--i >= 0) {
3355 ref = PyList_GET_ITEM(list, i);
3356 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003357 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Anthony Baxtera6286212006-04-11 07:42:36 +00003358 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003359 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003360 result = PyList_Append(list, newobj);
3361 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003362 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003363}
3364
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003365static void
3366remove_subclass(PyTypeObject *base, PyTypeObject *type)
3367{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003368 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003369 PyObject *list, *ref;
3370
3371 list = base->tp_subclasses;
3372 if (list == NULL) {
3373 return;
3374 }
3375 assert(PyList_Check(list));
3376 i = PyList_GET_SIZE(list);
3377 while (--i >= 0) {
3378 ref = PyList_GET_ITEM(list, i);
3379 assert(PyWeakref_CheckRef(ref));
3380 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3381 /* this can't fail, right? */
3382 PySequence_DelItem(list, i);
3383 return;
3384 }
3385 }
3386}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003387
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003388static int
3389check_num_args(PyObject *ob, int n)
3390{
3391 if (!PyTuple_CheckExact(ob)) {
3392 PyErr_SetString(PyExc_SystemError,
3393 "PyArg_UnpackTuple() argument list is not a tuple");
3394 return 0;
3395 }
3396 if (n == PyTuple_GET_SIZE(ob))
3397 return 1;
3398 PyErr_Format(
3399 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003400 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003401 return 0;
3402}
3403
Tim Peters6d6c1a32001-08-02 04:15:00 +00003404/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3405
3406/* There's a wrapper *function* for each distinct function typedef used
3407 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3408 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3409 Most tables have only one entry; the tables for binary operators have two
3410 entries, one regular and one with reversed arguments. */
3411
3412static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003413wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003414{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003415 lenfunc func = (lenfunc)wrapped;
3416 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003417
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003418 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003419 return NULL;
3420 res = (*func)(self);
3421 if (res == -1 && PyErr_Occurred())
3422 return NULL;
3423 return PyInt_FromLong((long)res);
3424}
3425
Tim Peters6d6c1a32001-08-02 04:15:00 +00003426static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003427wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3428{
3429 inquiry func = (inquiry)wrapped;
3430 int res;
3431
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003432 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003433 return NULL;
3434 res = (*func)(self);
3435 if (res == -1 && PyErr_Occurred())
3436 return NULL;
3437 return PyBool_FromLong((long)res);
3438}
3439
3440static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003441wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3442{
3443 binaryfunc func = (binaryfunc)wrapped;
3444 PyObject *other;
3445
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003446 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003447 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003448 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003449 return (*func)(self, other);
3450}
3451
3452static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003453wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3454{
3455 binaryfunc func = (binaryfunc)wrapped;
3456 PyObject *other;
3457
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003458 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003459 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003460 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003461 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003462 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003463 Py_INCREF(Py_NotImplemented);
3464 return Py_NotImplemented;
3465 }
3466 return (*func)(self, other);
3467}
3468
3469static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003470wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3471{
3472 binaryfunc func = (binaryfunc)wrapped;
3473 PyObject *other;
3474
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003475 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003476 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003477 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003478 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003479 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003480 Py_INCREF(Py_NotImplemented);
3481 return Py_NotImplemented;
3482 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003483 return (*func)(other, self);
3484}
3485
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003486static PyObject *
3487wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3488{
3489 coercion func = (coercion)wrapped;
3490 PyObject *other, *res;
3491 int ok;
3492
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003493 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003494 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003495 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003496 ok = func(&self, &other);
3497 if (ok < 0)
3498 return NULL;
3499 if (ok > 0) {
3500 Py_INCREF(Py_NotImplemented);
3501 return Py_NotImplemented;
3502 }
3503 res = PyTuple_New(2);
3504 if (res == NULL) {
3505 Py_DECREF(self);
3506 Py_DECREF(other);
3507 return NULL;
3508 }
3509 PyTuple_SET_ITEM(res, 0, self);
3510 PyTuple_SET_ITEM(res, 1, other);
3511 return res;
3512}
3513
Tim Peters6d6c1a32001-08-02 04:15:00 +00003514static PyObject *
3515wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3516{
3517 ternaryfunc func = (ternaryfunc)wrapped;
3518 PyObject *other;
3519 PyObject *third = Py_None;
3520
3521 /* Note: This wrapper only works for __pow__() */
3522
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003523 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003524 return NULL;
3525 return (*func)(self, other, third);
3526}
3527
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003528static PyObject *
3529wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3530{
3531 ternaryfunc func = (ternaryfunc)wrapped;
3532 PyObject *other;
3533 PyObject *third = Py_None;
3534
3535 /* Note: This wrapper only works for __pow__() */
3536
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003537 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003538 return NULL;
3539 return (*func)(other, self, third);
3540}
3541
Tim Peters6d6c1a32001-08-02 04:15:00 +00003542static PyObject *
3543wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3544{
3545 unaryfunc func = (unaryfunc)wrapped;
3546
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003547 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003548 return NULL;
3549 return (*func)(self);
3550}
3551
Tim Peters6d6c1a32001-08-02 04:15:00 +00003552static PyObject *
Armin Rigo314861c2006-03-30 14:04:02 +00003553wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003554{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003555 ssizeargfunc func = (ssizeargfunc)wrapped;
Armin Rigo314861c2006-03-30 14:04:02 +00003556 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003557 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003558
Armin Rigo314861c2006-03-30 14:04:02 +00003559 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
3560 return NULL;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00003561 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Armin Rigo314861c2006-03-30 14:04:02 +00003562 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003563 return NULL;
3564 return (*func)(self, i);
3565}
3566
Martin v. Löwis18e16552006-02-15 17:27:45 +00003567static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00003568getindex(PyObject *self, PyObject *arg)
3569{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003570 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003571
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00003572 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003573 if (i == -1 && PyErr_Occurred())
3574 return -1;
3575 if (i < 0) {
3576 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3577 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003578 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003579 if (n < 0)
3580 return -1;
3581 i += n;
3582 }
3583 }
3584 return i;
3585}
3586
3587static PyObject *
3588wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3589{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003590 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003591 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003592 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003593
Guido van Rossumf4593e02001-10-03 12:09:30 +00003594 if (PyTuple_GET_SIZE(args) == 1) {
3595 arg = PyTuple_GET_ITEM(args, 0);
3596 i = getindex(self, arg);
3597 if (i == -1 && PyErr_Occurred())
3598 return NULL;
3599 return (*func)(self, i);
3600 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003601 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003602 assert(PyErr_Occurred());
3603 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003604}
3605
Tim Peters6d6c1a32001-08-02 04:15:00 +00003606static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003607wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003608{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003609 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
3610 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003611
Martin v. Löwis18e16552006-02-15 17:27:45 +00003612 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003613 return NULL;
3614 return (*func)(self, i, j);
3615}
3616
Tim Peters6d6c1a32001-08-02 04:15:00 +00003617static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003618wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003619{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003620 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3621 Py_ssize_t i;
3622 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003623 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003624
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003625 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003626 return NULL;
3627 i = getindex(self, arg);
3628 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003629 return NULL;
3630 res = (*func)(self, i, value);
3631 if (res == -1 && PyErr_Occurred())
3632 return NULL;
3633 Py_INCREF(Py_None);
3634 return Py_None;
3635}
3636
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003637static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003638wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003639{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003640 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3641 Py_ssize_t i;
3642 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003643 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003644
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003645 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003646 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003647 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003648 i = getindex(self, arg);
3649 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003650 return NULL;
3651 res = (*func)(self, i, NULL);
3652 if (res == -1 && PyErr_Occurred())
3653 return NULL;
3654 Py_INCREF(Py_None);
3655 return Py_None;
3656}
3657
Tim Peters6d6c1a32001-08-02 04:15:00 +00003658static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003659wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003660{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003661 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3662 Py_ssize_t i, j;
3663 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003664 PyObject *value;
3665
Martin v. Löwis18e16552006-02-15 17:27:45 +00003666 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003667 return NULL;
3668 res = (*func)(self, i, j, value);
3669 if (res == -1 && PyErr_Occurred())
3670 return NULL;
3671 Py_INCREF(Py_None);
3672 return Py_None;
3673}
3674
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003675static PyObject *
3676wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3677{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003678 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3679 Py_ssize_t i, j;
3680 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003681
Martin v. Löwis18e16552006-02-15 17:27:45 +00003682 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003683 return NULL;
3684 res = (*func)(self, i, j, NULL);
3685 if (res == -1 && PyErr_Occurred())
3686 return NULL;
3687 Py_INCREF(Py_None);
3688 return Py_None;
3689}
3690
Tim Peters6d6c1a32001-08-02 04:15:00 +00003691/* XXX objobjproc is a misnomer; should be objargpred */
3692static PyObject *
3693wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3694{
3695 objobjproc func = (objobjproc)wrapped;
3696 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003697 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003698
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003699 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003700 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003701 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003702 res = (*func)(self, value);
3703 if (res == -1 && PyErr_Occurred())
3704 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003705 else
3706 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003707}
3708
Tim Peters6d6c1a32001-08-02 04:15:00 +00003709static PyObject *
3710wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3711{
3712 objobjargproc func = (objobjargproc)wrapped;
3713 int res;
3714 PyObject *key, *value;
3715
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003716 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003717 return NULL;
3718 res = (*func)(self, key, value);
3719 if (res == -1 && PyErr_Occurred())
3720 return NULL;
3721 Py_INCREF(Py_None);
3722 return Py_None;
3723}
3724
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003725static PyObject *
3726wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3727{
3728 objobjargproc func = (objobjargproc)wrapped;
3729 int res;
3730 PyObject *key;
3731
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003732 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003733 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003734 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003735 res = (*func)(self, key, NULL);
3736 if (res == -1 && PyErr_Occurred())
3737 return NULL;
3738 Py_INCREF(Py_None);
3739 return Py_None;
3740}
3741
Tim Peters6d6c1a32001-08-02 04:15:00 +00003742static PyObject *
3743wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3744{
3745 cmpfunc func = (cmpfunc)wrapped;
3746 int res;
3747 PyObject *other;
3748
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003749 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003750 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003751 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003752 if (other->ob_type->tp_compare != func &&
3753 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003754 PyErr_Format(
3755 PyExc_TypeError,
3756 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3757 self->ob_type->tp_name,
3758 self->ob_type->tp_name,
3759 other->ob_type->tp_name);
3760 return NULL;
3761 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003762 res = (*func)(self, other);
3763 if (PyErr_Occurred())
3764 return NULL;
3765 return PyInt_FromLong((long)res);
3766}
3767
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003768/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003769 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003770static int
3771hackcheck(PyObject *self, setattrofunc func, char *what)
3772{
3773 PyTypeObject *type = self->ob_type;
3774 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3775 type = type->tp_base;
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003776 /* If type is NULL now, this is a really weird type.
Andrew M. Kuchlingb3f37552006-10-09 18:05:19 +00003777 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003778 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003779 PyErr_Format(PyExc_TypeError,
3780 "can't apply this %s to %s object",
3781 what,
3782 type->tp_name);
3783 return 0;
3784 }
3785 return 1;
3786}
3787
Tim Peters6d6c1a32001-08-02 04:15:00 +00003788static PyObject *
3789wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3790{
3791 setattrofunc func = (setattrofunc)wrapped;
3792 int res;
3793 PyObject *name, *value;
3794
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003795 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003796 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003797 if (!hackcheck(self, func, "__setattr__"))
3798 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003799 res = (*func)(self, name, value);
3800 if (res < 0)
3801 return NULL;
3802 Py_INCREF(Py_None);
3803 return Py_None;
3804}
3805
3806static PyObject *
3807wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3808{
3809 setattrofunc func = (setattrofunc)wrapped;
3810 int res;
3811 PyObject *name;
3812
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003813 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003814 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003815 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003816 if (!hackcheck(self, func, "__delattr__"))
3817 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003818 res = (*func)(self, name, NULL);
3819 if (res < 0)
3820 return NULL;
3821 Py_INCREF(Py_None);
3822 return Py_None;
3823}
3824
Tim Peters6d6c1a32001-08-02 04:15:00 +00003825static PyObject *
3826wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3827{
3828 hashfunc func = (hashfunc)wrapped;
3829 long res;
3830
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003831 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003832 return NULL;
3833 res = (*func)(self);
3834 if (res == -1 && PyErr_Occurred())
3835 return NULL;
3836 return PyInt_FromLong(res);
3837}
3838
Tim Peters6d6c1a32001-08-02 04:15:00 +00003839static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003840wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003841{
3842 ternaryfunc func = (ternaryfunc)wrapped;
3843
Guido van Rossumc8e56452001-10-22 00:43:43 +00003844 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003845}
3846
Tim Peters6d6c1a32001-08-02 04:15:00 +00003847static PyObject *
3848wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3849{
3850 richcmpfunc func = (richcmpfunc)wrapped;
3851 PyObject *other;
3852
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003853 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003854 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003855 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003856 return (*func)(self, other, op);
3857}
3858
3859#undef RICHCMP_WRAPPER
3860#define RICHCMP_WRAPPER(NAME, OP) \
3861static PyObject * \
3862richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3863{ \
3864 return wrap_richcmpfunc(self, args, wrapped, OP); \
3865}
3866
Jack Jansen8e938b42001-08-08 15:29:49 +00003867RICHCMP_WRAPPER(lt, Py_LT)
3868RICHCMP_WRAPPER(le, Py_LE)
3869RICHCMP_WRAPPER(eq, Py_EQ)
3870RICHCMP_WRAPPER(ne, Py_NE)
3871RICHCMP_WRAPPER(gt, Py_GT)
3872RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003873
Tim Peters6d6c1a32001-08-02 04:15:00 +00003874static PyObject *
3875wrap_next(PyObject *self, PyObject *args, void *wrapped)
3876{
3877 unaryfunc func = (unaryfunc)wrapped;
3878 PyObject *res;
3879
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003880 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003881 return NULL;
3882 res = (*func)(self);
3883 if (res == NULL && !PyErr_Occurred())
3884 PyErr_SetNone(PyExc_StopIteration);
3885 return res;
3886}
3887
Tim Peters6d6c1a32001-08-02 04:15:00 +00003888static PyObject *
3889wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3890{
3891 descrgetfunc func = (descrgetfunc)wrapped;
3892 PyObject *obj;
3893 PyObject *type = NULL;
3894
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003895 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003896 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003897 if (obj == Py_None)
3898 obj = NULL;
3899 if (type == Py_None)
3900 type = NULL;
3901 if (type == NULL &&obj == NULL) {
3902 PyErr_SetString(PyExc_TypeError,
3903 "__get__(None, None) is invalid");
3904 return NULL;
3905 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003906 return (*func)(self, obj, type);
3907}
3908
Tim Peters6d6c1a32001-08-02 04:15:00 +00003909static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003910wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003911{
3912 descrsetfunc func = (descrsetfunc)wrapped;
3913 PyObject *obj, *value;
3914 int ret;
3915
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003916 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003917 return NULL;
3918 ret = (*func)(self, obj, value);
3919 if (ret < 0)
3920 return NULL;
3921 Py_INCREF(Py_None);
3922 return Py_None;
3923}
Guido van Rossum22b13872002-08-06 21:41:44 +00003924
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003925static PyObject *
3926wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3927{
3928 descrsetfunc func = (descrsetfunc)wrapped;
3929 PyObject *obj;
3930 int ret;
3931
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003932 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003933 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003934 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003935 ret = (*func)(self, obj, NULL);
3936 if (ret < 0)
3937 return NULL;
3938 Py_INCREF(Py_None);
3939 return Py_None;
3940}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003941
Tim Peters6d6c1a32001-08-02 04:15:00 +00003942static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003943wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003944{
3945 initproc func = (initproc)wrapped;
3946
Guido van Rossumc8e56452001-10-22 00:43:43 +00003947 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003948 return NULL;
3949 Py_INCREF(Py_None);
3950 return Py_None;
3951}
3952
Tim Peters6d6c1a32001-08-02 04:15:00 +00003953static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003954tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003955{
Barry Warsaw60f01882001-08-22 19:24:42 +00003956 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003957 PyObject *arg0, *res;
3958
3959 if (self == NULL || !PyType_Check(self))
3960 Py_FatalError("__new__() called with non-type 'self'");
3961 type = (PyTypeObject *)self;
3962 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003963 PyErr_Format(PyExc_TypeError,
3964 "%s.__new__(): not enough arguments",
3965 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003966 return NULL;
3967 }
3968 arg0 = PyTuple_GET_ITEM(args, 0);
3969 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003970 PyErr_Format(PyExc_TypeError,
3971 "%s.__new__(X): X is not a type object (%s)",
3972 type->tp_name,
3973 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003974 return NULL;
3975 }
3976 subtype = (PyTypeObject *)arg0;
3977 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003978 PyErr_Format(PyExc_TypeError,
3979 "%s.__new__(%s): %s is not a subtype of %s",
3980 type->tp_name,
3981 subtype->tp_name,
3982 subtype->tp_name,
3983 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003984 return NULL;
3985 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003986
3987 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003988 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003989 most derived base that's not a heap type is this type. */
3990 staticbase = subtype;
3991 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3992 staticbase = staticbase->tp_base;
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003993 /* If staticbase is NULL now, it is a really weird type.
Andrew M. Kuchlingb3f37552006-10-09 18:05:19 +00003994 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003995 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003996 PyErr_Format(PyExc_TypeError,
3997 "%s.__new__(%s) is not safe, use %s.__new__()",
3998 type->tp_name,
3999 subtype->tp_name,
4000 staticbase == NULL ? "?" : staticbase->tp_name);
4001 return NULL;
4002 }
4003
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004004 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4005 if (args == NULL)
4006 return NULL;
4007 res = type->tp_new(subtype, args, kwds);
4008 Py_DECREF(args);
4009 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004010}
4011
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004012static struct PyMethodDef tp_new_methoddef[] = {
4013 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004014 PyDoc_STR("T.__new__(S, ...) -> "
4015 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004016 {0}
4017};
4018
4019static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004020add_tp_new_wrapper(PyTypeObject *type)
4021{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004022 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004023
Guido van Rossum687ae002001-10-15 22:03:32 +00004024 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004025 return 0;
4026 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004027 if (func == NULL)
4028 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004029 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004030 Py_DECREF(func);
4031 return -1;
4032 }
4033 Py_DECREF(func);
4034 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004035}
4036
Guido van Rossumf040ede2001-08-07 16:40:56 +00004037/* Slot wrappers that call the corresponding __foo__ slot. See comments
4038 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004039
Guido van Rossumdc91b992001-08-08 22:26:22 +00004040#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004041static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004042FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004043{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004044 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004045 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004046}
4047
Guido van Rossumdc91b992001-08-08 22:26:22 +00004048#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004049static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004050FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004051{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004052 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004053 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004054}
4055
Guido van Rossumcd118802003-01-06 22:57:47 +00004056/* Boolean helper for SLOT1BINFULL().
4057 right.__class__ is a nontrivial subclass of left.__class__. */
4058static int
4059method_is_overloaded(PyObject *left, PyObject *right, char *name)
4060{
4061 PyObject *a, *b;
4062 int ok;
4063
4064 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
4065 if (b == NULL) {
4066 PyErr_Clear();
4067 /* If right doesn't have it, it's not overloaded */
4068 return 0;
4069 }
4070
4071 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
4072 if (a == NULL) {
4073 PyErr_Clear();
4074 Py_DECREF(b);
4075 /* If right has it but left doesn't, it's overloaded */
4076 return 1;
4077 }
4078
4079 ok = PyObject_RichCompareBool(a, b, Py_NE);
4080 Py_DECREF(a);
4081 Py_DECREF(b);
4082 if (ok < 0) {
4083 PyErr_Clear();
4084 return 0;
4085 }
4086
4087 return ok;
4088}
4089
Guido van Rossumdc91b992001-08-08 22:26:22 +00004090
4091#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004092static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004093FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004094{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004095 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004096 int do_other = self->ob_type != other->ob_type && \
4097 other->ob_type->tp_as_number != NULL && \
4098 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004099 if (self->ob_type->tp_as_number != NULL && \
4100 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
4101 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004102 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004103 PyType_IsSubtype(other->ob_type, self->ob_type) && \
4104 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004105 r = call_maybe( \
4106 other, ROPSTR, &rcache_str, "(O)", self); \
4107 if (r != Py_NotImplemented) \
4108 return r; \
4109 Py_DECREF(r); \
4110 do_other = 0; \
4111 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004112 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004113 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004114 if (r != Py_NotImplemented || \
4115 other->ob_type == self->ob_type) \
4116 return r; \
4117 Py_DECREF(r); \
4118 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004119 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004120 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004121 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004122 } \
4123 Py_INCREF(Py_NotImplemented); \
4124 return Py_NotImplemented; \
4125}
4126
4127#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4128 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4129
4130#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4131static PyObject * \
4132FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4133{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004134 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004135 return call_method(self, OPSTR, &cache_str, \
4136 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004137}
4138
Martin v. Löwis18e16552006-02-15 17:27:45 +00004139static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004140slot_sq_length(PyObject *self)
4141{
Guido van Rossum2730b132001-08-28 18:22:14 +00004142 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004143 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004144 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004145
4146 if (res == NULL)
4147 return -1;
Neal Norwitz1872b1c2006-08-12 18:44:06 +00004148 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004149 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004150 if (len < 0) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00004151 if (!PyErr_Occurred())
4152 PyErr_SetString(PyExc_ValueError,
4153 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004154 return -1;
4155 }
Guido van Rossum26111622001-10-01 16:42:49 +00004156 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004157}
4158
Guido van Rossumf4593e02001-10-03 12:09:30 +00004159/* Super-optimized version of slot_sq_item.
4160 Other slots could do the same... */
4161static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004162slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004163{
4164 static PyObject *getitem_str;
4165 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4166 descrgetfunc f;
4167
4168 if (getitem_str == NULL) {
4169 getitem_str = PyString_InternFromString("__getitem__");
4170 if (getitem_str == NULL)
4171 return NULL;
4172 }
4173 func = _PyType_Lookup(self->ob_type, getitem_str);
4174 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004175 if ((f = func->ob_type->tp_descr_get) == NULL)
4176 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004177 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004178 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004179 if (func == NULL) {
4180 return NULL;
4181 }
4182 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004183 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004184 if (ival != NULL) {
4185 args = PyTuple_New(1);
4186 if (args != NULL) {
4187 PyTuple_SET_ITEM(args, 0, ival);
4188 retval = PyObject_Call(func, args, NULL);
4189 Py_XDECREF(args);
4190 Py_XDECREF(func);
4191 return retval;
4192 }
4193 }
4194 }
4195 else {
4196 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4197 }
4198 Py_XDECREF(args);
4199 Py_XDECREF(ival);
4200 Py_XDECREF(func);
4201 return NULL;
4202}
4203
Martin v. Löwis18e16552006-02-15 17:27:45 +00004204SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004205
4206static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004207slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004208{
4209 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004210 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004211
4212 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004213 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004214 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004215 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004216 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004217 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004218 if (res == NULL)
4219 return -1;
4220 Py_DECREF(res);
4221 return 0;
4222}
4223
4224static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004225slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004226{
4227 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004228 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004229
4230 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004231 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004232 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004233 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004234 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004235 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004236 if (res == NULL)
4237 return -1;
4238 Py_DECREF(res);
4239 return 0;
4240}
4241
4242static int
4243slot_sq_contains(PyObject *self, PyObject *value)
4244{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004245 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004246 int result = -1;
4247
Guido van Rossum60718732001-08-28 17:47:51 +00004248 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004249
Guido van Rossum55f20992001-10-01 17:18:22 +00004250 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004251 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004252 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004253 if (args == NULL)
4254 res = NULL;
4255 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004256 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004257 Py_DECREF(args);
4258 }
4259 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004260 if (res != NULL) {
4261 result = PyObject_IsTrue(res);
4262 Py_DECREF(res);
4263 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004264 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004265 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004266 /* Possible results: -1 and 1 */
4267 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004268 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004269 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004270 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004271}
4272
Tim Peters6d6c1a32001-08-02 04:15:00 +00004273#define slot_mp_length slot_sq_length
4274
Guido van Rossumdc91b992001-08-08 22:26:22 +00004275SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004276
4277static int
4278slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4279{
4280 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004281 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004282
4283 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004284 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004285 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004286 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004287 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004288 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004289 if (res == NULL)
4290 return -1;
4291 Py_DECREF(res);
4292 return 0;
4293}
4294
Guido van Rossumdc91b992001-08-08 22:26:22 +00004295SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4296SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4297SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4298SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4299SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4300SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4301
Jeremy Hylton938ace62002-07-17 16:30:39 +00004302static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004303
4304SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4305 nb_power, "__pow__", "__rpow__")
4306
4307static PyObject *
4308slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4309{
Guido van Rossum2730b132001-08-28 18:22:14 +00004310 static PyObject *pow_str;
4311
Guido van Rossumdc91b992001-08-08 22:26:22 +00004312 if (modulus == Py_None)
4313 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004314 /* Three-arg power doesn't use __rpow__. But ternary_op
4315 can call this when the second argument's type uses
4316 slot_nb_power, so check before calling self.__pow__. */
4317 if (self->ob_type->tp_as_number != NULL &&
4318 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4319 return call_method(self, "__pow__", &pow_str,
4320 "(OO)", other, modulus);
4321 }
4322 Py_INCREF(Py_NotImplemented);
4323 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004324}
4325
4326SLOT0(slot_nb_negative, "__neg__")
4327SLOT0(slot_nb_positive, "__pos__")
4328SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004329
4330static int
4331slot_nb_nonzero(PyObject *self)
4332{
Tim Petersea7f75d2002-12-07 21:39:16 +00004333 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004334 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004335 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004336
Guido van Rossum55f20992001-10-01 17:18:22 +00004337 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004338 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004339 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004340 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004341 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004342 if (func == NULL)
4343 return PyErr_Occurred() ? -1 : 1;
4344 }
4345 args = PyTuple_New(0);
4346 if (args != NULL) {
4347 PyObject *temp = PyObject_Call(func, args, NULL);
4348 Py_DECREF(args);
4349 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004350 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004351 result = PyObject_IsTrue(temp);
4352 else {
4353 PyErr_Format(PyExc_TypeError,
4354 "__nonzero__ should return "
4355 "bool or int, returned %s",
4356 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004357 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004358 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004359 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004360 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004361 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004362 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004363 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004364}
4365
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004366
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004367static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004368slot_nb_index(PyObject *self)
4369{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004370 static PyObject *index_str;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004371 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004372}
4373
4374
Guido van Rossumdc91b992001-08-08 22:26:22 +00004375SLOT0(slot_nb_invert, "__invert__")
4376SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4377SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4378SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4379SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4380SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004381
4382static int
4383slot_nb_coerce(PyObject **a, PyObject **b)
4384{
4385 static PyObject *coerce_str;
4386 PyObject *self = *a, *other = *b;
4387
4388 if (self->ob_type->tp_as_number != NULL &&
4389 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4390 PyObject *r;
4391 r = call_maybe(
4392 self, "__coerce__", &coerce_str, "(O)", other);
4393 if (r == NULL)
4394 return -1;
4395 if (r == Py_NotImplemented) {
4396 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004397 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004398 else {
4399 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4400 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004401 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004402 Py_DECREF(r);
4403 return -1;
4404 }
4405 *a = PyTuple_GET_ITEM(r, 0);
4406 Py_INCREF(*a);
4407 *b = PyTuple_GET_ITEM(r, 1);
4408 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004409 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004410 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004411 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004412 }
4413 if (other->ob_type->tp_as_number != NULL &&
4414 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4415 PyObject *r;
4416 r = call_maybe(
4417 other, "__coerce__", &coerce_str, "(O)", self);
4418 if (r == NULL)
4419 return -1;
4420 if (r == Py_NotImplemented) {
4421 Py_DECREF(r);
4422 return 1;
4423 }
4424 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4425 PyErr_SetString(PyExc_TypeError,
4426 "__coerce__ didn't return a 2-tuple");
4427 Py_DECREF(r);
4428 return -1;
4429 }
4430 *a = PyTuple_GET_ITEM(r, 1);
4431 Py_INCREF(*a);
4432 *b = PyTuple_GET_ITEM(r, 0);
4433 Py_INCREF(*b);
4434 Py_DECREF(r);
4435 return 0;
4436 }
4437 return 1;
4438}
4439
Guido van Rossumdc91b992001-08-08 22:26:22 +00004440SLOT0(slot_nb_int, "__int__")
4441SLOT0(slot_nb_long, "__long__")
4442SLOT0(slot_nb_float, "__float__")
4443SLOT0(slot_nb_oct, "__oct__")
4444SLOT0(slot_nb_hex, "__hex__")
4445SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4446SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4447SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4448SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4449SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Martin v. Löwisfd963262007-02-09 12:19:32 +00004450/* Can't use SLOT1 here, because nb_inplace_power is ternary */
4451static PyObject *
4452slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4453{
4454 static PyObject *cache_str;
4455 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
4456}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004457SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4458SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4459SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4460SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4461SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4462SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4463 "__floordiv__", "__rfloordiv__")
4464SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4465SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4466SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004467
4468static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004469half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004470{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004471 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004472 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004473 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004474
Guido van Rossum60718732001-08-28 17:47:51 +00004475 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004476 if (func == NULL) {
4477 PyErr_Clear();
4478 }
4479 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004480 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004481 if (args == NULL)
4482 res = NULL;
4483 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004484 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004485 Py_DECREF(args);
4486 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004487 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004488 if (res != Py_NotImplemented) {
4489 if (res == NULL)
4490 return -2;
4491 c = PyInt_AsLong(res);
4492 Py_DECREF(res);
4493 if (c == -1 && PyErr_Occurred())
4494 return -2;
4495 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4496 }
4497 Py_DECREF(res);
4498 }
4499 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004500}
4501
Guido van Rossumab3b0342001-09-18 20:38:53 +00004502/* This slot is published for the benefit of try_3way_compare in object.c */
4503int
4504_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004505{
4506 int c;
4507
Guido van Rossumab3b0342001-09-18 20:38:53 +00004508 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004509 c = half_compare(self, other);
4510 if (c <= 1)
4511 return c;
4512 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004513 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004514 c = half_compare(other, self);
4515 if (c < -1)
4516 return -2;
4517 if (c <= 1)
4518 return -c;
4519 }
4520 return (void *)self < (void *)other ? -1 :
4521 (void *)self > (void *)other ? 1 : 0;
4522}
4523
4524static PyObject *
4525slot_tp_repr(PyObject *self)
4526{
4527 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004528 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004529
Guido van Rossum60718732001-08-28 17:47:51 +00004530 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004531 if (func != NULL) {
4532 res = PyEval_CallObject(func, NULL);
4533 Py_DECREF(func);
4534 return res;
4535 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004536 PyErr_Clear();
4537 return PyString_FromFormat("<%s object at %p>",
4538 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004539}
4540
4541static PyObject *
4542slot_tp_str(PyObject *self)
4543{
4544 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004545 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004546
Guido van Rossum60718732001-08-28 17:47:51 +00004547 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004548 if (func != NULL) {
4549 res = PyEval_CallObject(func, NULL);
4550 Py_DECREF(func);
4551 return res;
4552 }
4553 else {
4554 PyErr_Clear();
4555 return slot_tp_repr(self);
4556 }
4557}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004558
4559static long
4560slot_tp_hash(PyObject *self)
4561{
Tim Peters61ce0a92002-12-06 23:38:02 +00004562 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004563 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004564 long h;
4565
Guido van Rossum60718732001-08-28 17:47:51 +00004566 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004567
4568 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004569 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004570 Py_DECREF(func);
4571 if (res == NULL)
4572 return -1;
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00004573 if (PyLong_Check(res))
Armin Rigo51fc8c42006-08-09 14:55:26 +00004574 h = PyLong_Type.tp_hash(res);
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00004575 else
4576 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004577 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004578 }
4579 else {
4580 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004581 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004582 if (func == NULL) {
4583 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004584 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004585 }
4586 if (func != NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00004587 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
4588 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004589 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004590 return -1;
4591 }
4592 PyErr_Clear();
4593 h = _Py_HashPointer((void *)self);
4594 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004595 if (h == -1 && !PyErr_Occurred())
4596 h = -2;
4597 return h;
4598}
4599
4600static PyObject *
4601slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4602{
Guido van Rossum60718732001-08-28 17:47:51 +00004603 static PyObject *call_str;
4604 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004605 PyObject *res;
4606
4607 if (meth == NULL)
4608 return NULL;
Armin Rigo53c1692f2006-06-21 21:58:50 +00004609
4610 /* PyObject_Call() will end up calling slot_tp_call() again if
4611 the object returned for __call__ has __call__ itself defined
4612 upon it. This can be an infinite recursion if you set
4613 __call__ in a class to an instance of it. */
Neal Norwitzb1149842006-06-23 03:32:44 +00004614 if (Py_EnterRecursiveCall(" in __call__")) {
4615 Py_DECREF(meth);
Armin Rigo53c1692f2006-06-21 21:58:50 +00004616 return NULL;
Neal Norwitzb1149842006-06-23 03:32:44 +00004617 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004618 res = PyObject_Call(meth, args, kwds);
Armin Rigo53c1692f2006-06-21 21:58:50 +00004619 Py_LeaveRecursiveCall();
4620
Tim Peters6d6c1a32001-08-02 04:15:00 +00004621 Py_DECREF(meth);
4622 return res;
4623}
4624
Guido van Rossum14a6f832001-10-17 13:59:09 +00004625/* There are two slot dispatch functions for tp_getattro.
4626
4627 - slot_tp_getattro() is used when __getattribute__ is overridden
4628 but no __getattr__ hook is present;
4629
4630 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4631
Guido van Rossumc334df52002-04-04 23:44:47 +00004632 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4633 detects the absence of __getattr__ and then installs the simpler slot if
4634 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004635
Tim Peters6d6c1a32001-08-02 04:15:00 +00004636static PyObject *
4637slot_tp_getattro(PyObject *self, PyObject *name)
4638{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004639 static PyObject *getattribute_str = NULL;
4640 return call_method(self, "__getattribute__", &getattribute_str,
4641 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004642}
4643
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004644static PyObject *
4645slot_tp_getattr_hook(PyObject *self, PyObject *name)
4646{
4647 PyTypeObject *tp = self->ob_type;
4648 PyObject *getattr, *getattribute, *res;
4649 static PyObject *getattribute_str = NULL;
4650 static PyObject *getattr_str = NULL;
4651
4652 if (getattr_str == NULL) {
4653 getattr_str = PyString_InternFromString("__getattr__");
4654 if (getattr_str == NULL)
4655 return NULL;
4656 }
4657 if (getattribute_str == NULL) {
4658 getattribute_str =
4659 PyString_InternFromString("__getattribute__");
4660 if (getattribute_str == NULL)
4661 return NULL;
4662 }
4663 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004664 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004665 /* No __getattr__ hook: use a simpler dispatcher */
4666 tp->tp_getattro = slot_tp_getattro;
4667 return slot_tp_getattro(self, name);
4668 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004669 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004670 if (getattribute == NULL ||
4671 (getattribute->ob_type == &PyWrapperDescr_Type &&
4672 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4673 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004674 res = PyObject_GenericGetAttr(self, name);
4675 else
Georg Brandl684fd0c2006-05-25 19:15:31 +00004676 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004677 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004678 PyErr_Clear();
Georg Brandl684fd0c2006-05-25 19:15:31 +00004679 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004680 }
4681 return res;
4682}
4683
Tim Peters6d6c1a32001-08-02 04:15:00 +00004684static int
4685slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4686{
4687 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004688 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004689
4690 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004691 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004692 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004693 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004694 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004695 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004696 if (res == NULL)
4697 return -1;
4698 Py_DECREF(res);
4699 return 0;
4700}
4701
4702/* Map rich comparison operators to their __xx__ namesakes */
4703static char *name_op[] = {
4704 "__lt__",
4705 "__le__",
4706 "__eq__",
4707 "__ne__",
4708 "__gt__",
4709 "__ge__",
4710};
4711
4712static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004713half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004714{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004715 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004716 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004717
Guido van Rossum60718732001-08-28 17:47:51 +00004718 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004719 if (func == NULL) {
4720 PyErr_Clear();
4721 Py_INCREF(Py_NotImplemented);
4722 return Py_NotImplemented;
4723 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004724 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004725 if (args == NULL)
4726 res = NULL;
4727 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004728 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004729 Py_DECREF(args);
4730 }
4731 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004732 return res;
4733}
4734
Guido van Rossumb8f63662001-08-15 23:57:02 +00004735static PyObject *
4736slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4737{
4738 PyObject *res;
4739
4740 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4741 res = half_richcompare(self, other, op);
4742 if (res != Py_NotImplemented)
4743 return res;
4744 Py_DECREF(res);
4745 }
4746 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004747 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004748 if (res != Py_NotImplemented) {
4749 return res;
4750 }
4751 Py_DECREF(res);
4752 }
4753 Py_INCREF(Py_NotImplemented);
4754 return Py_NotImplemented;
4755}
4756
4757static PyObject *
4758slot_tp_iter(PyObject *self)
4759{
4760 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004761 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004762
Guido van Rossum60718732001-08-28 17:47:51 +00004763 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004764 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004765 PyObject *args;
4766 args = res = PyTuple_New(0);
4767 if (args != NULL) {
4768 res = PyObject_Call(func, args, NULL);
4769 Py_DECREF(args);
4770 }
4771 Py_DECREF(func);
4772 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004773 }
4774 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004775 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004776 if (func == NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00004777 PyErr_Format(PyExc_TypeError,
4778 "'%.200s' object is not iterable",
4779 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004780 return NULL;
4781 }
4782 Py_DECREF(func);
4783 return PySeqIter_New(self);
4784}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004785
4786static PyObject *
4787slot_tp_iternext(PyObject *self)
4788{
Guido van Rossum2730b132001-08-28 18:22:14 +00004789 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004790 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004791}
4792
Guido van Rossum1a493502001-08-17 16:47:50 +00004793static PyObject *
4794slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4795{
4796 PyTypeObject *tp = self->ob_type;
4797 PyObject *get;
4798 static PyObject *get_str = NULL;
4799
4800 if (get_str == NULL) {
4801 get_str = PyString_InternFromString("__get__");
4802 if (get_str == NULL)
4803 return NULL;
4804 }
4805 get = _PyType_Lookup(tp, get_str);
4806 if (get == NULL) {
4807 /* Avoid further slowdowns */
4808 if (tp->tp_descr_get == slot_tp_descr_get)
4809 tp->tp_descr_get = NULL;
4810 Py_INCREF(self);
4811 return self;
4812 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004813 if (obj == NULL)
4814 obj = Py_None;
4815 if (type == NULL)
4816 type = Py_None;
Georg Brandl684fd0c2006-05-25 19:15:31 +00004817 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00004818}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004819
4820static int
4821slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4822{
Guido van Rossum2c252392001-08-24 10:13:31 +00004823 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004824 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004825
4826 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004827 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004828 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004829 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004830 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004831 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004832 if (res == NULL)
4833 return -1;
4834 Py_DECREF(res);
4835 return 0;
4836}
4837
4838static int
4839slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4840{
Guido van Rossum60718732001-08-28 17:47:51 +00004841 static PyObject *init_str;
4842 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004843 PyObject *res;
4844
4845 if (meth == NULL)
4846 return -1;
4847 res = PyObject_Call(meth, args, kwds);
4848 Py_DECREF(meth);
4849 if (res == NULL)
4850 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004851 if (res != Py_None) {
Georg Brandlccff7852006-06-18 22:17:29 +00004852 PyErr_Format(PyExc_TypeError,
4853 "__init__() should return None, not '%.200s'",
4854 res->ob_type->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004855 Py_DECREF(res);
4856 return -1;
4857 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004858 Py_DECREF(res);
4859 return 0;
4860}
4861
4862static PyObject *
4863slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4864{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004865 static PyObject *new_str;
4866 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004867 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004868 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004869
Guido van Rossum7bed2132002-08-08 21:57:53 +00004870 if (new_str == NULL) {
4871 new_str = PyString_InternFromString("__new__");
4872 if (new_str == NULL)
4873 return NULL;
4874 }
4875 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004876 if (func == NULL)
4877 return NULL;
4878 assert(PyTuple_Check(args));
4879 n = PyTuple_GET_SIZE(args);
4880 newargs = PyTuple_New(n+1);
4881 if (newargs == NULL)
4882 return NULL;
4883 Py_INCREF(type);
4884 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4885 for (i = 0; i < n; i++) {
4886 x = PyTuple_GET_ITEM(args, i);
4887 Py_INCREF(x);
4888 PyTuple_SET_ITEM(newargs, i+1, x);
4889 }
4890 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004891 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004892 Py_DECREF(func);
4893 return x;
4894}
4895
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004896static void
4897slot_tp_del(PyObject *self)
4898{
4899 static PyObject *del_str = NULL;
4900 PyObject *del, *res;
4901 PyObject *error_type, *error_value, *error_traceback;
4902
4903 /* Temporarily resurrect the object. */
4904 assert(self->ob_refcnt == 0);
4905 self->ob_refcnt = 1;
4906
4907 /* Save the current exception, if any. */
4908 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4909
4910 /* Execute __del__ method, if any. */
4911 del = lookup_maybe(self, "__del__", &del_str);
4912 if (del != NULL) {
4913 res = PyEval_CallObject(del, NULL);
4914 if (res == NULL)
4915 PyErr_WriteUnraisable(del);
4916 else
4917 Py_DECREF(res);
4918 Py_DECREF(del);
4919 }
4920
4921 /* Restore the saved exception. */
4922 PyErr_Restore(error_type, error_value, error_traceback);
4923
4924 /* Undo the temporary resurrection; can't use DECREF here, it would
4925 * cause a recursive call.
4926 */
4927 assert(self->ob_refcnt > 0);
4928 if (--self->ob_refcnt == 0)
4929 return; /* this is the normal path out */
4930
4931 /* __del__ resurrected it! Make it look like the original Py_DECREF
4932 * never happened.
4933 */
4934 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004935 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004936 _Py_NewReference(self);
4937 self->ob_refcnt = refcnt;
4938 }
4939 assert(!PyType_IS_GC(self->ob_type) ||
4940 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00004941 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
4942 * we need to undo that. */
4943 _Py_DEC_REFTOTAL;
4944 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4945 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004946 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4947 * _Py_NewReference bumped tp_allocs: both of those need to be
4948 * undone.
4949 */
4950#ifdef COUNT_ALLOCS
4951 --self->ob_type->tp_frees;
4952 --self->ob_type->tp_allocs;
4953#endif
4954}
4955
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004956
4957/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004958 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004959 structure, which incorporates the additional structures used for numbers,
4960 sequences and mappings.
4961 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004962 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004963 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4964 terminated with an all-zero entry. (This table is further initialized and
4965 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004966
Guido van Rossum6d204072001-10-21 00:44:31 +00004967typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004968
4969#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004970#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004971#undef ETSLOT
4972#undef SQSLOT
4973#undef MPSLOT
4974#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004975#undef UNSLOT
4976#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004977#undef BINSLOT
4978#undef RBINSLOT
4979
Guido van Rossum6d204072001-10-21 00:44:31 +00004980#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004981 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4982 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004983#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4984 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004985 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004986#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004987 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004988 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004989#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4990 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4991#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4992 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4993#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4994 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4995#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4996 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4997 "x." NAME "() <==> " DOC)
4998#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4999 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5000 "x." NAME "(y) <==> x" DOC "y")
5001#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5002 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5003 "x." NAME "(y) <==> x" DOC "y")
5004#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5005 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5006 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005007#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5008 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5009 "x." NAME "(y) <==> " DOC)
5010#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5011 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5012 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005013
5014static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005015 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005016 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005017 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5018 The logic in abstract.c always falls back to nb_add/nb_multiply in
5019 this case. Defining both the nb_* and the sq_* slots to call the
5020 user-defined methods has unexpected side-effects, as shown by
5021 test_descr.notimplemented() */
5022 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5023 "x.__add__(y) <==> x+y"),
Armin Rigo314861c2006-03-30 14:04:02 +00005024 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Armin Rigofd163f92005-12-29 15:59:19 +00005025 "x.__mul__(n) <==> x*n"),
Armin Rigo314861c2006-03-30 14:04:02 +00005026 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Armin Rigofd163f92005-12-29 15:59:19 +00005027 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005028 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5029 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005030 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005031 "x.__getslice__(i, j) <==> x[i:j]\n\
5032 \n\
5033 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005034 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005035 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005036 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005037 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005038 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005039 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005040 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
5041 \n\
5042 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005043 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005044 "x.__delslice__(i, j) <==> del x[i:j]\n\
5045 \n\
5046 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005047 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5048 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005049 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5050 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5051 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Armin Rigo314861c2006-03-30 14:04:02 +00005052 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005053
Martin v. Löwis18e16552006-02-15 17:27:45 +00005054 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005055 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005056 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005057 wrap_binaryfunc,
5058 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005059 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005060 wrap_objobjargproc,
5061 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005062 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005063 wrap_delitem,
5064 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005065
Guido van Rossum6d204072001-10-21 00:44:31 +00005066 BINSLOT("__add__", nb_add, slot_nb_add,
5067 "+"),
5068 RBINSLOT("__radd__", nb_add, slot_nb_add,
5069 "+"),
5070 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5071 "-"),
5072 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5073 "-"),
5074 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5075 "*"),
5076 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5077 "*"),
5078 BINSLOT("__div__", nb_divide, slot_nb_divide,
5079 "/"),
5080 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5081 "/"),
5082 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5083 "%"),
5084 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5085 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005086 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005087 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005088 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005089 "divmod(y, x)"),
5090 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5091 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5092 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5093 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5094 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5095 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5096 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5097 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005098 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005099 "x != 0"),
5100 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5101 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5102 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5103 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5104 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5105 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5106 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5107 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5108 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5109 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5110 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5111 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5112 "x.__coerce__(y) <==> coerce(x, y)"),
5113 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5114 "int(x)"),
5115 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5116 "long(x)"),
5117 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5118 "float(x)"),
5119 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5120 "oct(x)"),
5121 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5122 "hex(x)"),
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005123 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005124 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005125 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5126 wrap_binaryfunc, "+"),
5127 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5128 wrap_binaryfunc, "-"),
5129 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5130 wrap_binaryfunc, "*"),
5131 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5132 wrap_binaryfunc, "/"),
5133 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5134 wrap_binaryfunc, "%"),
5135 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005136 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005137 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5138 wrap_binaryfunc, "<<"),
5139 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5140 wrap_binaryfunc, ">>"),
5141 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5142 wrap_binaryfunc, "&"),
5143 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5144 wrap_binaryfunc, "^"),
5145 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5146 wrap_binaryfunc, "|"),
5147 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5148 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5149 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5150 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5151 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5152 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5153 IBSLOT("__itruediv__", nb_inplace_true_divide,
5154 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005155
Guido van Rossum6d204072001-10-21 00:44:31 +00005156 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5157 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005158 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005159 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5160 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005161 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005162 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5163 "x.__cmp__(y) <==> cmp(x,y)"),
5164 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5165 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005166 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5167 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005168 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005169 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5170 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5171 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5172 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5173 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5174 "x.__setattr__('name', value) <==> x.name = value"),
5175 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5176 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5177 "x.__delattr__('name') <==> del x.name"),
5178 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5179 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5180 "x.__lt__(y) <==> x<y"),
5181 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5182 "x.__le__(y) <==> x<=y"),
5183 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5184 "x.__eq__(y) <==> x==y"),
5185 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5186 "x.__ne__(y) <==> x!=y"),
5187 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5188 "x.__gt__(y) <==> x>y"),
5189 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5190 "x.__ge__(y) <==> x>=y"),
5191 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5192 "x.__iter__() <==> iter(x)"),
5193 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5194 "x.next() -> the next value, or raise StopIteration"),
5195 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5196 "descr.__get__(obj[, type]) -> value"),
5197 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5198 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005199 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5200 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005201 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005202 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005203 "see x.__class__.__doc__ for signature",
5204 PyWrapperFlag_KEYWORDS),
5205 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005206 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005207 {NULL}
5208};
5209
Guido van Rossumc334df52002-04-04 23:44:47 +00005210/* Given a type pointer and an offset gotten from a slotdef entry, return a
5211 pointer to the actual slot. This is not quite the same as simply adding
5212 the offset to the type pointer, since it takes care to indirect through the
5213 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5214 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005215static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005216slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005217{
5218 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005219 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005220
Guido van Rossume5c691a2003-03-07 15:13:17 +00005221 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005222 assert(offset >= 0);
Skip Montanaro429433b2006-04-18 00:35:43 +00005223 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5224 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005225 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005226 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005227 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005228 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005229 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005230 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005231 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005232 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005233 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005234 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005235 }
5236 else {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005237 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005238 }
5239 if (ptr != NULL)
5240 ptr += offset;
5241 return (void **)ptr;
5242}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005243
Guido van Rossumc334df52002-04-04 23:44:47 +00005244/* Length of array of slotdef pointers used to store slots with the
5245 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5246 the same __name__, for any __name__. Since that's a static property, it is
5247 appropriate to declare fixed-size arrays for this. */
5248#define MAX_EQUIV 10
5249
5250/* Return a slot pointer for a given name, but ONLY if the attribute has
5251 exactly one slot function. The name must be an interned string. */
5252static void **
5253resolve_slotdups(PyTypeObject *type, PyObject *name)
5254{
5255 /* XXX Maybe this could be optimized more -- but is it worth it? */
5256
5257 /* pname and ptrs act as a little cache */
5258 static PyObject *pname;
5259 static slotdef *ptrs[MAX_EQUIV];
5260 slotdef *p, **pp;
5261 void **res, **ptr;
5262
5263 if (pname != name) {
5264 /* Collect all slotdefs that match name into ptrs. */
5265 pname = name;
5266 pp = ptrs;
5267 for (p = slotdefs; p->name_strobj; p++) {
5268 if (p->name_strobj == name)
5269 *pp++ = p;
5270 }
5271 *pp = NULL;
5272 }
5273
5274 /* Look in all matching slots of the type; if exactly one of these has
5275 a filled-in slot, return its value. Otherwise return NULL. */
5276 res = NULL;
5277 for (pp = ptrs; *pp; pp++) {
5278 ptr = slotptr(type, (*pp)->offset);
5279 if (ptr == NULL || *ptr == NULL)
5280 continue;
5281 if (res != NULL)
5282 return NULL;
5283 res = ptr;
5284 }
5285 return res;
5286}
5287
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005288/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005289 does some incredibly complex thinking and then sticks something into the
5290 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5291 interests, and then stores a generic wrapper or a specific function into
5292 the slot.) Return a pointer to the next slotdef with a different offset,
5293 because that's convenient for fixup_slot_dispatchers(). */
5294static slotdef *
5295update_one_slot(PyTypeObject *type, slotdef *p)
5296{
5297 PyObject *descr;
5298 PyWrapperDescrObject *d;
5299 void *generic = NULL, *specific = NULL;
5300 int use_generic = 0;
5301 int offset = p->offset;
5302 void **ptr = slotptr(type, offset);
5303
5304 if (ptr == NULL) {
5305 do {
5306 ++p;
5307 } while (p->offset == offset);
5308 return p;
5309 }
5310 do {
5311 descr = _PyType_Lookup(type, p->name_strobj);
5312 if (descr == NULL)
5313 continue;
5314 if (descr->ob_type == &PyWrapperDescr_Type) {
5315 void **tptr = resolve_slotdups(type, p->name_strobj);
5316 if (tptr == NULL || tptr == ptr)
5317 generic = p->function;
5318 d = (PyWrapperDescrObject *)descr;
5319 if (d->d_base->wrapper == p->wrapper &&
5320 PyType_IsSubtype(type, d->d_type))
5321 {
5322 if (specific == NULL ||
5323 specific == d->d_wrapped)
5324 specific = d->d_wrapped;
5325 else
5326 use_generic = 1;
5327 }
5328 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005329 else if (descr->ob_type == &PyCFunction_Type &&
5330 PyCFunction_GET_FUNCTION(descr) ==
5331 (PyCFunction)tp_new_wrapper &&
5332 strcmp(p->name, "__new__") == 0)
5333 {
5334 /* The __new__ wrapper is not a wrapper descriptor,
5335 so must be special-cased differently.
5336 If we don't do this, creating an instance will
5337 always use slot_tp_new which will look up
5338 __new__ in the MRO which will call tp_new_wrapper
5339 which will look through the base classes looking
5340 for a static base and call its tp_new (usually
5341 PyType_GenericNew), after performing various
5342 sanity checks and constructing a new argument
5343 list. Cut all that nonsense short -- this speeds
5344 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005345 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005346 /* XXX I'm not 100% sure that there isn't a hole
5347 in this reasoning that requires additional
5348 sanity checks. I'll buy the first person to
5349 point out a bug in this reasoning a beer. */
5350 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005351 else {
5352 use_generic = 1;
5353 generic = p->function;
5354 }
5355 } while ((++p)->offset == offset);
5356 if (specific && !use_generic)
5357 *ptr = specific;
5358 else
5359 *ptr = generic;
5360 return p;
5361}
5362
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005363/* In the type, update the slots whose slotdefs are gathered in the pp array.
5364 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005365static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005366update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005367{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005368 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005369
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005370 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005371 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005372 return 0;
5373}
5374
Guido van Rossumc334df52002-04-04 23:44:47 +00005375/* Comparison function for qsort() to compare slotdefs by their offset, and
5376 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005377static int
5378slotdef_cmp(const void *aa, const void *bb)
5379{
5380 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5381 int c = a->offset - b->offset;
5382 if (c != 0)
5383 return c;
5384 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005385 /* Cannot use a-b, as this gives off_t,
5386 which may lose precision when converted to int. */
5387 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005388}
5389
Guido van Rossumc334df52002-04-04 23:44:47 +00005390/* Initialize the slotdefs table by adding interned string objects for the
5391 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005392static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005393init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005394{
5395 slotdef *p;
5396 static int initialized = 0;
5397
5398 if (initialized)
5399 return;
5400 for (p = slotdefs; p->name; p++) {
5401 p->name_strobj = PyString_InternFromString(p->name);
5402 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005403 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005404 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005405 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5406 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005407 initialized = 1;
5408}
5409
Guido van Rossumc334df52002-04-04 23:44:47 +00005410/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005411static int
5412update_slot(PyTypeObject *type, PyObject *name)
5413{
Guido van Rossumc334df52002-04-04 23:44:47 +00005414 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005415 slotdef *p;
5416 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005417 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005418
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005419 init_slotdefs();
5420 pp = ptrs;
5421 for (p = slotdefs; p->name; p++) {
5422 /* XXX assume name is interned! */
5423 if (p->name_strobj == name)
5424 *pp++ = p;
5425 }
5426 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005427 for (pp = ptrs; *pp; pp++) {
5428 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005429 offset = p->offset;
5430 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005431 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005432 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005433 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005434 if (ptrs[0] == NULL)
5435 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005436 return update_subclasses(type, name,
5437 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005438}
5439
Guido van Rossumc334df52002-04-04 23:44:47 +00005440/* Store the proper functions in the slot dispatches at class (type)
5441 definition time, based upon which operations the class overrides in its
5442 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005443static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005444fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005445{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005446 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005447
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005448 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005449 for (p = slotdefs; p->name; )
5450 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005451}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005452
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005453static void
5454update_all_slots(PyTypeObject* type)
5455{
5456 slotdef *p;
5457
5458 init_slotdefs();
5459 for (p = slotdefs; p->name; p++) {
5460 /* update_slot returns int but can't actually fail */
5461 update_slot(type, p->name_strobj);
5462 }
5463}
5464
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005465/* recurse_down_subclasses() and update_subclasses() are mutually
5466 recursive functions to call a callback for all subclasses,
5467 but refraining from recursing into subclasses that define 'name'. */
5468
5469static int
5470update_subclasses(PyTypeObject *type, PyObject *name,
5471 update_callback callback, void *data)
5472{
5473 if (callback(type, data) < 0)
5474 return -1;
5475 return recurse_down_subclasses(type, name, callback, data);
5476}
5477
5478static int
5479recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5480 update_callback callback, void *data)
5481{
5482 PyTypeObject *subclass;
5483 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005484 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005485
5486 subclasses = type->tp_subclasses;
5487 if (subclasses == NULL)
5488 return 0;
5489 assert(PyList_Check(subclasses));
5490 n = PyList_GET_SIZE(subclasses);
5491 for (i = 0; i < n; i++) {
5492 ref = PyList_GET_ITEM(subclasses, i);
5493 assert(PyWeakref_CheckRef(ref));
5494 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5495 assert(subclass != NULL);
5496 if ((PyObject *)subclass == Py_None)
5497 continue;
5498 assert(PyType_Check(subclass));
5499 /* Avoid recursing down into unaffected classes */
5500 dict = subclass->tp_dict;
5501 if (dict != NULL && PyDict_Check(dict) &&
5502 PyDict_GetItem(dict, name) != NULL)
5503 continue;
5504 if (update_subclasses(subclass, name, callback, data) < 0)
5505 return -1;
5506 }
5507 return 0;
5508}
5509
Guido van Rossum6d204072001-10-21 00:44:31 +00005510/* This function is called by PyType_Ready() to populate the type's
5511 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005512 function slot (like tp_repr) that's defined in the type, one or more
5513 corresponding descriptors are added in the type's tp_dict dictionary
5514 under the appropriate name (like __repr__). Some function slots
5515 cause more than one descriptor to be added (for example, the nb_add
5516 slot adds both __add__ and __radd__ descriptors) and some function
5517 slots compete for the same descriptor (for example both sq_item and
5518 mp_subscript generate a __getitem__ descriptor).
5519
5520 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005521 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005522 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005523 between competing slots: the members of PyHeapTypeObject are listed
5524 from most general to least general, so the most general slot is
5525 preferred. In particular, because as_mapping comes before as_sequence,
5526 for a type that defines both mp_subscript and sq_item, mp_subscript
5527 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005528
5529 This only adds new descriptors and doesn't overwrite entries in
5530 tp_dict that were previously defined. The descriptors contain a
5531 reference to the C function they must call, so that it's safe if they
5532 are copied into a subtype's __dict__ and the subtype has a different
5533 C function in its slot -- calling the method defined by the
5534 descriptor will call the C function that was used to create it,
5535 rather than the C function present in the slot when it is called.
5536 (This is important because a subtype may have a C function in the
5537 slot that calls the method from the dictionary, and we want to avoid
5538 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005539
5540static int
5541add_operators(PyTypeObject *type)
5542{
5543 PyObject *dict = type->tp_dict;
5544 slotdef *p;
5545 PyObject *descr;
5546 void **ptr;
5547
5548 init_slotdefs();
5549 for (p = slotdefs; p->name; p++) {
5550 if (p->wrapper == NULL)
5551 continue;
5552 ptr = slotptr(type, p->offset);
5553 if (!ptr || !*ptr)
5554 continue;
5555 if (PyDict_GetItem(dict, p->name_strobj))
5556 continue;
5557 descr = PyDescr_NewWrapper(type, p, *ptr);
5558 if (descr == NULL)
5559 return -1;
5560 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5561 return -1;
5562 Py_DECREF(descr);
5563 }
5564 if (type->tp_new != NULL) {
5565 if (add_tp_new_wrapper(type) < 0)
5566 return -1;
5567 }
5568 return 0;
5569}
5570
Guido van Rossum705f0f52001-08-24 16:47:00 +00005571
5572/* Cooperative 'super' */
5573
5574typedef struct {
5575 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005576 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005577 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005578 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005579} superobject;
5580
Guido van Rossum6f799372001-09-20 20:46:19 +00005581static PyMemberDef super_members[] = {
5582 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5583 "the class invoking super()"},
5584 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5585 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005586 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005587 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005588 {0}
5589};
5590
Guido van Rossum705f0f52001-08-24 16:47:00 +00005591static void
5592super_dealloc(PyObject *self)
5593{
5594 superobject *su = (superobject *)self;
5595
Guido van Rossum048eb752001-10-02 21:24:57 +00005596 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005597 Py_XDECREF(su->obj);
5598 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005599 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005600 self->ob_type->tp_free(self);
5601}
5602
5603static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005604super_repr(PyObject *self)
5605{
5606 superobject *su = (superobject *)self;
5607
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005608 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005609 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005610 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005611 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005612 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005613 else
5614 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005615 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005616 su->type ? su->type->tp_name : "NULL");
5617}
5618
5619static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005620super_getattro(PyObject *self, PyObject *name)
5621{
5622 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005623 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005624
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005625 if (!skip) {
5626 /* We want __class__ to return the class of the super object
5627 (i.e. super, or a subclass), not the class of su->obj. */
5628 skip = (PyString_Check(name) &&
5629 PyString_GET_SIZE(name) == 9 &&
5630 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5631 }
5632
5633 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005634 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005635 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005636 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005637 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005638
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005639 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005640 mro = starttype->tp_mro;
5641
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005642 if (mro == NULL)
5643 n = 0;
5644 else {
5645 assert(PyTuple_Check(mro));
5646 n = PyTuple_GET_SIZE(mro);
5647 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005648 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005649 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005650 break;
5651 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005652 i++;
5653 res = NULL;
5654 for (; i < n; i++) {
5655 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005656 if (PyType_Check(tmp))
5657 dict = ((PyTypeObject *)tmp)->tp_dict;
5658 else if (PyClass_Check(tmp))
5659 dict = ((PyClassObject *)tmp)->cl_dict;
5660 else
5661 continue;
5662 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005663 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005664 Py_INCREF(res);
5665 f = res->ob_type->tp_descr_get;
5666 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005667 tmp = f(res,
5668 /* Only pass 'obj' param if
5669 this is instance-mode super
5670 (See SF ID #743627)
5671 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005672 (su->obj == (PyObject *)
5673 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005674 ? (PyObject *)NULL
5675 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005676 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005677 Py_DECREF(res);
5678 res = tmp;
5679 }
5680 return res;
5681 }
5682 }
5683 }
5684 return PyObject_GenericGetAttr(self, name);
5685}
5686
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005687static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005688supercheck(PyTypeObject *type, PyObject *obj)
5689{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005690 /* Check that a super() call makes sense. Return a type object.
5691
5692 obj can be a new-style class, or an instance of one:
5693
5694 - If it is a class, it must be a subclass of 'type'. This case is
5695 used for class methods; the return value is obj.
5696
5697 - If it is an instance, it must be an instance of 'type'. This is
5698 the normal case; the return value is obj.__class__.
5699
5700 But... when obj is an instance, we want to allow for the case where
5701 obj->ob_type is not a subclass of type, but obj.__class__ is!
5702 This will allow using super() with a proxy for obj.
5703 */
5704
Guido van Rossum8e80a722003-02-18 19:22:22 +00005705 /* Check for first bullet above (special case) */
5706 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5707 Py_INCREF(obj);
5708 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005709 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005710
5711 /* Normal case */
5712 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005713 Py_INCREF(obj->ob_type);
5714 return obj->ob_type;
5715 }
5716 else {
5717 /* Try the slow way */
5718 static PyObject *class_str = NULL;
5719 PyObject *class_attr;
5720
5721 if (class_str == NULL) {
5722 class_str = PyString_FromString("__class__");
5723 if (class_str == NULL)
5724 return NULL;
5725 }
5726
5727 class_attr = PyObject_GetAttr(obj, class_str);
5728
5729 if (class_attr != NULL &&
5730 PyType_Check(class_attr) &&
5731 (PyTypeObject *)class_attr != obj->ob_type)
5732 {
5733 int ok = PyType_IsSubtype(
5734 (PyTypeObject *)class_attr, type);
5735 if (ok)
5736 return (PyTypeObject *)class_attr;
5737 }
5738
5739 if (class_attr == NULL)
5740 PyErr_Clear();
5741 else
5742 Py_DECREF(class_attr);
5743 }
5744
Tim Peters97e5ff52003-02-18 19:32:50 +00005745 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005746 "super(type, obj): "
5747 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005748 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005749}
5750
Guido van Rossum705f0f52001-08-24 16:47:00 +00005751static PyObject *
5752super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5753{
5754 superobject *su = (superobject *)self;
Anthony Baxtera6286212006-04-11 07:42:36 +00005755 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005756
5757 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5758 /* Not binding to an object, or already bound */
5759 Py_INCREF(self);
5760 return self;
5761 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005762 if (su->ob_type != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005763 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005764 call its type */
Georg Brandl684fd0c2006-05-25 19:15:31 +00005765 return PyObject_CallFunctionObjArgs((PyObject *)su->ob_type,
5766 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005767 else {
5768 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005769 PyTypeObject *obj_type = supercheck(su->type, obj);
5770 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005771 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00005772 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005773 NULL, NULL);
Anthony Baxtera6286212006-04-11 07:42:36 +00005774 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005775 return NULL;
5776 Py_INCREF(su->type);
5777 Py_INCREF(obj);
Anthony Baxtera6286212006-04-11 07:42:36 +00005778 newobj->type = su->type;
5779 newobj->obj = obj;
5780 newobj->obj_type = obj_type;
5781 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005782 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005783}
5784
5785static int
5786super_init(PyObject *self, PyObject *args, PyObject *kwds)
5787{
5788 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005789 PyTypeObject *type;
5790 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005791 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005792
Georg Brandl5d59c092006-09-30 08:43:30 +00005793 if (!_PyArg_NoKeywords("super", kwds))
5794 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005795 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5796 return -1;
5797 if (obj == Py_None)
5798 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005799 if (obj != NULL) {
5800 obj_type = supercheck(type, obj);
5801 if (obj_type == NULL)
5802 return -1;
5803 Py_INCREF(obj);
5804 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005805 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005806 su->type = type;
5807 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005808 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005809 return 0;
5810}
5811
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005812PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005813"super(type) -> unbound super object\n"
5814"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005815"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005816"Typical use to call a cooperative superclass method:\n"
5817"class C(B):\n"
5818" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005819" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005820
Guido van Rossum048eb752001-10-02 21:24:57 +00005821static int
5822super_traverse(PyObject *self, visitproc visit, void *arg)
5823{
5824 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00005825
Thomas Woutersc6e55062006-04-15 21:47:09 +00005826 Py_VISIT(su->obj);
5827 Py_VISIT(su->type);
5828 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005829
5830 return 0;
5831}
5832
Guido van Rossum705f0f52001-08-24 16:47:00 +00005833PyTypeObject PySuper_Type = {
5834 PyObject_HEAD_INIT(&PyType_Type)
5835 0, /* ob_size */
5836 "super", /* tp_name */
5837 sizeof(superobject), /* tp_basicsize */
5838 0, /* tp_itemsize */
5839 /* methods */
5840 super_dealloc, /* tp_dealloc */
5841 0, /* tp_print */
5842 0, /* tp_getattr */
5843 0, /* tp_setattr */
5844 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005845 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005846 0, /* tp_as_number */
5847 0, /* tp_as_sequence */
5848 0, /* tp_as_mapping */
5849 0, /* tp_hash */
5850 0, /* tp_call */
5851 0, /* tp_str */
5852 super_getattro, /* tp_getattro */
5853 0, /* tp_setattro */
5854 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005855 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5856 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005857 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005858 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005859 0, /* tp_clear */
5860 0, /* tp_richcompare */
5861 0, /* tp_weaklistoffset */
5862 0, /* tp_iter */
5863 0, /* tp_iternext */
5864 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005865 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005866 0, /* tp_getset */
5867 0, /* tp_base */
5868 0, /* tp_dict */
5869 super_descr_get, /* tp_descr_get */
5870 0, /* tp_descr_set */
5871 0, /* tp_dictoffset */
5872 super_init, /* tp_init */
5873 PyType_GenericAlloc, /* tp_alloc */
5874 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005875 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005876};