blob: 760ef95858d2b5469f1f9a26445633f920ccb6dc [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(
101 type->tp_name, (int)(s - type->tp_name));
102 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);
Guido van Rossum1987c662003-05-29 14:29:23 +0000669 }
670
Guido van Rossum59195fd2003-06-13 20:54:40 +0000671 /* Clear slots up to the nearest base with a different tp_dealloc */
672 base = type;
673 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
674 if (base->ob_size)
675 clear_slots(base, self);
676 base = base->tp_base;
677 assert(base);
678 }
679
Tim Peters6d6c1a32001-08-02 04:15:00 +0000680 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000681 if (type->tp_dictoffset && !base->tp_dictoffset) {
682 PyObject **dictptr = _PyObject_GetDictPtr(self);
683 if (dictptr != NULL) {
684 PyObject *dict = *dictptr;
685 if (dict != NULL) {
686 Py_DECREF(dict);
687 *dictptr = NULL;
688 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000689 }
690 }
691
Tim Peters0bd743c2003-11-13 22:50:00 +0000692 /* Call the base tp_dealloc(); first retrack self if
693 * basedealloc knows about gc.
694 */
695 if (PyType_IS_GC(base))
696 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000697 assert(basedealloc);
698 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000699
700 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000701 Py_DECREF(type);
702
Guido van Rossum0906e072002-08-07 20:42:09 +0000703 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000704 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000705 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000706 --_PyTrash_delete_nesting;
707
708 /* Explanation of the weirdness around the trashcan macros:
709
710 Q. What do the trashcan macros do?
711
712 A. Read the comment titled "Trashcan mechanism" in object.h.
713 For one, this explains why there must be a call to GC-untrack
714 before the trashcan begin macro. Without understanding the
715 trashcan code, the answers to the following questions don't make
716 sense.
717
718 Q. Why do we GC-untrack before the trashcan and then immediately
719 GC-track again afterward?
720
721 A. In the case that the base class is GC-aware, the base class
722 probably GC-untracks the object. If it does that using the
723 UNTRACK macro, this will crash when the object is already
724 untracked. Because we don't know what the base class does, the
725 only safe thing is to make sure the object is tracked when we
726 call the base class dealloc. But... The trashcan begin macro
727 requires that the object is *untracked* before it is called. So
728 the dance becomes:
729
730 GC untrack
731 trashcan begin
732 GC track
733
Tim Petersf7f9e992003-11-13 21:59:32 +0000734 Q. Why did the last question say "immediately GC-track again"?
735 It's nowhere near immediately.
736
737 A. Because the code *used* to re-track immediately. Bad Idea.
738 self has a refcount of 0, and if gc ever gets its hands on it
739 (which can happen if any weakref callback gets invoked), it
740 looks like trash to gc too, and gc also tries to delete self
741 then. But we're already deleting self. Double dealloction is
742 a subtle disaster.
743
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000744 Q. Why the bizarre (net-zero) manipulation of
745 _PyTrash_delete_nesting around the trashcan macros?
746
747 A. Some base classes (e.g. list) also use the trashcan mechanism.
748 The following scenario used to be possible:
749
750 - suppose the trashcan level is one below the trashcan limit
751
752 - subtype_dealloc() is called
753
754 - the trashcan limit is not yet reached, so the trashcan level
755 is incremented and the code between trashcan begin and end is
756 executed
757
758 - this destroys much of the object's contents, including its
759 slots and __dict__
760
761 - basedealloc() is called; this is really list_dealloc(), or
762 some other type which also uses the trashcan macros
763
764 - the trashcan limit is now reached, so the object is put on the
765 trashcan's to-be-deleted-later list
766
767 - basedealloc() returns
768
769 - subtype_dealloc() decrefs the object's type
770
771 - subtype_dealloc() returns
772
773 - later, the trashcan code starts deleting the objects from its
774 to-be-deleted-later list
775
776 - subtype_dealloc() is called *AGAIN* for the same object
777
778 - at the very least (if the destroyed slots and __dict__ don't
779 cause problems) the object's type gets decref'ed a second
780 time, which is *BAD*!!!
781
782 The remedy is to make sure that if the code between trashcan
783 begin and end in subtype_dealloc() is called, the code between
784 trashcan begin and end in basedealloc() will also be called.
785 This is done by decrementing the level after passing into the
786 trashcan block, and incrementing it just before leaving the
787 block.
788
789 But now it's possible that a chain of objects consisting solely
790 of objects whose deallocator is subtype_dealloc() will defeat
791 the trashcan mechanism completely: the decremented level means
792 that the effective level never reaches the limit. Therefore, we
793 *increment* the level *before* entering the trashcan block, and
794 matchingly decrement it after leaving. This means the trashcan
795 code will trigger a little early, but that's no big deal.
796
797 Q. Are there any live examples of code in need of all this
798 complexity?
799
800 A. Yes. See SF bug 668433 for code that crashed (when Python was
801 compiled in debug mode) before the trashcan level manipulations
802 were added. For more discussion, see SF patches 581742, 575073
803 and bug 574207.
804 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000805}
806
Jeremy Hylton938ace62002-07-17 16:30:39 +0000807static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000808
Tim Peters6d6c1a32001-08-02 04:15:00 +0000809/* type test with subclassing support */
810
811int
812PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
813{
814 PyObject *mro;
815
Guido van Rossum9478d072001-09-07 18:52:13 +0000816 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
817 return b == a || b == &PyBaseObject_Type;
818
Tim Peters6d6c1a32001-08-02 04:15:00 +0000819 mro = a->tp_mro;
820 if (mro != NULL) {
821 /* Deal with multiple inheritance without recursion
822 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000823 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000824 assert(PyTuple_Check(mro));
825 n = PyTuple_GET_SIZE(mro);
826 for (i = 0; i < n; i++) {
827 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
828 return 1;
829 }
830 return 0;
831 }
832 else {
833 /* a is not completely initilized yet; follow tp_base */
834 do {
835 if (a == b)
836 return 1;
837 a = a->tp_base;
838 } while (a != NULL);
839 return b == &PyBaseObject_Type;
840 }
841}
842
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000843/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000844 without looking in the instance dictionary
845 (so we can't use PyObject_GetAttr) but still binding
846 it to the instance. The arguments are the object,
847 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000848 static variable used to cache the interned Python string.
849
850 Two variants:
851
852 - lookup_maybe() returns NULL without raising an exception
853 when the _PyType_Lookup() call fails;
854
855 - lookup_method() always raises an exception upon errors.
856*/
Guido van Rossum60718732001-08-28 17:47:51 +0000857
858static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000859lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000860{
861 PyObject *res;
862
863 if (*attrobj == NULL) {
864 *attrobj = PyString_InternFromString(attrstr);
865 if (*attrobj == NULL)
866 return NULL;
867 }
868 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000869 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000870 descrgetfunc f;
871 if ((f = res->ob_type->tp_descr_get) == NULL)
872 Py_INCREF(res);
873 else
874 res = f(res, self, (PyObject *)(self->ob_type));
875 }
876 return res;
877}
878
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000879static PyObject *
880lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
881{
882 PyObject *res = lookup_maybe(self, attrstr, attrobj);
883 if (res == NULL && !PyErr_Occurred())
884 PyErr_SetObject(PyExc_AttributeError, *attrobj);
885 return res;
886}
887
Guido van Rossum2730b132001-08-28 18:22:14 +0000888/* A variation of PyObject_CallMethod that uses lookup_method()
889 instead of PyObject_GetAttrString(). This uses the same convention
890 as lookup_method to cache the interned name string object. */
891
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000892static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000893call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
894{
895 va_list va;
896 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000897 va_start(va, format);
898
Guido van Rossumda21c012001-10-03 00:50:18 +0000899 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000900 if (func == NULL) {
901 va_end(va);
902 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000903 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000904 return NULL;
905 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000906
907 if (format && *format)
908 args = Py_VaBuildValue(format, va);
909 else
910 args = PyTuple_New(0);
911
912 va_end(va);
913
914 if (args == NULL)
915 return NULL;
916
917 assert(PyTuple_Check(args));
918 retval = PyObject_Call(func, args, NULL);
919
920 Py_DECREF(args);
921 Py_DECREF(func);
922
923 return retval;
924}
925
926/* Clone of call_method() that returns NotImplemented when the lookup fails. */
927
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000928static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000929call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
930{
931 va_list va;
932 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000933 va_start(va, format);
934
Guido van Rossumda21c012001-10-03 00:50:18 +0000935 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000936 if (func == NULL) {
937 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000938 if (!PyErr_Occurred()) {
939 Py_INCREF(Py_NotImplemented);
940 return Py_NotImplemented;
941 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000942 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000943 }
944
945 if (format && *format)
946 args = Py_VaBuildValue(format, va);
947 else
948 args = PyTuple_New(0);
949
950 va_end(va);
951
Guido van Rossum717ce002001-09-14 16:58:08 +0000952 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000953 return NULL;
954
Guido van Rossum717ce002001-09-14 16:58:08 +0000955 assert(PyTuple_Check(args));
956 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000957
958 Py_DECREF(args);
959 Py_DECREF(func);
960
961 return retval;
962}
963
Tim Petersa91e9642001-11-14 23:32:33 +0000964static int
965fill_classic_mro(PyObject *mro, PyObject *cls)
966{
967 PyObject *bases, *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000968 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +0000969
970 assert(PyList_Check(mro));
971 assert(PyClass_Check(cls));
972 i = PySequence_Contains(mro, cls);
973 if (i < 0)
974 return -1;
975 if (!i) {
976 if (PyList_Append(mro, cls) < 0)
977 return -1;
978 }
979 bases = ((PyClassObject *)cls)->cl_bases;
980 assert(bases && PyTuple_Check(bases));
981 n = PyTuple_GET_SIZE(bases);
982 for (i = 0; i < n; i++) {
983 base = PyTuple_GET_ITEM(bases, i);
984 if (fill_classic_mro(mro, base) < 0)
985 return -1;
986 }
987 return 0;
988}
989
990static PyObject *
991classic_mro(PyObject *cls)
992{
993 PyObject *mro;
994
995 assert(PyClass_Check(cls));
996 mro = PyList_New(0);
997 if (mro != NULL) {
998 if (fill_classic_mro(mro, cls) == 0)
999 return mro;
1000 Py_DECREF(mro);
1001 }
1002 return NULL;
1003}
1004
Tim Petersea7f75d2002-12-07 21:39:16 +00001005/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001006 Method resolution order algorithm C3 described in
1007 "A Monotonic Superclass Linearization for Dylan",
1008 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001009 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001010 (OOPSLA 1996)
1011
Guido van Rossum98f33732002-11-25 21:36:54 +00001012 Some notes about the rules implied by C3:
1013
Tim Petersea7f75d2002-12-07 21:39:16 +00001014 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001015 It isn't legal to repeat a class in a list of base classes.
1016
1017 The next three properties are the 3 constraints in "C3".
1018
Tim Petersea7f75d2002-12-07 21:39:16 +00001019 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001020 If A precedes B in C's MRO, then A will precede B in the MRO of all
1021 subclasses of C.
1022
1023 Monotonicity.
1024 The MRO of a class must be an extension without reordering of the
1025 MRO of each of its superclasses.
1026
1027 Extended Precedence Graph (EPG).
1028 Linearization is consistent if there is a path in the EPG from
1029 each class to all its successors in the linearization. See
1030 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001031 */
1032
Tim Petersea7f75d2002-12-07 21:39:16 +00001033static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001034tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001035 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +00001036 size = PyList_GET_SIZE(list);
1037
1038 for (j = whence+1; j < size; j++) {
1039 if (PyList_GET_ITEM(list, j) == o)
1040 return 1;
1041 }
1042 return 0;
1043}
1044
Guido van Rossum98f33732002-11-25 21:36:54 +00001045static PyObject *
1046class_name(PyObject *cls)
1047{
1048 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1049 if (name == NULL) {
1050 PyErr_Clear();
1051 Py_XDECREF(name);
1052 name = PyObject_Repr(cls);
1053 }
1054 if (name == NULL)
1055 return NULL;
1056 if (!PyString_Check(name)) {
1057 Py_DECREF(name);
1058 return NULL;
1059 }
1060 return name;
1061}
1062
1063static int
1064check_duplicates(PyObject *list)
1065{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001066 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001067 /* Let's use a quadratic time algorithm,
1068 assuming that the bases lists is short.
1069 */
1070 n = PyList_GET_SIZE(list);
1071 for (i = 0; i < n; i++) {
1072 PyObject *o = PyList_GET_ITEM(list, i);
1073 for (j = i + 1; j < n; j++) {
1074 if (PyList_GET_ITEM(list, j) == o) {
1075 o = class_name(o);
1076 PyErr_Format(PyExc_TypeError,
1077 "duplicate base class %s",
1078 o ? PyString_AS_STRING(o) : "?");
1079 Py_XDECREF(o);
1080 return -1;
1081 }
1082 }
1083 }
1084 return 0;
1085}
1086
1087/* Raise a TypeError for an MRO order disagreement.
1088
1089 It's hard to produce a good error message. In the absence of better
1090 insight into error reporting, report the classes that were candidates
1091 to be put next into the MRO. There is some conflict between the
1092 order in which they should be put in the MRO, but it's hard to
1093 diagnose what constraint can't be satisfied.
1094*/
1095
1096static void
1097set_mro_error(PyObject *to_merge, int *remain)
1098{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001099 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001100 char buf[1000];
1101 PyObject *k, *v;
1102 PyObject *set = PyDict_New();
Georg Brandl5c170fd2006-03-17 19:03:25 +00001103 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001104
1105 to_merge_size = PyList_GET_SIZE(to_merge);
1106 for (i = 0; i < to_merge_size; i++) {
1107 PyObject *L = PyList_GET_ITEM(to_merge, i);
1108 if (remain[i] < PyList_GET_SIZE(L)) {
1109 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Georg Brandl5c170fd2006-03-17 19:03:25 +00001110 if (PyDict_SetItem(set, c, Py_None) < 0) {
1111 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001112 return;
Georg Brandl5c170fd2006-03-17 19:03:25 +00001113 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001114 }
1115 }
1116 n = PyDict_Size(set);
1117
Raymond Hettingerf394df42003-04-06 19:13:41 +00001118 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1119consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001120 i = 0;
Skip Montanaro429433b2006-04-18 00:35:43 +00001121 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001122 PyObject *name = class_name(k);
1123 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1124 name ? PyString_AS_STRING(name) : "?");
1125 Py_XDECREF(name);
Skip Montanaro429433b2006-04-18 00:35:43 +00001126 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001127 buf[off++] = ',';
1128 buf[off] = '\0';
1129 }
1130 }
1131 PyErr_SetString(PyExc_TypeError, buf);
1132 Py_DECREF(set);
1133}
1134
Tim Petersea7f75d2002-12-07 21:39:16 +00001135static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001136pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001137 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001138 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001139 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001140
Guido van Rossum1f121312002-11-14 19:49:16 +00001141 to_merge_size = PyList_GET_SIZE(to_merge);
1142
Guido van Rossum98f33732002-11-25 21:36:54 +00001143 /* remain stores an index into each sublist of to_merge.
1144 remain[i] is the index of the next base in to_merge[i]
1145 that is not included in acc.
1146 */
Anthony Baxtera6286212006-04-11 07:42:36 +00001147 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001148 if (remain == NULL)
1149 return -1;
1150 for (i = 0; i < to_merge_size; i++)
1151 remain[i] = 0;
1152
1153 again:
1154 empty_cnt = 0;
1155 for (i = 0; i < to_merge_size; i++) {
1156 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001157
Guido van Rossum1f121312002-11-14 19:49:16 +00001158 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1159
1160 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1161 empty_cnt++;
1162 continue;
1163 }
1164
Guido van Rossum98f33732002-11-25 21:36:54 +00001165 /* Choose next candidate for MRO.
1166
1167 The input sequences alone can determine the choice.
1168 If not, choose the class which appears in the MRO
1169 of the earliest direct superclass of the new class.
1170 */
1171
Guido van Rossum1f121312002-11-14 19:49:16 +00001172 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1173 for (j = 0; j < to_merge_size; j++) {
1174 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001175 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001176 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001177 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001178 }
1179 ok = PyList_Append(acc, candidate);
1180 if (ok < 0) {
1181 PyMem_Free(remain);
1182 return -1;
1183 }
1184 for (j = 0; j < to_merge_size; j++) {
1185 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001186 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1187 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001188 remain[j]++;
1189 }
1190 }
1191 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001192 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001193 }
1194
Guido van Rossum98f33732002-11-25 21:36:54 +00001195 if (empty_cnt == to_merge_size) {
1196 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001197 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001198 }
1199 set_mro_error(to_merge, remain);
1200 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001201 return -1;
1202}
1203
Tim Peters6d6c1a32001-08-02 04:15:00 +00001204static PyObject *
1205mro_implementation(PyTypeObject *type)
1206{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001207 Py_ssize_t i, n;
1208 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001209 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001210 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001211
Guido van Rossum63517572002-06-18 16:44:57 +00001212 if(type->tp_dict == NULL) {
1213 if(PyType_Ready(type) < 0)
1214 return NULL;
1215 }
1216
Guido van Rossum98f33732002-11-25 21:36:54 +00001217 /* Find a superclass linearization that honors the constraints
1218 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001219 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001220
1221 to_merge is a list of lists, where each list is a superclass
1222 linearization implied by a base class. The last element of
1223 to_merge is the declared list of bases.
1224 */
1225
Tim Peters6d6c1a32001-08-02 04:15:00 +00001226 bases = type->tp_bases;
1227 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001228
1229 to_merge = PyList_New(n+1);
1230 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001231 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001232
Tim Peters6d6c1a32001-08-02 04:15:00 +00001233 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001234 PyObject *base = PyTuple_GET_ITEM(bases, i);
1235 PyObject *parentMRO;
1236 if (PyType_Check(base))
1237 parentMRO = PySequence_List(
1238 ((PyTypeObject*)base)->tp_mro);
1239 else
1240 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001241 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001242 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001243 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001244 }
1245
1246 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001247 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001248
1249 bases_aslist = PySequence_List(bases);
1250 if (bases_aslist == NULL) {
1251 Py_DECREF(to_merge);
1252 return NULL;
1253 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001254 /* This is just a basic sanity check. */
1255 if (check_duplicates(bases_aslist) < 0) {
1256 Py_DECREF(to_merge);
1257 Py_DECREF(bases_aslist);
1258 return NULL;
1259 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001260 PyList_SET_ITEM(to_merge, n, bases_aslist);
1261
1262 result = Py_BuildValue("[O]", (PyObject *)type);
1263 if (result == NULL) {
1264 Py_DECREF(to_merge);
1265 return NULL;
1266 }
1267
1268 ok = pmerge(result, to_merge);
1269 Py_DECREF(to_merge);
1270 if (ok < 0) {
1271 Py_DECREF(result);
1272 return NULL;
1273 }
1274
Tim Peters6d6c1a32001-08-02 04:15:00 +00001275 return result;
1276}
1277
1278static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001279mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001280{
1281 PyTypeObject *type = (PyTypeObject *)self;
1282
Tim Peters6d6c1a32001-08-02 04:15:00 +00001283 return mro_implementation(type);
1284}
1285
1286static int
1287mro_internal(PyTypeObject *type)
1288{
1289 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001290 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001291
1292 if (type->ob_type == &PyType_Type) {
1293 result = mro_implementation(type);
1294 }
1295 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001296 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001297 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001298 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001299 if (mro == NULL)
1300 return -1;
1301 result = PyObject_CallObject(mro, NULL);
1302 Py_DECREF(mro);
1303 }
1304 if (result == NULL)
1305 return -1;
1306 tuple = PySequence_Tuple(result);
1307 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001308 if (tuple == NULL)
1309 return -1;
1310 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001311 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001312 PyObject *cls;
1313 PyTypeObject *solid;
1314
1315 solid = solid_base(type);
1316
1317 len = PyTuple_GET_SIZE(tuple);
1318
1319 for (i = 0; i < len; i++) {
1320 PyTypeObject *t;
1321 cls = PyTuple_GET_ITEM(tuple, i);
1322 if (PyClass_Check(cls))
1323 continue;
1324 else if (!PyType_Check(cls)) {
1325 PyErr_Format(PyExc_TypeError,
1326 "mro() returned a non-class ('%.500s')",
1327 cls->ob_type->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001328 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001329 return -1;
1330 }
1331 t = (PyTypeObject*)cls;
1332 if (!PyType_IsSubtype(solid, solid_base(t))) {
1333 PyErr_Format(PyExc_TypeError,
1334 "mro() returned base with unsuitable layout ('%.500s')",
1335 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001336 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001337 return -1;
1338 }
1339 }
1340 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001341 type->tp_mro = tuple;
1342 return 0;
1343}
1344
1345
1346/* Calculate the best base amongst multiple base classes.
1347 This is the first one that's on the path to the "solid base". */
1348
1349static PyTypeObject *
1350best_base(PyObject *bases)
1351{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001352 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001353 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001354 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001355
1356 assert(PyTuple_Check(bases));
1357 n = PyTuple_GET_SIZE(bases);
1358 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001359 base = NULL;
1360 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001361 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001362 base_proto = PyTuple_GET_ITEM(bases, i);
1363 if (PyClass_Check(base_proto))
1364 continue;
1365 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001366 PyErr_SetString(
1367 PyExc_TypeError,
1368 "bases must be types");
1369 return NULL;
1370 }
Tim Petersa91e9642001-11-14 23:32:33 +00001371 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001372 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001373 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001374 return NULL;
1375 }
1376 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001377 if (winner == NULL) {
1378 winner = candidate;
1379 base = base_i;
1380 }
1381 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001382 ;
1383 else if (PyType_IsSubtype(candidate, winner)) {
1384 winner = candidate;
1385 base = base_i;
1386 }
1387 else {
1388 PyErr_SetString(
1389 PyExc_TypeError,
1390 "multiple bases have "
1391 "instance lay-out conflict");
1392 return NULL;
1393 }
1394 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001395 if (base == NULL)
1396 PyErr_SetString(PyExc_TypeError,
1397 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001398 return base;
1399}
1400
1401static int
1402extra_ivars(PyTypeObject *type, PyTypeObject *base)
1403{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001404 size_t t_size = type->tp_basicsize;
1405 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001406
Guido van Rossum9676b222001-08-17 20:32:36 +00001407 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001408 if (type->tp_itemsize || base->tp_itemsize) {
1409 /* If itemsize is involved, stricter rules */
1410 return t_size != b_size ||
1411 type->tp_itemsize != base->tp_itemsize;
1412 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001413 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1414 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1415 t_size -= sizeof(PyObject *);
1416 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1417 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1418 t_size -= sizeof(PyObject *);
1419
1420 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001421}
1422
1423static PyTypeObject *
1424solid_base(PyTypeObject *type)
1425{
1426 PyTypeObject *base;
1427
1428 if (type->tp_base)
1429 base = solid_base(type->tp_base);
1430 else
1431 base = &PyBaseObject_Type;
1432 if (extra_ivars(type, base))
1433 return type;
1434 else
1435 return base;
1436}
1437
Jeremy Hylton938ace62002-07-17 16:30:39 +00001438static void object_dealloc(PyObject *);
1439static int object_init(PyObject *, PyObject *, PyObject *);
1440static int update_slot(PyTypeObject *, PyObject *);
1441static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001442
1443static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001444subtype_dict(PyObject *obj, void *context)
1445{
1446 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1447 PyObject *dict;
1448
1449 if (dictptr == NULL) {
1450 PyErr_SetString(PyExc_AttributeError,
1451 "This object has no __dict__");
1452 return NULL;
1453 }
1454 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001455 if (dict == NULL)
1456 *dictptr = dict = PyDict_New();
1457 Py_XINCREF(dict);
1458 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001459}
1460
Guido van Rossum6661be32001-10-26 04:26:12 +00001461static int
1462subtype_setdict(PyObject *obj, PyObject *value, void *context)
1463{
1464 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1465 PyObject *dict;
1466
1467 if (dictptr == NULL) {
1468 PyErr_SetString(PyExc_AttributeError,
1469 "This object has no __dict__");
1470 return -1;
1471 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001472 if (value != NULL && !PyDict_Check(value)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001473 PyErr_Format(PyExc_TypeError,
1474 "__dict__ must be set to a dictionary, "
1475 "not a '%.200s'", value->ob_type->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001476 return -1;
1477 }
1478 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001479 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001480 *dictptr = value;
1481 Py_XDECREF(dict);
1482 return 0;
1483}
1484
Guido van Rossumad47da02002-08-12 19:05:44 +00001485static PyObject *
1486subtype_getweakref(PyObject *obj, void *context)
1487{
1488 PyObject **weaklistptr;
1489 PyObject *result;
1490
1491 if (obj->ob_type->tp_weaklistoffset == 0) {
1492 PyErr_SetString(PyExc_AttributeError,
1493 "This object has no __weaklist__");
1494 return NULL;
1495 }
1496 assert(obj->ob_type->tp_weaklistoffset > 0);
1497 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001498 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001499 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001500 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001501 if (*weaklistptr == NULL)
1502 result = Py_None;
1503 else
1504 result = *weaklistptr;
1505 Py_INCREF(result);
1506 return result;
1507}
1508
Guido van Rossum373c7412003-01-07 13:41:37 +00001509/* Three variants on the subtype_getsets list. */
1510
1511static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001512 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001513 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001514 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001515 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001516 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001517};
1518
Guido van Rossum373c7412003-01-07 13:41:37 +00001519static PyGetSetDef subtype_getsets_dict_only[] = {
1520 {"__dict__", subtype_dict, subtype_setdict,
1521 PyDoc_STR("dictionary for instance variables (if defined)")},
1522 {0}
1523};
1524
1525static PyGetSetDef subtype_getsets_weakref_only[] = {
1526 {"__weakref__", subtype_getweakref, NULL,
1527 PyDoc_STR("list of weak references to the object (if defined)")},
1528 {0}
1529};
1530
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001531static int
1532valid_identifier(PyObject *s)
1533{
Guido van Rossum03013a02002-07-16 14:30:28 +00001534 unsigned char *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001535 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001536
1537 if (!PyString_Check(s)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001538 PyErr_Format(PyExc_TypeError,
1539 "__slots__ items must be strings, not '%.200s'",
1540 s->ob_type->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001541 return 0;
1542 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001543 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001544 n = PyString_GET_SIZE(s);
1545 /* We must reject an empty name. As a hack, we bump the
1546 length to 1 so that the loop will balk on the trailing \0. */
1547 if (n == 0)
1548 n = 1;
1549 for (i = 0; i < n; i++, p++) {
1550 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1551 PyErr_SetString(PyExc_TypeError,
1552 "__slots__ must be identifiers");
1553 return 0;
1554 }
1555 }
1556 return 1;
1557}
1558
Martin v. Löwisd919a592002-10-14 21:07:28 +00001559#ifdef Py_USING_UNICODE
1560/* Replace Unicode objects in slots. */
1561
1562static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001563_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001564{
1565 PyObject *tmp = slots;
1566 PyObject *o, *o1;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001567 Py_ssize_t i;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001568 ssizessizeargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001569 for (i = 0; i < nslots; i++) {
1570 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1571 if (tmp == slots) {
1572 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1573 if (tmp == NULL)
1574 return NULL;
1575 }
1576 o1 = _PyUnicode_AsDefaultEncodedString
1577 (o, NULL);
1578 if (o1 == NULL) {
1579 Py_DECREF(tmp);
1580 return 0;
1581 }
1582 Py_INCREF(o1);
1583 Py_DECREF(o);
1584 PyTuple_SET_ITEM(tmp, i, o1);
1585 }
1586 }
1587 return tmp;
1588}
1589#endif
1590
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001591static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001592type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1593{
1594 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001595 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001596 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001597 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001598 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001599 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001600 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001601 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001602
Tim Peters3abca122001-10-27 19:37:48 +00001603 assert(args != NULL && PyTuple_Check(args));
1604 assert(kwds == NULL || PyDict_Check(kwds));
1605
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001606 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001607 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001608 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1609 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001610
1611 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1612 PyObject *x = PyTuple_GET_ITEM(args, 0);
1613 Py_INCREF(x->ob_type);
1614 return (PyObject *) x->ob_type;
1615 }
1616
1617 /* SF bug 475327 -- if that didn't trigger, we need 3
1618 arguments. but PyArg_ParseTupleAndKeywords below may give
1619 a msg saying type() needs exactly 3. */
1620 if (nargs + nkwds != 3) {
1621 PyErr_SetString(PyExc_TypeError,
1622 "type() takes 1 or 3 arguments");
1623 return NULL;
1624 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001625 }
1626
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001627 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001628 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1629 &name,
1630 &PyTuple_Type, &bases,
1631 &PyDict_Type, &dict))
1632 return NULL;
1633
1634 /* Determine the proper metatype to deal with this,
1635 and check for metatype conflicts while we're at it.
1636 Note that if some other metatype wins to contract,
1637 it's possible that its instances are not types. */
1638 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001639 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001640 for (i = 0; i < nbases; i++) {
1641 tmp = PyTuple_GET_ITEM(bases, i);
1642 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001643 if (tmptype == &PyClass_Type)
1644 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001645 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001646 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001647 if (PyType_IsSubtype(tmptype, winner)) {
1648 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001649 continue;
1650 }
1651 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001652 "metaclass conflict: "
1653 "the metaclass of a derived class "
1654 "must be a (non-strict) subclass "
1655 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001656 return NULL;
1657 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001658 if (winner != metatype) {
1659 if (winner->tp_new != type_new) /* Pass it to the winner */
1660 return winner->tp_new(winner, args, kwds);
1661 metatype = winner;
1662 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001663
1664 /* Adjust for empty tuple bases */
1665 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001666 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001667 if (bases == NULL)
1668 return NULL;
1669 nbases = 1;
1670 }
1671 else
1672 Py_INCREF(bases);
1673
1674 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1675
1676 /* Calculate best base, and check that all bases are type objects */
1677 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001678 if (base == NULL) {
1679 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001680 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001681 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001682 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1683 PyErr_Format(PyExc_TypeError,
1684 "type '%.100s' is not an acceptable base type",
1685 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001686 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001687 return NULL;
1688 }
1689
Tim Peters6d6c1a32001-08-02 04:15:00 +00001690 /* Check for a __slots__ sequence variable in dict, and count it */
1691 slots = PyDict_GetItemString(dict, "__slots__");
1692 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001693 add_dict = 0;
1694 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001695 may_add_dict = base->tp_dictoffset == 0;
1696 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1697 if (slots == NULL) {
1698 if (may_add_dict) {
1699 add_dict++;
1700 }
1701 if (may_add_weak) {
1702 add_weak++;
1703 }
1704 }
1705 else {
1706 /* Have slots */
1707
Tim Peters6d6c1a32001-08-02 04:15:00 +00001708 /* Make it into a tuple */
1709 if (PyString_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001710 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001711 else
1712 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001713 if (slots == NULL) {
1714 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001715 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001716 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001717 assert(PyTuple_Check(slots));
1718
1719 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001720 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001721 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001722 PyErr_Format(PyExc_TypeError,
1723 "nonempty __slots__ "
1724 "not supported for subtype of '%s'",
1725 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001726 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001727 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001728 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001729 return NULL;
1730 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001731
Martin v. Löwisd919a592002-10-14 21:07:28 +00001732#ifdef Py_USING_UNICODE
1733 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001734 if (tmp != slots) {
1735 Py_DECREF(slots);
1736 slots = tmp;
1737 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001738 if (!tmp)
1739 return NULL;
1740#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001741 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001742 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001743 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1744 char *s;
1745 if (!valid_identifier(tmp))
1746 goto bad_slots;
1747 assert(PyString_Check(tmp));
1748 s = PyString_AS_STRING(tmp);
1749 if (strcmp(s, "__dict__") == 0) {
1750 if (!may_add_dict || add_dict) {
1751 PyErr_SetString(PyExc_TypeError,
1752 "__dict__ slot disallowed: "
1753 "we already got one");
1754 goto bad_slots;
1755 }
1756 add_dict++;
1757 }
1758 if (strcmp(s, "__weakref__") == 0) {
1759 if (!may_add_weak || add_weak) {
1760 PyErr_SetString(PyExc_TypeError,
1761 "__weakref__ slot disallowed: "
1762 "either we already got one, "
1763 "or __itemsize__ != 0");
1764 goto bad_slots;
1765 }
1766 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001767 }
1768 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001769
Guido van Rossumad47da02002-08-12 19:05:44 +00001770 /* Copy slots into yet another tuple, demangling names */
1771 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001772 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001773 goto bad_slots;
1774 for (i = j = 0; i < nslots; i++) {
1775 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001776 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001777 s = PyString_AS_STRING(tmp);
1778 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1779 (add_weak && strcmp(s, "__weakref__") == 0))
1780 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001781 tmp =_Py_Mangle(name, tmp);
1782 if (!tmp)
1783 goto bad_slots;
Guido van Rossumad47da02002-08-12 19:05:44 +00001784 PyTuple_SET_ITEM(newslots, j, tmp);
1785 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001786 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001787 assert(j == nslots - add_dict - add_weak);
1788 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001789 Py_DECREF(slots);
1790 slots = newslots;
1791
Guido van Rossumad47da02002-08-12 19:05:44 +00001792 /* Secondary bases may provide weakrefs or dict */
1793 if (nbases > 1 &&
1794 ((may_add_dict && !add_dict) ||
1795 (may_add_weak && !add_weak))) {
1796 for (i = 0; i < nbases; i++) {
1797 tmp = PyTuple_GET_ITEM(bases, i);
1798 if (tmp == (PyObject *)base)
1799 continue; /* Skip primary base */
1800 if (PyClass_Check(tmp)) {
1801 /* Classic base class provides both */
1802 if (may_add_dict && !add_dict)
1803 add_dict++;
1804 if (may_add_weak && !add_weak)
1805 add_weak++;
1806 break;
1807 }
1808 assert(PyType_Check(tmp));
1809 tmptype = (PyTypeObject *)tmp;
1810 if (may_add_dict && !add_dict &&
1811 tmptype->tp_dictoffset != 0)
1812 add_dict++;
1813 if (may_add_weak && !add_weak &&
1814 tmptype->tp_weaklistoffset != 0)
1815 add_weak++;
1816 if (may_add_dict && !add_dict)
1817 continue;
1818 if (may_add_weak && !add_weak)
1819 continue;
1820 /* Nothing more to check */
1821 break;
1822 }
1823 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001824 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001825
1826 /* XXX From here until type is safely allocated,
1827 "return NULL" may leak slots! */
1828
1829 /* Allocate the type object */
1830 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001831 if (type == NULL) {
1832 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001833 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001834 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001835 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001836
1837 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001838 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001839 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00001840 et->ht_name = name;
1841 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001842
Guido van Rossumdc91b992001-08-08 22:26:22 +00001843 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001844 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1845 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001846 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1847 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001848
1849 /* It's a new-style number unless it specifically inherits any
1850 old-style numeric behavior */
1851 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1852 (base->tp_as_number == NULL))
1853 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1854
1855 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001856 type->tp_as_number = &et->as_number;
1857 type->tp_as_sequence = &et->as_sequence;
1858 type->tp_as_mapping = &et->as_mapping;
1859 type->tp_as_buffer = &et->as_buffer;
1860 type->tp_name = PyString_AS_STRING(name);
1861
1862 /* Set tp_base and tp_bases */
1863 type->tp_bases = bases;
1864 Py_INCREF(base);
1865 type->tp_base = base;
1866
Guido van Rossum687ae002001-10-15 22:03:32 +00001867 /* Initialize tp_dict from passed-in dict */
1868 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001869 if (dict == NULL) {
1870 Py_DECREF(type);
1871 return NULL;
1872 }
1873
Guido van Rossumc3542212001-08-16 09:18:56 +00001874 /* Set __module__ in the dict */
1875 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1876 tmp = PyEval_GetGlobals();
1877 if (tmp != NULL) {
1878 tmp = PyDict_GetItemString(tmp, "__name__");
1879 if (tmp != NULL) {
1880 if (PyDict_SetItemString(dict, "__module__",
1881 tmp) < 0)
1882 return NULL;
1883 }
1884 }
1885 }
1886
Tim Peters2f93e282001-10-04 05:27:00 +00001887 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001888 and is a string. The __doc__ accessor will first look for tp_doc;
1889 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001890 */
1891 {
1892 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1893 if (doc != NULL && PyString_Check(doc)) {
1894 const size_t n = (size_t)PyString_GET_SIZE(doc);
Anthony Baxtera6286212006-04-11 07:42:36 +00001895 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001896 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00001897 Py_DECREF(type);
1898 return NULL;
1899 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001900 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
1901 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00001902 }
1903 }
1904
Tim Peters6d6c1a32001-08-02 04:15:00 +00001905 /* Special-case __new__: if it's a plain function,
1906 make it a static function */
1907 tmp = PyDict_GetItemString(dict, "__new__");
1908 if (tmp != NULL && PyFunction_Check(tmp)) {
1909 tmp = PyStaticMethod_New(tmp);
1910 if (tmp == NULL) {
1911 Py_DECREF(type);
1912 return NULL;
1913 }
1914 PyDict_SetItemString(dict, "__new__", tmp);
1915 Py_DECREF(tmp);
1916 }
1917
1918 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001919 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001920 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001921 if (slots != NULL) {
1922 for (i = 0; i < nslots; i++, mp++) {
1923 mp->name = PyString_AS_STRING(
1924 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001925 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001926 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001927 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001928 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001929 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001930 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001931 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001932 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001933 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001934 slotoffset += sizeof(PyObject *);
1935 }
1936 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001937 if (add_dict) {
1938 if (base->tp_itemsize)
1939 type->tp_dictoffset = -(long)sizeof(PyObject *);
1940 else
1941 type->tp_dictoffset = slotoffset;
1942 slotoffset += sizeof(PyObject *);
1943 }
1944 if (add_weak) {
1945 assert(!base->tp_itemsize);
1946 type->tp_weaklistoffset = slotoffset;
1947 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001948 }
1949 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001950 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001951 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001952
1953 if (type->tp_weaklistoffset && type->tp_dictoffset)
1954 type->tp_getset = subtype_getsets_full;
1955 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1956 type->tp_getset = subtype_getsets_weakref_only;
1957 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1958 type->tp_getset = subtype_getsets_dict_only;
1959 else
1960 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001961
1962 /* Special case some slots */
1963 if (type->tp_dictoffset != 0 || nslots > 0) {
1964 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1965 type->tp_getattro = PyObject_GenericGetAttr;
1966 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1967 type->tp_setattro = PyObject_GenericSetAttr;
1968 }
1969 type->tp_dealloc = subtype_dealloc;
1970
Guido van Rossum9475a232001-10-05 20:51:39 +00001971 /* Enable GC unless there are really no instance variables possible */
1972 if (!(type->tp_basicsize == sizeof(PyObject) &&
1973 type->tp_itemsize == 0))
1974 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1975
Tim Peters6d6c1a32001-08-02 04:15:00 +00001976 /* Always override allocation strategy to use regular heap */
1977 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001978 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001979 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001980 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001981 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001982 }
1983 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001984 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001985
1986 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001987 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001988 Py_DECREF(type);
1989 return NULL;
1990 }
1991
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001992 /* Put the proper slots in place */
1993 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001994
Tim Peters6d6c1a32001-08-02 04:15:00 +00001995 return (PyObject *)type;
1996}
1997
1998/* Internal API to look for a name through the MRO.
1999 This returns a borrowed reference, and doesn't set an exception! */
2000PyObject *
2001_PyType_Lookup(PyTypeObject *type, PyObject *name)
2002{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002003 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002004 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002005
Guido van Rossum687ae002001-10-15 22:03:32 +00002006 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002007 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002008
2009 /* If mro is NULL, the type is either not yet initialized
2010 by PyType_Ready(), or already cleared by type_clear().
2011 Either way the safest thing to do is to return NULL. */
2012 if (mro == NULL)
2013 return NULL;
2014
Tim Peters6d6c1a32001-08-02 04:15:00 +00002015 assert(PyTuple_Check(mro));
2016 n = PyTuple_GET_SIZE(mro);
2017 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002018 base = PyTuple_GET_ITEM(mro, i);
2019 if (PyClass_Check(base))
2020 dict = ((PyClassObject *)base)->cl_dict;
2021 else {
2022 assert(PyType_Check(base));
2023 dict = ((PyTypeObject *)base)->tp_dict;
2024 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002025 assert(dict && PyDict_Check(dict));
2026 res = PyDict_GetItem(dict, name);
2027 if (res != NULL)
2028 return res;
2029 }
2030 return NULL;
2031}
2032
2033/* This is similar to PyObject_GenericGetAttr(),
2034 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2035static PyObject *
2036type_getattro(PyTypeObject *type, PyObject *name)
2037{
2038 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002039 PyObject *meta_attribute, *attribute;
2040 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002041
2042 /* Initialize this type (we'll assume the metatype is initialized) */
2043 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002044 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002045 return NULL;
2046 }
2047
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002048 /* No readable descriptor found yet */
2049 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002050
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002051 /* Look for the attribute in the metatype */
2052 meta_attribute = _PyType_Lookup(metatype, name);
2053
2054 if (meta_attribute != NULL) {
2055 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002056
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002057 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2058 /* Data descriptors implement tp_descr_set to intercept
2059 * writes. Assume the attribute is not overridden in
2060 * type's tp_dict (and bases): call the descriptor now.
2061 */
2062 return meta_get(meta_attribute, (PyObject *)type,
2063 (PyObject *)metatype);
2064 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002065 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002066 }
2067
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002068 /* No data descriptor found on metatype. Look in tp_dict of this
2069 * type and its bases */
2070 attribute = _PyType_Lookup(type, name);
2071 if (attribute != NULL) {
2072 /* Implement descriptor functionality, if any */
2073 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002074
2075 Py_XDECREF(meta_attribute);
2076
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002077 if (local_get != NULL) {
2078 /* NULL 2nd argument indicates the descriptor was
2079 * found on the target object itself (or a base) */
2080 return local_get(attribute, (PyObject *)NULL,
2081 (PyObject *)type);
2082 }
Tim Peters34592512002-07-11 06:23:50 +00002083
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002084 Py_INCREF(attribute);
2085 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002086 }
2087
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002088 /* No attribute found in local __dict__ (or bases): use the
2089 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002090 if (meta_get != NULL) {
2091 PyObject *res;
2092 res = meta_get(meta_attribute, (PyObject *)type,
2093 (PyObject *)metatype);
2094 Py_DECREF(meta_attribute);
2095 return res;
2096 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002097
2098 /* If an ordinary attribute was found on the metatype, return it now */
2099 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002100 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002101 }
2102
2103 /* Give up */
2104 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002105 "type object '%.50s' has no attribute '%.400s'",
2106 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002107 return NULL;
2108}
2109
2110static int
2111type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2112{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002113 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2114 PyErr_Format(
2115 PyExc_TypeError,
2116 "can't set attributes of built-in/extension type '%s'",
2117 type->tp_name);
2118 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002119 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002120 /* XXX Example of how I expect this to be used...
2121 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2122 return -1;
2123 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002124 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2125 return -1;
2126 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002127}
2128
2129static void
2130type_dealloc(PyTypeObject *type)
2131{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002132 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002133
2134 /* Assert this is a heap-allocated type object */
2135 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002136 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002137 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002138 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002139 Py_XDECREF(type->tp_base);
2140 Py_XDECREF(type->tp_dict);
2141 Py_XDECREF(type->tp_bases);
2142 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002143 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002144 Py_XDECREF(type->tp_subclasses);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002145 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2146 * of most other objects. It's okay to cast it to char *.
2147 */
2148 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002149 Py_XDECREF(et->ht_name);
2150 Py_XDECREF(et->ht_slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002151 type->ob_type->tp_free((PyObject *)type);
2152}
2153
Guido van Rossum1c450732001-10-08 15:18:27 +00002154static PyObject *
2155type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2156{
2157 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002158 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002159
2160 list = PyList_New(0);
2161 if (list == NULL)
2162 return NULL;
2163 raw = type->tp_subclasses;
2164 if (raw == NULL)
2165 return list;
2166 assert(PyList_Check(raw));
2167 n = PyList_GET_SIZE(raw);
2168 for (i = 0; i < n; i++) {
2169 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002170 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002171 ref = PyWeakref_GET_OBJECT(ref);
2172 if (ref != Py_None) {
2173 if (PyList_Append(list, ref) < 0) {
2174 Py_DECREF(list);
2175 return NULL;
2176 }
2177 }
2178 }
2179 return list;
2180}
2181
Tim Peters6d6c1a32001-08-02 04:15:00 +00002182static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002183 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002184 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002185 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002186 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002187 {0}
2188};
2189
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002190PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002191"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002192"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002193
Guido van Rossum048eb752001-10-02 21:24:57 +00002194static int
2195type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2196{
Guido van Rossuma3862092002-06-10 15:24:42 +00002197 /* Because of type_is_gc(), the collector only calls this
2198 for heaptypes. */
2199 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002200
Thomas Woutersc6e55062006-04-15 21:47:09 +00002201 Py_VISIT(type->tp_dict);
2202 Py_VISIT(type->tp_cache);
2203 Py_VISIT(type->tp_mro);
2204 Py_VISIT(type->tp_bases);
2205 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002206
2207 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002208 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002209 in cycles; tp_subclasses is a list of weak references,
2210 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002211
Guido van Rossum048eb752001-10-02 21:24:57 +00002212 return 0;
2213}
2214
2215static int
2216type_clear(PyTypeObject *type)
2217{
Guido van Rossuma3862092002-06-10 15:24:42 +00002218 /* Because of type_is_gc(), the collector only calls this
2219 for heaptypes. */
2220 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002221
Guido van Rossuma3862092002-06-10 15:24:42 +00002222 /* The only field we need to clear is tp_mro, which is part of a
2223 hard cycle (its first element is the class itself) that won't
2224 be broken otherwise (it's a tuple and tuples don't have a
2225 tp_clear handler). None of the other fields need to be
2226 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002227
Guido van Rossuma3862092002-06-10 15:24:42 +00002228 tp_dict:
2229 It is a dict, so the collector will call its tp_clear.
2230
2231 tp_cache:
2232 Not used; if it were, it would be a dict.
2233
2234 tp_bases, tp_base:
2235 If these are involved in a cycle, there must be at least
2236 one other, mutable object in the cycle, e.g. a base
2237 class's dict; the cycle will be broken that way.
2238
2239 tp_subclasses:
2240 A list of weak references can't be part of a cycle; and
2241 lists have their own tp_clear.
2242
Guido van Rossume5c691a2003-03-07 15:13:17 +00002243 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002244 A tuple of strings can't be part of a cycle.
2245 */
2246
Thomas Woutersedf17d82006-04-15 17:28:34 +00002247 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002248
2249 return 0;
2250}
2251
2252static int
2253type_is_gc(PyTypeObject *type)
2254{
2255 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2256}
2257
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002258PyTypeObject PyType_Type = {
2259 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002260 0, /* ob_size */
2261 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002262 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002263 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002264 (destructor)type_dealloc, /* tp_dealloc */
2265 0, /* tp_print */
2266 0, /* tp_getattr */
2267 0, /* tp_setattr */
2268 type_compare, /* tp_compare */
2269 (reprfunc)type_repr, /* tp_repr */
2270 0, /* tp_as_number */
2271 0, /* tp_as_sequence */
2272 0, /* tp_as_mapping */
2273 (hashfunc)_Py_HashPointer, /* tp_hash */
2274 (ternaryfunc)type_call, /* tp_call */
2275 0, /* tp_str */
2276 (getattrofunc)type_getattro, /* tp_getattro */
2277 (setattrofunc)type_setattro, /* tp_setattro */
2278 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002279 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2280 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002281 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002282 (traverseproc)type_traverse, /* tp_traverse */
2283 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002284 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002285 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002286 0, /* tp_iter */
2287 0, /* tp_iternext */
2288 type_methods, /* tp_methods */
2289 type_members, /* tp_members */
2290 type_getsets, /* tp_getset */
2291 0, /* tp_base */
2292 0, /* tp_dict */
2293 0, /* tp_descr_get */
2294 0, /* tp_descr_set */
2295 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2296 0, /* tp_init */
2297 0, /* tp_alloc */
2298 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002299 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002300 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002301};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002302
2303
2304/* The base type of all types (eventually)... except itself. */
2305
2306static int
2307object_init(PyObject *self, PyObject *args, PyObject *kwds)
2308{
2309 return 0;
2310}
2311
Guido van Rossum298e4212003-02-13 16:30:16 +00002312/* If we don't have a tp_new for a new-style class, new will use this one.
2313 Therefore this should take no arguments/keywords. However, this new may
2314 also be inherited by objects that define a tp_init but no tp_new. These
2315 objects WILL pass argumets to tp_new, because it gets the same args as
2316 tp_init. So only allow arguments if we aren't using the default init, in
2317 which case we expect init to handle argument parsing. */
2318static PyObject *
2319object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2320{
2321 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2322 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2323 PyErr_SetString(PyExc_TypeError,
2324 "default __new__ takes no parameters");
2325 return NULL;
2326 }
2327 return type->tp_alloc(type, 0);
2328}
2329
Tim Peters6d6c1a32001-08-02 04:15:00 +00002330static void
2331object_dealloc(PyObject *self)
2332{
2333 self->ob_type->tp_free(self);
2334}
2335
Guido van Rossum8e248182001-08-12 05:17:56 +00002336static PyObject *
2337object_repr(PyObject *self)
2338{
Guido van Rossum76e69632001-08-16 18:52:43 +00002339 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002340 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002341
Guido van Rossum76e69632001-08-16 18:52:43 +00002342 type = self->ob_type;
2343 mod = type_module(type, NULL);
2344 if (mod == NULL)
2345 PyErr_Clear();
2346 else if (!PyString_Check(mod)) {
2347 Py_DECREF(mod);
2348 mod = NULL;
2349 }
2350 name = type_name(type, NULL);
2351 if (name == NULL)
2352 return NULL;
2353 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002354 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002355 PyString_AS_STRING(mod),
2356 PyString_AS_STRING(name),
2357 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002358 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002359 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002360 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002361 Py_XDECREF(mod);
2362 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002363 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002364}
2365
Guido van Rossumb8f63662001-08-15 23:57:02 +00002366static PyObject *
2367object_str(PyObject *self)
2368{
2369 unaryfunc f;
2370
2371 f = self->ob_type->tp_repr;
2372 if (f == NULL)
2373 f = object_repr;
2374 return f(self);
2375}
2376
Guido van Rossum8e248182001-08-12 05:17:56 +00002377static long
2378object_hash(PyObject *self)
2379{
2380 return _Py_HashPointer(self);
2381}
Guido van Rossum8e248182001-08-12 05:17:56 +00002382
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002383static PyObject *
2384object_get_class(PyObject *self, void *closure)
2385{
2386 Py_INCREF(self->ob_type);
2387 return (PyObject *)(self->ob_type);
2388}
2389
2390static int
2391equiv_structs(PyTypeObject *a, PyTypeObject *b)
2392{
2393 return a == b ||
2394 (a != NULL &&
2395 b != NULL &&
2396 a->tp_basicsize == b->tp_basicsize &&
2397 a->tp_itemsize == b->tp_itemsize &&
2398 a->tp_dictoffset == b->tp_dictoffset &&
2399 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2400 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2401 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2402}
2403
2404static int
2405same_slots_added(PyTypeObject *a, PyTypeObject *b)
2406{
2407 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002408 Py_ssize_t size;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002409
2410 if (base != b->tp_base)
2411 return 0;
2412 if (equiv_structs(a, base) && equiv_structs(b, base))
2413 return 1;
2414 size = base->tp_basicsize;
2415 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2416 size += sizeof(PyObject *);
2417 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2418 size += sizeof(PyObject *);
2419 return size == a->tp_basicsize && size == b->tp_basicsize;
2420}
2421
2422static int
Anthony Baxtera6286212006-04-11 07:42:36 +00002423compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002424{
2425 PyTypeObject *newbase, *oldbase;
2426
Anthony Baxtera6286212006-04-11 07:42:36 +00002427 if (newto->tp_dealloc != oldto->tp_dealloc ||
2428 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002429 {
2430 PyErr_Format(PyExc_TypeError,
2431 "%s assignment: "
2432 "'%s' deallocator differs from '%s'",
2433 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002434 newto->tp_name,
2435 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002436 return 0;
2437 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002438 newbase = newto;
2439 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002440 while (equiv_structs(newbase, newbase->tp_base))
2441 newbase = newbase->tp_base;
2442 while (equiv_structs(oldbase, oldbase->tp_base))
2443 oldbase = oldbase->tp_base;
2444 if (newbase != oldbase &&
2445 (newbase->tp_base != oldbase->tp_base ||
2446 !same_slots_added(newbase, oldbase))) {
2447 PyErr_Format(PyExc_TypeError,
2448 "%s assignment: "
2449 "'%s' object layout differs from '%s'",
2450 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002451 newto->tp_name,
2452 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002453 return 0;
2454 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002455
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002456 return 1;
2457}
2458
2459static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002460object_set_class(PyObject *self, PyObject *value, void *closure)
2461{
Anthony Baxtera6286212006-04-11 07:42:36 +00002462 PyTypeObject *oldto = self->ob_type;
2463 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002464
Guido van Rossumb6b89422002-04-15 01:03:30 +00002465 if (value == NULL) {
2466 PyErr_SetString(PyExc_TypeError,
2467 "can't delete __class__ attribute");
2468 return -1;
2469 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002470 if (!PyType_Check(value)) {
2471 PyErr_Format(PyExc_TypeError,
2472 "__class__ must be set to new-style class, not '%s' object",
2473 value->ob_type->tp_name);
2474 return -1;
2475 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002476 newto = (PyTypeObject *)value;
2477 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2478 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002479 {
2480 PyErr_Format(PyExc_TypeError,
2481 "__class__ assignment: only for heap types");
2482 return -1;
2483 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002484 if (compatible_for_assignment(newto, oldto, "__class__")) {
2485 Py_INCREF(newto);
2486 self->ob_type = newto;
2487 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002488 return 0;
2489 }
2490 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002491 return -1;
2492 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002493}
2494
2495static PyGetSetDef object_getsets[] = {
2496 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002497 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002498 {0}
2499};
2500
Guido van Rossumc53f0092003-02-18 22:05:12 +00002501
Guido van Rossum036f9992003-02-21 22:02:54 +00002502/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2503 We fall back to helpers in copy_reg for:
2504 - pickle protocols < 2
2505 - calculating the list of slot names (done only once per class)
2506 - the __newobj__ function (which is used as a token but never called)
2507*/
2508
2509static PyObject *
2510import_copy_reg(void)
2511{
2512 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002513
2514 if (!copy_reg_str) {
2515 copy_reg_str = PyString_InternFromString("copy_reg");
2516 if (copy_reg_str == NULL)
2517 return NULL;
2518 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002519
2520 return PyImport_Import(copy_reg_str);
2521}
2522
2523static PyObject *
2524slotnames(PyObject *cls)
2525{
2526 PyObject *clsdict;
2527 PyObject *copy_reg;
2528 PyObject *slotnames;
2529
2530 if (!PyType_Check(cls)) {
2531 Py_INCREF(Py_None);
2532 return Py_None;
2533 }
2534
2535 clsdict = ((PyTypeObject *)cls)->tp_dict;
2536 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002537 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002538 Py_INCREF(slotnames);
2539 return slotnames;
2540 }
2541
2542 copy_reg = import_copy_reg();
2543 if (copy_reg == NULL)
2544 return NULL;
2545
2546 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2547 Py_DECREF(copy_reg);
2548 if (slotnames != NULL &&
2549 slotnames != Py_None &&
2550 !PyList_Check(slotnames))
2551 {
2552 PyErr_SetString(PyExc_TypeError,
2553 "copy_reg._slotnames didn't return a list or None");
2554 Py_DECREF(slotnames);
2555 slotnames = NULL;
2556 }
2557
2558 return slotnames;
2559}
2560
2561static PyObject *
2562reduce_2(PyObject *obj)
2563{
2564 PyObject *cls, *getnewargs;
2565 PyObject *args = NULL, *args2 = NULL;
2566 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2567 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2568 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002569 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00002570
2571 cls = PyObject_GetAttrString(obj, "__class__");
2572 if (cls == NULL)
2573 return NULL;
2574
2575 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2576 if (getnewargs != NULL) {
2577 args = PyObject_CallObject(getnewargs, NULL);
2578 Py_DECREF(getnewargs);
2579 if (args != NULL && !PyTuple_Check(args)) {
Georg Brandlccff7852006-06-18 22:17:29 +00002580 PyErr_Format(PyExc_TypeError,
2581 "__getnewargs__ should return a tuple, "
2582 "not '%.200s'", args->ob_type->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00002583 goto end;
2584 }
2585 }
2586 else {
2587 PyErr_Clear();
2588 args = PyTuple_New(0);
2589 }
2590 if (args == NULL)
2591 goto end;
2592
2593 getstate = PyObject_GetAttrString(obj, "__getstate__");
2594 if (getstate != NULL) {
2595 state = PyObject_CallObject(getstate, NULL);
2596 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002597 if (state == NULL)
2598 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002599 }
2600 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002601 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002602 state = PyObject_GetAttrString(obj, "__dict__");
2603 if (state == NULL) {
2604 PyErr_Clear();
2605 state = Py_None;
2606 Py_INCREF(state);
2607 }
2608 names = slotnames(cls);
2609 if (names == NULL)
2610 goto end;
2611 if (names != Py_None) {
2612 assert(PyList_Check(names));
2613 slots = PyDict_New();
2614 if (slots == NULL)
2615 goto end;
2616 n = 0;
2617 /* Can't pre-compute the list size; the list
2618 is stored on the class so accessible to other
2619 threads, which may be run by DECREF */
2620 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2621 PyObject *name, *value;
2622 name = PyList_GET_ITEM(names, i);
2623 value = PyObject_GetAttr(obj, name);
2624 if (value == NULL)
2625 PyErr_Clear();
2626 else {
2627 int err = PyDict_SetItem(slots, name,
2628 value);
2629 Py_DECREF(value);
2630 if (err)
2631 goto end;
2632 n++;
2633 }
2634 }
2635 if (n) {
2636 state = Py_BuildValue("(NO)", state, slots);
2637 if (state == NULL)
2638 goto end;
2639 }
2640 }
2641 }
2642
2643 if (!PyList_Check(obj)) {
2644 listitems = Py_None;
2645 Py_INCREF(listitems);
2646 }
2647 else {
2648 listitems = PyObject_GetIter(obj);
2649 if (listitems == NULL)
2650 goto end;
2651 }
2652
2653 if (!PyDict_Check(obj)) {
2654 dictitems = Py_None;
2655 Py_INCREF(dictitems);
2656 }
2657 else {
2658 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2659 if (dictitems == NULL)
2660 goto end;
2661 }
2662
2663 copy_reg = import_copy_reg();
2664 if (copy_reg == NULL)
2665 goto end;
2666 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2667 if (newobj == NULL)
2668 goto end;
2669
2670 n = PyTuple_GET_SIZE(args);
2671 args2 = PyTuple_New(n+1);
2672 if (args2 == NULL)
2673 goto end;
2674 PyTuple_SET_ITEM(args2, 0, cls);
2675 cls = NULL;
2676 for (i = 0; i < n; i++) {
2677 PyObject *v = PyTuple_GET_ITEM(args, i);
2678 Py_INCREF(v);
2679 PyTuple_SET_ITEM(args2, i+1, v);
2680 }
2681
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002682 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002683
2684 end:
2685 Py_XDECREF(cls);
2686 Py_XDECREF(args);
2687 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002688 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002689 Py_XDECREF(state);
2690 Py_XDECREF(names);
2691 Py_XDECREF(listitems);
2692 Py_XDECREF(dictitems);
2693 Py_XDECREF(copy_reg);
2694 Py_XDECREF(newobj);
2695 return res;
2696}
2697
2698static PyObject *
2699object_reduce_ex(PyObject *self, PyObject *args)
2700{
2701 /* Call copy_reg._reduce_ex(self, proto) */
2702 PyObject *reduce, *copy_reg, *res;
2703 int proto = 0;
2704
2705 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2706 return NULL;
2707
2708 reduce = PyObject_GetAttrString(self, "__reduce__");
2709 if (reduce == NULL)
2710 PyErr_Clear();
2711 else {
2712 PyObject *cls, *clsreduce, *objreduce;
2713 int override;
2714 cls = PyObject_GetAttrString(self, "__class__");
2715 if (cls == NULL) {
2716 Py_DECREF(reduce);
2717 return NULL;
2718 }
2719 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2720 Py_DECREF(cls);
2721 if (clsreduce == NULL) {
2722 Py_DECREF(reduce);
2723 return NULL;
2724 }
2725 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2726 "__reduce__");
2727 override = (clsreduce != objreduce);
2728 Py_DECREF(clsreduce);
2729 if (override) {
2730 res = PyObject_CallObject(reduce, NULL);
2731 Py_DECREF(reduce);
2732 return res;
2733 }
2734 else
2735 Py_DECREF(reduce);
2736 }
2737
2738 if (proto >= 2)
2739 return reduce_2(self);
2740
2741 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002742 if (!copy_reg)
2743 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002744
Guido van Rossumc53f0092003-02-18 22:05:12 +00002745 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002746 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002747
Guido van Rossum3926a632001-09-25 16:25:58 +00002748 return res;
2749}
2750
2751static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002752 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2753 PyDoc_STR("helper for pickle")},
2754 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002755 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002756 {0}
2757};
2758
Guido van Rossum036f9992003-02-21 22:02:54 +00002759
Tim Peters6d6c1a32001-08-02 04:15:00 +00002760PyTypeObject PyBaseObject_Type = {
2761 PyObject_HEAD_INIT(&PyType_Type)
2762 0, /* ob_size */
2763 "object", /* tp_name */
2764 sizeof(PyObject), /* tp_basicsize */
2765 0, /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00002766 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002767 0, /* tp_print */
2768 0, /* tp_getattr */
2769 0, /* tp_setattr */
2770 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002771 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002772 0, /* tp_as_number */
2773 0, /* tp_as_sequence */
2774 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002775 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002776 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002777 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002778 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002779 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002780 0, /* tp_as_buffer */
2781 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002782 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002783 0, /* tp_traverse */
2784 0, /* tp_clear */
2785 0, /* tp_richcompare */
2786 0, /* tp_weaklistoffset */
2787 0, /* tp_iter */
2788 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002789 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002790 0, /* tp_members */
2791 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002792 0, /* tp_base */
2793 0, /* tp_dict */
2794 0, /* tp_descr_get */
2795 0, /* tp_descr_set */
2796 0, /* tp_dictoffset */
2797 object_init, /* tp_init */
2798 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002799 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002800 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002801};
2802
2803
2804/* Initialize the __dict__ in a type object */
2805
2806static int
2807add_methods(PyTypeObject *type, PyMethodDef *meth)
2808{
Guido van Rossum687ae002001-10-15 22:03:32 +00002809 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002810
2811 for (; meth->ml_name != NULL; meth++) {
2812 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002813 if (PyDict_GetItemString(dict, meth->ml_name) &&
2814 !(meth->ml_flags & METH_COEXIST))
2815 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002816 if (meth->ml_flags & METH_CLASS) {
2817 if (meth->ml_flags & METH_STATIC) {
2818 PyErr_SetString(PyExc_ValueError,
2819 "method cannot be both class and static");
2820 return -1;
2821 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002822 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002823 }
2824 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002825 PyObject *cfunc = PyCFunction_New(meth, NULL);
2826 if (cfunc == NULL)
2827 return -1;
2828 descr = PyStaticMethod_New(cfunc);
2829 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002830 }
2831 else {
2832 descr = PyDescr_NewMethod(type, meth);
2833 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002834 if (descr == NULL)
2835 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002836 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002837 return -1;
2838 Py_DECREF(descr);
2839 }
2840 return 0;
2841}
2842
2843static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002844add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002845{
Guido van Rossum687ae002001-10-15 22:03:32 +00002846 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002847
2848 for (; memb->name != NULL; memb++) {
2849 PyObject *descr;
2850 if (PyDict_GetItemString(dict, memb->name))
2851 continue;
2852 descr = PyDescr_NewMember(type, memb);
2853 if (descr == NULL)
2854 return -1;
2855 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2856 return -1;
2857 Py_DECREF(descr);
2858 }
2859 return 0;
2860}
2861
2862static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002863add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002864{
Guido van Rossum687ae002001-10-15 22:03:32 +00002865 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002866
2867 for (; gsp->name != NULL; gsp++) {
2868 PyObject *descr;
2869 if (PyDict_GetItemString(dict, gsp->name))
2870 continue;
2871 descr = PyDescr_NewGetSet(type, gsp);
2872
2873 if (descr == NULL)
2874 return -1;
2875 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2876 return -1;
2877 Py_DECREF(descr);
2878 }
2879 return 0;
2880}
2881
Guido van Rossum13d52f02001-08-10 21:24:08 +00002882static void
2883inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002884{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002885 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002886
Guido van Rossum13d52f02001-08-10 21:24:08 +00002887 /* Special flag magic */
2888 if (!type->tp_as_buffer && base->tp_as_buffer) {
2889 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2890 type->tp_flags |=
2891 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2892 }
2893 if (!type->tp_as_sequence && base->tp_as_sequence) {
2894 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2895 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2896 }
2897 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2898 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2899 if ((!type->tp_as_number && base->tp_as_number) ||
2900 (!type->tp_as_sequence && base->tp_as_sequence)) {
2901 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2902 if (!type->tp_as_number && !type->tp_as_sequence) {
2903 type->tp_flags |= base->tp_flags &
2904 Py_TPFLAGS_HAVE_INPLACEOPS;
2905 }
2906 }
2907 /* Wow */
2908 }
2909 if (!type->tp_as_number && base->tp_as_number) {
2910 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2911 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2912 }
2913
2914 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002915 oldsize = base->tp_basicsize;
2916 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2917 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2918 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002919 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2920 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002921 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002922 if (type->tp_traverse == NULL)
2923 type->tp_traverse = base->tp_traverse;
2924 if (type->tp_clear == NULL)
2925 type->tp_clear = base->tp_clear;
2926 }
2927 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002928 /* The condition below could use some explanation.
2929 It appears that tp_new is not inherited for static types
2930 whose base class is 'object'; this seems to be a precaution
2931 so that old extension types don't suddenly become
2932 callable (object.__new__ wouldn't insure the invariants
2933 that the extension type's own factory function ensures).
2934 Heap types, of course, are under our control, so they do
2935 inherit tp_new; static extension types that specify some
2936 other built-in type as the default are considered
2937 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002938 if (base != &PyBaseObject_Type ||
2939 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2940 if (type->tp_new == NULL)
2941 type->tp_new = base->tp_new;
2942 }
2943 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002944 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002945
2946 /* Copy other non-function slots */
2947
2948#undef COPYVAL
2949#define COPYVAL(SLOT) \
2950 if (type->SLOT == 0) type->SLOT = base->SLOT
2951
2952 COPYVAL(tp_itemsize);
2953 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2954 COPYVAL(tp_weaklistoffset);
2955 }
2956 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2957 COPYVAL(tp_dictoffset);
2958 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002959}
2960
2961static void
2962inherit_slots(PyTypeObject *type, PyTypeObject *base)
2963{
2964 PyTypeObject *basebase;
2965
2966#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002967#undef COPYSLOT
2968#undef COPYNUM
2969#undef COPYSEQ
2970#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002971#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002972
2973#define SLOTDEFINED(SLOT) \
2974 (base->SLOT != 0 && \
2975 (basebase == NULL || base->SLOT != basebase->SLOT))
2976
Tim Peters6d6c1a32001-08-02 04:15:00 +00002977#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002978 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002979
2980#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2981#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2982#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002983#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002984
Guido van Rossum13d52f02001-08-10 21:24:08 +00002985 /* This won't inherit indirect slots (from tp_as_number etc.)
2986 if type doesn't provide the space. */
2987
2988 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2989 basebase = base->tp_base;
2990 if (basebase->tp_as_number == NULL)
2991 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002992 COPYNUM(nb_add);
2993 COPYNUM(nb_subtract);
2994 COPYNUM(nb_multiply);
2995 COPYNUM(nb_divide);
2996 COPYNUM(nb_remainder);
2997 COPYNUM(nb_divmod);
2998 COPYNUM(nb_power);
2999 COPYNUM(nb_negative);
3000 COPYNUM(nb_positive);
3001 COPYNUM(nb_absolute);
3002 COPYNUM(nb_nonzero);
3003 COPYNUM(nb_invert);
3004 COPYNUM(nb_lshift);
3005 COPYNUM(nb_rshift);
3006 COPYNUM(nb_and);
3007 COPYNUM(nb_xor);
3008 COPYNUM(nb_or);
3009 COPYNUM(nb_coerce);
3010 COPYNUM(nb_int);
3011 COPYNUM(nb_long);
3012 COPYNUM(nb_float);
3013 COPYNUM(nb_oct);
3014 COPYNUM(nb_hex);
3015 COPYNUM(nb_inplace_add);
3016 COPYNUM(nb_inplace_subtract);
3017 COPYNUM(nb_inplace_multiply);
3018 COPYNUM(nb_inplace_divide);
3019 COPYNUM(nb_inplace_remainder);
3020 COPYNUM(nb_inplace_power);
3021 COPYNUM(nb_inplace_lshift);
3022 COPYNUM(nb_inplace_rshift);
3023 COPYNUM(nb_inplace_and);
3024 COPYNUM(nb_inplace_xor);
3025 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003026 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3027 COPYNUM(nb_true_divide);
3028 COPYNUM(nb_floor_divide);
3029 COPYNUM(nb_inplace_true_divide);
3030 COPYNUM(nb_inplace_floor_divide);
3031 }
Guido van Rossum38fff8c2006-03-07 18:50:55 +00003032 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3033 COPYNUM(nb_index);
3034 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003035 }
3036
Guido van Rossum13d52f02001-08-10 21:24:08 +00003037 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3038 basebase = base->tp_base;
3039 if (basebase->tp_as_sequence == NULL)
3040 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003041 COPYSEQ(sq_length);
3042 COPYSEQ(sq_concat);
3043 COPYSEQ(sq_repeat);
3044 COPYSEQ(sq_item);
3045 COPYSEQ(sq_slice);
3046 COPYSEQ(sq_ass_item);
3047 COPYSEQ(sq_ass_slice);
3048 COPYSEQ(sq_contains);
3049 COPYSEQ(sq_inplace_concat);
3050 COPYSEQ(sq_inplace_repeat);
3051 }
3052
Guido van Rossum13d52f02001-08-10 21:24:08 +00003053 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3054 basebase = base->tp_base;
3055 if (basebase->tp_as_mapping == NULL)
3056 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003057 COPYMAP(mp_length);
3058 COPYMAP(mp_subscript);
3059 COPYMAP(mp_ass_subscript);
3060 }
3061
Tim Petersfc57ccb2001-10-12 02:38:24 +00003062 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3063 basebase = base->tp_base;
3064 if (basebase->tp_as_buffer == NULL)
3065 basebase = NULL;
3066 COPYBUF(bf_getreadbuffer);
3067 COPYBUF(bf_getwritebuffer);
3068 COPYBUF(bf_getsegcount);
3069 COPYBUF(bf_getcharbuffer);
3070 }
3071
Guido van Rossum13d52f02001-08-10 21:24:08 +00003072 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003073
Tim Peters6d6c1a32001-08-02 04:15:00 +00003074 COPYSLOT(tp_dealloc);
3075 COPYSLOT(tp_print);
3076 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3077 type->tp_getattr = base->tp_getattr;
3078 type->tp_getattro = base->tp_getattro;
3079 }
3080 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3081 type->tp_setattr = base->tp_setattr;
3082 type->tp_setattro = base->tp_setattro;
3083 }
3084 /* tp_compare see tp_richcompare */
3085 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003086 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003087 COPYSLOT(tp_call);
3088 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003089 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003090 if (type->tp_compare == NULL &&
3091 type->tp_richcompare == NULL &&
3092 type->tp_hash == NULL)
3093 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003094 type->tp_compare = base->tp_compare;
3095 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003096 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003097 }
3098 }
3099 else {
3100 COPYSLOT(tp_compare);
3101 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003102 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3103 COPYSLOT(tp_iter);
3104 COPYSLOT(tp_iternext);
3105 }
3106 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3107 COPYSLOT(tp_descr_get);
3108 COPYSLOT(tp_descr_set);
3109 COPYSLOT(tp_dictoffset);
3110 COPYSLOT(tp_init);
3111 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003112 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003113 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3114 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3115 /* They agree about gc. */
3116 COPYSLOT(tp_free);
3117 }
3118 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3119 type->tp_free == NULL &&
3120 base->tp_free == _PyObject_Del) {
3121 /* A bit of magic to plug in the correct default
3122 * tp_free function when a derived class adds gc,
3123 * didn't define tp_free, and the base uses the
3124 * default non-gc tp_free.
3125 */
3126 type->tp_free = PyObject_GC_Del;
3127 }
3128 /* else they didn't agree about gc, and there isn't something
3129 * obvious to be done -- the type is on its own.
3130 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003131 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003132}
3133
Jeremy Hylton938ace62002-07-17 16:30:39 +00003134static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003135
Tim Peters6d6c1a32001-08-02 04:15:00 +00003136int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003137PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003138{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003139 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003140 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003141 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003142
Guido van Rossumcab05802002-06-10 15:29:03 +00003143 if (type->tp_flags & Py_TPFLAGS_READY) {
3144 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003145 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003146 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003147 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003148
3149 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003150
Tim Peters36eb4df2003-03-23 03:33:13 +00003151#ifdef Py_TRACE_REFS
3152 /* PyType_Ready is the closest thing we have to a choke point
3153 * for type objects, so is the best place I can think of to try
3154 * to get type objects into the doubly-linked list of all objects.
3155 * Still, not all type objects go thru PyType_Ready.
3156 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003157 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003158#endif
3159
Tim Peters6d6c1a32001-08-02 04:15:00 +00003160 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3161 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003162 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003163 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003164 Py_INCREF(base);
3165 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003166
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003167 /* Now the only way base can still be NULL is if type is
3168 * &PyBaseObject_Type.
3169 */
3170
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003171 /* Initialize the base class */
3172 if (base && base->tp_dict == NULL) {
3173 if (PyType_Ready(base) < 0)
3174 goto error;
3175 }
3176
Guido van Rossum0986d822002-04-08 01:38:42 +00003177 /* Initialize ob_type if NULL. This means extensions that want to be
3178 compilable separately on Windows can call PyType_Ready() instead of
3179 initializing the ob_type field of their type objects. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003180 /* The test for base != NULL is really unnecessary, since base is only
3181 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3182 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3183 know that. */
3184 if (type->ob_type == NULL && base != NULL)
Guido van Rossum0986d822002-04-08 01:38:42 +00003185 type->ob_type = base->ob_type;
3186
Tim Peters6d6c1a32001-08-02 04:15:00 +00003187 /* Initialize tp_bases */
3188 bases = type->tp_bases;
3189 if (bases == NULL) {
3190 if (base == NULL)
3191 bases = PyTuple_New(0);
3192 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003193 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003194 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003195 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003196 type->tp_bases = bases;
3197 }
3198
Guido van Rossum687ae002001-10-15 22:03:32 +00003199 /* Initialize tp_dict */
3200 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003201 if (dict == NULL) {
3202 dict = PyDict_New();
3203 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003204 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003205 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003206 }
3207
Guido van Rossum687ae002001-10-15 22:03:32 +00003208 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003209 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003210 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003211 if (type->tp_methods != NULL) {
3212 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003213 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003214 }
3215 if (type->tp_members != NULL) {
3216 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003217 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003218 }
3219 if (type->tp_getset != NULL) {
3220 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003221 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003222 }
3223
Tim Peters6d6c1a32001-08-02 04:15:00 +00003224 /* Calculate method resolution order */
3225 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003226 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003227 }
3228
Guido van Rossum13d52f02001-08-10 21:24:08 +00003229 /* Inherit special flags from dominant base */
3230 if (type->tp_base != NULL)
3231 inherit_special(type, type->tp_base);
3232
Tim Peters6d6c1a32001-08-02 04:15:00 +00003233 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003234 bases = type->tp_mro;
3235 assert(bases != NULL);
3236 assert(PyTuple_Check(bases));
3237 n = PyTuple_GET_SIZE(bases);
3238 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003239 PyObject *b = PyTuple_GET_ITEM(bases, i);
3240 if (PyType_Check(b))
3241 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003242 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003243
Tim Peters3cfe7542003-05-21 21:29:48 +00003244 /* Sanity check for tp_free. */
3245 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3246 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3247 /* This base class needs to call tp_free, but doesn't have
3248 * one, or its tp_free is for non-gc'ed objects.
3249 */
3250 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3251 "gc and is a base type but has inappropriate "
3252 "tp_free slot",
3253 type->tp_name);
3254 goto error;
3255 }
3256
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003257 /* if the type dictionary doesn't contain a __doc__, set it from
3258 the tp_doc slot.
3259 */
3260 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3261 if (type->tp_doc != NULL) {
3262 PyObject *doc = PyString_FromString(type->tp_doc);
3263 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3264 Py_DECREF(doc);
3265 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003266 PyDict_SetItemString(type->tp_dict,
3267 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003268 }
3269 }
3270
Guido van Rossum13d52f02001-08-10 21:24:08 +00003271 /* Some more special stuff */
3272 base = type->tp_base;
3273 if (base != NULL) {
3274 if (type->tp_as_number == NULL)
3275 type->tp_as_number = base->tp_as_number;
3276 if (type->tp_as_sequence == NULL)
3277 type->tp_as_sequence = base->tp_as_sequence;
3278 if (type->tp_as_mapping == NULL)
3279 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003280 if (type->tp_as_buffer == NULL)
3281 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003282 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003283
Guido van Rossum1c450732001-10-08 15:18:27 +00003284 /* Link into each base class's list of subclasses */
3285 bases = type->tp_bases;
3286 n = PyTuple_GET_SIZE(bases);
3287 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003288 PyObject *b = PyTuple_GET_ITEM(bases, i);
3289 if (PyType_Check(b) &&
3290 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003291 goto error;
3292 }
3293
Guido van Rossum13d52f02001-08-10 21:24:08 +00003294 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003295 assert(type->tp_dict != NULL);
3296 type->tp_flags =
3297 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003298 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003299
3300 error:
3301 type->tp_flags &= ~Py_TPFLAGS_READYING;
3302 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003303}
3304
Guido van Rossum1c450732001-10-08 15:18:27 +00003305static int
3306add_subclass(PyTypeObject *base, PyTypeObject *type)
3307{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003308 Py_ssize_t i;
3309 int result;
Anthony Baxtera6286212006-04-11 07:42:36 +00003310 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003311
3312 list = base->tp_subclasses;
3313 if (list == NULL) {
3314 base->tp_subclasses = list = PyList_New(0);
3315 if (list == NULL)
3316 return -1;
3317 }
3318 assert(PyList_Check(list));
Anthony Baxtera6286212006-04-11 07:42:36 +00003319 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003320 i = PyList_GET_SIZE(list);
3321 while (--i >= 0) {
3322 ref = PyList_GET_ITEM(list, i);
3323 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003324 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Anthony Baxtera6286212006-04-11 07:42:36 +00003325 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003326 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003327 result = PyList_Append(list, newobj);
3328 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003329 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003330}
3331
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003332static void
3333remove_subclass(PyTypeObject *base, PyTypeObject *type)
3334{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003335 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003336 PyObject *list, *ref;
3337
3338 list = base->tp_subclasses;
3339 if (list == NULL) {
3340 return;
3341 }
3342 assert(PyList_Check(list));
3343 i = PyList_GET_SIZE(list);
3344 while (--i >= 0) {
3345 ref = PyList_GET_ITEM(list, i);
3346 assert(PyWeakref_CheckRef(ref));
3347 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3348 /* this can't fail, right? */
3349 PySequence_DelItem(list, i);
3350 return;
3351 }
3352 }
3353}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003354
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003355static int
3356check_num_args(PyObject *ob, int n)
3357{
3358 if (!PyTuple_CheckExact(ob)) {
3359 PyErr_SetString(PyExc_SystemError,
3360 "PyArg_UnpackTuple() argument list is not a tuple");
3361 return 0;
3362 }
3363 if (n == PyTuple_GET_SIZE(ob))
3364 return 1;
3365 PyErr_Format(
3366 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003367 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003368 return 0;
3369}
3370
Tim Peters6d6c1a32001-08-02 04:15:00 +00003371/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3372
3373/* There's a wrapper *function* for each distinct function typedef used
3374 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3375 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3376 Most tables have only one entry; the tables for binary operators have two
3377 entries, one regular and one with reversed arguments. */
3378
3379static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003380wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003381{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003382 lenfunc func = (lenfunc)wrapped;
3383 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003384
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003385 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003386 return NULL;
3387 res = (*func)(self);
3388 if (res == -1 && PyErr_Occurred())
3389 return NULL;
3390 return PyInt_FromLong((long)res);
3391}
3392
Tim Peters6d6c1a32001-08-02 04:15:00 +00003393static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003394wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3395{
3396 inquiry func = (inquiry)wrapped;
3397 int res;
3398
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003399 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003400 return NULL;
3401 res = (*func)(self);
3402 if (res == -1 && PyErr_Occurred())
3403 return NULL;
3404 return PyBool_FromLong((long)res);
3405}
3406
3407static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003408wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3409{
3410 binaryfunc func = (binaryfunc)wrapped;
3411 PyObject *other;
3412
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003413 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003414 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003415 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003416 return (*func)(self, other);
3417}
3418
3419static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003420wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3421{
3422 binaryfunc func = (binaryfunc)wrapped;
3423 PyObject *other;
3424
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003425 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003426 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003427 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003428 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003429 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003430 Py_INCREF(Py_NotImplemented);
3431 return Py_NotImplemented;
3432 }
3433 return (*func)(self, other);
3434}
3435
3436static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003437wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3438{
3439 binaryfunc func = (binaryfunc)wrapped;
3440 PyObject *other;
3441
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003442 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003443 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003444 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003445 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003446 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003447 Py_INCREF(Py_NotImplemented);
3448 return Py_NotImplemented;
3449 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003450 return (*func)(other, self);
3451}
3452
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003453static PyObject *
3454wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3455{
3456 coercion func = (coercion)wrapped;
3457 PyObject *other, *res;
3458 int ok;
3459
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003460 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003461 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003462 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003463 ok = func(&self, &other);
3464 if (ok < 0)
3465 return NULL;
3466 if (ok > 0) {
3467 Py_INCREF(Py_NotImplemented);
3468 return Py_NotImplemented;
3469 }
3470 res = PyTuple_New(2);
3471 if (res == NULL) {
3472 Py_DECREF(self);
3473 Py_DECREF(other);
3474 return NULL;
3475 }
3476 PyTuple_SET_ITEM(res, 0, self);
3477 PyTuple_SET_ITEM(res, 1, other);
3478 return res;
3479}
3480
Tim Peters6d6c1a32001-08-02 04:15:00 +00003481static PyObject *
3482wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3483{
3484 ternaryfunc func = (ternaryfunc)wrapped;
3485 PyObject *other;
3486 PyObject *third = Py_None;
3487
3488 /* Note: This wrapper only works for __pow__() */
3489
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003490 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003491 return NULL;
3492 return (*func)(self, other, third);
3493}
3494
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003495static PyObject *
3496wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3497{
3498 ternaryfunc func = (ternaryfunc)wrapped;
3499 PyObject *other;
3500 PyObject *third = Py_None;
3501
3502 /* Note: This wrapper only works for __pow__() */
3503
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003504 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003505 return NULL;
3506 return (*func)(other, self, third);
3507}
3508
Tim Peters6d6c1a32001-08-02 04:15:00 +00003509static PyObject *
3510wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3511{
3512 unaryfunc func = (unaryfunc)wrapped;
3513
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003514 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003515 return NULL;
3516 return (*func)(self);
3517}
3518
Tim Peters6d6c1a32001-08-02 04:15:00 +00003519static PyObject *
Armin Rigo314861c2006-03-30 14:04:02 +00003520wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003521{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003522 ssizeargfunc func = (ssizeargfunc)wrapped;
Armin Rigo314861c2006-03-30 14:04:02 +00003523 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003524 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003525
Armin Rigo314861c2006-03-30 14:04:02 +00003526 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
3527 return NULL;
3528 i = PyNumber_Index(o);
3529 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003530 return NULL;
3531 return (*func)(self, i);
3532}
3533
Martin v. Löwis18e16552006-02-15 17:27:45 +00003534static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00003535getindex(PyObject *self, PyObject *arg)
3536{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003537 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003538
Armin Rigo314861c2006-03-30 14:04:02 +00003539 i = PyNumber_Index(arg);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003540 if (i == -1 && PyErr_Occurred())
3541 return -1;
3542 if (i < 0) {
3543 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3544 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003545 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003546 if (n < 0)
3547 return -1;
3548 i += n;
3549 }
3550 }
3551 return i;
3552}
3553
3554static PyObject *
3555wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3556{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003557 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003558 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003559 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003560
Guido van Rossumf4593e02001-10-03 12:09:30 +00003561 if (PyTuple_GET_SIZE(args) == 1) {
3562 arg = PyTuple_GET_ITEM(args, 0);
3563 i = getindex(self, arg);
3564 if (i == -1 && PyErr_Occurred())
3565 return NULL;
3566 return (*func)(self, i);
3567 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003568 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003569 assert(PyErr_Occurred());
3570 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003571}
3572
Tim Peters6d6c1a32001-08-02 04:15:00 +00003573static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003574wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003575{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003576 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
3577 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003578
Martin v. Löwis18e16552006-02-15 17:27:45 +00003579 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003580 return NULL;
3581 return (*func)(self, i, j);
3582}
3583
Tim Peters6d6c1a32001-08-02 04:15:00 +00003584static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003585wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003586{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003587 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3588 Py_ssize_t i;
3589 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003590 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003591
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003592 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003593 return NULL;
3594 i = getindex(self, arg);
3595 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003596 return NULL;
3597 res = (*func)(self, i, value);
3598 if (res == -1 && PyErr_Occurred())
3599 return NULL;
3600 Py_INCREF(Py_None);
3601 return Py_None;
3602}
3603
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003604static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003605wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003606{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003607 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3608 Py_ssize_t i;
3609 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003610 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003611
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003612 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003613 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003614 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003615 i = getindex(self, arg);
3616 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003617 return NULL;
3618 res = (*func)(self, i, NULL);
3619 if (res == -1 && PyErr_Occurred())
3620 return NULL;
3621 Py_INCREF(Py_None);
3622 return Py_None;
3623}
3624
Tim Peters6d6c1a32001-08-02 04:15:00 +00003625static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003626wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003627{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003628 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3629 Py_ssize_t i, j;
3630 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003631 PyObject *value;
3632
Martin v. Löwis18e16552006-02-15 17:27:45 +00003633 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003634 return NULL;
3635 res = (*func)(self, i, j, value);
3636 if (res == -1 && PyErr_Occurred())
3637 return NULL;
3638 Py_INCREF(Py_None);
3639 return Py_None;
3640}
3641
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003642static PyObject *
3643wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3644{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003645 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3646 Py_ssize_t i, j;
3647 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003648
Martin v. Löwis18e16552006-02-15 17:27:45 +00003649 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003650 return NULL;
3651 res = (*func)(self, i, j, 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 +00003658/* XXX objobjproc is a misnomer; should be objargpred */
3659static PyObject *
3660wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3661{
3662 objobjproc func = (objobjproc)wrapped;
3663 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003664 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003665
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003666 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003667 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003668 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003669 res = (*func)(self, value);
3670 if (res == -1 && PyErr_Occurred())
3671 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003672 else
3673 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003674}
3675
Tim Peters6d6c1a32001-08-02 04:15:00 +00003676static PyObject *
3677wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3678{
3679 objobjargproc func = (objobjargproc)wrapped;
3680 int res;
3681 PyObject *key, *value;
3682
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003683 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003684 return NULL;
3685 res = (*func)(self, key, value);
3686 if (res == -1 && PyErr_Occurred())
3687 return NULL;
3688 Py_INCREF(Py_None);
3689 return Py_None;
3690}
3691
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003692static PyObject *
3693wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3694{
3695 objobjargproc func = (objobjargproc)wrapped;
3696 int res;
3697 PyObject *key;
3698
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003699 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003700 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003701 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003702 res = (*func)(self, key, NULL);
3703 if (res == -1 && PyErr_Occurred())
3704 return NULL;
3705 Py_INCREF(Py_None);
3706 return Py_None;
3707}
3708
Tim Peters6d6c1a32001-08-02 04:15:00 +00003709static PyObject *
3710wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3711{
3712 cmpfunc func = (cmpfunc)wrapped;
3713 int res;
3714 PyObject *other;
3715
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003716 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003717 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003718 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003719 if (other->ob_type->tp_compare != func &&
3720 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003721 PyErr_Format(
3722 PyExc_TypeError,
3723 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3724 self->ob_type->tp_name,
3725 self->ob_type->tp_name,
3726 other->ob_type->tp_name);
3727 return NULL;
3728 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003729 res = (*func)(self, other);
3730 if (PyErr_Occurred())
3731 return NULL;
3732 return PyInt_FromLong((long)res);
3733}
3734
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003735/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003736 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003737static int
3738hackcheck(PyObject *self, setattrofunc func, char *what)
3739{
3740 PyTypeObject *type = self->ob_type;
3741 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3742 type = type->tp_base;
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003743 /* If type is NULL now, this is a really weird type.
3744 In the same of backwards compatibility (?), just shut up. */
3745 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003746 PyErr_Format(PyExc_TypeError,
3747 "can't apply this %s to %s object",
3748 what,
3749 type->tp_name);
3750 return 0;
3751 }
3752 return 1;
3753}
3754
Tim Peters6d6c1a32001-08-02 04:15:00 +00003755static PyObject *
3756wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3757{
3758 setattrofunc func = (setattrofunc)wrapped;
3759 int res;
3760 PyObject *name, *value;
3761
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003762 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003763 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003764 if (!hackcheck(self, func, "__setattr__"))
3765 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003766 res = (*func)(self, name, value);
3767 if (res < 0)
3768 return NULL;
3769 Py_INCREF(Py_None);
3770 return Py_None;
3771}
3772
3773static PyObject *
3774wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3775{
3776 setattrofunc func = (setattrofunc)wrapped;
3777 int res;
3778 PyObject *name;
3779
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003780 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003781 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003782 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003783 if (!hackcheck(self, func, "__delattr__"))
3784 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003785 res = (*func)(self, name, NULL);
3786 if (res < 0)
3787 return NULL;
3788 Py_INCREF(Py_None);
3789 return Py_None;
3790}
3791
Tim Peters6d6c1a32001-08-02 04:15:00 +00003792static PyObject *
3793wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3794{
3795 hashfunc func = (hashfunc)wrapped;
3796 long res;
3797
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003798 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003799 return NULL;
3800 res = (*func)(self);
3801 if (res == -1 && PyErr_Occurred())
3802 return NULL;
3803 return PyInt_FromLong(res);
3804}
3805
Tim Peters6d6c1a32001-08-02 04:15:00 +00003806static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003807wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003808{
3809 ternaryfunc func = (ternaryfunc)wrapped;
3810
Guido van Rossumc8e56452001-10-22 00:43:43 +00003811 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003812}
3813
Tim Peters6d6c1a32001-08-02 04:15:00 +00003814static PyObject *
3815wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3816{
3817 richcmpfunc func = (richcmpfunc)wrapped;
3818 PyObject *other;
3819
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003820 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003821 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003822 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003823 return (*func)(self, other, op);
3824}
3825
3826#undef RICHCMP_WRAPPER
3827#define RICHCMP_WRAPPER(NAME, OP) \
3828static PyObject * \
3829richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3830{ \
3831 return wrap_richcmpfunc(self, args, wrapped, OP); \
3832}
3833
Jack Jansen8e938b42001-08-08 15:29:49 +00003834RICHCMP_WRAPPER(lt, Py_LT)
3835RICHCMP_WRAPPER(le, Py_LE)
3836RICHCMP_WRAPPER(eq, Py_EQ)
3837RICHCMP_WRAPPER(ne, Py_NE)
3838RICHCMP_WRAPPER(gt, Py_GT)
3839RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003840
Tim Peters6d6c1a32001-08-02 04:15:00 +00003841static PyObject *
3842wrap_next(PyObject *self, PyObject *args, void *wrapped)
3843{
3844 unaryfunc func = (unaryfunc)wrapped;
3845 PyObject *res;
3846
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003847 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003848 return NULL;
3849 res = (*func)(self);
3850 if (res == NULL && !PyErr_Occurred())
3851 PyErr_SetNone(PyExc_StopIteration);
3852 return res;
3853}
3854
Tim Peters6d6c1a32001-08-02 04:15:00 +00003855static PyObject *
3856wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3857{
3858 descrgetfunc func = (descrgetfunc)wrapped;
3859 PyObject *obj;
3860 PyObject *type = NULL;
3861
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003862 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003863 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003864 if (obj == Py_None)
3865 obj = NULL;
3866 if (type == Py_None)
3867 type = NULL;
3868 if (type == NULL &&obj == NULL) {
3869 PyErr_SetString(PyExc_TypeError,
3870 "__get__(None, None) is invalid");
3871 return NULL;
3872 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003873 return (*func)(self, obj, type);
3874}
3875
Tim Peters6d6c1a32001-08-02 04:15:00 +00003876static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003877wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003878{
3879 descrsetfunc func = (descrsetfunc)wrapped;
3880 PyObject *obj, *value;
3881 int ret;
3882
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003883 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003884 return NULL;
3885 ret = (*func)(self, obj, value);
3886 if (ret < 0)
3887 return NULL;
3888 Py_INCREF(Py_None);
3889 return Py_None;
3890}
Guido van Rossum22b13872002-08-06 21:41:44 +00003891
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003892static PyObject *
3893wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3894{
3895 descrsetfunc func = (descrsetfunc)wrapped;
3896 PyObject *obj;
3897 int ret;
3898
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003899 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003900 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003901 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003902 ret = (*func)(self, obj, NULL);
3903 if (ret < 0)
3904 return NULL;
3905 Py_INCREF(Py_None);
3906 return Py_None;
3907}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003908
Tim Peters6d6c1a32001-08-02 04:15:00 +00003909static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003910wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003911{
3912 initproc func = (initproc)wrapped;
3913
Guido van Rossumc8e56452001-10-22 00:43:43 +00003914 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003915 return NULL;
3916 Py_INCREF(Py_None);
3917 return Py_None;
3918}
3919
Tim Peters6d6c1a32001-08-02 04:15:00 +00003920static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003921tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003922{
Barry Warsaw60f01882001-08-22 19:24:42 +00003923 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003924 PyObject *arg0, *res;
3925
3926 if (self == NULL || !PyType_Check(self))
3927 Py_FatalError("__new__() called with non-type 'self'");
3928 type = (PyTypeObject *)self;
3929 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003930 PyErr_Format(PyExc_TypeError,
3931 "%s.__new__(): not enough arguments",
3932 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003933 return NULL;
3934 }
3935 arg0 = PyTuple_GET_ITEM(args, 0);
3936 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003937 PyErr_Format(PyExc_TypeError,
3938 "%s.__new__(X): X is not a type object (%s)",
3939 type->tp_name,
3940 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003941 return NULL;
3942 }
3943 subtype = (PyTypeObject *)arg0;
3944 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003945 PyErr_Format(PyExc_TypeError,
3946 "%s.__new__(%s): %s is not a subtype of %s",
3947 type->tp_name,
3948 subtype->tp_name,
3949 subtype->tp_name,
3950 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003951 return NULL;
3952 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003953
3954 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003955 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003956 most derived base that's not a heap type is this type. */
3957 staticbase = subtype;
3958 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3959 staticbase = staticbase->tp_base;
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003960 /* If staticbase is NULL now, it is a really weird type.
3961 In the same of backwards compatibility (?), just shut up. */
3962 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003963 PyErr_Format(PyExc_TypeError,
3964 "%s.__new__(%s) is not safe, use %s.__new__()",
3965 type->tp_name,
3966 subtype->tp_name,
3967 staticbase == NULL ? "?" : staticbase->tp_name);
3968 return NULL;
3969 }
3970
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003971 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3972 if (args == NULL)
3973 return NULL;
3974 res = type->tp_new(subtype, args, kwds);
3975 Py_DECREF(args);
3976 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003977}
3978
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003979static struct PyMethodDef tp_new_methoddef[] = {
3980 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003981 PyDoc_STR("T.__new__(S, ...) -> "
3982 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003983 {0}
3984};
3985
3986static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003987add_tp_new_wrapper(PyTypeObject *type)
3988{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003989 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003990
Guido van Rossum687ae002001-10-15 22:03:32 +00003991 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003992 return 0;
3993 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003994 if (func == NULL)
3995 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00003996 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00003997 Py_DECREF(func);
3998 return -1;
3999 }
4000 Py_DECREF(func);
4001 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004002}
4003
Guido van Rossumf040ede2001-08-07 16:40:56 +00004004/* Slot wrappers that call the corresponding __foo__ slot. See comments
4005 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004006
Guido van Rossumdc91b992001-08-08 22:26:22 +00004007#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004008static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004009FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004010{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004011 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004012 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004013}
4014
Guido van Rossumdc91b992001-08-08 22:26:22 +00004015#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004016static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004017FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004018{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004019 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004020 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004021}
4022
Guido van Rossumcd118802003-01-06 22:57:47 +00004023/* Boolean helper for SLOT1BINFULL().
4024 right.__class__ is a nontrivial subclass of left.__class__. */
4025static int
4026method_is_overloaded(PyObject *left, PyObject *right, char *name)
4027{
4028 PyObject *a, *b;
4029 int ok;
4030
4031 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
4032 if (b == NULL) {
4033 PyErr_Clear();
4034 /* If right doesn't have it, it's not overloaded */
4035 return 0;
4036 }
4037
4038 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
4039 if (a == NULL) {
4040 PyErr_Clear();
4041 Py_DECREF(b);
4042 /* If right has it but left doesn't, it's overloaded */
4043 return 1;
4044 }
4045
4046 ok = PyObject_RichCompareBool(a, b, Py_NE);
4047 Py_DECREF(a);
4048 Py_DECREF(b);
4049 if (ok < 0) {
4050 PyErr_Clear();
4051 return 0;
4052 }
4053
4054 return ok;
4055}
4056
Guido van Rossumdc91b992001-08-08 22:26:22 +00004057
4058#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004059static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004060FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004061{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004062 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004063 int do_other = self->ob_type != other->ob_type && \
4064 other->ob_type->tp_as_number != NULL && \
4065 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004066 if (self->ob_type->tp_as_number != NULL && \
4067 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
4068 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004069 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004070 PyType_IsSubtype(other->ob_type, self->ob_type) && \
4071 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004072 r = call_maybe( \
4073 other, ROPSTR, &rcache_str, "(O)", self); \
4074 if (r != Py_NotImplemented) \
4075 return r; \
4076 Py_DECREF(r); \
4077 do_other = 0; \
4078 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004079 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004080 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004081 if (r != Py_NotImplemented || \
4082 other->ob_type == self->ob_type) \
4083 return r; \
4084 Py_DECREF(r); \
4085 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004086 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004087 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004088 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004089 } \
4090 Py_INCREF(Py_NotImplemented); \
4091 return Py_NotImplemented; \
4092}
4093
4094#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4095 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4096
4097#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4098static PyObject * \
4099FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4100{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004101 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004102 return call_method(self, OPSTR, &cache_str, \
4103 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004104}
4105
Martin v. Löwis18e16552006-02-15 17:27:45 +00004106static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004107slot_sq_length(PyObject *self)
4108{
Guido van Rossum2730b132001-08-28 18:22:14 +00004109 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004110 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004111 Py_ssize_t temp;
4112 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004113
4114 if (res == NULL)
4115 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004116 temp = PyInt_AsSsize_t(res);
Guido van Rossum630db602005-09-20 18:49:54 +00004117 len = (int)temp;
Guido van Rossum26111622001-10-01 16:42:49 +00004118 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00004119 if (len == -1 && PyErr_Occurred())
4120 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004121#if SIZEOF_SIZE_T < SIZEOF_LONG
4122 /* Overflow check -- range of PyInt is more than C ssize_t */
Guido van Rossum630db602005-09-20 18:49:54 +00004123 if (len != temp) {
4124 PyErr_SetString(PyExc_OverflowError,
4125 "__len__() should return 0 <= outcome < 2**31");
4126 return -1;
4127 }
4128#endif
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004129 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00004130 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004131 "__len__() should return >= 0");
4132 return -1;
4133 }
Guido van Rossum26111622001-10-01 16:42:49 +00004134 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004135}
4136
Guido van Rossumf4593e02001-10-03 12:09:30 +00004137/* Super-optimized version of slot_sq_item.
4138 Other slots could do the same... */
4139static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004140slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004141{
4142 static PyObject *getitem_str;
4143 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4144 descrgetfunc f;
4145
4146 if (getitem_str == NULL) {
4147 getitem_str = PyString_InternFromString("__getitem__");
4148 if (getitem_str == NULL)
4149 return NULL;
4150 }
4151 func = _PyType_Lookup(self->ob_type, getitem_str);
4152 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004153 if ((f = func->ob_type->tp_descr_get) == NULL)
4154 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004155 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004156 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004157 if (func == NULL) {
4158 return NULL;
4159 }
4160 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004161 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004162 if (ival != NULL) {
4163 args = PyTuple_New(1);
4164 if (args != NULL) {
4165 PyTuple_SET_ITEM(args, 0, ival);
4166 retval = PyObject_Call(func, args, NULL);
4167 Py_XDECREF(args);
4168 Py_XDECREF(func);
4169 return retval;
4170 }
4171 }
4172 }
4173 else {
4174 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4175 }
4176 Py_XDECREF(args);
4177 Py_XDECREF(ival);
4178 Py_XDECREF(func);
4179 return NULL;
4180}
4181
Martin v. Löwis18e16552006-02-15 17:27:45 +00004182SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004183
4184static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004185slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004186{
4187 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004188 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004189
4190 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004191 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004192 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004193 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004194 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004195 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004196 if (res == NULL)
4197 return -1;
4198 Py_DECREF(res);
4199 return 0;
4200}
4201
4202static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004203slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004204{
4205 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004206 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004207
4208 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004209 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004210 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004211 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004212 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004213 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004214 if (res == NULL)
4215 return -1;
4216 Py_DECREF(res);
4217 return 0;
4218}
4219
4220static int
4221slot_sq_contains(PyObject *self, PyObject *value)
4222{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004223 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004224 int result = -1;
4225
Guido van Rossum60718732001-08-28 17:47:51 +00004226 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004227
Guido van Rossum55f20992001-10-01 17:18:22 +00004228 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004229 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004230 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004231 if (args == NULL)
4232 res = NULL;
4233 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004234 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004235 Py_DECREF(args);
4236 }
4237 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004238 if (res != NULL) {
4239 result = PyObject_IsTrue(res);
4240 Py_DECREF(res);
4241 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004242 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004243 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004244 /* Possible results: -1 and 1 */
4245 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004246 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004247 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004248 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004249}
4250
Tim Peters6d6c1a32001-08-02 04:15:00 +00004251#define slot_mp_length slot_sq_length
4252
Guido van Rossumdc91b992001-08-08 22:26:22 +00004253SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004254
4255static int
4256slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4257{
4258 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004259 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004260
4261 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004262 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004263 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004264 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004265 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004266 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004267 if (res == NULL)
4268 return -1;
4269 Py_DECREF(res);
4270 return 0;
4271}
4272
Guido van Rossumdc91b992001-08-08 22:26:22 +00004273SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4274SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4275SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4276SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4277SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4278SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4279
Jeremy Hylton938ace62002-07-17 16:30:39 +00004280static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004281
4282SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4283 nb_power, "__pow__", "__rpow__")
4284
4285static PyObject *
4286slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4287{
Guido van Rossum2730b132001-08-28 18:22:14 +00004288 static PyObject *pow_str;
4289
Guido van Rossumdc91b992001-08-08 22:26:22 +00004290 if (modulus == Py_None)
4291 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004292 /* Three-arg power doesn't use __rpow__. But ternary_op
4293 can call this when the second argument's type uses
4294 slot_nb_power, so check before calling self.__pow__. */
4295 if (self->ob_type->tp_as_number != NULL &&
4296 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4297 return call_method(self, "__pow__", &pow_str,
4298 "(OO)", other, modulus);
4299 }
4300 Py_INCREF(Py_NotImplemented);
4301 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004302}
4303
4304SLOT0(slot_nb_negative, "__neg__")
4305SLOT0(slot_nb_positive, "__pos__")
4306SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004307
4308static int
4309slot_nb_nonzero(PyObject *self)
4310{
Tim Petersea7f75d2002-12-07 21:39:16 +00004311 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004312 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004313 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004314
Guido van Rossum55f20992001-10-01 17:18:22 +00004315 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004316 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004317 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004318 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004319 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004320 if (func == NULL)
4321 return PyErr_Occurred() ? -1 : 1;
4322 }
4323 args = PyTuple_New(0);
4324 if (args != NULL) {
4325 PyObject *temp = PyObject_Call(func, args, NULL);
4326 Py_DECREF(args);
4327 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004328 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004329 result = PyObject_IsTrue(temp);
4330 else {
4331 PyErr_Format(PyExc_TypeError,
4332 "__nonzero__ should return "
4333 "bool or int, returned %s",
4334 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004335 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004336 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004337 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004338 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004339 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004340 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004341 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004342}
4343
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004344
4345static Py_ssize_t
4346slot_nb_index(PyObject *self)
4347{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004348 static PyObject *index_str;
Armin Rigo314861c2006-03-30 14:04:02 +00004349 PyObject *temp = call_method(self, "__index__", &index_str, "()");
4350 Py_ssize_t result;
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004351
Armin Rigo314861c2006-03-30 14:04:02 +00004352 if (temp == NULL)
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004353 return -1;
Armin Rigo314861c2006-03-30 14:04:02 +00004354 if (PyInt_CheckExact(temp) || PyLong_CheckExact(temp)) {
4355 result = temp->ob_type->tp_as_number->nb_index(temp);
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004356 }
Armin Rigo314861c2006-03-30 14:04:02 +00004357 else {
Georg Brandlccff7852006-06-18 22:17:29 +00004358 PyErr_Format(PyExc_TypeError,
4359 "__index__ must return an int or a long, "
4360 "not '%.200s'", temp->ob_type->tp_name);
Armin Rigo314861c2006-03-30 14:04:02 +00004361 result = -1;
4362 }
4363 Py_DECREF(temp);
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004364 return result;
4365}
4366
4367
Guido van Rossumdc91b992001-08-08 22:26:22 +00004368SLOT0(slot_nb_invert, "__invert__")
4369SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4370SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4371SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4372SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4373SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004374
4375static int
4376slot_nb_coerce(PyObject **a, PyObject **b)
4377{
4378 static PyObject *coerce_str;
4379 PyObject *self = *a, *other = *b;
4380
4381 if (self->ob_type->tp_as_number != NULL &&
4382 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4383 PyObject *r;
4384 r = call_maybe(
4385 self, "__coerce__", &coerce_str, "(O)", other);
4386 if (r == NULL)
4387 return -1;
4388 if (r == Py_NotImplemented) {
4389 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004390 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004391 else {
4392 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4393 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004394 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004395 Py_DECREF(r);
4396 return -1;
4397 }
4398 *a = PyTuple_GET_ITEM(r, 0);
4399 Py_INCREF(*a);
4400 *b = PyTuple_GET_ITEM(r, 1);
4401 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004402 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004403 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004404 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004405 }
4406 if (other->ob_type->tp_as_number != NULL &&
4407 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4408 PyObject *r;
4409 r = call_maybe(
4410 other, "__coerce__", &coerce_str, "(O)", self);
4411 if (r == NULL)
4412 return -1;
4413 if (r == Py_NotImplemented) {
4414 Py_DECREF(r);
4415 return 1;
4416 }
4417 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4418 PyErr_SetString(PyExc_TypeError,
4419 "__coerce__ didn't return a 2-tuple");
4420 Py_DECREF(r);
4421 return -1;
4422 }
4423 *a = PyTuple_GET_ITEM(r, 1);
4424 Py_INCREF(*a);
4425 *b = PyTuple_GET_ITEM(r, 0);
4426 Py_INCREF(*b);
4427 Py_DECREF(r);
4428 return 0;
4429 }
4430 return 1;
4431}
4432
Guido van Rossumdc91b992001-08-08 22:26:22 +00004433SLOT0(slot_nb_int, "__int__")
4434SLOT0(slot_nb_long, "__long__")
4435SLOT0(slot_nb_float, "__float__")
4436SLOT0(slot_nb_oct, "__oct__")
4437SLOT0(slot_nb_hex, "__hex__")
4438SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4439SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4440SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4441SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4442SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004443SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004444SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4445SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4446SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4447SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4448SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4449SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4450 "__floordiv__", "__rfloordiv__")
4451SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4452SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4453SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004454
4455static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004456half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004457{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004458 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004459 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004460 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004461
Guido van Rossum60718732001-08-28 17:47:51 +00004462 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004463 if (func == NULL) {
4464 PyErr_Clear();
4465 }
4466 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004467 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004468 if (args == NULL)
4469 res = NULL;
4470 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004471 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004472 Py_DECREF(args);
4473 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004474 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004475 if (res != Py_NotImplemented) {
4476 if (res == NULL)
4477 return -2;
4478 c = PyInt_AsLong(res);
4479 Py_DECREF(res);
4480 if (c == -1 && PyErr_Occurred())
4481 return -2;
4482 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4483 }
4484 Py_DECREF(res);
4485 }
4486 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004487}
4488
Guido van Rossumab3b0342001-09-18 20:38:53 +00004489/* This slot is published for the benefit of try_3way_compare in object.c */
4490int
4491_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004492{
4493 int c;
4494
Guido van Rossumab3b0342001-09-18 20:38:53 +00004495 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004496 c = half_compare(self, other);
4497 if (c <= 1)
4498 return c;
4499 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004500 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004501 c = half_compare(other, self);
4502 if (c < -1)
4503 return -2;
4504 if (c <= 1)
4505 return -c;
4506 }
4507 return (void *)self < (void *)other ? -1 :
4508 (void *)self > (void *)other ? 1 : 0;
4509}
4510
4511static PyObject *
4512slot_tp_repr(PyObject *self)
4513{
4514 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004515 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004516
Guido van Rossum60718732001-08-28 17:47:51 +00004517 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004518 if (func != NULL) {
4519 res = PyEval_CallObject(func, NULL);
4520 Py_DECREF(func);
4521 return res;
4522 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004523 PyErr_Clear();
4524 return PyString_FromFormat("<%s object at %p>",
4525 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004526}
4527
4528static PyObject *
4529slot_tp_str(PyObject *self)
4530{
4531 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004532 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004533
Guido van Rossum60718732001-08-28 17:47:51 +00004534 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004535 if (func != NULL) {
4536 res = PyEval_CallObject(func, NULL);
4537 Py_DECREF(func);
4538 return res;
4539 }
4540 else {
4541 PyErr_Clear();
4542 return slot_tp_repr(self);
4543 }
4544}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004545
4546static long
4547slot_tp_hash(PyObject *self)
4548{
Tim Peters61ce0a92002-12-06 23:38:02 +00004549 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004550 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004551 long h;
4552
Guido van Rossum60718732001-08-28 17:47:51 +00004553 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004554
4555 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004556 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004557 Py_DECREF(func);
4558 if (res == NULL)
4559 return -1;
4560 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004561 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004562 }
4563 else {
4564 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004565 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004566 if (func == NULL) {
4567 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004568 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004569 }
4570 if (func != NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00004571 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
4572 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004573 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004574 return -1;
4575 }
4576 PyErr_Clear();
4577 h = _Py_HashPointer((void *)self);
4578 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004579 if (h == -1 && !PyErr_Occurred())
4580 h = -2;
4581 return h;
4582}
4583
4584static PyObject *
4585slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4586{
Guido van Rossum60718732001-08-28 17:47:51 +00004587 static PyObject *call_str;
4588 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004589 PyObject *res;
4590
4591 if (meth == NULL)
4592 return NULL;
Armin Rigo53c1692f2006-06-21 21:58:50 +00004593
4594 /* PyObject_Call() will end up calling slot_tp_call() again if
4595 the object returned for __call__ has __call__ itself defined
4596 upon it. This can be an infinite recursion if you set
4597 __call__ in a class to an instance of it. */
4598 if (Py_EnterRecursiveCall(" in __call__"))
4599 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004600 res = PyObject_Call(meth, args, kwds);
Armin Rigo53c1692f2006-06-21 21:58:50 +00004601 Py_LeaveRecursiveCall();
4602
Tim Peters6d6c1a32001-08-02 04:15:00 +00004603 Py_DECREF(meth);
4604 return res;
4605}
4606
Guido van Rossum14a6f832001-10-17 13:59:09 +00004607/* There are two slot dispatch functions for tp_getattro.
4608
4609 - slot_tp_getattro() is used when __getattribute__ is overridden
4610 but no __getattr__ hook is present;
4611
4612 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4613
Guido van Rossumc334df52002-04-04 23:44:47 +00004614 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4615 detects the absence of __getattr__ and then installs the simpler slot if
4616 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004617
Tim Peters6d6c1a32001-08-02 04:15:00 +00004618static PyObject *
4619slot_tp_getattro(PyObject *self, PyObject *name)
4620{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004621 static PyObject *getattribute_str = NULL;
4622 return call_method(self, "__getattribute__", &getattribute_str,
4623 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004624}
4625
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004626static PyObject *
4627slot_tp_getattr_hook(PyObject *self, PyObject *name)
4628{
4629 PyTypeObject *tp = self->ob_type;
4630 PyObject *getattr, *getattribute, *res;
4631 static PyObject *getattribute_str = NULL;
4632 static PyObject *getattr_str = NULL;
4633
4634 if (getattr_str == NULL) {
4635 getattr_str = PyString_InternFromString("__getattr__");
4636 if (getattr_str == NULL)
4637 return NULL;
4638 }
4639 if (getattribute_str == NULL) {
4640 getattribute_str =
4641 PyString_InternFromString("__getattribute__");
4642 if (getattribute_str == NULL)
4643 return NULL;
4644 }
4645 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004646 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004647 /* No __getattr__ hook: use a simpler dispatcher */
4648 tp->tp_getattro = slot_tp_getattro;
4649 return slot_tp_getattro(self, name);
4650 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004651 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004652 if (getattribute == NULL ||
4653 (getattribute->ob_type == &PyWrapperDescr_Type &&
4654 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4655 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004656 res = PyObject_GenericGetAttr(self, name);
4657 else
Georg Brandl684fd0c2006-05-25 19:15:31 +00004658 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004659 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004660 PyErr_Clear();
Georg Brandl684fd0c2006-05-25 19:15:31 +00004661 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004662 }
4663 return res;
4664}
4665
Tim Peters6d6c1a32001-08-02 04:15:00 +00004666static int
4667slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4668{
4669 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004670 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004671
4672 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004673 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004674 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004675 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004676 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004677 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004678 if (res == NULL)
4679 return -1;
4680 Py_DECREF(res);
4681 return 0;
4682}
4683
4684/* Map rich comparison operators to their __xx__ namesakes */
4685static char *name_op[] = {
4686 "__lt__",
4687 "__le__",
4688 "__eq__",
4689 "__ne__",
4690 "__gt__",
4691 "__ge__",
4692};
4693
4694static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004695half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004696{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004697 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004698 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004699
Guido van Rossum60718732001-08-28 17:47:51 +00004700 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004701 if (func == NULL) {
4702 PyErr_Clear();
4703 Py_INCREF(Py_NotImplemented);
4704 return Py_NotImplemented;
4705 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004706 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004707 if (args == NULL)
4708 res = NULL;
4709 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004710 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004711 Py_DECREF(args);
4712 }
4713 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004714 return res;
4715}
4716
Guido van Rossumb8f63662001-08-15 23:57:02 +00004717static PyObject *
4718slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4719{
4720 PyObject *res;
4721
4722 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4723 res = half_richcompare(self, other, op);
4724 if (res != Py_NotImplemented)
4725 return res;
4726 Py_DECREF(res);
4727 }
4728 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004729 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004730 if (res != Py_NotImplemented) {
4731 return res;
4732 }
4733 Py_DECREF(res);
4734 }
4735 Py_INCREF(Py_NotImplemented);
4736 return Py_NotImplemented;
4737}
4738
4739static PyObject *
4740slot_tp_iter(PyObject *self)
4741{
4742 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004743 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004744
Guido van Rossum60718732001-08-28 17:47:51 +00004745 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004746 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004747 PyObject *args;
4748 args = res = PyTuple_New(0);
4749 if (args != NULL) {
4750 res = PyObject_Call(func, args, NULL);
4751 Py_DECREF(args);
4752 }
4753 Py_DECREF(func);
4754 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004755 }
4756 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004757 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004758 if (func == NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00004759 PyErr_Format(PyExc_TypeError,
4760 "'%.200s' object is not iterable",
4761 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004762 return NULL;
4763 }
4764 Py_DECREF(func);
4765 return PySeqIter_New(self);
4766}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004767
4768static PyObject *
4769slot_tp_iternext(PyObject *self)
4770{
Guido van Rossum2730b132001-08-28 18:22:14 +00004771 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004772 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004773}
4774
Guido van Rossum1a493502001-08-17 16:47:50 +00004775static PyObject *
4776slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4777{
4778 PyTypeObject *tp = self->ob_type;
4779 PyObject *get;
4780 static PyObject *get_str = NULL;
4781
4782 if (get_str == NULL) {
4783 get_str = PyString_InternFromString("__get__");
4784 if (get_str == NULL)
4785 return NULL;
4786 }
4787 get = _PyType_Lookup(tp, get_str);
4788 if (get == NULL) {
4789 /* Avoid further slowdowns */
4790 if (tp->tp_descr_get == slot_tp_descr_get)
4791 tp->tp_descr_get = NULL;
4792 Py_INCREF(self);
4793 return self;
4794 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004795 if (obj == NULL)
4796 obj = Py_None;
4797 if (type == NULL)
4798 type = Py_None;
Georg Brandl684fd0c2006-05-25 19:15:31 +00004799 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00004800}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004801
4802static int
4803slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4804{
Guido van Rossum2c252392001-08-24 10:13:31 +00004805 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004806 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004807
4808 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004809 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004810 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004811 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004812 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004813 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004814 if (res == NULL)
4815 return -1;
4816 Py_DECREF(res);
4817 return 0;
4818}
4819
4820static int
4821slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4822{
Guido van Rossum60718732001-08-28 17:47:51 +00004823 static PyObject *init_str;
4824 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004825 PyObject *res;
4826
4827 if (meth == NULL)
4828 return -1;
4829 res = PyObject_Call(meth, args, kwds);
4830 Py_DECREF(meth);
4831 if (res == NULL)
4832 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004833 if (res != Py_None) {
Georg Brandlccff7852006-06-18 22:17:29 +00004834 PyErr_Format(PyExc_TypeError,
4835 "__init__() should return None, not '%.200s'",
4836 res->ob_type->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004837 Py_DECREF(res);
4838 return -1;
4839 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004840 Py_DECREF(res);
4841 return 0;
4842}
4843
4844static PyObject *
4845slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4846{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004847 static PyObject *new_str;
4848 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004849 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004850 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004851
Guido van Rossum7bed2132002-08-08 21:57:53 +00004852 if (new_str == NULL) {
4853 new_str = PyString_InternFromString("__new__");
4854 if (new_str == NULL)
4855 return NULL;
4856 }
4857 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004858 if (func == NULL)
4859 return NULL;
4860 assert(PyTuple_Check(args));
4861 n = PyTuple_GET_SIZE(args);
4862 newargs = PyTuple_New(n+1);
4863 if (newargs == NULL)
4864 return NULL;
4865 Py_INCREF(type);
4866 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4867 for (i = 0; i < n; i++) {
4868 x = PyTuple_GET_ITEM(args, i);
4869 Py_INCREF(x);
4870 PyTuple_SET_ITEM(newargs, i+1, x);
4871 }
4872 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004873 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004874 Py_DECREF(func);
4875 return x;
4876}
4877
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004878static void
4879slot_tp_del(PyObject *self)
4880{
4881 static PyObject *del_str = NULL;
4882 PyObject *del, *res;
4883 PyObject *error_type, *error_value, *error_traceback;
4884
4885 /* Temporarily resurrect the object. */
4886 assert(self->ob_refcnt == 0);
4887 self->ob_refcnt = 1;
4888
4889 /* Save the current exception, if any. */
4890 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4891
4892 /* Execute __del__ method, if any. */
4893 del = lookup_maybe(self, "__del__", &del_str);
4894 if (del != NULL) {
4895 res = PyEval_CallObject(del, NULL);
4896 if (res == NULL)
4897 PyErr_WriteUnraisable(del);
4898 else
4899 Py_DECREF(res);
4900 Py_DECREF(del);
4901 }
4902
4903 /* Restore the saved exception. */
4904 PyErr_Restore(error_type, error_value, error_traceback);
4905
4906 /* Undo the temporary resurrection; can't use DECREF here, it would
4907 * cause a recursive call.
4908 */
4909 assert(self->ob_refcnt > 0);
4910 if (--self->ob_refcnt == 0)
4911 return; /* this is the normal path out */
4912
4913 /* __del__ resurrected it! Make it look like the original Py_DECREF
4914 * never happened.
4915 */
4916 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004917 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004918 _Py_NewReference(self);
4919 self->ob_refcnt = refcnt;
4920 }
4921 assert(!PyType_IS_GC(self->ob_type) ||
4922 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00004923 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
4924 * we need to undo that. */
4925 _Py_DEC_REFTOTAL;
4926 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4927 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004928 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4929 * _Py_NewReference bumped tp_allocs: both of those need to be
4930 * undone.
4931 */
4932#ifdef COUNT_ALLOCS
4933 --self->ob_type->tp_frees;
4934 --self->ob_type->tp_allocs;
4935#endif
4936}
4937
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004938
4939/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004940 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004941 structure, which incorporates the additional structures used for numbers,
4942 sequences and mappings.
4943 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004944 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004945 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4946 terminated with an all-zero entry. (This table is further initialized and
4947 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004948
Guido van Rossum6d204072001-10-21 00:44:31 +00004949typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004950
4951#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004952#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004953#undef ETSLOT
4954#undef SQSLOT
4955#undef MPSLOT
4956#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004957#undef UNSLOT
4958#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004959#undef BINSLOT
4960#undef RBINSLOT
4961
Guido van Rossum6d204072001-10-21 00:44:31 +00004962#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004963 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4964 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004965#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4966 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004967 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004968#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004969 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004970 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004971#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4972 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4973#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4974 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4975#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4976 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4977#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4978 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4979 "x." NAME "() <==> " DOC)
4980#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4981 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4982 "x." NAME "(y) <==> x" DOC "y")
4983#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4984 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4985 "x." NAME "(y) <==> x" DOC "y")
4986#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4987 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4988 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00004989#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
4990 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4991 "x." NAME "(y) <==> " DOC)
4992#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
4993 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4994 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004995
4996static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00004997 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00004998 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00004999 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5000 The logic in abstract.c always falls back to nb_add/nb_multiply in
5001 this case. Defining both the nb_* and the sq_* slots to call the
5002 user-defined methods has unexpected side-effects, as shown by
5003 test_descr.notimplemented() */
5004 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5005 "x.__add__(y) <==> x+y"),
Armin Rigo314861c2006-03-30 14:04:02 +00005006 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Armin Rigofd163f92005-12-29 15:59:19 +00005007 "x.__mul__(n) <==> x*n"),
Armin Rigo314861c2006-03-30 14:04:02 +00005008 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Armin Rigofd163f92005-12-29 15:59:19 +00005009 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005010 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5011 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005012 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005013 "x.__getslice__(i, j) <==> x[i:j]\n\
5014 \n\
5015 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005016 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005017 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005018 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005019 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005020 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005021 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005022 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
5023 \n\
5024 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005025 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005026 "x.__delslice__(i, j) <==> del x[i:j]\n\
5027 \n\
5028 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005029 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5030 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005031 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5032 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5033 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Armin Rigo314861c2006-03-30 14:04:02 +00005034 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005035
Martin v. Löwis18e16552006-02-15 17:27:45 +00005036 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005037 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005038 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005039 wrap_binaryfunc,
5040 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005041 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005042 wrap_objobjargproc,
5043 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005044 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005045 wrap_delitem,
5046 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005047
Guido van Rossum6d204072001-10-21 00:44:31 +00005048 BINSLOT("__add__", nb_add, slot_nb_add,
5049 "+"),
5050 RBINSLOT("__radd__", nb_add, slot_nb_add,
5051 "+"),
5052 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5053 "-"),
5054 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5055 "-"),
5056 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5057 "*"),
5058 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5059 "*"),
5060 BINSLOT("__div__", nb_divide, slot_nb_divide,
5061 "/"),
5062 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5063 "/"),
5064 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5065 "%"),
5066 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5067 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005068 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005069 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005070 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005071 "divmod(y, x)"),
5072 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5073 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5074 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5075 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5076 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5077 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5078 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5079 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005080 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005081 "x != 0"),
5082 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5083 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5084 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5085 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5086 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5087 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5088 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5089 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5090 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5091 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5092 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5093 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5094 "x.__coerce__(y) <==> coerce(x, y)"),
5095 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5096 "int(x)"),
5097 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5098 "long(x)"),
5099 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5100 "float(x)"),
5101 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5102 "oct(x)"),
5103 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5104 "hex(x)"),
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005105 NBSLOT("__index__", nb_index, slot_nb_index, wrap_lenfunc,
5106 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005107 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5108 wrap_binaryfunc, "+"),
5109 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5110 wrap_binaryfunc, "-"),
5111 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5112 wrap_binaryfunc, "*"),
5113 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5114 wrap_binaryfunc, "/"),
5115 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5116 wrap_binaryfunc, "%"),
5117 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005118 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005119 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5120 wrap_binaryfunc, "<<"),
5121 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5122 wrap_binaryfunc, ">>"),
5123 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5124 wrap_binaryfunc, "&"),
5125 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5126 wrap_binaryfunc, "^"),
5127 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5128 wrap_binaryfunc, "|"),
5129 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5130 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5131 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5132 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5133 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5134 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5135 IBSLOT("__itruediv__", nb_inplace_true_divide,
5136 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005137
Guido van Rossum6d204072001-10-21 00:44:31 +00005138 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5139 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005140 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005141 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5142 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005143 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005144 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5145 "x.__cmp__(y) <==> cmp(x,y)"),
5146 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5147 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005148 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5149 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005150 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005151 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5152 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5153 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5154 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5155 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5156 "x.__setattr__('name', value) <==> x.name = value"),
5157 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5158 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5159 "x.__delattr__('name') <==> del x.name"),
5160 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5161 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5162 "x.__lt__(y) <==> x<y"),
5163 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5164 "x.__le__(y) <==> x<=y"),
5165 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5166 "x.__eq__(y) <==> x==y"),
5167 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5168 "x.__ne__(y) <==> x!=y"),
5169 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5170 "x.__gt__(y) <==> x>y"),
5171 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5172 "x.__ge__(y) <==> x>=y"),
5173 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5174 "x.__iter__() <==> iter(x)"),
5175 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5176 "x.next() -> the next value, or raise StopIteration"),
5177 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5178 "descr.__get__(obj[, type]) -> value"),
5179 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5180 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005181 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5182 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005183 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005184 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005185 "see x.__class__.__doc__ for signature",
5186 PyWrapperFlag_KEYWORDS),
5187 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005188 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005189 {NULL}
5190};
5191
Guido van Rossumc334df52002-04-04 23:44:47 +00005192/* Given a type pointer and an offset gotten from a slotdef entry, return a
5193 pointer to the actual slot. This is not quite the same as simply adding
5194 the offset to the type pointer, since it takes care to indirect through the
5195 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5196 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005197static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005198slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005199{
5200 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005201 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005202
Guido van Rossume5c691a2003-03-07 15:13:17 +00005203 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005204 assert(offset >= 0);
Skip Montanaro429433b2006-04-18 00:35:43 +00005205 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5206 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005207 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005208 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005209 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005210 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005211 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005212 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005213 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005214 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005215 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005216 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005217 }
5218 else {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005219 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005220 }
5221 if (ptr != NULL)
5222 ptr += offset;
5223 return (void **)ptr;
5224}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005225
Guido van Rossumc334df52002-04-04 23:44:47 +00005226/* Length of array of slotdef pointers used to store slots with the
5227 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5228 the same __name__, for any __name__. Since that's a static property, it is
5229 appropriate to declare fixed-size arrays for this. */
5230#define MAX_EQUIV 10
5231
5232/* Return a slot pointer for a given name, but ONLY if the attribute has
5233 exactly one slot function. The name must be an interned string. */
5234static void **
5235resolve_slotdups(PyTypeObject *type, PyObject *name)
5236{
5237 /* XXX Maybe this could be optimized more -- but is it worth it? */
5238
5239 /* pname and ptrs act as a little cache */
5240 static PyObject *pname;
5241 static slotdef *ptrs[MAX_EQUIV];
5242 slotdef *p, **pp;
5243 void **res, **ptr;
5244
5245 if (pname != name) {
5246 /* Collect all slotdefs that match name into ptrs. */
5247 pname = name;
5248 pp = ptrs;
5249 for (p = slotdefs; p->name_strobj; p++) {
5250 if (p->name_strobj == name)
5251 *pp++ = p;
5252 }
5253 *pp = NULL;
5254 }
5255
5256 /* Look in all matching slots of the type; if exactly one of these has
5257 a filled-in slot, return its value. Otherwise return NULL. */
5258 res = NULL;
5259 for (pp = ptrs; *pp; pp++) {
5260 ptr = slotptr(type, (*pp)->offset);
5261 if (ptr == NULL || *ptr == NULL)
5262 continue;
5263 if (res != NULL)
5264 return NULL;
5265 res = ptr;
5266 }
5267 return res;
5268}
5269
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005270/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005271 does some incredibly complex thinking and then sticks something into the
5272 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5273 interests, and then stores a generic wrapper or a specific function into
5274 the slot.) Return a pointer to the next slotdef with a different offset,
5275 because that's convenient for fixup_slot_dispatchers(). */
5276static slotdef *
5277update_one_slot(PyTypeObject *type, slotdef *p)
5278{
5279 PyObject *descr;
5280 PyWrapperDescrObject *d;
5281 void *generic = NULL, *specific = NULL;
5282 int use_generic = 0;
5283 int offset = p->offset;
5284 void **ptr = slotptr(type, offset);
5285
5286 if (ptr == NULL) {
5287 do {
5288 ++p;
5289 } while (p->offset == offset);
5290 return p;
5291 }
5292 do {
5293 descr = _PyType_Lookup(type, p->name_strobj);
5294 if (descr == NULL)
5295 continue;
5296 if (descr->ob_type == &PyWrapperDescr_Type) {
5297 void **tptr = resolve_slotdups(type, p->name_strobj);
5298 if (tptr == NULL || tptr == ptr)
5299 generic = p->function;
5300 d = (PyWrapperDescrObject *)descr;
5301 if (d->d_base->wrapper == p->wrapper &&
5302 PyType_IsSubtype(type, d->d_type))
5303 {
5304 if (specific == NULL ||
5305 specific == d->d_wrapped)
5306 specific = d->d_wrapped;
5307 else
5308 use_generic = 1;
5309 }
5310 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005311 else if (descr->ob_type == &PyCFunction_Type &&
5312 PyCFunction_GET_FUNCTION(descr) ==
5313 (PyCFunction)tp_new_wrapper &&
5314 strcmp(p->name, "__new__") == 0)
5315 {
5316 /* The __new__ wrapper is not a wrapper descriptor,
5317 so must be special-cased differently.
5318 If we don't do this, creating an instance will
5319 always use slot_tp_new which will look up
5320 __new__ in the MRO which will call tp_new_wrapper
5321 which will look through the base classes looking
5322 for a static base and call its tp_new (usually
5323 PyType_GenericNew), after performing various
5324 sanity checks and constructing a new argument
5325 list. Cut all that nonsense short -- this speeds
5326 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005327 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005328 /* XXX I'm not 100% sure that there isn't a hole
5329 in this reasoning that requires additional
5330 sanity checks. I'll buy the first person to
5331 point out a bug in this reasoning a beer. */
5332 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005333 else {
5334 use_generic = 1;
5335 generic = p->function;
5336 }
5337 } while ((++p)->offset == offset);
5338 if (specific && !use_generic)
5339 *ptr = specific;
5340 else
5341 *ptr = generic;
5342 return p;
5343}
5344
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005345/* In the type, update the slots whose slotdefs are gathered in the pp array.
5346 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005347static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005348update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005349{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005350 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005351
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005352 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005353 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005354 return 0;
5355}
5356
Guido van Rossumc334df52002-04-04 23:44:47 +00005357/* Comparison function for qsort() to compare slotdefs by their offset, and
5358 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005359static int
5360slotdef_cmp(const void *aa, const void *bb)
5361{
5362 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5363 int c = a->offset - b->offset;
5364 if (c != 0)
5365 return c;
5366 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005367 /* Cannot use a-b, as this gives off_t,
5368 which may lose precision when converted to int. */
5369 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005370}
5371
Guido van Rossumc334df52002-04-04 23:44:47 +00005372/* Initialize the slotdefs table by adding interned string objects for the
5373 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005374static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005375init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005376{
5377 slotdef *p;
5378 static int initialized = 0;
5379
5380 if (initialized)
5381 return;
5382 for (p = slotdefs; p->name; p++) {
5383 p->name_strobj = PyString_InternFromString(p->name);
5384 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005385 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005386 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005387 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5388 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005389 initialized = 1;
5390}
5391
Guido van Rossumc334df52002-04-04 23:44:47 +00005392/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005393static int
5394update_slot(PyTypeObject *type, PyObject *name)
5395{
Guido van Rossumc334df52002-04-04 23:44:47 +00005396 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005397 slotdef *p;
5398 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005399 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005400
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005401 init_slotdefs();
5402 pp = ptrs;
5403 for (p = slotdefs; p->name; p++) {
5404 /* XXX assume name is interned! */
5405 if (p->name_strobj == name)
5406 *pp++ = p;
5407 }
5408 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005409 for (pp = ptrs; *pp; pp++) {
5410 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005411 offset = p->offset;
5412 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005413 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005414 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005415 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005416 if (ptrs[0] == NULL)
5417 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005418 return update_subclasses(type, name,
5419 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005420}
5421
Guido van Rossumc334df52002-04-04 23:44:47 +00005422/* Store the proper functions in the slot dispatches at class (type)
5423 definition time, based upon which operations the class overrides in its
5424 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005425static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005426fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005427{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005428 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005429
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005430 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005431 for (p = slotdefs; p->name; )
5432 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005433}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005434
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005435static void
5436update_all_slots(PyTypeObject* type)
5437{
5438 slotdef *p;
5439
5440 init_slotdefs();
5441 for (p = slotdefs; p->name; p++) {
5442 /* update_slot returns int but can't actually fail */
5443 update_slot(type, p->name_strobj);
5444 }
5445}
5446
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005447/* recurse_down_subclasses() and update_subclasses() are mutually
5448 recursive functions to call a callback for all subclasses,
5449 but refraining from recursing into subclasses that define 'name'. */
5450
5451static int
5452update_subclasses(PyTypeObject *type, PyObject *name,
5453 update_callback callback, void *data)
5454{
5455 if (callback(type, data) < 0)
5456 return -1;
5457 return recurse_down_subclasses(type, name, callback, data);
5458}
5459
5460static int
5461recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5462 update_callback callback, void *data)
5463{
5464 PyTypeObject *subclass;
5465 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005466 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005467
5468 subclasses = type->tp_subclasses;
5469 if (subclasses == NULL)
5470 return 0;
5471 assert(PyList_Check(subclasses));
5472 n = PyList_GET_SIZE(subclasses);
5473 for (i = 0; i < n; i++) {
5474 ref = PyList_GET_ITEM(subclasses, i);
5475 assert(PyWeakref_CheckRef(ref));
5476 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5477 assert(subclass != NULL);
5478 if ((PyObject *)subclass == Py_None)
5479 continue;
5480 assert(PyType_Check(subclass));
5481 /* Avoid recursing down into unaffected classes */
5482 dict = subclass->tp_dict;
5483 if (dict != NULL && PyDict_Check(dict) &&
5484 PyDict_GetItem(dict, name) != NULL)
5485 continue;
5486 if (update_subclasses(subclass, name, callback, data) < 0)
5487 return -1;
5488 }
5489 return 0;
5490}
5491
Guido van Rossum6d204072001-10-21 00:44:31 +00005492/* This function is called by PyType_Ready() to populate the type's
5493 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005494 function slot (like tp_repr) that's defined in the type, one or more
5495 corresponding descriptors are added in the type's tp_dict dictionary
5496 under the appropriate name (like __repr__). Some function slots
5497 cause more than one descriptor to be added (for example, the nb_add
5498 slot adds both __add__ and __radd__ descriptors) and some function
5499 slots compete for the same descriptor (for example both sq_item and
5500 mp_subscript generate a __getitem__ descriptor).
5501
5502 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005503 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005504 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005505 between competing slots: the members of PyHeapTypeObject are listed
5506 from most general to least general, so the most general slot is
5507 preferred. In particular, because as_mapping comes before as_sequence,
5508 for a type that defines both mp_subscript and sq_item, mp_subscript
5509 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005510
5511 This only adds new descriptors and doesn't overwrite entries in
5512 tp_dict that were previously defined. The descriptors contain a
5513 reference to the C function they must call, so that it's safe if they
5514 are copied into a subtype's __dict__ and the subtype has a different
5515 C function in its slot -- calling the method defined by the
5516 descriptor will call the C function that was used to create it,
5517 rather than the C function present in the slot when it is called.
5518 (This is important because a subtype may have a C function in the
5519 slot that calls the method from the dictionary, and we want to avoid
5520 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005521
5522static int
5523add_operators(PyTypeObject *type)
5524{
5525 PyObject *dict = type->tp_dict;
5526 slotdef *p;
5527 PyObject *descr;
5528 void **ptr;
5529
5530 init_slotdefs();
5531 for (p = slotdefs; p->name; p++) {
5532 if (p->wrapper == NULL)
5533 continue;
5534 ptr = slotptr(type, p->offset);
5535 if (!ptr || !*ptr)
5536 continue;
5537 if (PyDict_GetItem(dict, p->name_strobj))
5538 continue;
5539 descr = PyDescr_NewWrapper(type, p, *ptr);
5540 if (descr == NULL)
5541 return -1;
5542 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5543 return -1;
5544 Py_DECREF(descr);
5545 }
5546 if (type->tp_new != NULL) {
5547 if (add_tp_new_wrapper(type) < 0)
5548 return -1;
5549 }
5550 return 0;
5551}
5552
Guido van Rossum705f0f52001-08-24 16:47:00 +00005553
5554/* Cooperative 'super' */
5555
5556typedef struct {
5557 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005558 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005559 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005560 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005561} superobject;
5562
Guido van Rossum6f799372001-09-20 20:46:19 +00005563static PyMemberDef super_members[] = {
5564 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5565 "the class invoking super()"},
5566 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5567 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005568 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005569 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005570 {0}
5571};
5572
Guido van Rossum705f0f52001-08-24 16:47:00 +00005573static void
5574super_dealloc(PyObject *self)
5575{
5576 superobject *su = (superobject *)self;
5577
Guido van Rossum048eb752001-10-02 21:24:57 +00005578 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005579 Py_XDECREF(su->obj);
5580 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005581 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005582 self->ob_type->tp_free(self);
5583}
5584
5585static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005586super_repr(PyObject *self)
5587{
5588 superobject *su = (superobject *)self;
5589
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005590 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005591 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005592 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005593 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005594 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005595 else
5596 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005597 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005598 su->type ? su->type->tp_name : "NULL");
5599}
5600
5601static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005602super_getattro(PyObject *self, PyObject *name)
5603{
5604 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005605 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005606
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005607 if (!skip) {
5608 /* We want __class__ to return the class of the super object
5609 (i.e. super, or a subclass), not the class of su->obj. */
5610 skip = (PyString_Check(name) &&
5611 PyString_GET_SIZE(name) == 9 &&
5612 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5613 }
5614
5615 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005616 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005617 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005618 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005619 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005620
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005621 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005622 mro = starttype->tp_mro;
5623
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005624 if (mro == NULL)
5625 n = 0;
5626 else {
5627 assert(PyTuple_Check(mro));
5628 n = PyTuple_GET_SIZE(mro);
5629 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005630 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005631 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005632 break;
5633 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005634 i++;
5635 res = NULL;
5636 for (; i < n; i++) {
5637 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005638 if (PyType_Check(tmp))
5639 dict = ((PyTypeObject *)tmp)->tp_dict;
5640 else if (PyClass_Check(tmp))
5641 dict = ((PyClassObject *)tmp)->cl_dict;
5642 else
5643 continue;
5644 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005645 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005646 Py_INCREF(res);
5647 f = res->ob_type->tp_descr_get;
5648 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005649 tmp = f(res,
5650 /* Only pass 'obj' param if
5651 this is instance-mode super
5652 (See SF ID #743627)
5653 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005654 (su->obj == (PyObject *)
5655 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005656 ? (PyObject *)NULL
5657 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005658 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005659 Py_DECREF(res);
5660 res = tmp;
5661 }
5662 return res;
5663 }
5664 }
5665 }
5666 return PyObject_GenericGetAttr(self, name);
5667}
5668
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005669static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005670supercheck(PyTypeObject *type, PyObject *obj)
5671{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005672 /* Check that a super() call makes sense. Return a type object.
5673
5674 obj can be a new-style class, or an instance of one:
5675
5676 - If it is a class, it must be a subclass of 'type'. This case is
5677 used for class methods; the return value is obj.
5678
5679 - If it is an instance, it must be an instance of 'type'. This is
5680 the normal case; the return value is obj.__class__.
5681
5682 But... when obj is an instance, we want to allow for the case where
5683 obj->ob_type is not a subclass of type, but obj.__class__ is!
5684 This will allow using super() with a proxy for obj.
5685 */
5686
Guido van Rossum8e80a722003-02-18 19:22:22 +00005687 /* Check for first bullet above (special case) */
5688 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5689 Py_INCREF(obj);
5690 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005691 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005692
5693 /* Normal case */
5694 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005695 Py_INCREF(obj->ob_type);
5696 return obj->ob_type;
5697 }
5698 else {
5699 /* Try the slow way */
5700 static PyObject *class_str = NULL;
5701 PyObject *class_attr;
5702
5703 if (class_str == NULL) {
5704 class_str = PyString_FromString("__class__");
5705 if (class_str == NULL)
5706 return NULL;
5707 }
5708
5709 class_attr = PyObject_GetAttr(obj, class_str);
5710
5711 if (class_attr != NULL &&
5712 PyType_Check(class_attr) &&
5713 (PyTypeObject *)class_attr != obj->ob_type)
5714 {
5715 int ok = PyType_IsSubtype(
5716 (PyTypeObject *)class_attr, type);
5717 if (ok)
5718 return (PyTypeObject *)class_attr;
5719 }
5720
5721 if (class_attr == NULL)
5722 PyErr_Clear();
5723 else
5724 Py_DECREF(class_attr);
5725 }
5726
Tim Peters97e5ff52003-02-18 19:32:50 +00005727 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005728 "super(type, obj): "
5729 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005730 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005731}
5732
Guido van Rossum705f0f52001-08-24 16:47:00 +00005733static PyObject *
5734super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5735{
5736 superobject *su = (superobject *)self;
Anthony Baxtera6286212006-04-11 07:42:36 +00005737 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005738
5739 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5740 /* Not binding to an object, or already bound */
5741 Py_INCREF(self);
5742 return self;
5743 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005744 if (su->ob_type != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005745 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005746 call its type */
Georg Brandl684fd0c2006-05-25 19:15:31 +00005747 return PyObject_CallFunctionObjArgs((PyObject *)su->ob_type,
5748 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005749 else {
5750 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005751 PyTypeObject *obj_type = supercheck(su->type, obj);
5752 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005753 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00005754 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005755 NULL, NULL);
Anthony Baxtera6286212006-04-11 07:42:36 +00005756 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005757 return NULL;
5758 Py_INCREF(su->type);
5759 Py_INCREF(obj);
Anthony Baxtera6286212006-04-11 07:42:36 +00005760 newobj->type = su->type;
5761 newobj->obj = obj;
5762 newobj->obj_type = obj_type;
5763 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005764 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005765}
5766
5767static int
5768super_init(PyObject *self, PyObject *args, PyObject *kwds)
5769{
5770 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005771 PyTypeObject *type;
5772 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005773 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005774
5775 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5776 return -1;
5777 if (obj == Py_None)
5778 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005779 if (obj != NULL) {
5780 obj_type = supercheck(type, obj);
5781 if (obj_type == NULL)
5782 return -1;
5783 Py_INCREF(obj);
5784 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005785 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005786 su->type = type;
5787 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005788 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005789 return 0;
5790}
5791
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005792PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005793"super(type) -> unbound super object\n"
5794"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005795"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005796"Typical use to call a cooperative superclass method:\n"
5797"class C(B):\n"
5798" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005799" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005800
Guido van Rossum048eb752001-10-02 21:24:57 +00005801static int
5802super_traverse(PyObject *self, visitproc visit, void *arg)
5803{
5804 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00005805
Thomas Woutersc6e55062006-04-15 21:47:09 +00005806 Py_VISIT(su->obj);
5807 Py_VISIT(su->type);
5808 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005809
5810 return 0;
5811}
5812
Guido van Rossum705f0f52001-08-24 16:47:00 +00005813PyTypeObject PySuper_Type = {
5814 PyObject_HEAD_INIT(&PyType_Type)
5815 0, /* ob_size */
5816 "super", /* tp_name */
5817 sizeof(superobject), /* tp_basicsize */
5818 0, /* tp_itemsize */
5819 /* methods */
5820 super_dealloc, /* tp_dealloc */
5821 0, /* tp_print */
5822 0, /* tp_getattr */
5823 0, /* tp_setattr */
5824 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005825 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005826 0, /* tp_as_number */
5827 0, /* tp_as_sequence */
5828 0, /* tp_as_mapping */
5829 0, /* tp_hash */
5830 0, /* tp_call */
5831 0, /* tp_str */
5832 super_getattro, /* tp_getattro */
5833 0, /* tp_setattro */
5834 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005835 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5836 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005837 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005838 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005839 0, /* tp_clear */
5840 0, /* tp_richcompare */
5841 0, /* tp_weaklistoffset */
5842 0, /* tp_iter */
5843 0, /* tp_iternext */
5844 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005845 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005846 0, /* tp_getset */
5847 0, /* tp_base */
5848 0, /* tp_dict */
5849 super_descr_get, /* tp_descr_get */
5850 0, /* tp_descr_set */
5851 0, /* tp_dictoffset */
5852 super_init, /* tp_init */
5853 PyType_GenericAlloc, /* tp_alloc */
5854 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005855 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005856};