blob: 60c4fbc6d10d56aaefbcd4405cfc231b5332bbe1 [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{
24 char *s;
25
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
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000029 Py_INCREF(et->name);
30 return et->name;
31 }
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
74 Py_DECREF(et->name);
75 et->name = value;
76
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__");
90 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +000091 return mod;
92 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000093 else {
94 s = strrchr(type->tp_name, '.');
95 if (s != NULL)
96 return PyString_FromStringAndSize(
97 type->tp_name, (int)(s - type->tp_name));
98 return PyString_FromString("__builtin__");
99 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000100}
101
Guido van Rossum3926a632001-09-25 16:25:58 +0000102static int
103type_set_module(PyTypeObject *type, PyObject *value, void *context)
104{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000105 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000106 PyErr_Format(PyExc_TypeError,
107 "can't set %s.__module__", type->tp_name);
108 return -1;
109 }
110 if (!value) {
111 PyErr_Format(PyExc_TypeError,
112 "can't delete %s.__module__", type->tp_name);
113 return -1;
114 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000115
Guido van Rossum3926a632001-09-25 16:25:58 +0000116 return PyDict_SetItemString(type->tp_dict, "__module__", value);
117}
118
Tim Peters6d6c1a32001-08-02 04:15:00 +0000119static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000120type_get_bases(PyTypeObject *type, void *context)
121{
122 Py_INCREF(type->tp_bases);
123 return type->tp_bases;
124}
125
126static PyTypeObject *best_base(PyObject *);
127static int mro_internal(PyTypeObject *);
128static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
129static int add_subclass(PyTypeObject*, PyTypeObject*);
130static void remove_subclass(PyTypeObject *, PyTypeObject *);
131static void update_all_slots(PyTypeObject *);
132
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000133typedef int (*update_callback)(PyTypeObject *, void *);
134static int update_subclasses(PyTypeObject *type, PyObject *name,
135 update_callback callback, void *data);
136static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
137 update_callback callback, void *data);
138
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000139static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000140mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000141{
142 PyTypeObject *subclass;
143 PyObject *ref, *subclasses, *old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000144 int i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000145
146 subclasses = type->tp_subclasses;
147 if (subclasses == NULL)
148 return 0;
149 assert(PyList_Check(subclasses));
150 n = PyList_GET_SIZE(subclasses);
151 for (i = 0; i < n; i++) {
152 ref = PyList_GET_ITEM(subclasses, i);
153 assert(PyWeakref_CheckRef(ref));
154 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
155 assert(subclass != NULL);
156 if ((PyObject *)subclass == Py_None)
157 continue;
158 assert(PyType_Check(subclass));
159 old_mro = subclass->tp_mro;
160 if (mro_internal(subclass) < 0) {
161 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000162 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000163 }
164 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000165 PyObject* tuple;
166 tuple = Py_BuildValue("OO", subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000167 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000168 if (!tuple)
169 return -1;
170 if (PyList_Append(temp, tuple) < 0)
171 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000172 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000173 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000174 if (mro_subclasses(subclass, temp) < 0)
175 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000176 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000177 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000178}
179
180static int
181type_set_bases(PyTypeObject *type, PyObject *value, void *context)
182{
183 int i, r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000184 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000185 PyTypeObject *new_base, *old_base;
186 PyObject *old_bases, *old_mro;
187
188 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
189 PyErr_Format(PyExc_TypeError,
190 "can't set %s.__bases__", type->tp_name);
191 return -1;
192 }
193 if (!value) {
194 PyErr_Format(PyExc_TypeError,
195 "can't delete %s.__bases__", type->tp_name);
196 return -1;
197 }
198 if (!PyTuple_Check(value)) {
199 PyErr_Format(PyExc_TypeError,
200 "can only assign tuple to %s.__bases__, not %s",
201 type->tp_name, value->ob_type->tp_name);
202 return -1;
203 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000204 if (PyTuple_GET_SIZE(value) == 0) {
205 PyErr_Format(PyExc_TypeError,
206 "can only assign non-empty tuple to %s.__bases__, not ()",
207 type->tp_name);
208 return -1;
209 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000210 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
211 ob = PyTuple_GET_ITEM(value, i);
212 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
213 PyErr_Format(
214 PyExc_TypeError,
215 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
216 type->tp_name, ob->ob_type->tp_name);
217 return -1;
218 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000219 if (PyType_Check(ob)) {
220 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
221 PyErr_SetString(PyExc_TypeError,
222 "a __bases__ item causes an inheritance cycle");
223 return -1;
224 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000225 }
226 }
227
228 new_base = best_base(value);
229
230 if (!new_base) {
231 return -1;
232 }
233
234 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
235 return -1;
236
237 Py_INCREF(new_base);
238 Py_INCREF(value);
239
240 old_bases = type->tp_bases;
241 old_base = type->tp_base;
242 old_mro = type->tp_mro;
243
244 type->tp_bases = value;
245 type->tp_base = new_base;
246
247 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000248 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000249 }
250
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000251 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000252 if (!temp)
253 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000254
255 r = mro_subclasses(type, temp);
256
257 if (r < 0) {
258 for (i = 0; i < PyList_Size(temp); i++) {
259 PyTypeObject* cls;
260 PyObject* mro;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000261 PyArg_ParseTuple(PyList_GET_ITEM(temp, i),
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000262 "OO", &cls, &mro);
263 Py_DECREF(cls->tp_mro);
264 cls->tp_mro = mro;
265 Py_INCREF(cls->tp_mro);
266 }
267 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000268 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000269 }
270
271 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000272
273 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000274 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000275 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000276 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000277
278 /* for now, sod that: just remove from all old_bases,
279 add to all new_bases */
280
281 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
282 ob = PyTuple_GET_ITEM(old_bases, i);
283 if (PyType_Check(ob)) {
284 remove_subclass(
285 (PyTypeObject*)ob, type);
286 }
287 }
288
289 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
290 ob = PyTuple_GET_ITEM(value, i);
291 if (PyType_Check(ob)) {
292 if (add_subclass((PyTypeObject*)ob, type) < 0)
293 r = -1;
294 }
295 }
296
297 update_all_slots(type);
298
299 Py_DECREF(old_bases);
300 Py_DECREF(old_base);
301 Py_DECREF(old_mro);
302
303 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000304
305 bail:
306 type->tp_bases = old_bases;
307 type->tp_base = old_base;
308 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000309
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000310 Py_DECREF(value);
311 Py_DECREF(new_base);
Tim Petersea7f75d2002-12-07 21:39:16 +0000312
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000313 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000314}
315
316static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000317type_dict(PyTypeObject *type, void *context)
318{
319 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000320 Py_INCREF(Py_None);
321 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000322 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000323 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000324}
325
Tim Peters24008312002-03-17 18:56:20 +0000326static PyObject *
327type_get_doc(PyTypeObject *type, void *context)
328{
329 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000330 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000331 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000332 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000333 if (result == NULL) {
334 result = Py_None;
335 Py_INCREF(result);
336 }
337 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000338 result = result->ob_type->tp_descr_get(result, NULL,
339 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000340 }
341 else {
342 Py_INCREF(result);
343 }
Tim Peters24008312002-03-17 18:56:20 +0000344 return result;
345}
346
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000347static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000348 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
349 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000350 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000351 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000352 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000353 {0}
354};
355
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000356static int
357type_compare(PyObject *v, PyObject *w)
358{
359 /* This is called with type objects only. So we
360 can just compare the addresses. */
361 Py_uintptr_t vv = (Py_uintptr_t)v;
362 Py_uintptr_t ww = (Py_uintptr_t)w;
363 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
364}
365
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000366static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000367type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000368{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000369 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000370 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000371
372 mod = type_module(type, NULL);
373 if (mod == NULL)
374 PyErr_Clear();
375 else if (!PyString_Check(mod)) {
376 Py_DECREF(mod);
377 mod = NULL;
378 }
379 name = type_name(type, NULL);
380 if (name == NULL)
381 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000382
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000383 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
384 kind = "class";
385 else
386 kind = "type";
387
Barry Warsaw7ce36942001-08-24 18:34:26 +0000388 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000389 rtn = PyString_FromFormat("<%s '%s.%s'>",
390 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000391 PyString_AS_STRING(mod),
392 PyString_AS_STRING(name));
393 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000394 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000395 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000396
Guido van Rossumc3542212001-08-16 09:18:56 +0000397 Py_XDECREF(mod);
398 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000399 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000400}
401
Tim Peters6d6c1a32001-08-02 04:15:00 +0000402static PyObject *
403type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
404{
405 PyObject *obj;
406
407 if (type->tp_new == NULL) {
408 PyErr_Format(PyExc_TypeError,
409 "cannot create '%.100s' instances",
410 type->tp_name);
411 return NULL;
412 }
413
Tim Peters3f996e72001-09-13 19:18:27 +0000414 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000415 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000416 /* Ugly exception: when the call was type(something),
417 don't call tp_init on the result. */
418 if (type == &PyType_Type &&
419 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
420 (kwds == NULL ||
421 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
422 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000423 /* If the returned object is not an instance of type,
424 it won't be initialized. */
425 if (!PyType_IsSubtype(obj->ob_type, type))
426 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000427 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000428 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
429 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000430 type->tp_init(obj, args, kwds) < 0) {
431 Py_DECREF(obj);
432 obj = NULL;
433 }
434 }
435 return obj;
436}
437
438PyObject *
439PyType_GenericAlloc(PyTypeObject *type, int nitems)
440{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000441 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000442 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
443 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000444
445 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000446 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000447 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000448 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000449
Neil Schemenauerc806c882001-08-29 23:54:54 +0000450 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000451 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000452
Neil Schemenauerc806c882001-08-29 23:54:54 +0000453 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000454
Tim Peters6d6c1a32001-08-02 04:15:00 +0000455 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
456 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000457
Tim Peters6d6c1a32001-08-02 04:15:00 +0000458 if (type->tp_itemsize == 0)
459 PyObject_INIT(obj, type);
460 else
461 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000462
Tim Peters6d6c1a32001-08-02 04:15:00 +0000463 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000464 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000465 return obj;
466}
467
468PyObject *
469PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
470{
471 return type->tp_alloc(type, 0);
472}
473
Guido van Rossum9475a232001-10-05 20:51:39 +0000474/* Helpers for subtyping */
475
476static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000477traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
478{
479 int i, n;
480 PyMemberDef *mp;
481
482 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000483 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000484 for (i = 0; i < n; i++, mp++) {
485 if (mp->type == T_OBJECT_EX) {
486 char *addr = (char *)self + mp->offset;
487 PyObject *obj = *(PyObject **)addr;
488 if (obj != NULL) {
489 int err = visit(obj, arg);
490 if (err)
491 return err;
492 }
493 }
494 }
495 return 0;
496}
497
498static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000499subtype_traverse(PyObject *self, visitproc visit, void *arg)
500{
501 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000502 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000503
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000504 /* Find the nearest base with a different tp_traverse,
505 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000506 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000507 base = type;
508 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
509 if (base->ob_size) {
510 int err = traverse_slots(base, self, visit, arg);
511 if (err)
512 return err;
513 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000514 base = base->tp_base;
515 assert(base);
516 }
517
518 if (type->tp_dictoffset != base->tp_dictoffset) {
519 PyObject **dictptr = _PyObject_GetDictPtr(self);
520 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000521 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000522 if (err)
523 return err;
524 }
525 }
526
Guido van Rossuma3862092002-06-10 15:24:42 +0000527 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
528 /* For a heaptype, the instances count as references
529 to the type. Traverse the type so the collector
530 can find cycles involving this link. */
531 int err = visit((PyObject *)type, arg);
532 if (err)
533 return err;
534 }
535
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000536 if (basetraverse)
537 return basetraverse(self, visit, arg);
538 return 0;
539}
540
541static void
542clear_slots(PyTypeObject *type, PyObject *self)
543{
544 int i, n;
545 PyMemberDef *mp;
546
547 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000548 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000549 for (i = 0; i < n; i++, mp++) {
550 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
551 char *addr = (char *)self + mp->offset;
552 PyObject *obj = *(PyObject **)addr;
553 if (obj != NULL) {
554 Py_DECREF(obj);
555 *(PyObject **)addr = NULL;
556 }
557 }
558 }
559}
560
561static int
562subtype_clear(PyObject *self)
563{
564 PyTypeObject *type, *base;
565 inquiry baseclear;
566
567 /* Find the nearest base with a different tp_clear
568 and clear slots while we're at it */
569 type = self->ob_type;
570 base = type;
571 while ((baseclear = base->tp_clear) == subtype_clear) {
572 if (base->ob_size)
573 clear_slots(base, self);
574 base = base->tp_base;
575 assert(base);
576 }
577
Guido van Rossuma3862092002-06-10 15:24:42 +0000578 /* There's no need to clear the instance dict (if any);
579 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000580
581 if (baseclear)
582 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000583 return 0;
584}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000585
586static void
587subtype_dealloc(PyObject *self)
588{
Guido van Rossum14227b42001-12-06 02:35:58 +0000589 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000590 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000591
Guido van Rossum22b13872002-08-06 21:41:44 +0000592 /* Extract the type; we expect it to be a heap type */
593 type = self->ob_type;
594 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000595
Guido van Rossum22b13872002-08-06 21:41:44 +0000596 /* Test whether the type has GC exactly once */
597
598 if (!PyType_IS_GC(type)) {
599 /* It's really rare to find a dynamic type that doesn't have
600 GC; it can only happen when deriving from 'object' and not
601 adding any slots or instance variables. This allows
602 certain simplifications: there's no need to call
603 clear_slots(), or DECREF the dict, or clear weakrefs. */
604
605 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000606 if (type->tp_del) {
607 type->tp_del(self);
608 if (self->ob_refcnt > 0)
609 return;
610 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000611
612 /* Find the nearest base with a different tp_dealloc */
613 base = type;
614 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
615 assert(base->ob_size == 0);
616 base = base->tp_base;
617 assert(base);
618 }
619
620 /* Call the base tp_dealloc() */
621 assert(basedealloc);
622 basedealloc(self);
623
624 /* Can't reference self beyond this point */
625 Py_DECREF(type);
626
627 /* Done */
628 return;
629 }
630
631 /* We get here only if the type has GC */
632
633 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000634 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000635 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000636 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000637 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000638 --_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000639 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
640
Guido van Rossum59195fd2003-06-13 20:54:40 +0000641 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000642 base = type;
643 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000644 base = base->tp_base;
645 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000646 }
647
Guido van Rossum1987c662003-05-29 14:29:23 +0000648 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000649 the finalizer (__del__), clearing slots, or clearing the instance
650 dict. */
651
Guido van Rossum1987c662003-05-29 14:29:23 +0000652 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
653 PyObject_ClearWeakRefs(self);
654
655 /* Maybe call finalizer; exit early if resurrected */
656 if (type->tp_del) {
657 type->tp_del(self);
658 if (self->ob_refcnt > 0)
659 goto endlabel;
660 }
661
Guido van Rossum59195fd2003-06-13 20:54:40 +0000662 /* Clear slots up to the nearest base with a different tp_dealloc */
663 base = type;
664 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
665 if (base->ob_size)
666 clear_slots(base, self);
667 base = base->tp_base;
668 assert(base);
669 }
670
Tim Peters6d6c1a32001-08-02 04:15:00 +0000671 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000672 if (type->tp_dictoffset && !base->tp_dictoffset) {
673 PyObject **dictptr = _PyObject_GetDictPtr(self);
674 if (dictptr != NULL) {
675 PyObject *dict = *dictptr;
676 if (dict != NULL) {
677 Py_DECREF(dict);
678 *dictptr = NULL;
679 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000680 }
681 }
682
683 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000684 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000685 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000686
687 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000688 assert(basedealloc);
689 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000690
691 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000692 Py_DECREF(type);
693
Guido van Rossum0906e072002-08-07 20:42:09 +0000694 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000695 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000696 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000697 --_PyTrash_delete_nesting;
698
699 /* Explanation of the weirdness around the trashcan macros:
700
701 Q. What do the trashcan macros do?
702
703 A. Read the comment titled "Trashcan mechanism" in object.h.
704 For one, this explains why there must be a call to GC-untrack
705 before the trashcan begin macro. Without understanding the
706 trashcan code, the answers to the following questions don't make
707 sense.
708
709 Q. Why do we GC-untrack before the trashcan and then immediately
710 GC-track again afterward?
711
712 A. In the case that the base class is GC-aware, the base class
713 probably GC-untracks the object. If it does that using the
714 UNTRACK macro, this will crash when the object is already
715 untracked. Because we don't know what the base class does, the
716 only safe thing is to make sure the object is tracked when we
717 call the base class dealloc. But... The trashcan begin macro
718 requires that the object is *untracked* before it is called. So
719 the dance becomes:
720
721 GC untrack
722 trashcan begin
723 GC track
724
725 Q. Why the bizarre (net-zero) manipulation of
726 _PyTrash_delete_nesting around the trashcan macros?
727
728 A. Some base classes (e.g. list) also use the trashcan mechanism.
729 The following scenario used to be possible:
730
731 - suppose the trashcan level is one below the trashcan limit
732
733 - subtype_dealloc() is called
734
735 - the trashcan limit is not yet reached, so the trashcan level
736 is incremented and the code between trashcan begin and end is
737 executed
738
739 - this destroys much of the object's contents, including its
740 slots and __dict__
741
742 - basedealloc() is called; this is really list_dealloc(), or
743 some other type which also uses the trashcan macros
744
745 - the trashcan limit is now reached, so the object is put on the
746 trashcan's to-be-deleted-later list
747
748 - basedealloc() returns
749
750 - subtype_dealloc() decrefs the object's type
751
752 - subtype_dealloc() returns
753
754 - later, the trashcan code starts deleting the objects from its
755 to-be-deleted-later list
756
757 - subtype_dealloc() is called *AGAIN* for the same object
758
759 - at the very least (if the destroyed slots and __dict__ don't
760 cause problems) the object's type gets decref'ed a second
761 time, which is *BAD*!!!
762
763 The remedy is to make sure that if the code between trashcan
764 begin and end in subtype_dealloc() is called, the code between
765 trashcan begin and end in basedealloc() will also be called.
766 This is done by decrementing the level after passing into the
767 trashcan block, and incrementing it just before leaving the
768 block.
769
770 But now it's possible that a chain of objects consisting solely
771 of objects whose deallocator is subtype_dealloc() will defeat
772 the trashcan mechanism completely: the decremented level means
773 that the effective level never reaches the limit. Therefore, we
774 *increment* the level *before* entering the trashcan block, and
775 matchingly decrement it after leaving. This means the trashcan
776 code will trigger a little early, but that's no big deal.
777
778 Q. Are there any live examples of code in need of all this
779 complexity?
780
781 A. Yes. See SF bug 668433 for code that crashed (when Python was
782 compiled in debug mode) before the trashcan level manipulations
783 were added. For more discussion, see SF patches 581742, 575073
784 and bug 574207.
785 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000786}
787
Jeremy Hylton938ace62002-07-17 16:30:39 +0000788static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000789
Tim Peters6d6c1a32001-08-02 04:15:00 +0000790/* type test with subclassing support */
791
792int
793PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
794{
795 PyObject *mro;
796
Guido van Rossum9478d072001-09-07 18:52:13 +0000797 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
798 return b == a || b == &PyBaseObject_Type;
799
Tim Peters6d6c1a32001-08-02 04:15:00 +0000800 mro = a->tp_mro;
801 if (mro != NULL) {
802 /* Deal with multiple inheritance without recursion
803 by walking the MRO tuple */
804 int i, n;
805 assert(PyTuple_Check(mro));
806 n = PyTuple_GET_SIZE(mro);
807 for (i = 0; i < n; i++) {
808 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
809 return 1;
810 }
811 return 0;
812 }
813 else {
814 /* a is not completely initilized yet; follow tp_base */
815 do {
816 if (a == b)
817 return 1;
818 a = a->tp_base;
819 } while (a != NULL);
820 return b == &PyBaseObject_Type;
821 }
822}
823
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000824/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000825 without looking in the instance dictionary
826 (so we can't use PyObject_GetAttr) but still binding
827 it to the instance. The arguments are the object,
828 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000829 static variable used to cache the interned Python string.
830
831 Two variants:
832
833 - lookup_maybe() returns NULL without raising an exception
834 when the _PyType_Lookup() call fails;
835
836 - lookup_method() always raises an exception upon errors.
837*/
Guido van Rossum60718732001-08-28 17:47:51 +0000838
839static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000840lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000841{
842 PyObject *res;
843
844 if (*attrobj == NULL) {
845 *attrobj = PyString_InternFromString(attrstr);
846 if (*attrobj == NULL)
847 return NULL;
848 }
849 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000850 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000851 descrgetfunc f;
852 if ((f = res->ob_type->tp_descr_get) == NULL)
853 Py_INCREF(res);
854 else
855 res = f(res, self, (PyObject *)(self->ob_type));
856 }
857 return res;
858}
859
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000860static PyObject *
861lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
862{
863 PyObject *res = lookup_maybe(self, attrstr, attrobj);
864 if (res == NULL && !PyErr_Occurred())
865 PyErr_SetObject(PyExc_AttributeError, *attrobj);
866 return res;
867}
868
Guido van Rossum2730b132001-08-28 18:22:14 +0000869/* A variation of PyObject_CallMethod that uses lookup_method()
870 instead of PyObject_GetAttrString(). This uses the same convention
871 as lookup_method to cache the interned name string object. */
872
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000873static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000874call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
875{
876 va_list va;
877 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000878 va_start(va, format);
879
Guido van Rossumda21c012001-10-03 00:50:18 +0000880 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000881 if (func == NULL) {
882 va_end(va);
883 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000884 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000885 return NULL;
886 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000887
888 if (format && *format)
889 args = Py_VaBuildValue(format, va);
890 else
891 args = PyTuple_New(0);
892
893 va_end(va);
894
895 if (args == NULL)
896 return NULL;
897
898 assert(PyTuple_Check(args));
899 retval = PyObject_Call(func, args, NULL);
900
901 Py_DECREF(args);
902 Py_DECREF(func);
903
904 return retval;
905}
906
907/* Clone of call_method() that returns NotImplemented when the lookup fails. */
908
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000909static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000910call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
911{
912 va_list va;
913 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000914 va_start(va, format);
915
Guido van Rossumda21c012001-10-03 00:50:18 +0000916 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000917 if (func == NULL) {
918 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000919 if (!PyErr_Occurred()) {
920 Py_INCREF(Py_NotImplemented);
921 return Py_NotImplemented;
922 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000923 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000924 }
925
926 if (format && *format)
927 args = Py_VaBuildValue(format, va);
928 else
929 args = PyTuple_New(0);
930
931 va_end(va);
932
Guido van Rossum717ce002001-09-14 16:58:08 +0000933 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000934 return NULL;
935
Guido van Rossum717ce002001-09-14 16:58:08 +0000936 assert(PyTuple_Check(args));
937 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000938
939 Py_DECREF(args);
940 Py_DECREF(func);
941
942 return retval;
943}
944
Tim Petersa91e9642001-11-14 23:32:33 +0000945static int
946fill_classic_mro(PyObject *mro, PyObject *cls)
947{
948 PyObject *bases, *base;
949 int i, n;
950
951 assert(PyList_Check(mro));
952 assert(PyClass_Check(cls));
953 i = PySequence_Contains(mro, cls);
954 if (i < 0)
955 return -1;
956 if (!i) {
957 if (PyList_Append(mro, cls) < 0)
958 return -1;
959 }
960 bases = ((PyClassObject *)cls)->cl_bases;
961 assert(bases && PyTuple_Check(bases));
962 n = PyTuple_GET_SIZE(bases);
963 for (i = 0; i < n; i++) {
964 base = PyTuple_GET_ITEM(bases, i);
965 if (fill_classic_mro(mro, base) < 0)
966 return -1;
967 }
968 return 0;
969}
970
971static PyObject *
972classic_mro(PyObject *cls)
973{
974 PyObject *mro;
975
976 assert(PyClass_Check(cls));
977 mro = PyList_New(0);
978 if (mro != NULL) {
979 if (fill_classic_mro(mro, cls) == 0)
980 return mro;
981 Py_DECREF(mro);
982 }
983 return NULL;
984}
985
Tim Petersea7f75d2002-12-07 21:39:16 +0000986/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000987 Method resolution order algorithm C3 described in
988 "A Monotonic Superclass Linearization for Dylan",
989 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000990 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000991 (OOPSLA 1996)
992
Guido van Rossum98f33732002-11-25 21:36:54 +0000993 Some notes about the rules implied by C3:
994
Tim Petersea7f75d2002-12-07 21:39:16 +0000995 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +0000996 It isn't legal to repeat a class in a list of base classes.
997
998 The next three properties are the 3 constraints in "C3".
999
Tim Petersea7f75d2002-12-07 21:39:16 +00001000 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001001 If A precedes B in C's MRO, then A will precede B in the MRO of all
1002 subclasses of C.
1003
1004 Monotonicity.
1005 The MRO of a class must be an extension without reordering of the
1006 MRO of each of its superclasses.
1007
1008 Extended Precedence Graph (EPG).
1009 Linearization is consistent if there is a path in the EPG from
1010 each class to all its successors in the linearization. See
1011 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001012 */
1013
Tim Petersea7f75d2002-12-07 21:39:16 +00001014static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001015tail_contains(PyObject *list, int whence, PyObject *o) {
1016 int j, size;
1017 size = PyList_GET_SIZE(list);
1018
1019 for (j = whence+1; j < size; j++) {
1020 if (PyList_GET_ITEM(list, j) == o)
1021 return 1;
1022 }
1023 return 0;
1024}
1025
Guido van Rossum98f33732002-11-25 21:36:54 +00001026static PyObject *
1027class_name(PyObject *cls)
1028{
1029 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1030 if (name == NULL) {
1031 PyErr_Clear();
1032 Py_XDECREF(name);
1033 name = PyObject_Repr(cls);
1034 }
1035 if (name == NULL)
1036 return NULL;
1037 if (!PyString_Check(name)) {
1038 Py_DECREF(name);
1039 return NULL;
1040 }
1041 return name;
1042}
1043
1044static int
1045check_duplicates(PyObject *list)
1046{
1047 int i, j, n;
1048 /* Let's use a quadratic time algorithm,
1049 assuming that the bases lists is short.
1050 */
1051 n = PyList_GET_SIZE(list);
1052 for (i = 0; i < n; i++) {
1053 PyObject *o = PyList_GET_ITEM(list, i);
1054 for (j = i + 1; j < n; j++) {
1055 if (PyList_GET_ITEM(list, j) == o) {
1056 o = class_name(o);
1057 PyErr_Format(PyExc_TypeError,
1058 "duplicate base class %s",
1059 o ? PyString_AS_STRING(o) : "?");
1060 Py_XDECREF(o);
1061 return -1;
1062 }
1063 }
1064 }
1065 return 0;
1066}
1067
1068/* Raise a TypeError for an MRO order disagreement.
1069
1070 It's hard to produce a good error message. In the absence of better
1071 insight into error reporting, report the classes that were candidates
1072 to be put next into the MRO. There is some conflict between the
1073 order in which they should be put in the MRO, but it's hard to
1074 diagnose what constraint can't be satisfied.
1075*/
1076
1077static void
1078set_mro_error(PyObject *to_merge, int *remain)
1079{
1080 int i, n, off, to_merge_size;
1081 char buf[1000];
1082 PyObject *k, *v;
1083 PyObject *set = PyDict_New();
1084
1085 to_merge_size = PyList_GET_SIZE(to_merge);
1086 for (i = 0; i < to_merge_size; i++) {
1087 PyObject *L = PyList_GET_ITEM(to_merge, i);
1088 if (remain[i] < PyList_GET_SIZE(L)) {
1089 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1090 if (PyDict_SetItem(set, c, Py_None) < 0)
1091 return;
1092 }
1093 }
1094 n = PyDict_Size(set);
1095
Raymond Hettingerf394df42003-04-06 19:13:41 +00001096 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1097consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001098 i = 0;
1099 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1100 PyObject *name = class_name(k);
1101 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1102 name ? PyString_AS_STRING(name) : "?");
1103 Py_XDECREF(name);
1104 if (--n && off+1 < sizeof(buf)) {
1105 buf[off++] = ',';
1106 buf[off] = '\0';
1107 }
1108 }
1109 PyErr_SetString(PyExc_TypeError, buf);
1110 Py_DECREF(set);
1111}
1112
Tim Petersea7f75d2002-12-07 21:39:16 +00001113static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001114pmerge(PyObject *acc, PyObject* to_merge) {
1115 int i, j, to_merge_size;
1116 int *remain;
1117 int ok, empty_cnt;
Tim Petersea7f75d2002-12-07 21:39:16 +00001118
Guido van Rossum1f121312002-11-14 19:49:16 +00001119 to_merge_size = PyList_GET_SIZE(to_merge);
1120
Guido van Rossum98f33732002-11-25 21:36:54 +00001121 /* remain stores an index into each sublist of to_merge.
1122 remain[i] is the index of the next base in to_merge[i]
1123 that is not included in acc.
1124 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001125 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1126 if (remain == NULL)
1127 return -1;
1128 for (i = 0; i < to_merge_size; i++)
1129 remain[i] = 0;
1130
1131 again:
1132 empty_cnt = 0;
1133 for (i = 0; i < to_merge_size; i++) {
1134 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001135
Guido van Rossum1f121312002-11-14 19:49:16 +00001136 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1137
1138 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1139 empty_cnt++;
1140 continue;
1141 }
1142
Guido van Rossum98f33732002-11-25 21:36:54 +00001143 /* Choose next candidate for MRO.
1144
1145 The input sequences alone can determine the choice.
1146 If not, choose the class which appears in the MRO
1147 of the earliest direct superclass of the new class.
1148 */
1149
Guido van Rossum1f121312002-11-14 19:49:16 +00001150 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1151 for (j = 0; j < to_merge_size; j++) {
1152 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001153 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001154 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001155 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001156 }
1157 ok = PyList_Append(acc, candidate);
1158 if (ok < 0) {
1159 PyMem_Free(remain);
1160 return -1;
1161 }
1162 for (j = 0; j < to_merge_size; j++) {
1163 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001164 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1165 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001166 remain[j]++;
1167 }
1168 }
1169 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001170 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001171 }
1172
Guido van Rossum98f33732002-11-25 21:36:54 +00001173 if (empty_cnt == to_merge_size) {
1174 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001175 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001176 }
1177 set_mro_error(to_merge, remain);
1178 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001179 return -1;
1180}
1181
Tim Peters6d6c1a32001-08-02 04:15:00 +00001182static PyObject *
1183mro_implementation(PyTypeObject *type)
1184{
1185 int i, n, ok;
1186 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001187 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001188
Guido van Rossum63517572002-06-18 16:44:57 +00001189 if(type->tp_dict == NULL) {
1190 if(PyType_Ready(type) < 0)
1191 return NULL;
1192 }
1193
Guido van Rossum98f33732002-11-25 21:36:54 +00001194 /* Find a superclass linearization that honors the constraints
1195 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001196 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001197
1198 to_merge is a list of lists, where each list is a superclass
1199 linearization implied by a base class. The last element of
1200 to_merge is the declared list of bases.
1201 */
1202
Tim Peters6d6c1a32001-08-02 04:15:00 +00001203 bases = type->tp_bases;
1204 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001205
1206 to_merge = PyList_New(n+1);
1207 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001208 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001209
Tim Peters6d6c1a32001-08-02 04:15:00 +00001210 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001211 PyObject *base = PyTuple_GET_ITEM(bases, i);
1212 PyObject *parentMRO;
1213 if (PyType_Check(base))
1214 parentMRO = PySequence_List(
1215 ((PyTypeObject*)base)->tp_mro);
1216 else
1217 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001218 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001219 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001220 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001221 }
1222
1223 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001224 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001225
1226 bases_aslist = PySequence_List(bases);
1227 if (bases_aslist == NULL) {
1228 Py_DECREF(to_merge);
1229 return NULL;
1230 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001231 /* This is just a basic sanity check. */
1232 if (check_duplicates(bases_aslist) < 0) {
1233 Py_DECREF(to_merge);
1234 Py_DECREF(bases_aslist);
1235 return NULL;
1236 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001237 PyList_SET_ITEM(to_merge, n, bases_aslist);
1238
1239 result = Py_BuildValue("[O]", (PyObject *)type);
1240 if (result == NULL) {
1241 Py_DECREF(to_merge);
1242 return NULL;
1243 }
1244
1245 ok = pmerge(result, to_merge);
1246 Py_DECREF(to_merge);
1247 if (ok < 0) {
1248 Py_DECREF(result);
1249 return NULL;
1250 }
1251
Tim Peters6d6c1a32001-08-02 04:15:00 +00001252 return result;
1253}
1254
1255static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001256mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001257{
1258 PyTypeObject *type = (PyTypeObject *)self;
1259
Tim Peters6d6c1a32001-08-02 04:15:00 +00001260 return mro_implementation(type);
1261}
1262
1263static int
1264mro_internal(PyTypeObject *type)
1265{
1266 PyObject *mro, *result, *tuple;
1267
1268 if (type->ob_type == &PyType_Type) {
1269 result = mro_implementation(type);
1270 }
1271 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001272 static PyObject *mro_str;
1273 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001274 if (mro == NULL)
1275 return -1;
1276 result = PyObject_CallObject(mro, NULL);
1277 Py_DECREF(mro);
1278 }
1279 if (result == NULL)
1280 return -1;
1281 tuple = PySequence_Tuple(result);
1282 Py_DECREF(result);
1283 type->tp_mro = tuple;
1284 return 0;
1285}
1286
1287
1288/* Calculate the best base amongst multiple base classes.
1289 This is the first one that's on the path to the "solid base". */
1290
1291static PyTypeObject *
1292best_base(PyObject *bases)
1293{
1294 int i, n;
1295 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001296 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001297
1298 assert(PyTuple_Check(bases));
1299 n = PyTuple_GET_SIZE(bases);
1300 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001301 base = NULL;
1302 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001304 base_proto = PyTuple_GET_ITEM(bases, i);
1305 if (PyClass_Check(base_proto))
1306 continue;
1307 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001308 PyErr_SetString(
1309 PyExc_TypeError,
1310 "bases must be types");
1311 return NULL;
1312 }
Tim Petersa91e9642001-11-14 23:32:33 +00001313 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001314 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001315 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001316 return NULL;
1317 }
1318 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001319 if (winner == NULL) {
1320 winner = candidate;
1321 base = base_i;
1322 }
1323 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001324 ;
1325 else if (PyType_IsSubtype(candidate, winner)) {
1326 winner = candidate;
1327 base = base_i;
1328 }
1329 else {
1330 PyErr_SetString(
1331 PyExc_TypeError,
1332 "multiple bases have "
1333 "instance lay-out conflict");
1334 return NULL;
1335 }
1336 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001337 if (base == NULL)
1338 PyErr_SetString(PyExc_TypeError,
1339 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001340 return base;
1341}
1342
1343static int
1344extra_ivars(PyTypeObject *type, PyTypeObject *base)
1345{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001346 size_t t_size = type->tp_basicsize;
1347 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001348
Guido van Rossum9676b222001-08-17 20:32:36 +00001349 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001350 if (type->tp_itemsize || base->tp_itemsize) {
1351 /* If itemsize is involved, stricter rules */
1352 return t_size != b_size ||
1353 type->tp_itemsize != base->tp_itemsize;
1354 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001355 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1356 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1357 t_size -= sizeof(PyObject *);
1358 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1359 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1360 t_size -= sizeof(PyObject *);
1361
1362 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001363}
1364
1365static PyTypeObject *
1366solid_base(PyTypeObject *type)
1367{
1368 PyTypeObject *base;
1369
1370 if (type->tp_base)
1371 base = solid_base(type->tp_base);
1372 else
1373 base = &PyBaseObject_Type;
1374 if (extra_ivars(type, base))
1375 return type;
1376 else
1377 return base;
1378}
1379
Jeremy Hylton938ace62002-07-17 16:30:39 +00001380static void object_dealloc(PyObject *);
1381static int object_init(PyObject *, PyObject *, PyObject *);
1382static int update_slot(PyTypeObject *, PyObject *);
1383static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001384
1385static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001386subtype_dict(PyObject *obj, void *context)
1387{
1388 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1389 PyObject *dict;
1390
1391 if (dictptr == NULL) {
1392 PyErr_SetString(PyExc_AttributeError,
1393 "This object has no __dict__");
1394 return NULL;
1395 }
1396 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001397 if (dict == NULL)
1398 *dictptr = dict = PyDict_New();
1399 Py_XINCREF(dict);
1400 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001401}
1402
Guido van Rossum6661be32001-10-26 04:26:12 +00001403static int
1404subtype_setdict(PyObject *obj, PyObject *value, void *context)
1405{
1406 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1407 PyObject *dict;
1408
1409 if (dictptr == NULL) {
1410 PyErr_SetString(PyExc_AttributeError,
1411 "This object has no __dict__");
1412 return -1;
1413 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001414 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001415 PyErr_SetString(PyExc_TypeError,
1416 "__dict__ must be set to a dictionary");
1417 return -1;
1418 }
1419 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001420 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001421 *dictptr = value;
1422 Py_XDECREF(dict);
1423 return 0;
1424}
1425
Guido van Rossumad47da02002-08-12 19:05:44 +00001426static PyObject *
1427subtype_getweakref(PyObject *obj, void *context)
1428{
1429 PyObject **weaklistptr;
1430 PyObject *result;
1431
1432 if (obj->ob_type->tp_weaklistoffset == 0) {
1433 PyErr_SetString(PyExc_AttributeError,
1434 "This object has no __weaklist__");
1435 return NULL;
1436 }
1437 assert(obj->ob_type->tp_weaklistoffset > 0);
1438 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001439 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001440 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001441 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001442 if (*weaklistptr == NULL)
1443 result = Py_None;
1444 else
1445 result = *weaklistptr;
1446 Py_INCREF(result);
1447 return result;
1448}
1449
Guido van Rossum373c7412003-01-07 13:41:37 +00001450/* Three variants on the subtype_getsets list. */
1451
1452static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001453 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001454 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001455 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001456 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001457 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001458};
1459
Guido van Rossum373c7412003-01-07 13:41:37 +00001460static PyGetSetDef subtype_getsets_dict_only[] = {
1461 {"__dict__", subtype_dict, subtype_setdict,
1462 PyDoc_STR("dictionary for instance variables (if defined)")},
1463 {0}
1464};
1465
1466static PyGetSetDef subtype_getsets_weakref_only[] = {
1467 {"__weakref__", subtype_getweakref, NULL,
1468 PyDoc_STR("list of weak references to the object (if defined)")},
1469 {0}
1470};
1471
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001472static int
1473valid_identifier(PyObject *s)
1474{
Guido van Rossum03013a02002-07-16 14:30:28 +00001475 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001476 int i, n;
1477
1478 if (!PyString_Check(s)) {
1479 PyErr_SetString(PyExc_TypeError,
1480 "__slots__ must be strings");
1481 return 0;
1482 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001483 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001484 n = PyString_GET_SIZE(s);
1485 /* We must reject an empty name. As a hack, we bump the
1486 length to 1 so that the loop will balk on the trailing \0. */
1487 if (n == 0)
1488 n = 1;
1489 for (i = 0; i < n; i++, p++) {
1490 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1491 PyErr_SetString(PyExc_TypeError,
1492 "__slots__ must be identifiers");
1493 return 0;
1494 }
1495 }
1496 return 1;
1497}
1498
Martin v. Löwisd919a592002-10-14 21:07:28 +00001499#ifdef Py_USING_UNICODE
1500/* Replace Unicode objects in slots. */
1501
1502static PyObject *
1503_unicode_to_string(PyObject *slots, int nslots)
1504{
1505 PyObject *tmp = slots;
1506 PyObject *o, *o1;
1507 int i;
1508 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1509 for (i = 0; i < nslots; i++) {
1510 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1511 if (tmp == slots) {
1512 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1513 if (tmp == NULL)
1514 return NULL;
1515 }
1516 o1 = _PyUnicode_AsDefaultEncodedString
1517 (o, NULL);
1518 if (o1 == NULL) {
1519 Py_DECREF(tmp);
1520 return 0;
1521 }
1522 Py_INCREF(o1);
1523 Py_DECREF(o);
1524 PyTuple_SET_ITEM(tmp, i, o1);
1525 }
1526 }
1527 return tmp;
1528}
1529#endif
1530
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001531static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001532type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1533{
1534 PyObject *name, *bases, *dict;
1535 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001536 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001537 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001538 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001539 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001540 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001541 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001542
Tim Peters3abca122001-10-27 19:37:48 +00001543 assert(args != NULL && PyTuple_Check(args));
1544 assert(kwds == NULL || PyDict_Check(kwds));
1545
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001546 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001547 {
1548 const int nargs = PyTuple_GET_SIZE(args);
1549 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1550
1551 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1552 PyObject *x = PyTuple_GET_ITEM(args, 0);
1553 Py_INCREF(x->ob_type);
1554 return (PyObject *) x->ob_type;
1555 }
1556
1557 /* SF bug 475327 -- if that didn't trigger, we need 3
1558 arguments. but PyArg_ParseTupleAndKeywords below may give
1559 a msg saying type() needs exactly 3. */
1560 if (nargs + nkwds != 3) {
1561 PyErr_SetString(PyExc_TypeError,
1562 "type() takes 1 or 3 arguments");
1563 return NULL;
1564 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001565 }
1566
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001567 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001568 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1569 &name,
1570 &PyTuple_Type, &bases,
1571 &PyDict_Type, &dict))
1572 return NULL;
1573
1574 /* Determine the proper metatype to deal with this,
1575 and check for metatype conflicts while we're at it.
1576 Note that if some other metatype wins to contract,
1577 it's possible that its instances are not types. */
1578 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001579 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001580 for (i = 0; i < nbases; i++) {
1581 tmp = PyTuple_GET_ITEM(bases, i);
1582 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001583 if (tmptype == &PyClass_Type)
1584 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001585 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001586 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001587 if (PyType_IsSubtype(tmptype, winner)) {
1588 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001589 continue;
1590 }
1591 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001592 "metaclass conflict: "
1593 "the metaclass of a derived class "
1594 "must be a (non-strict) subclass "
1595 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001596 return NULL;
1597 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001598 if (winner != metatype) {
1599 if (winner->tp_new != type_new) /* Pass it to the winner */
1600 return winner->tp_new(winner, args, kwds);
1601 metatype = winner;
1602 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001603
1604 /* Adjust for empty tuple bases */
1605 if (nbases == 0) {
1606 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1607 if (bases == NULL)
1608 return NULL;
1609 nbases = 1;
1610 }
1611 else
1612 Py_INCREF(bases);
1613
1614 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1615
1616 /* Calculate best base, and check that all bases are type objects */
1617 base = best_base(bases);
1618 if (base == NULL)
1619 return NULL;
1620 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1621 PyErr_Format(PyExc_TypeError,
1622 "type '%.100s' is not an acceptable base type",
1623 base->tp_name);
1624 return NULL;
1625 }
1626
Tim Peters6d6c1a32001-08-02 04:15:00 +00001627 /* Check for a __slots__ sequence variable in dict, and count it */
1628 slots = PyDict_GetItemString(dict, "__slots__");
1629 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001630 add_dict = 0;
1631 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001632 may_add_dict = base->tp_dictoffset == 0;
1633 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1634 if (slots == NULL) {
1635 if (may_add_dict) {
1636 add_dict++;
1637 }
1638 if (may_add_weak) {
1639 add_weak++;
1640 }
1641 }
1642 else {
1643 /* Have slots */
1644
Tim Peters6d6c1a32001-08-02 04:15:00 +00001645 /* Make it into a tuple */
1646 if (PyString_Check(slots))
1647 slots = Py_BuildValue("(O)", slots);
1648 else
1649 slots = PySequence_Tuple(slots);
1650 if (slots == NULL)
1651 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001652 assert(PyTuple_Check(slots));
1653
1654 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001655 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001656 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001657 PyErr_Format(PyExc_TypeError,
1658 "nonempty __slots__ "
1659 "not supported for subtype of '%s'",
1660 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001661 bad_slots:
1662 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001663 return NULL;
1664 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001665
Martin v. Löwisd919a592002-10-14 21:07:28 +00001666#ifdef Py_USING_UNICODE
1667 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001668 if (tmp != slots) {
1669 Py_DECREF(slots);
1670 slots = tmp;
1671 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001672 if (!tmp)
1673 return NULL;
1674#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001675 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001676 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001677 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1678 char *s;
1679 if (!valid_identifier(tmp))
1680 goto bad_slots;
1681 assert(PyString_Check(tmp));
1682 s = PyString_AS_STRING(tmp);
1683 if (strcmp(s, "__dict__") == 0) {
1684 if (!may_add_dict || add_dict) {
1685 PyErr_SetString(PyExc_TypeError,
1686 "__dict__ slot disallowed: "
1687 "we already got one");
1688 goto bad_slots;
1689 }
1690 add_dict++;
1691 }
1692 if (strcmp(s, "__weakref__") == 0) {
1693 if (!may_add_weak || add_weak) {
1694 PyErr_SetString(PyExc_TypeError,
1695 "__weakref__ slot disallowed: "
1696 "either we already got one, "
1697 "or __itemsize__ != 0");
1698 goto bad_slots;
1699 }
1700 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001701 }
1702 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001703
Guido van Rossumad47da02002-08-12 19:05:44 +00001704 /* Copy slots into yet another tuple, demangling names */
1705 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001706 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001707 goto bad_slots;
1708 for (i = j = 0; i < nslots; i++) {
1709 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001710 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001711 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001712 s = PyString_AS_STRING(tmp);
1713 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1714 (add_weak && strcmp(s, "__weakref__") == 0))
1715 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001716 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001717 PyString_AS_STRING(tmp),
1718 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001719 {
1720 tmp = PyString_FromString(buffer);
1721 } else {
1722 Py_INCREF(tmp);
1723 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001724 PyTuple_SET_ITEM(newslots, j, tmp);
1725 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001726 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001727 assert(j == nslots - add_dict - add_weak);
1728 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001729 Py_DECREF(slots);
1730 slots = newslots;
1731
Guido van Rossumad47da02002-08-12 19:05:44 +00001732 /* Secondary bases may provide weakrefs or dict */
1733 if (nbases > 1 &&
1734 ((may_add_dict && !add_dict) ||
1735 (may_add_weak && !add_weak))) {
1736 for (i = 0; i < nbases; i++) {
1737 tmp = PyTuple_GET_ITEM(bases, i);
1738 if (tmp == (PyObject *)base)
1739 continue; /* Skip primary base */
1740 if (PyClass_Check(tmp)) {
1741 /* Classic base class provides both */
1742 if (may_add_dict && !add_dict)
1743 add_dict++;
1744 if (may_add_weak && !add_weak)
1745 add_weak++;
1746 break;
1747 }
1748 assert(PyType_Check(tmp));
1749 tmptype = (PyTypeObject *)tmp;
1750 if (may_add_dict && !add_dict &&
1751 tmptype->tp_dictoffset != 0)
1752 add_dict++;
1753 if (may_add_weak && !add_weak &&
1754 tmptype->tp_weaklistoffset != 0)
1755 add_weak++;
1756 if (may_add_dict && !add_dict)
1757 continue;
1758 if (may_add_weak && !add_weak)
1759 continue;
1760 /* Nothing more to check */
1761 break;
1762 }
1763 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001764 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001765
1766 /* XXX From here until type is safely allocated,
1767 "return NULL" may leak slots! */
1768
1769 /* Allocate the type object */
1770 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001771 if (type == NULL) {
1772 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001773 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001774 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001775
1776 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001777 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001778 Py_INCREF(name);
1779 et->name = name;
1780 et->slots = slots;
1781
Guido van Rossumdc91b992001-08-08 22:26:22 +00001782 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001783 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1784 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001785 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1786 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001787
1788 /* It's a new-style number unless it specifically inherits any
1789 old-style numeric behavior */
1790 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1791 (base->tp_as_number == NULL))
1792 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1793
1794 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001795 type->tp_as_number = &et->as_number;
1796 type->tp_as_sequence = &et->as_sequence;
1797 type->tp_as_mapping = &et->as_mapping;
1798 type->tp_as_buffer = &et->as_buffer;
1799 type->tp_name = PyString_AS_STRING(name);
1800
1801 /* Set tp_base and tp_bases */
1802 type->tp_bases = bases;
1803 Py_INCREF(base);
1804 type->tp_base = base;
1805
Guido van Rossum687ae002001-10-15 22:03:32 +00001806 /* Initialize tp_dict from passed-in dict */
1807 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001808 if (dict == NULL) {
1809 Py_DECREF(type);
1810 return NULL;
1811 }
1812
Guido van Rossumc3542212001-08-16 09:18:56 +00001813 /* Set __module__ in the dict */
1814 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1815 tmp = PyEval_GetGlobals();
1816 if (tmp != NULL) {
1817 tmp = PyDict_GetItemString(tmp, "__name__");
1818 if (tmp != NULL) {
1819 if (PyDict_SetItemString(dict, "__module__",
1820 tmp) < 0)
1821 return NULL;
1822 }
1823 }
1824 }
1825
Tim Peters2f93e282001-10-04 05:27:00 +00001826 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001827 and is a string. The __doc__ accessor will first look for tp_doc;
1828 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001829 */
1830 {
1831 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1832 if (doc != NULL && PyString_Check(doc)) {
1833 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001834 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001835 if (type->tp_doc == NULL) {
1836 Py_DECREF(type);
1837 return NULL;
1838 }
1839 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1840 }
1841 }
1842
Tim Peters6d6c1a32001-08-02 04:15:00 +00001843 /* Special-case __new__: if it's a plain function,
1844 make it a static function */
1845 tmp = PyDict_GetItemString(dict, "__new__");
1846 if (tmp != NULL && PyFunction_Check(tmp)) {
1847 tmp = PyStaticMethod_New(tmp);
1848 if (tmp == NULL) {
1849 Py_DECREF(type);
1850 return NULL;
1851 }
1852 PyDict_SetItemString(dict, "__new__", tmp);
1853 Py_DECREF(tmp);
1854 }
1855
1856 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001857 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001858 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001859 if (slots != NULL) {
1860 for (i = 0; i < nslots; i++, mp++) {
1861 mp->name = PyString_AS_STRING(
1862 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001863 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001864 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001865 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001866 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001867 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001868 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001869 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001870 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001871 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001872 slotoffset += sizeof(PyObject *);
1873 }
1874 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001875 if (add_dict) {
1876 if (base->tp_itemsize)
1877 type->tp_dictoffset = -(long)sizeof(PyObject *);
1878 else
1879 type->tp_dictoffset = slotoffset;
1880 slotoffset += sizeof(PyObject *);
1881 }
1882 if (add_weak) {
1883 assert(!base->tp_itemsize);
1884 type->tp_weaklistoffset = slotoffset;
1885 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001886 }
1887 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001888 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001889 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001890
1891 if (type->tp_weaklistoffset && type->tp_dictoffset)
1892 type->tp_getset = subtype_getsets_full;
1893 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1894 type->tp_getset = subtype_getsets_weakref_only;
1895 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1896 type->tp_getset = subtype_getsets_dict_only;
1897 else
1898 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001899
1900 /* Special case some slots */
1901 if (type->tp_dictoffset != 0 || nslots > 0) {
1902 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1903 type->tp_getattro = PyObject_GenericGetAttr;
1904 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1905 type->tp_setattro = PyObject_GenericSetAttr;
1906 }
1907 type->tp_dealloc = subtype_dealloc;
1908
Guido van Rossum9475a232001-10-05 20:51:39 +00001909 /* Enable GC unless there are really no instance variables possible */
1910 if (!(type->tp_basicsize == sizeof(PyObject) &&
1911 type->tp_itemsize == 0))
1912 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1913
Tim Peters6d6c1a32001-08-02 04:15:00 +00001914 /* Always override allocation strategy to use regular heap */
1915 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001916 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001917 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001918 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001919 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001920 }
1921 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001922 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001923
1924 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001925 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001926 Py_DECREF(type);
1927 return NULL;
1928 }
1929
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001930 /* Put the proper slots in place */
1931 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001932
Tim Peters6d6c1a32001-08-02 04:15:00 +00001933 return (PyObject *)type;
1934}
1935
1936/* Internal API to look for a name through the MRO.
1937 This returns a borrowed reference, and doesn't set an exception! */
1938PyObject *
1939_PyType_Lookup(PyTypeObject *type, PyObject *name)
1940{
1941 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001942 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001943
Guido van Rossum687ae002001-10-15 22:03:32 +00001944 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001945 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001946
1947 /* If mro is NULL, the type is either not yet initialized
1948 by PyType_Ready(), or already cleared by type_clear().
1949 Either way the safest thing to do is to return NULL. */
1950 if (mro == NULL)
1951 return NULL;
1952
Tim Peters6d6c1a32001-08-02 04:15:00 +00001953 assert(PyTuple_Check(mro));
1954 n = PyTuple_GET_SIZE(mro);
1955 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001956 base = PyTuple_GET_ITEM(mro, i);
1957 if (PyClass_Check(base))
1958 dict = ((PyClassObject *)base)->cl_dict;
1959 else {
1960 assert(PyType_Check(base));
1961 dict = ((PyTypeObject *)base)->tp_dict;
1962 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001963 assert(dict && PyDict_Check(dict));
1964 res = PyDict_GetItem(dict, name);
1965 if (res != NULL)
1966 return res;
1967 }
1968 return NULL;
1969}
1970
1971/* This is similar to PyObject_GenericGetAttr(),
1972 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1973static PyObject *
1974type_getattro(PyTypeObject *type, PyObject *name)
1975{
1976 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001977 PyObject *meta_attribute, *attribute;
1978 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001979
1980 /* Initialize this type (we'll assume the metatype is initialized) */
1981 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001982 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001983 return NULL;
1984 }
1985
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001986 /* No readable descriptor found yet */
1987 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001988
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001989 /* Look for the attribute in the metatype */
1990 meta_attribute = _PyType_Lookup(metatype, name);
1991
1992 if (meta_attribute != NULL) {
1993 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001994
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001995 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1996 /* Data descriptors implement tp_descr_set to intercept
1997 * writes. Assume the attribute is not overridden in
1998 * type's tp_dict (and bases): call the descriptor now.
1999 */
2000 return meta_get(meta_attribute, (PyObject *)type,
2001 (PyObject *)metatype);
2002 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002003 }
2004
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002005 /* No data descriptor found on metatype. Look in tp_dict of this
2006 * type and its bases */
2007 attribute = _PyType_Lookup(type, name);
2008 if (attribute != NULL) {
2009 /* Implement descriptor functionality, if any */
2010 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
2011 if (local_get != NULL) {
2012 /* NULL 2nd argument indicates the descriptor was
2013 * found on the target object itself (or a base) */
2014 return local_get(attribute, (PyObject *)NULL,
2015 (PyObject *)type);
2016 }
Tim Peters34592512002-07-11 06:23:50 +00002017
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002018 Py_INCREF(attribute);
2019 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002020 }
2021
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002022 /* No attribute found in local __dict__ (or bases): use the
2023 * descriptor from the metatype, if any */
2024 if (meta_get != NULL)
2025 return meta_get(meta_attribute, (PyObject *)type,
2026 (PyObject *)metatype);
2027
2028 /* If an ordinary attribute was found on the metatype, return it now */
2029 if (meta_attribute != NULL) {
2030 Py_INCREF(meta_attribute);
2031 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002032 }
2033
2034 /* Give up */
2035 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002036 "type object '%.50s' has no attribute '%.400s'",
2037 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002038 return NULL;
2039}
2040
2041static int
2042type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2043{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002044 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2045 PyErr_Format(
2046 PyExc_TypeError,
2047 "can't set attributes of built-in/extension type '%s'",
2048 type->tp_name);
2049 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002050 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002051 /* XXX Example of how I expect this to be used...
2052 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2053 return -1;
2054 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002055 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2056 return -1;
2057 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002058}
2059
2060static void
2061type_dealloc(PyTypeObject *type)
2062{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002063 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002064
2065 /* Assert this is a heap-allocated type object */
2066 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002067 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002068 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002069 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002070 Py_XDECREF(type->tp_base);
2071 Py_XDECREF(type->tp_dict);
2072 Py_XDECREF(type->tp_bases);
2073 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002074 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002075 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00002076 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002077 Py_XDECREF(et->name);
2078 Py_XDECREF(et->slots);
2079 type->ob_type->tp_free((PyObject *)type);
2080}
2081
Guido van Rossum1c450732001-10-08 15:18:27 +00002082static PyObject *
2083type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2084{
2085 PyObject *list, *raw, *ref;
2086 int i, n;
2087
2088 list = PyList_New(0);
2089 if (list == NULL)
2090 return NULL;
2091 raw = type->tp_subclasses;
2092 if (raw == NULL)
2093 return list;
2094 assert(PyList_Check(raw));
2095 n = PyList_GET_SIZE(raw);
2096 for (i = 0; i < n; i++) {
2097 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002098 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002099 ref = PyWeakref_GET_OBJECT(ref);
2100 if (ref != Py_None) {
2101 if (PyList_Append(list, ref) < 0) {
2102 Py_DECREF(list);
2103 return NULL;
2104 }
2105 }
2106 }
2107 return list;
2108}
2109
Tim Peters6d6c1a32001-08-02 04:15:00 +00002110static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002111 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002112 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002113 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002114 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002115 {0}
2116};
2117
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002118PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002119"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002120"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002121
Guido van Rossum048eb752001-10-02 21:24:57 +00002122static int
2123type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2124{
Guido van Rossum048eb752001-10-02 21:24:57 +00002125 int err;
2126
Guido van Rossuma3862092002-06-10 15:24:42 +00002127 /* Because of type_is_gc(), the collector only calls this
2128 for heaptypes. */
2129 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002130
2131#define VISIT(SLOT) \
2132 if (SLOT) { \
2133 err = visit((PyObject *)(SLOT), arg); \
2134 if (err) \
2135 return err; \
2136 }
2137
2138 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002139 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002140 VISIT(type->tp_mro);
2141 VISIT(type->tp_bases);
2142 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002143
2144 /* There's no need to visit type->tp_subclasses or
Guido van Rossume5c691a2003-03-07 15:13:17 +00002145 ((PyHeapTypeObject *)type)->slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002146 in cycles; tp_subclasses is a list of weak references,
2147 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002148
2149#undef VISIT
2150
2151 return 0;
2152}
2153
2154static int
2155type_clear(PyTypeObject *type)
2156{
Guido van Rossum048eb752001-10-02 21:24:57 +00002157 PyObject *tmp;
2158
Guido van Rossuma3862092002-06-10 15:24:42 +00002159 /* Because of type_is_gc(), the collector only calls this
2160 for heaptypes. */
2161 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002162
2163#define CLEAR(SLOT) \
2164 if (SLOT) { \
2165 tmp = (PyObject *)(SLOT); \
2166 SLOT = NULL; \
2167 Py_DECREF(tmp); \
2168 }
2169
Guido van Rossuma3862092002-06-10 15:24:42 +00002170 /* The only field we need to clear is tp_mro, which is part of a
2171 hard cycle (its first element is the class itself) that won't
2172 be broken otherwise (it's a tuple and tuples don't have a
2173 tp_clear handler). None of the other fields need to be
2174 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002175
Guido van Rossuma3862092002-06-10 15:24:42 +00002176 tp_dict:
2177 It is a dict, so the collector will call its tp_clear.
2178
2179 tp_cache:
2180 Not used; if it were, it would be a dict.
2181
2182 tp_bases, tp_base:
2183 If these are involved in a cycle, there must be at least
2184 one other, mutable object in the cycle, e.g. a base
2185 class's dict; the cycle will be broken that way.
2186
2187 tp_subclasses:
2188 A list of weak references can't be part of a cycle; and
2189 lists have their own tp_clear.
2190
Guido van Rossume5c691a2003-03-07 15:13:17 +00002191 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002192 A tuple of strings can't be part of a cycle.
2193 */
2194
2195 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002196
Guido van Rossum048eb752001-10-02 21:24:57 +00002197#undef CLEAR
2198
2199 return 0;
2200}
2201
2202static int
2203type_is_gc(PyTypeObject *type)
2204{
2205 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2206}
2207
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002208PyTypeObject PyType_Type = {
2209 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002210 0, /* ob_size */
2211 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002212 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002213 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002214 (destructor)type_dealloc, /* tp_dealloc */
2215 0, /* tp_print */
2216 0, /* tp_getattr */
2217 0, /* tp_setattr */
2218 type_compare, /* tp_compare */
2219 (reprfunc)type_repr, /* tp_repr */
2220 0, /* tp_as_number */
2221 0, /* tp_as_sequence */
2222 0, /* tp_as_mapping */
2223 (hashfunc)_Py_HashPointer, /* tp_hash */
2224 (ternaryfunc)type_call, /* tp_call */
2225 0, /* tp_str */
2226 (getattrofunc)type_getattro, /* tp_getattro */
2227 (setattrofunc)type_setattro, /* tp_setattro */
2228 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002229 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2230 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002231 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002232 (traverseproc)type_traverse, /* tp_traverse */
2233 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002234 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002235 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002236 0, /* tp_iter */
2237 0, /* tp_iternext */
2238 type_methods, /* tp_methods */
2239 type_members, /* tp_members */
2240 type_getsets, /* tp_getset */
2241 0, /* tp_base */
2242 0, /* tp_dict */
2243 0, /* tp_descr_get */
2244 0, /* tp_descr_set */
2245 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2246 0, /* tp_init */
2247 0, /* tp_alloc */
2248 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002249 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002250 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002251};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002252
2253
2254/* The base type of all types (eventually)... except itself. */
2255
2256static int
2257object_init(PyObject *self, PyObject *args, PyObject *kwds)
2258{
2259 return 0;
2260}
2261
Guido van Rossum298e4212003-02-13 16:30:16 +00002262/* If we don't have a tp_new for a new-style class, new will use this one.
2263 Therefore this should take no arguments/keywords. However, this new may
2264 also be inherited by objects that define a tp_init but no tp_new. These
2265 objects WILL pass argumets to tp_new, because it gets the same args as
2266 tp_init. So only allow arguments if we aren't using the default init, in
2267 which case we expect init to handle argument parsing. */
2268static PyObject *
2269object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2270{
2271 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2272 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2273 PyErr_SetString(PyExc_TypeError,
2274 "default __new__ takes no parameters");
2275 return NULL;
2276 }
2277 return type->tp_alloc(type, 0);
2278}
2279
Tim Peters6d6c1a32001-08-02 04:15:00 +00002280static void
2281object_dealloc(PyObject *self)
2282{
2283 self->ob_type->tp_free(self);
2284}
2285
Guido van Rossum8e248182001-08-12 05:17:56 +00002286static PyObject *
2287object_repr(PyObject *self)
2288{
Guido van Rossum76e69632001-08-16 18:52:43 +00002289 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002290 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002291
Guido van Rossum76e69632001-08-16 18:52:43 +00002292 type = self->ob_type;
2293 mod = type_module(type, NULL);
2294 if (mod == NULL)
2295 PyErr_Clear();
2296 else if (!PyString_Check(mod)) {
2297 Py_DECREF(mod);
2298 mod = NULL;
2299 }
2300 name = type_name(type, NULL);
2301 if (name == NULL)
2302 return NULL;
2303 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002304 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002305 PyString_AS_STRING(mod),
2306 PyString_AS_STRING(name),
2307 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002308 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002309 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002310 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002311 Py_XDECREF(mod);
2312 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002313 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002314}
2315
Guido van Rossumb8f63662001-08-15 23:57:02 +00002316static PyObject *
2317object_str(PyObject *self)
2318{
2319 unaryfunc f;
2320
2321 f = self->ob_type->tp_repr;
2322 if (f == NULL)
2323 f = object_repr;
2324 return f(self);
2325}
2326
Guido van Rossum8e248182001-08-12 05:17:56 +00002327static long
2328object_hash(PyObject *self)
2329{
2330 return _Py_HashPointer(self);
2331}
Guido van Rossum8e248182001-08-12 05:17:56 +00002332
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002333static PyObject *
2334object_get_class(PyObject *self, void *closure)
2335{
2336 Py_INCREF(self->ob_type);
2337 return (PyObject *)(self->ob_type);
2338}
2339
2340static int
2341equiv_structs(PyTypeObject *a, PyTypeObject *b)
2342{
2343 return a == b ||
2344 (a != NULL &&
2345 b != NULL &&
2346 a->tp_basicsize == b->tp_basicsize &&
2347 a->tp_itemsize == b->tp_itemsize &&
2348 a->tp_dictoffset == b->tp_dictoffset &&
2349 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2350 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2351 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2352}
2353
2354static int
2355same_slots_added(PyTypeObject *a, PyTypeObject *b)
2356{
2357 PyTypeObject *base = a->tp_base;
2358 int size;
2359
2360 if (base != b->tp_base)
2361 return 0;
2362 if (equiv_structs(a, base) && equiv_structs(b, base))
2363 return 1;
2364 size = base->tp_basicsize;
2365 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2366 size += sizeof(PyObject *);
2367 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2368 size += sizeof(PyObject *);
2369 return size == a->tp_basicsize && size == b->tp_basicsize;
2370}
2371
2372static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002373compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2374{
2375 PyTypeObject *newbase, *oldbase;
2376
2377 if (new->tp_dealloc != old->tp_dealloc ||
2378 new->tp_free != old->tp_free)
2379 {
2380 PyErr_Format(PyExc_TypeError,
2381 "%s assignment: "
2382 "'%s' deallocator differs from '%s'",
2383 attr,
2384 new->tp_name,
2385 old->tp_name);
2386 return 0;
2387 }
2388 newbase = new;
2389 oldbase = old;
2390 while (equiv_structs(newbase, newbase->tp_base))
2391 newbase = newbase->tp_base;
2392 while (equiv_structs(oldbase, oldbase->tp_base))
2393 oldbase = oldbase->tp_base;
2394 if (newbase != oldbase &&
2395 (newbase->tp_base != oldbase->tp_base ||
2396 !same_slots_added(newbase, oldbase))) {
2397 PyErr_Format(PyExc_TypeError,
2398 "%s assignment: "
2399 "'%s' object layout differs from '%s'",
2400 attr,
2401 new->tp_name,
2402 old->tp_name);
2403 return 0;
2404 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002405
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002406 return 1;
2407}
2408
2409static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002410object_set_class(PyObject *self, PyObject *value, void *closure)
2411{
2412 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002413 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002414
Guido van Rossumb6b89422002-04-15 01:03:30 +00002415 if (value == NULL) {
2416 PyErr_SetString(PyExc_TypeError,
2417 "can't delete __class__ attribute");
2418 return -1;
2419 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002420 if (!PyType_Check(value)) {
2421 PyErr_Format(PyExc_TypeError,
2422 "__class__ must be set to new-style class, not '%s' object",
2423 value->ob_type->tp_name);
2424 return -1;
2425 }
2426 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002427 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2428 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2429 {
2430 PyErr_Format(PyExc_TypeError,
2431 "__class__ assignment: only for heap types");
2432 return -1;
2433 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002434 if (compatible_for_assignment(new, old, "__class__")) {
2435 Py_INCREF(new);
2436 self->ob_type = new;
2437 Py_DECREF(old);
2438 return 0;
2439 }
2440 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002441 return -1;
2442 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002443}
2444
2445static PyGetSetDef object_getsets[] = {
2446 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002447 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002448 {0}
2449};
2450
Guido van Rossumc53f0092003-02-18 22:05:12 +00002451
Guido van Rossum036f9992003-02-21 22:02:54 +00002452/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2453 We fall back to helpers in copy_reg for:
2454 - pickle protocols < 2
2455 - calculating the list of slot names (done only once per class)
2456 - the __newobj__ function (which is used as a token but never called)
2457*/
2458
2459static PyObject *
2460import_copy_reg(void)
2461{
2462 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002463
2464 if (!copy_reg_str) {
2465 copy_reg_str = PyString_InternFromString("copy_reg");
2466 if (copy_reg_str == NULL)
2467 return NULL;
2468 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002469
2470 return PyImport_Import(copy_reg_str);
2471}
2472
2473static PyObject *
2474slotnames(PyObject *cls)
2475{
2476 PyObject *clsdict;
2477 PyObject *copy_reg;
2478 PyObject *slotnames;
2479
2480 if (!PyType_Check(cls)) {
2481 Py_INCREF(Py_None);
2482 return Py_None;
2483 }
2484
2485 clsdict = ((PyTypeObject *)cls)->tp_dict;
2486 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
2487 if (slotnames != NULL) {
2488 Py_INCREF(slotnames);
2489 return slotnames;
2490 }
2491
2492 copy_reg = import_copy_reg();
2493 if (copy_reg == NULL)
2494 return NULL;
2495
2496 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2497 Py_DECREF(copy_reg);
2498 if (slotnames != NULL &&
2499 slotnames != Py_None &&
2500 !PyList_Check(slotnames))
2501 {
2502 PyErr_SetString(PyExc_TypeError,
2503 "copy_reg._slotnames didn't return a list or None");
2504 Py_DECREF(slotnames);
2505 slotnames = NULL;
2506 }
2507
2508 return slotnames;
2509}
2510
2511static PyObject *
2512reduce_2(PyObject *obj)
2513{
2514 PyObject *cls, *getnewargs;
2515 PyObject *args = NULL, *args2 = NULL;
2516 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2517 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2518 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
2519 int i, n;
2520
2521 cls = PyObject_GetAttrString(obj, "__class__");
2522 if (cls == NULL)
2523 return NULL;
2524
2525 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2526 if (getnewargs != NULL) {
2527 args = PyObject_CallObject(getnewargs, NULL);
2528 Py_DECREF(getnewargs);
2529 if (args != NULL && !PyTuple_Check(args)) {
2530 PyErr_SetString(PyExc_TypeError,
2531 "__getnewargs__ should return a tuple");
2532 goto end;
2533 }
2534 }
2535 else {
2536 PyErr_Clear();
2537 args = PyTuple_New(0);
2538 }
2539 if (args == NULL)
2540 goto end;
2541
2542 getstate = PyObject_GetAttrString(obj, "__getstate__");
2543 if (getstate != NULL) {
2544 state = PyObject_CallObject(getstate, NULL);
2545 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002546 if (state == NULL)
2547 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002548 }
2549 else {
2550 state = PyObject_GetAttrString(obj, "__dict__");
2551 if (state == NULL) {
2552 PyErr_Clear();
2553 state = Py_None;
2554 Py_INCREF(state);
2555 }
2556 names = slotnames(cls);
2557 if (names == NULL)
2558 goto end;
2559 if (names != Py_None) {
2560 assert(PyList_Check(names));
2561 slots = PyDict_New();
2562 if (slots == NULL)
2563 goto end;
2564 n = 0;
2565 /* Can't pre-compute the list size; the list
2566 is stored on the class so accessible to other
2567 threads, which may be run by DECREF */
2568 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2569 PyObject *name, *value;
2570 name = PyList_GET_ITEM(names, i);
2571 value = PyObject_GetAttr(obj, name);
2572 if (value == NULL)
2573 PyErr_Clear();
2574 else {
2575 int err = PyDict_SetItem(slots, name,
2576 value);
2577 Py_DECREF(value);
2578 if (err)
2579 goto end;
2580 n++;
2581 }
2582 }
2583 if (n) {
2584 state = Py_BuildValue("(NO)", state, slots);
2585 if (state == NULL)
2586 goto end;
2587 }
2588 }
2589 }
2590
2591 if (!PyList_Check(obj)) {
2592 listitems = Py_None;
2593 Py_INCREF(listitems);
2594 }
2595 else {
2596 listitems = PyObject_GetIter(obj);
2597 if (listitems == NULL)
2598 goto end;
2599 }
2600
2601 if (!PyDict_Check(obj)) {
2602 dictitems = Py_None;
2603 Py_INCREF(dictitems);
2604 }
2605 else {
2606 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2607 if (dictitems == NULL)
2608 goto end;
2609 }
2610
2611 copy_reg = import_copy_reg();
2612 if (copy_reg == NULL)
2613 goto end;
2614 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2615 if (newobj == NULL)
2616 goto end;
2617
2618 n = PyTuple_GET_SIZE(args);
2619 args2 = PyTuple_New(n+1);
2620 if (args2 == NULL)
2621 goto end;
2622 PyTuple_SET_ITEM(args2, 0, cls);
2623 cls = NULL;
2624 for (i = 0; i < n; i++) {
2625 PyObject *v = PyTuple_GET_ITEM(args, i);
2626 Py_INCREF(v);
2627 PyTuple_SET_ITEM(args2, i+1, v);
2628 }
2629
2630 res = Py_BuildValue("(OOOOO)",
2631 newobj, args2, state, listitems, dictitems);
2632
2633 end:
2634 Py_XDECREF(cls);
2635 Py_XDECREF(args);
2636 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002637 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002638 Py_XDECREF(state);
2639 Py_XDECREF(names);
2640 Py_XDECREF(listitems);
2641 Py_XDECREF(dictitems);
2642 Py_XDECREF(copy_reg);
2643 Py_XDECREF(newobj);
2644 return res;
2645}
2646
2647static PyObject *
2648object_reduce_ex(PyObject *self, PyObject *args)
2649{
2650 /* Call copy_reg._reduce_ex(self, proto) */
2651 PyObject *reduce, *copy_reg, *res;
2652 int proto = 0;
2653
2654 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2655 return NULL;
2656
2657 reduce = PyObject_GetAttrString(self, "__reduce__");
2658 if (reduce == NULL)
2659 PyErr_Clear();
2660 else {
2661 PyObject *cls, *clsreduce, *objreduce;
2662 int override;
2663 cls = PyObject_GetAttrString(self, "__class__");
2664 if (cls == NULL) {
2665 Py_DECREF(reduce);
2666 return NULL;
2667 }
2668 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2669 Py_DECREF(cls);
2670 if (clsreduce == NULL) {
2671 Py_DECREF(reduce);
2672 return NULL;
2673 }
2674 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2675 "__reduce__");
2676 override = (clsreduce != objreduce);
2677 Py_DECREF(clsreduce);
2678 if (override) {
2679 res = PyObject_CallObject(reduce, NULL);
2680 Py_DECREF(reduce);
2681 return res;
2682 }
2683 else
2684 Py_DECREF(reduce);
2685 }
2686
2687 if (proto >= 2)
2688 return reduce_2(self);
2689
2690 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002691 if (!copy_reg)
2692 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002693
Guido van Rossumc53f0092003-02-18 22:05:12 +00002694 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002695 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002696
Guido van Rossum3926a632001-09-25 16:25:58 +00002697 return res;
2698}
2699
2700static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002701 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2702 PyDoc_STR("helper for pickle")},
2703 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002704 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002705 {0}
2706};
2707
Guido van Rossum036f9992003-02-21 22:02:54 +00002708
Tim Peters6d6c1a32001-08-02 04:15:00 +00002709PyTypeObject PyBaseObject_Type = {
2710 PyObject_HEAD_INIT(&PyType_Type)
2711 0, /* ob_size */
2712 "object", /* tp_name */
2713 sizeof(PyObject), /* tp_basicsize */
2714 0, /* tp_itemsize */
2715 (destructor)object_dealloc, /* tp_dealloc */
2716 0, /* tp_print */
2717 0, /* tp_getattr */
2718 0, /* tp_setattr */
2719 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002720 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002721 0, /* tp_as_number */
2722 0, /* tp_as_sequence */
2723 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002724 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002725 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002726 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002727 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002728 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002729 0, /* tp_as_buffer */
2730 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002731 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002732 0, /* tp_traverse */
2733 0, /* tp_clear */
2734 0, /* tp_richcompare */
2735 0, /* tp_weaklistoffset */
2736 0, /* tp_iter */
2737 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002738 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002739 0, /* tp_members */
2740 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002741 0, /* tp_base */
2742 0, /* tp_dict */
2743 0, /* tp_descr_get */
2744 0, /* tp_descr_set */
2745 0, /* tp_dictoffset */
2746 object_init, /* tp_init */
2747 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002748 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002749 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002750};
2751
2752
2753/* Initialize the __dict__ in a type object */
2754
2755static int
2756add_methods(PyTypeObject *type, PyMethodDef *meth)
2757{
Guido van Rossum687ae002001-10-15 22:03:32 +00002758 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002759
2760 for (; meth->ml_name != NULL; meth++) {
2761 PyObject *descr;
2762 if (PyDict_GetItemString(dict, meth->ml_name))
2763 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002764 if (meth->ml_flags & METH_CLASS) {
2765 if (meth->ml_flags & METH_STATIC) {
2766 PyErr_SetString(PyExc_ValueError,
2767 "method cannot be both class and static");
2768 return -1;
2769 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002770 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002771 }
2772 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002773 PyObject *cfunc = PyCFunction_New(meth, NULL);
2774 if (cfunc == NULL)
2775 return -1;
2776 descr = PyStaticMethod_New(cfunc);
2777 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002778 }
2779 else {
2780 descr = PyDescr_NewMethod(type, meth);
2781 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002782 if (descr == NULL)
2783 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002784 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002785 return -1;
2786 Py_DECREF(descr);
2787 }
2788 return 0;
2789}
2790
2791static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002792add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002793{
Guido van Rossum687ae002001-10-15 22:03:32 +00002794 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002795
2796 for (; memb->name != NULL; memb++) {
2797 PyObject *descr;
2798 if (PyDict_GetItemString(dict, memb->name))
2799 continue;
2800 descr = PyDescr_NewMember(type, memb);
2801 if (descr == NULL)
2802 return -1;
2803 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2804 return -1;
2805 Py_DECREF(descr);
2806 }
2807 return 0;
2808}
2809
2810static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002811add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002812{
Guido van Rossum687ae002001-10-15 22:03:32 +00002813 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002814
2815 for (; gsp->name != NULL; gsp++) {
2816 PyObject *descr;
2817 if (PyDict_GetItemString(dict, gsp->name))
2818 continue;
2819 descr = PyDescr_NewGetSet(type, gsp);
2820
2821 if (descr == NULL)
2822 return -1;
2823 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2824 return -1;
2825 Py_DECREF(descr);
2826 }
2827 return 0;
2828}
2829
Guido van Rossum13d52f02001-08-10 21:24:08 +00002830static void
2831inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002832{
2833 int oldsize, newsize;
2834
Guido van Rossum13d52f02001-08-10 21:24:08 +00002835 /* Special flag magic */
2836 if (!type->tp_as_buffer && base->tp_as_buffer) {
2837 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2838 type->tp_flags |=
2839 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2840 }
2841 if (!type->tp_as_sequence && base->tp_as_sequence) {
2842 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2843 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2844 }
2845 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2846 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2847 if ((!type->tp_as_number && base->tp_as_number) ||
2848 (!type->tp_as_sequence && base->tp_as_sequence)) {
2849 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2850 if (!type->tp_as_number && !type->tp_as_sequence) {
2851 type->tp_flags |= base->tp_flags &
2852 Py_TPFLAGS_HAVE_INPLACEOPS;
2853 }
2854 }
2855 /* Wow */
2856 }
2857 if (!type->tp_as_number && base->tp_as_number) {
2858 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2859 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2860 }
2861
2862 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002863 oldsize = base->tp_basicsize;
2864 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2865 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2866 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002867 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2868 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002869 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002870 if (type->tp_traverse == NULL)
2871 type->tp_traverse = base->tp_traverse;
2872 if (type->tp_clear == NULL)
2873 type->tp_clear = base->tp_clear;
2874 }
2875 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002876 /* The condition below could use some explanation.
2877 It appears that tp_new is not inherited for static types
2878 whose base class is 'object'; this seems to be a precaution
2879 so that old extension types don't suddenly become
2880 callable (object.__new__ wouldn't insure the invariants
2881 that the extension type's own factory function ensures).
2882 Heap types, of course, are under our control, so they do
2883 inherit tp_new; static extension types that specify some
2884 other built-in type as the default are considered
2885 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002886 if (base != &PyBaseObject_Type ||
2887 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2888 if (type->tp_new == NULL)
2889 type->tp_new = base->tp_new;
2890 }
2891 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002892 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002893
2894 /* Copy other non-function slots */
2895
2896#undef COPYVAL
2897#define COPYVAL(SLOT) \
2898 if (type->SLOT == 0) type->SLOT = base->SLOT
2899
2900 COPYVAL(tp_itemsize);
2901 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2902 COPYVAL(tp_weaklistoffset);
2903 }
2904 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2905 COPYVAL(tp_dictoffset);
2906 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002907}
2908
2909static void
2910inherit_slots(PyTypeObject *type, PyTypeObject *base)
2911{
2912 PyTypeObject *basebase;
2913
2914#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002915#undef COPYSLOT
2916#undef COPYNUM
2917#undef COPYSEQ
2918#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002919#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002920
2921#define SLOTDEFINED(SLOT) \
2922 (base->SLOT != 0 && \
2923 (basebase == NULL || base->SLOT != basebase->SLOT))
2924
Tim Peters6d6c1a32001-08-02 04:15:00 +00002925#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002926 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002927
2928#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2929#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2930#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002931#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002932
Guido van Rossum13d52f02001-08-10 21:24:08 +00002933 /* This won't inherit indirect slots (from tp_as_number etc.)
2934 if type doesn't provide the space. */
2935
2936 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2937 basebase = base->tp_base;
2938 if (basebase->tp_as_number == NULL)
2939 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002940 COPYNUM(nb_add);
2941 COPYNUM(nb_subtract);
2942 COPYNUM(nb_multiply);
2943 COPYNUM(nb_divide);
2944 COPYNUM(nb_remainder);
2945 COPYNUM(nb_divmod);
2946 COPYNUM(nb_power);
2947 COPYNUM(nb_negative);
2948 COPYNUM(nb_positive);
2949 COPYNUM(nb_absolute);
2950 COPYNUM(nb_nonzero);
2951 COPYNUM(nb_invert);
2952 COPYNUM(nb_lshift);
2953 COPYNUM(nb_rshift);
2954 COPYNUM(nb_and);
2955 COPYNUM(nb_xor);
2956 COPYNUM(nb_or);
2957 COPYNUM(nb_coerce);
2958 COPYNUM(nb_int);
2959 COPYNUM(nb_long);
2960 COPYNUM(nb_float);
2961 COPYNUM(nb_oct);
2962 COPYNUM(nb_hex);
2963 COPYNUM(nb_inplace_add);
2964 COPYNUM(nb_inplace_subtract);
2965 COPYNUM(nb_inplace_multiply);
2966 COPYNUM(nb_inplace_divide);
2967 COPYNUM(nb_inplace_remainder);
2968 COPYNUM(nb_inplace_power);
2969 COPYNUM(nb_inplace_lshift);
2970 COPYNUM(nb_inplace_rshift);
2971 COPYNUM(nb_inplace_and);
2972 COPYNUM(nb_inplace_xor);
2973 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002974 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2975 COPYNUM(nb_true_divide);
2976 COPYNUM(nb_floor_divide);
2977 COPYNUM(nb_inplace_true_divide);
2978 COPYNUM(nb_inplace_floor_divide);
2979 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002980 }
2981
Guido van Rossum13d52f02001-08-10 21:24:08 +00002982 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2983 basebase = base->tp_base;
2984 if (basebase->tp_as_sequence == NULL)
2985 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002986 COPYSEQ(sq_length);
2987 COPYSEQ(sq_concat);
2988 COPYSEQ(sq_repeat);
2989 COPYSEQ(sq_item);
2990 COPYSEQ(sq_slice);
2991 COPYSEQ(sq_ass_item);
2992 COPYSEQ(sq_ass_slice);
2993 COPYSEQ(sq_contains);
2994 COPYSEQ(sq_inplace_concat);
2995 COPYSEQ(sq_inplace_repeat);
2996 }
2997
Guido van Rossum13d52f02001-08-10 21:24:08 +00002998 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2999 basebase = base->tp_base;
3000 if (basebase->tp_as_mapping == NULL)
3001 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003002 COPYMAP(mp_length);
3003 COPYMAP(mp_subscript);
3004 COPYMAP(mp_ass_subscript);
3005 }
3006
Tim Petersfc57ccb2001-10-12 02:38:24 +00003007 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3008 basebase = base->tp_base;
3009 if (basebase->tp_as_buffer == NULL)
3010 basebase = NULL;
3011 COPYBUF(bf_getreadbuffer);
3012 COPYBUF(bf_getwritebuffer);
3013 COPYBUF(bf_getsegcount);
3014 COPYBUF(bf_getcharbuffer);
3015 }
3016
Guido van Rossum13d52f02001-08-10 21:24:08 +00003017 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003018
Tim Peters6d6c1a32001-08-02 04:15:00 +00003019 COPYSLOT(tp_dealloc);
3020 COPYSLOT(tp_print);
3021 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3022 type->tp_getattr = base->tp_getattr;
3023 type->tp_getattro = base->tp_getattro;
3024 }
3025 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3026 type->tp_setattr = base->tp_setattr;
3027 type->tp_setattro = base->tp_setattro;
3028 }
3029 /* tp_compare see tp_richcompare */
3030 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003031 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003032 COPYSLOT(tp_call);
3033 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003034 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003035 if (type->tp_compare == NULL &&
3036 type->tp_richcompare == NULL &&
3037 type->tp_hash == NULL)
3038 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003039 type->tp_compare = base->tp_compare;
3040 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003041 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003042 }
3043 }
3044 else {
3045 COPYSLOT(tp_compare);
3046 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003047 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3048 COPYSLOT(tp_iter);
3049 COPYSLOT(tp_iternext);
3050 }
3051 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3052 COPYSLOT(tp_descr_get);
3053 COPYSLOT(tp_descr_set);
3054 COPYSLOT(tp_dictoffset);
3055 COPYSLOT(tp_init);
3056 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003057 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003058 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3059 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3060 /* They agree about gc. */
3061 COPYSLOT(tp_free);
3062 }
3063 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3064 type->tp_free == NULL &&
3065 base->tp_free == _PyObject_Del) {
3066 /* A bit of magic to plug in the correct default
3067 * tp_free function when a derived class adds gc,
3068 * didn't define tp_free, and the base uses the
3069 * default non-gc tp_free.
3070 */
3071 type->tp_free = PyObject_GC_Del;
3072 }
3073 /* else they didn't agree about gc, and there isn't something
3074 * obvious to be done -- the type is on its own.
3075 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003076 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003077}
3078
Jeremy Hylton938ace62002-07-17 16:30:39 +00003079static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003080
Tim Peters6d6c1a32001-08-02 04:15:00 +00003081int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003082PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003083{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003084 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003085 PyTypeObject *base;
3086 int i, n;
3087
Guido van Rossumcab05802002-06-10 15:29:03 +00003088 if (type->tp_flags & Py_TPFLAGS_READY) {
3089 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003090 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003091 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003092 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003093
3094 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003095
Tim Peters36eb4df2003-03-23 03:33:13 +00003096#ifdef Py_TRACE_REFS
3097 /* PyType_Ready is the closest thing we have to a choke point
3098 * for type objects, so is the best place I can think of to try
3099 * to get type objects into the doubly-linked list of all objects.
3100 * Still, not all type objects go thru PyType_Ready.
3101 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003102 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003103#endif
3104
Tim Peters6d6c1a32001-08-02 04:15:00 +00003105 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3106 base = type->tp_base;
3107 if (base == NULL && type != &PyBaseObject_Type)
3108 base = type->tp_base = &PyBaseObject_Type;
3109
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003110 /* Initialize the base class */
3111 if (base && base->tp_dict == NULL) {
3112 if (PyType_Ready(base) < 0)
3113 goto error;
3114 }
3115
Guido van Rossum0986d822002-04-08 01:38:42 +00003116 /* Initialize ob_type if NULL. This means extensions that want to be
3117 compilable separately on Windows can call PyType_Ready() instead of
3118 initializing the ob_type field of their type objects. */
3119 if (type->ob_type == NULL)
3120 type->ob_type = base->ob_type;
3121
Tim Peters6d6c1a32001-08-02 04:15:00 +00003122 /* Initialize tp_bases */
3123 bases = type->tp_bases;
3124 if (bases == NULL) {
3125 if (base == NULL)
3126 bases = PyTuple_New(0);
3127 else
3128 bases = Py_BuildValue("(O)", base);
3129 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003130 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003131 type->tp_bases = bases;
3132 }
3133
Guido van Rossum687ae002001-10-15 22:03:32 +00003134 /* Initialize tp_dict */
3135 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003136 if (dict == NULL) {
3137 dict = PyDict_New();
3138 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003139 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003140 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003141 }
3142
Guido van Rossum687ae002001-10-15 22:03:32 +00003143 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003144 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003145 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003146 if (type->tp_methods != NULL) {
3147 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003148 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003149 }
3150 if (type->tp_members != NULL) {
3151 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003152 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003153 }
3154 if (type->tp_getset != NULL) {
3155 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003156 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003157 }
3158
Tim Peters6d6c1a32001-08-02 04:15:00 +00003159 /* Calculate method resolution order */
3160 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003161 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003162 }
3163
Guido van Rossum13d52f02001-08-10 21:24:08 +00003164 /* Inherit special flags from dominant base */
3165 if (type->tp_base != NULL)
3166 inherit_special(type, type->tp_base);
3167
Tim Peters6d6c1a32001-08-02 04:15:00 +00003168 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003169 bases = type->tp_mro;
3170 assert(bases != NULL);
3171 assert(PyTuple_Check(bases));
3172 n = PyTuple_GET_SIZE(bases);
3173 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003174 PyObject *b = PyTuple_GET_ITEM(bases, i);
3175 if (PyType_Check(b))
3176 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003177 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003178
Tim Peters3cfe7542003-05-21 21:29:48 +00003179 /* Sanity check for tp_free. */
3180 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3181 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3182 /* This base class needs to call tp_free, but doesn't have
3183 * one, or its tp_free is for non-gc'ed objects.
3184 */
3185 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3186 "gc and is a base type but has inappropriate "
3187 "tp_free slot",
3188 type->tp_name);
3189 goto error;
3190 }
3191
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003192 /* if the type dictionary doesn't contain a __doc__, set it from
3193 the tp_doc slot.
3194 */
3195 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3196 if (type->tp_doc != NULL) {
3197 PyObject *doc = PyString_FromString(type->tp_doc);
3198 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3199 Py_DECREF(doc);
3200 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003201 PyDict_SetItemString(type->tp_dict,
3202 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003203 }
3204 }
3205
Guido van Rossum13d52f02001-08-10 21:24:08 +00003206 /* Some more special stuff */
3207 base = type->tp_base;
3208 if (base != NULL) {
3209 if (type->tp_as_number == NULL)
3210 type->tp_as_number = base->tp_as_number;
3211 if (type->tp_as_sequence == NULL)
3212 type->tp_as_sequence = base->tp_as_sequence;
3213 if (type->tp_as_mapping == NULL)
3214 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003215 if (type->tp_as_buffer == NULL)
3216 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003217 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003218
Guido van Rossum1c450732001-10-08 15:18:27 +00003219 /* Link into each base class's list of subclasses */
3220 bases = type->tp_bases;
3221 n = PyTuple_GET_SIZE(bases);
3222 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003223 PyObject *b = PyTuple_GET_ITEM(bases, i);
3224 if (PyType_Check(b) &&
3225 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003226 goto error;
3227 }
3228
Guido van Rossum13d52f02001-08-10 21:24:08 +00003229 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003230 assert(type->tp_dict != NULL);
3231 type->tp_flags =
3232 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003233 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003234
3235 error:
3236 type->tp_flags &= ~Py_TPFLAGS_READYING;
3237 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003238}
3239
Guido van Rossum1c450732001-10-08 15:18:27 +00003240static int
3241add_subclass(PyTypeObject *base, PyTypeObject *type)
3242{
3243 int i;
3244 PyObject *list, *ref, *new;
3245
3246 list = base->tp_subclasses;
3247 if (list == NULL) {
3248 base->tp_subclasses = list = PyList_New(0);
3249 if (list == NULL)
3250 return -1;
3251 }
3252 assert(PyList_Check(list));
3253 new = PyWeakref_NewRef((PyObject *)type, NULL);
3254 i = PyList_GET_SIZE(list);
3255 while (--i >= 0) {
3256 ref = PyList_GET_ITEM(list, i);
3257 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003258 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3259 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003260 }
3261 i = PyList_Append(list, new);
3262 Py_DECREF(new);
3263 return i;
3264}
3265
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003266static void
3267remove_subclass(PyTypeObject *base, PyTypeObject *type)
3268{
3269 int i;
3270 PyObject *list, *ref;
3271
3272 list = base->tp_subclasses;
3273 if (list == NULL) {
3274 return;
3275 }
3276 assert(PyList_Check(list));
3277 i = PyList_GET_SIZE(list);
3278 while (--i >= 0) {
3279 ref = PyList_GET_ITEM(list, i);
3280 assert(PyWeakref_CheckRef(ref));
3281 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3282 /* this can't fail, right? */
3283 PySequence_DelItem(list, i);
3284 return;
3285 }
3286 }
3287}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003288
3289/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3290
3291/* There's a wrapper *function* for each distinct function typedef used
3292 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3293 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3294 Most tables have only one entry; the tables for binary operators have two
3295 entries, one regular and one with reversed arguments. */
3296
3297static PyObject *
3298wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3299{
3300 inquiry func = (inquiry)wrapped;
3301 int res;
3302
3303 if (!PyArg_ParseTuple(args, ""))
3304 return NULL;
3305 res = (*func)(self);
3306 if (res == -1 && PyErr_Occurred())
3307 return NULL;
3308 return PyInt_FromLong((long)res);
3309}
3310
Tim Peters6d6c1a32001-08-02 04:15:00 +00003311static PyObject *
3312wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3313{
3314 binaryfunc func = (binaryfunc)wrapped;
3315 PyObject *other;
3316
3317 if (!PyArg_ParseTuple(args, "O", &other))
3318 return NULL;
3319 return (*func)(self, other);
3320}
3321
3322static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003323wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3324{
3325 binaryfunc func = (binaryfunc)wrapped;
3326 PyObject *other;
3327
3328 if (!PyArg_ParseTuple(args, "O", &other))
3329 return NULL;
3330 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003331 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003332 Py_INCREF(Py_NotImplemented);
3333 return Py_NotImplemented;
3334 }
3335 return (*func)(self, other);
3336}
3337
3338static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003339wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3340{
3341 binaryfunc func = (binaryfunc)wrapped;
3342 PyObject *other;
3343
3344 if (!PyArg_ParseTuple(args, "O", &other))
3345 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003346 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003347 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003348 Py_INCREF(Py_NotImplemented);
3349 return Py_NotImplemented;
3350 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003351 return (*func)(other, self);
3352}
3353
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003354static PyObject *
3355wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3356{
3357 coercion func = (coercion)wrapped;
3358 PyObject *other, *res;
3359 int ok;
3360
3361 if (!PyArg_ParseTuple(args, "O", &other))
3362 return NULL;
3363 ok = func(&self, &other);
3364 if (ok < 0)
3365 return NULL;
3366 if (ok > 0) {
3367 Py_INCREF(Py_NotImplemented);
3368 return Py_NotImplemented;
3369 }
3370 res = PyTuple_New(2);
3371 if (res == NULL) {
3372 Py_DECREF(self);
3373 Py_DECREF(other);
3374 return NULL;
3375 }
3376 PyTuple_SET_ITEM(res, 0, self);
3377 PyTuple_SET_ITEM(res, 1, other);
3378 return res;
3379}
3380
Tim Peters6d6c1a32001-08-02 04:15:00 +00003381static PyObject *
3382wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3383{
3384 ternaryfunc func = (ternaryfunc)wrapped;
3385 PyObject *other;
3386 PyObject *third = Py_None;
3387
3388 /* Note: This wrapper only works for __pow__() */
3389
3390 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3391 return NULL;
3392 return (*func)(self, other, third);
3393}
3394
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003395static PyObject *
3396wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3397{
3398 ternaryfunc func = (ternaryfunc)wrapped;
3399 PyObject *other;
3400 PyObject *third = Py_None;
3401
3402 /* Note: This wrapper only works for __pow__() */
3403
3404 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3405 return NULL;
3406 return (*func)(other, self, third);
3407}
3408
Tim Peters6d6c1a32001-08-02 04:15:00 +00003409static PyObject *
3410wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3411{
3412 unaryfunc func = (unaryfunc)wrapped;
3413
3414 if (!PyArg_ParseTuple(args, ""))
3415 return NULL;
3416 return (*func)(self);
3417}
3418
Tim Peters6d6c1a32001-08-02 04:15:00 +00003419static PyObject *
3420wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3421{
3422 intargfunc func = (intargfunc)wrapped;
3423 int i;
3424
3425 if (!PyArg_ParseTuple(args, "i", &i))
3426 return NULL;
3427 return (*func)(self, i);
3428}
3429
Guido van Rossum5d815f32001-08-17 21:57:47 +00003430static int
3431getindex(PyObject *self, PyObject *arg)
3432{
3433 int i;
3434
3435 i = PyInt_AsLong(arg);
3436 if (i == -1 && PyErr_Occurred())
3437 return -1;
3438 if (i < 0) {
3439 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3440 if (sq && sq->sq_length) {
3441 int n = (*sq->sq_length)(self);
3442 if (n < 0)
3443 return -1;
3444 i += n;
3445 }
3446 }
3447 return i;
3448}
3449
3450static PyObject *
3451wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3452{
3453 intargfunc func = (intargfunc)wrapped;
3454 PyObject *arg;
3455 int i;
3456
Guido van Rossumf4593e02001-10-03 12:09:30 +00003457 if (PyTuple_GET_SIZE(args) == 1) {
3458 arg = PyTuple_GET_ITEM(args, 0);
3459 i = getindex(self, arg);
3460 if (i == -1 && PyErr_Occurred())
3461 return NULL;
3462 return (*func)(self, i);
3463 }
3464 PyArg_ParseTuple(args, "O", &arg);
3465 assert(PyErr_Occurred());
3466 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003467}
3468
Tim Peters6d6c1a32001-08-02 04:15:00 +00003469static PyObject *
3470wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3471{
3472 intintargfunc func = (intintargfunc)wrapped;
3473 int i, j;
3474
3475 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3476 return NULL;
3477 return (*func)(self, i, j);
3478}
3479
Tim Peters6d6c1a32001-08-02 04:15:00 +00003480static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003481wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003482{
3483 intobjargproc func = (intobjargproc)wrapped;
3484 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003485 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003486
Guido van Rossum5d815f32001-08-17 21:57:47 +00003487 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3488 return NULL;
3489 i = getindex(self, arg);
3490 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003491 return NULL;
3492 res = (*func)(self, i, value);
3493 if (res == -1 && PyErr_Occurred())
3494 return NULL;
3495 Py_INCREF(Py_None);
3496 return Py_None;
3497}
3498
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003499static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003500wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003501{
3502 intobjargproc func = (intobjargproc)wrapped;
3503 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003504 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003505
Guido van Rossum5d815f32001-08-17 21:57:47 +00003506 if (!PyArg_ParseTuple(args, "O", &arg))
3507 return NULL;
3508 i = getindex(self, arg);
3509 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003510 return NULL;
3511 res = (*func)(self, i, NULL);
3512 if (res == -1 && PyErr_Occurred())
3513 return NULL;
3514 Py_INCREF(Py_None);
3515 return Py_None;
3516}
3517
Tim Peters6d6c1a32001-08-02 04:15:00 +00003518static PyObject *
3519wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3520{
3521 intintobjargproc func = (intintobjargproc)wrapped;
3522 int i, j, res;
3523 PyObject *value;
3524
3525 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3526 return NULL;
3527 res = (*func)(self, i, j, value);
3528 if (res == -1 && PyErr_Occurred())
3529 return NULL;
3530 Py_INCREF(Py_None);
3531 return Py_None;
3532}
3533
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003534static PyObject *
3535wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3536{
3537 intintobjargproc func = (intintobjargproc)wrapped;
3538 int i, j, res;
3539
3540 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3541 return NULL;
3542 res = (*func)(self, i, j, NULL);
3543 if (res == -1 && PyErr_Occurred())
3544 return NULL;
3545 Py_INCREF(Py_None);
3546 return Py_None;
3547}
3548
Tim Peters6d6c1a32001-08-02 04:15:00 +00003549/* XXX objobjproc is a misnomer; should be objargpred */
3550static PyObject *
3551wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3552{
3553 objobjproc func = (objobjproc)wrapped;
3554 int res;
3555 PyObject *value;
3556
3557 if (!PyArg_ParseTuple(args, "O", &value))
3558 return NULL;
3559 res = (*func)(self, value);
3560 if (res == -1 && PyErr_Occurred())
3561 return NULL;
3562 return PyInt_FromLong((long)res);
3563}
3564
Tim Peters6d6c1a32001-08-02 04:15:00 +00003565static PyObject *
3566wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3567{
3568 objobjargproc func = (objobjargproc)wrapped;
3569 int res;
3570 PyObject *key, *value;
3571
3572 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3573 return NULL;
3574 res = (*func)(self, key, value);
3575 if (res == -1 && PyErr_Occurred())
3576 return NULL;
3577 Py_INCREF(Py_None);
3578 return Py_None;
3579}
3580
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003581static PyObject *
3582wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3583{
3584 objobjargproc func = (objobjargproc)wrapped;
3585 int res;
3586 PyObject *key;
3587
3588 if (!PyArg_ParseTuple(args, "O", &key))
3589 return NULL;
3590 res = (*func)(self, key, NULL);
3591 if (res == -1 && PyErr_Occurred())
3592 return NULL;
3593 Py_INCREF(Py_None);
3594 return Py_None;
3595}
3596
Tim Peters6d6c1a32001-08-02 04:15:00 +00003597static PyObject *
3598wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3599{
3600 cmpfunc func = (cmpfunc)wrapped;
3601 int res;
3602 PyObject *other;
3603
3604 if (!PyArg_ParseTuple(args, "O", &other))
3605 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003606 if (other->ob_type->tp_compare != func &&
3607 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003608 PyErr_Format(
3609 PyExc_TypeError,
3610 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3611 self->ob_type->tp_name,
3612 self->ob_type->tp_name,
3613 other->ob_type->tp_name);
3614 return NULL;
3615 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003616 res = (*func)(self, other);
3617 if (PyErr_Occurred())
3618 return NULL;
3619 return PyInt_FromLong((long)res);
3620}
3621
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003622/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003623 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003624static int
3625hackcheck(PyObject *self, setattrofunc func, char *what)
3626{
3627 PyTypeObject *type = self->ob_type;
3628 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3629 type = type->tp_base;
3630 if (type->tp_setattro != func) {
3631 PyErr_Format(PyExc_TypeError,
3632 "can't apply this %s to %s object",
3633 what,
3634 type->tp_name);
3635 return 0;
3636 }
3637 return 1;
3638}
3639
Tim Peters6d6c1a32001-08-02 04:15:00 +00003640static PyObject *
3641wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3642{
3643 setattrofunc func = (setattrofunc)wrapped;
3644 int res;
3645 PyObject *name, *value;
3646
3647 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3648 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003649 if (!hackcheck(self, func, "__setattr__"))
3650 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003651 res = (*func)(self, name, value);
3652 if (res < 0)
3653 return NULL;
3654 Py_INCREF(Py_None);
3655 return Py_None;
3656}
3657
3658static PyObject *
3659wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3660{
3661 setattrofunc func = (setattrofunc)wrapped;
3662 int res;
3663 PyObject *name;
3664
3665 if (!PyArg_ParseTuple(args, "O", &name))
3666 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003667 if (!hackcheck(self, func, "__delattr__"))
3668 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003669 res = (*func)(self, name, NULL);
3670 if (res < 0)
3671 return NULL;
3672 Py_INCREF(Py_None);
3673 return Py_None;
3674}
3675
Tim Peters6d6c1a32001-08-02 04:15:00 +00003676static PyObject *
3677wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3678{
3679 hashfunc func = (hashfunc)wrapped;
3680 long res;
3681
3682 if (!PyArg_ParseTuple(args, ""))
3683 return NULL;
3684 res = (*func)(self);
3685 if (res == -1 && PyErr_Occurred())
3686 return NULL;
3687 return PyInt_FromLong(res);
3688}
3689
Tim Peters6d6c1a32001-08-02 04:15:00 +00003690static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003691wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003692{
3693 ternaryfunc func = (ternaryfunc)wrapped;
3694
Guido van Rossumc8e56452001-10-22 00:43:43 +00003695 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003696}
3697
Tim Peters6d6c1a32001-08-02 04:15:00 +00003698static PyObject *
3699wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3700{
3701 richcmpfunc func = (richcmpfunc)wrapped;
3702 PyObject *other;
3703
3704 if (!PyArg_ParseTuple(args, "O", &other))
3705 return NULL;
3706 return (*func)(self, other, op);
3707}
3708
3709#undef RICHCMP_WRAPPER
3710#define RICHCMP_WRAPPER(NAME, OP) \
3711static PyObject * \
3712richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3713{ \
3714 return wrap_richcmpfunc(self, args, wrapped, OP); \
3715}
3716
Jack Jansen8e938b42001-08-08 15:29:49 +00003717RICHCMP_WRAPPER(lt, Py_LT)
3718RICHCMP_WRAPPER(le, Py_LE)
3719RICHCMP_WRAPPER(eq, Py_EQ)
3720RICHCMP_WRAPPER(ne, Py_NE)
3721RICHCMP_WRAPPER(gt, Py_GT)
3722RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003723
Tim Peters6d6c1a32001-08-02 04:15:00 +00003724static PyObject *
3725wrap_next(PyObject *self, PyObject *args, void *wrapped)
3726{
3727 unaryfunc func = (unaryfunc)wrapped;
3728 PyObject *res;
3729
3730 if (!PyArg_ParseTuple(args, ""))
3731 return NULL;
3732 res = (*func)(self);
3733 if (res == NULL && !PyErr_Occurred())
3734 PyErr_SetNone(PyExc_StopIteration);
3735 return res;
3736}
3737
Tim Peters6d6c1a32001-08-02 04:15:00 +00003738static PyObject *
3739wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3740{
3741 descrgetfunc func = (descrgetfunc)wrapped;
3742 PyObject *obj;
3743 PyObject *type = NULL;
3744
3745 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3746 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003747 if (obj == Py_None)
3748 obj = NULL;
3749 if (type == Py_None)
3750 type = NULL;
3751 if (type == NULL &&obj == NULL) {
3752 PyErr_SetString(PyExc_TypeError,
3753 "__get__(None, None) is invalid");
3754 return NULL;
3755 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003756 return (*func)(self, obj, type);
3757}
3758
Tim Peters6d6c1a32001-08-02 04:15:00 +00003759static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003760wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003761{
3762 descrsetfunc func = (descrsetfunc)wrapped;
3763 PyObject *obj, *value;
3764 int ret;
3765
3766 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3767 return NULL;
3768 ret = (*func)(self, obj, value);
3769 if (ret < 0)
3770 return NULL;
3771 Py_INCREF(Py_None);
3772 return Py_None;
3773}
Guido van Rossum22b13872002-08-06 21:41:44 +00003774
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003775static PyObject *
3776wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3777{
3778 descrsetfunc func = (descrsetfunc)wrapped;
3779 PyObject *obj;
3780 int ret;
3781
3782 if (!PyArg_ParseTuple(args, "O", &obj))
3783 return NULL;
3784 ret = (*func)(self, obj, NULL);
3785 if (ret < 0)
3786 return NULL;
3787 Py_INCREF(Py_None);
3788 return Py_None;
3789}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003790
Tim Peters6d6c1a32001-08-02 04:15:00 +00003791static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003792wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003793{
3794 initproc func = (initproc)wrapped;
3795
Guido van Rossumc8e56452001-10-22 00:43:43 +00003796 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003797 return NULL;
3798 Py_INCREF(Py_None);
3799 return Py_None;
3800}
3801
Tim Peters6d6c1a32001-08-02 04:15:00 +00003802static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003803tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003804{
Barry Warsaw60f01882001-08-22 19:24:42 +00003805 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003806 PyObject *arg0, *res;
3807
3808 if (self == NULL || !PyType_Check(self))
3809 Py_FatalError("__new__() called with non-type 'self'");
3810 type = (PyTypeObject *)self;
3811 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003812 PyErr_Format(PyExc_TypeError,
3813 "%s.__new__(): not enough arguments",
3814 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003815 return NULL;
3816 }
3817 arg0 = PyTuple_GET_ITEM(args, 0);
3818 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003819 PyErr_Format(PyExc_TypeError,
3820 "%s.__new__(X): X is not a type object (%s)",
3821 type->tp_name,
3822 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003823 return NULL;
3824 }
3825 subtype = (PyTypeObject *)arg0;
3826 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003827 PyErr_Format(PyExc_TypeError,
3828 "%s.__new__(%s): %s is not a subtype of %s",
3829 type->tp_name,
3830 subtype->tp_name,
3831 subtype->tp_name,
3832 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003833 return NULL;
3834 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003835
3836 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003837 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003838 most derived base that's not a heap type is this type. */
3839 staticbase = subtype;
3840 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3841 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003842 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003843 PyErr_Format(PyExc_TypeError,
3844 "%s.__new__(%s) is not safe, use %s.__new__()",
3845 type->tp_name,
3846 subtype->tp_name,
3847 staticbase == NULL ? "?" : staticbase->tp_name);
3848 return NULL;
3849 }
3850
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003851 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3852 if (args == NULL)
3853 return NULL;
3854 res = type->tp_new(subtype, args, kwds);
3855 Py_DECREF(args);
3856 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003857}
3858
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003859static struct PyMethodDef tp_new_methoddef[] = {
3860 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003861 PyDoc_STR("T.__new__(S, ...) -> "
3862 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003863 {0}
3864};
3865
3866static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003867add_tp_new_wrapper(PyTypeObject *type)
3868{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003869 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003870
Guido van Rossum687ae002001-10-15 22:03:32 +00003871 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003872 return 0;
3873 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003874 if (func == NULL)
3875 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003876 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003877}
3878
Guido van Rossumf040ede2001-08-07 16:40:56 +00003879/* Slot wrappers that call the corresponding __foo__ slot. See comments
3880 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003881
Guido van Rossumdc91b992001-08-08 22:26:22 +00003882#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003883static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003884FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003885{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003886 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003887 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003888}
3889
Guido van Rossumdc91b992001-08-08 22:26:22 +00003890#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003891static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003892FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003893{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003894 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003895 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003896}
3897
Guido van Rossumcd118802003-01-06 22:57:47 +00003898/* Boolean helper for SLOT1BINFULL().
3899 right.__class__ is a nontrivial subclass of left.__class__. */
3900static int
3901method_is_overloaded(PyObject *left, PyObject *right, char *name)
3902{
3903 PyObject *a, *b;
3904 int ok;
3905
3906 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3907 if (b == NULL) {
3908 PyErr_Clear();
3909 /* If right doesn't have it, it's not overloaded */
3910 return 0;
3911 }
3912
3913 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3914 if (a == NULL) {
3915 PyErr_Clear();
3916 Py_DECREF(b);
3917 /* If right has it but left doesn't, it's overloaded */
3918 return 1;
3919 }
3920
3921 ok = PyObject_RichCompareBool(a, b, Py_NE);
3922 Py_DECREF(a);
3923 Py_DECREF(b);
3924 if (ok < 0) {
3925 PyErr_Clear();
3926 return 0;
3927 }
3928
3929 return ok;
3930}
3931
Guido van Rossumdc91b992001-08-08 22:26:22 +00003932
3933#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003934static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003935FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003936{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003937 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003938 int do_other = self->ob_type != other->ob_type && \
3939 other->ob_type->tp_as_number != NULL && \
3940 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003941 if (self->ob_type->tp_as_number != NULL && \
3942 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3943 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003944 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00003945 PyType_IsSubtype(other->ob_type, self->ob_type) && \
3946 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00003947 r = call_maybe( \
3948 other, ROPSTR, &rcache_str, "(O)", self); \
3949 if (r != Py_NotImplemented) \
3950 return r; \
3951 Py_DECREF(r); \
3952 do_other = 0; \
3953 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003954 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003955 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003956 if (r != Py_NotImplemented || \
3957 other->ob_type == self->ob_type) \
3958 return r; \
3959 Py_DECREF(r); \
3960 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003961 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003962 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003963 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003964 } \
3965 Py_INCREF(Py_NotImplemented); \
3966 return Py_NotImplemented; \
3967}
3968
3969#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3970 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3971
3972#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3973static PyObject * \
3974FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3975{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003976 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003977 return call_method(self, OPSTR, &cache_str, \
3978 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003979}
3980
3981static int
3982slot_sq_length(PyObject *self)
3983{
Guido van Rossum2730b132001-08-28 18:22:14 +00003984 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003985 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003986 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003987
3988 if (res == NULL)
3989 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003990 len = (int)PyInt_AsLong(res);
3991 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003992 if (len == -1 && PyErr_Occurred())
3993 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003994 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003995 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003996 "__len__() should return >= 0");
3997 return -1;
3998 }
Guido van Rossum26111622001-10-01 16:42:49 +00003999 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004000}
4001
Guido van Rossumdc91b992001-08-08 22:26:22 +00004002SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
4003SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00004004
4005/* Super-optimized version of slot_sq_item.
4006 Other slots could do the same... */
4007static PyObject *
4008slot_sq_item(PyObject *self, int i)
4009{
4010 static PyObject *getitem_str;
4011 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4012 descrgetfunc f;
4013
4014 if (getitem_str == NULL) {
4015 getitem_str = PyString_InternFromString("__getitem__");
4016 if (getitem_str == NULL)
4017 return NULL;
4018 }
4019 func = _PyType_Lookup(self->ob_type, getitem_str);
4020 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004021 if ((f = func->ob_type->tp_descr_get) == NULL)
4022 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004023 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004024 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004025 if (func == NULL) {
4026 return NULL;
4027 }
4028 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00004029 ival = PyInt_FromLong(i);
4030 if (ival != NULL) {
4031 args = PyTuple_New(1);
4032 if (args != NULL) {
4033 PyTuple_SET_ITEM(args, 0, ival);
4034 retval = PyObject_Call(func, args, NULL);
4035 Py_XDECREF(args);
4036 Py_XDECREF(func);
4037 return retval;
4038 }
4039 }
4040 }
4041 else {
4042 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4043 }
4044 Py_XDECREF(args);
4045 Py_XDECREF(ival);
4046 Py_XDECREF(func);
4047 return NULL;
4048}
4049
Guido van Rossumdc91b992001-08-08 22:26:22 +00004050SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004051
4052static int
4053slot_sq_ass_item(PyObject *self, int index, PyObject *value)
4054{
4055 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004056 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004057
4058 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004059 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004060 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004061 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004062 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004063 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004064 if (res == NULL)
4065 return -1;
4066 Py_DECREF(res);
4067 return 0;
4068}
4069
4070static int
4071slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
4072{
4073 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004074 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004075
4076 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004077 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004078 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004079 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004080 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004081 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004082 if (res == NULL)
4083 return -1;
4084 Py_DECREF(res);
4085 return 0;
4086}
4087
4088static int
4089slot_sq_contains(PyObject *self, PyObject *value)
4090{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004091 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004092 int result = -1;
4093
Guido van Rossum60718732001-08-28 17:47:51 +00004094 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004095
Guido van Rossum55f20992001-10-01 17:18:22 +00004096 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004097 if (func != NULL) {
4098 args = Py_BuildValue("(O)", value);
4099 if (args == NULL)
4100 res = NULL;
4101 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004102 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004103 Py_DECREF(args);
4104 }
4105 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004106 if (res != NULL) {
4107 result = PyObject_IsTrue(res);
4108 Py_DECREF(res);
4109 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004110 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004111 else if (! PyErr_Occurred()) {
4112 result = _PySequence_IterSearch(self, value,
4113 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004114 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004115 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004116}
4117
Guido van Rossumdc91b992001-08-08 22:26:22 +00004118SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
4119SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004120
4121#define slot_mp_length slot_sq_length
4122
Guido van Rossumdc91b992001-08-08 22:26:22 +00004123SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004124
4125static int
4126slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4127{
4128 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004129 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004130
4131 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004132 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004133 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004134 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004135 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004136 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004137 if (res == NULL)
4138 return -1;
4139 Py_DECREF(res);
4140 return 0;
4141}
4142
Guido van Rossumdc91b992001-08-08 22:26:22 +00004143SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4144SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4145SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4146SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4147SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4148SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4149
Jeremy Hylton938ace62002-07-17 16:30:39 +00004150static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004151
4152SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4153 nb_power, "__pow__", "__rpow__")
4154
4155static PyObject *
4156slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4157{
Guido van Rossum2730b132001-08-28 18:22:14 +00004158 static PyObject *pow_str;
4159
Guido van Rossumdc91b992001-08-08 22:26:22 +00004160 if (modulus == Py_None)
4161 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004162 /* Three-arg power doesn't use __rpow__. But ternary_op
4163 can call this when the second argument's type uses
4164 slot_nb_power, so check before calling self.__pow__. */
4165 if (self->ob_type->tp_as_number != NULL &&
4166 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4167 return call_method(self, "__pow__", &pow_str,
4168 "(OO)", other, modulus);
4169 }
4170 Py_INCREF(Py_NotImplemented);
4171 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004172}
4173
4174SLOT0(slot_nb_negative, "__neg__")
4175SLOT0(slot_nb_positive, "__pos__")
4176SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004177
4178static int
4179slot_nb_nonzero(PyObject *self)
4180{
Tim Petersea7f75d2002-12-07 21:39:16 +00004181 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004182 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004183 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004184
Guido van Rossum55f20992001-10-01 17:18:22 +00004185 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004186 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004187 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004188 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004189 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004190 if (func == NULL)
4191 return PyErr_Occurred() ? -1 : 1;
4192 }
4193 args = PyTuple_New(0);
4194 if (args != NULL) {
4195 PyObject *temp = PyObject_Call(func, args, NULL);
4196 Py_DECREF(args);
4197 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004198 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004199 result = PyObject_IsTrue(temp);
4200 else {
4201 PyErr_Format(PyExc_TypeError,
4202 "__nonzero__ should return "
4203 "bool or int, returned %s",
4204 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004205 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004206 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004207 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004208 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004209 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004210 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004211 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004212}
4213
Guido van Rossumdc91b992001-08-08 22:26:22 +00004214SLOT0(slot_nb_invert, "__invert__")
4215SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4216SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4217SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4218SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4219SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004220
4221static int
4222slot_nb_coerce(PyObject **a, PyObject **b)
4223{
4224 static PyObject *coerce_str;
4225 PyObject *self = *a, *other = *b;
4226
4227 if (self->ob_type->tp_as_number != NULL &&
4228 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4229 PyObject *r;
4230 r = call_maybe(
4231 self, "__coerce__", &coerce_str, "(O)", other);
4232 if (r == NULL)
4233 return -1;
4234 if (r == Py_NotImplemented) {
4235 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004236 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004237 else {
4238 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4239 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004240 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004241 Py_DECREF(r);
4242 return -1;
4243 }
4244 *a = PyTuple_GET_ITEM(r, 0);
4245 Py_INCREF(*a);
4246 *b = PyTuple_GET_ITEM(r, 1);
4247 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004248 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004249 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004250 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004251 }
4252 if (other->ob_type->tp_as_number != NULL &&
4253 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4254 PyObject *r;
4255 r = call_maybe(
4256 other, "__coerce__", &coerce_str, "(O)", self);
4257 if (r == NULL)
4258 return -1;
4259 if (r == Py_NotImplemented) {
4260 Py_DECREF(r);
4261 return 1;
4262 }
4263 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4264 PyErr_SetString(PyExc_TypeError,
4265 "__coerce__ didn't return a 2-tuple");
4266 Py_DECREF(r);
4267 return -1;
4268 }
4269 *a = PyTuple_GET_ITEM(r, 1);
4270 Py_INCREF(*a);
4271 *b = PyTuple_GET_ITEM(r, 0);
4272 Py_INCREF(*b);
4273 Py_DECREF(r);
4274 return 0;
4275 }
4276 return 1;
4277}
4278
Guido van Rossumdc91b992001-08-08 22:26:22 +00004279SLOT0(slot_nb_int, "__int__")
4280SLOT0(slot_nb_long, "__long__")
4281SLOT0(slot_nb_float, "__float__")
4282SLOT0(slot_nb_oct, "__oct__")
4283SLOT0(slot_nb_hex, "__hex__")
4284SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4285SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4286SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4287SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4288SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004289SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004290SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4291SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4292SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4293SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4294SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4295SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4296 "__floordiv__", "__rfloordiv__")
4297SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4298SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4299SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004300
4301static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004302half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004303{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004304 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004305 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004306 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004307
Guido van Rossum60718732001-08-28 17:47:51 +00004308 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004309 if (func == NULL) {
4310 PyErr_Clear();
4311 }
4312 else {
4313 args = Py_BuildValue("(O)", other);
4314 if (args == NULL)
4315 res = NULL;
4316 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004317 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004318 Py_DECREF(args);
4319 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004320 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004321 if (res != Py_NotImplemented) {
4322 if (res == NULL)
4323 return -2;
4324 c = PyInt_AsLong(res);
4325 Py_DECREF(res);
4326 if (c == -1 && PyErr_Occurred())
4327 return -2;
4328 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4329 }
4330 Py_DECREF(res);
4331 }
4332 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004333}
4334
Guido van Rossumab3b0342001-09-18 20:38:53 +00004335/* This slot is published for the benefit of try_3way_compare in object.c */
4336int
4337_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004338{
4339 int c;
4340
Guido van Rossumab3b0342001-09-18 20:38:53 +00004341 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004342 c = half_compare(self, other);
4343 if (c <= 1)
4344 return c;
4345 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004346 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004347 c = half_compare(other, self);
4348 if (c < -1)
4349 return -2;
4350 if (c <= 1)
4351 return -c;
4352 }
4353 return (void *)self < (void *)other ? -1 :
4354 (void *)self > (void *)other ? 1 : 0;
4355}
4356
4357static PyObject *
4358slot_tp_repr(PyObject *self)
4359{
4360 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004361 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004362
Guido van Rossum60718732001-08-28 17:47:51 +00004363 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004364 if (func != NULL) {
4365 res = PyEval_CallObject(func, NULL);
4366 Py_DECREF(func);
4367 return res;
4368 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004369 PyErr_Clear();
4370 return PyString_FromFormat("<%s object at %p>",
4371 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004372}
4373
4374static PyObject *
4375slot_tp_str(PyObject *self)
4376{
4377 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004378 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004379
Guido van Rossum60718732001-08-28 17:47:51 +00004380 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004381 if (func != NULL) {
4382 res = PyEval_CallObject(func, NULL);
4383 Py_DECREF(func);
4384 return res;
4385 }
4386 else {
4387 PyErr_Clear();
4388 return slot_tp_repr(self);
4389 }
4390}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004391
4392static long
4393slot_tp_hash(PyObject *self)
4394{
Tim Peters61ce0a92002-12-06 23:38:02 +00004395 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004396 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004397 long h;
4398
Guido van Rossum60718732001-08-28 17:47:51 +00004399 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004400
4401 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004402 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004403 Py_DECREF(func);
4404 if (res == NULL)
4405 return -1;
4406 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004407 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004408 }
4409 else {
4410 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004411 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004412 if (func == NULL) {
4413 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004414 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004415 }
4416 if (func != NULL) {
4417 Py_DECREF(func);
4418 PyErr_SetString(PyExc_TypeError, "unhashable type");
4419 return -1;
4420 }
4421 PyErr_Clear();
4422 h = _Py_HashPointer((void *)self);
4423 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004424 if (h == -1 && !PyErr_Occurred())
4425 h = -2;
4426 return h;
4427}
4428
4429static PyObject *
4430slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4431{
Guido van Rossum60718732001-08-28 17:47:51 +00004432 static PyObject *call_str;
4433 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004434 PyObject *res;
4435
4436 if (meth == NULL)
4437 return NULL;
4438 res = PyObject_Call(meth, args, kwds);
4439 Py_DECREF(meth);
4440 return res;
4441}
4442
Guido van Rossum14a6f832001-10-17 13:59:09 +00004443/* There are two slot dispatch functions for tp_getattro.
4444
4445 - slot_tp_getattro() is used when __getattribute__ is overridden
4446 but no __getattr__ hook is present;
4447
4448 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4449
Guido van Rossumc334df52002-04-04 23:44:47 +00004450 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4451 detects the absence of __getattr__ and then installs the simpler slot if
4452 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004453
Tim Peters6d6c1a32001-08-02 04:15:00 +00004454static PyObject *
4455slot_tp_getattro(PyObject *self, PyObject *name)
4456{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004457 static PyObject *getattribute_str = NULL;
4458 return call_method(self, "__getattribute__", &getattribute_str,
4459 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004460}
4461
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004462static PyObject *
4463slot_tp_getattr_hook(PyObject *self, PyObject *name)
4464{
4465 PyTypeObject *tp = self->ob_type;
4466 PyObject *getattr, *getattribute, *res;
4467 static PyObject *getattribute_str = NULL;
4468 static PyObject *getattr_str = NULL;
4469
4470 if (getattr_str == NULL) {
4471 getattr_str = PyString_InternFromString("__getattr__");
4472 if (getattr_str == NULL)
4473 return NULL;
4474 }
4475 if (getattribute_str == NULL) {
4476 getattribute_str =
4477 PyString_InternFromString("__getattribute__");
4478 if (getattribute_str == NULL)
4479 return NULL;
4480 }
4481 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004482 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004483 /* No __getattr__ hook: use a simpler dispatcher */
4484 tp->tp_getattro = slot_tp_getattro;
4485 return slot_tp_getattro(self, name);
4486 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004487 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004488 if (getattribute == NULL ||
4489 (getattribute->ob_type == &PyWrapperDescr_Type &&
4490 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4491 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004492 res = PyObject_GenericGetAttr(self, name);
4493 else
4494 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004495 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004496 PyErr_Clear();
4497 res = PyObject_CallFunction(getattr, "OO", self, name);
4498 }
4499 return res;
4500}
4501
Tim Peters6d6c1a32001-08-02 04:15:00 +00004502static int
4503slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4504{
4505 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004506 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004507
4508 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004509 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004510 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004511 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004512 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004513 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004514 if (res == NULL)
4515 return -1;
4516 Py_DECREF(res);
4517 return 0;
4518}
4519
4520/* Map rich comparison operators to their __xx__ namesakes */
4521static char *name_op[] = {
4522 "__lt__",
4523 "__le__",
4524 "__eq__",
4525 "__ne__",
4526 "__gt__",
4527 "__ge__",
4528};
4529
4530static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004531half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004532{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004533 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004534 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004535
Guido van Rossum60718732001-08-28 17:47:51 +00004536 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004537 if (func == NULL) {
4538 PyErr_Clear();
4539 Py_INCREF(Py_NotImplemented);
4540 return Py_NotImplemented;
4541 }
4542 args = Py_BuildValue("(O)", other);
4543 if (args == NULL)
4544 res = NULL;
4545 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004546 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004547 Py_DECREF(args);
4548 }
4549 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004550 return res;
4551}
4552
Guido van Rossumb8f63662001-08-15 23:57:02 +00004553/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4554static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4555
4556static PyObject *
4557slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4558{
4559 PyObject *res;
4560
4561 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4562 res = half_richcompare(self, other, op);
4563 if (res != Py_NotImplemented)
4564 return res;
4565 Py_DECREF(res);
4566 }
4567 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4568 res = half_richcompare(other, self, swapped_op[op]);
4569 if (res != Py_NotImplemented) {
4570 return res;
4571 }
4572 Py_DECREF(res);
4573 }
4574 Py_INCREF(Py_NotImplemented);
4575 return Py_NotImplemented;
4576}
4577
4578static PyObject *
4579slot_tp_iter(PyObject *self)
4580{
4581 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004582 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004583
Guido van Rossum60718732001-08-28 17:47:51 +00004584 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004585 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004586 PyObject *args;
4587 args = res = PyTuple_New(0);
4588 if (args != NULL) {
4589 res = PyObject_Call(func, args, NULL);
4590 Py_DECREF(args);
4591 }
4592 Py_DECREF(func);
4593 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004594 }
4595 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004596 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004597 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004598 PyErr_SetString(PyExc_TypeError,
4599 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004600 return NULL;
4601 }
4602 Py_DECREF(func);
4603 return PySeqIter_New(self);
4604}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004605
4606static PyObject *
4607slot_tp_iternext(PyObject *self)
4608{
Guido van Rossum2730b132001-08-28 18:22:14 +00004609 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004610 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004611}
4612
Guido van Rossum1a493502001-08-17 16:47:50 +00004613static PyObject *
4614slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4615{
4616 PyTypeObject *tp = self->ob_type;
4617 PyObject *get;
4618 static PyObject *get_str = NULL;
4619
4620 if (get_str == NULL) {
4621 get_str = PyString_InternFromString("__get__");
4622 if (get_str == NULL)
4623 return NULL;
4624 }
4625 get = _PyType_Lookup(tp, get_str);
4626 if (get == NULL) {
4627 /* Avoid further slowdowns */
4628 if (tp->tp_descr_get == slot_tp_descr_get)
4629 tp->tp_descr_get = NULL;
4630 Py_INCREF(self);
4631 return self;
4632 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004633 if (obj == NULL)
4634 obj = Py_None;
4635 if (type == NULL)
4636 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004637 return PyObject_CallFunction(get, "OOO", self, obj, type);
4638}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004639
4640static int
4641slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4642{
Guido van Rossum2c252392001-08-24 10:13:31 +00004643 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004644 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004645
4646 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004647 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004648 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004649 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004650 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004651 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004652 if (res == NULL)
4653 return -1;
4654 Py_DECREF(res);
4655 return 0;
4656}
4657
4658static int
4659slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4660{
Guido van Rossum60718732001-08-28 17:47:51 +00004661 static PyObject *init_str;
4662 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004663 PyObject *res;
4664
4665 if (meth == NULL)
4666 return -1;
4667 res = PyObject_Call(meth, args, kwds);
4668 Py_DECREF(meth);
4669 if (res == NULL)
4670 return -1;
4671 Py_DECREF(res);
4672 return 0;
4673}
4674
4675static PyObject *
4676slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4677{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004678 static PyObject *new_str;
4679 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004680 PyObject *newargs, *x;
4681 int i, n;
4682
Guido van Rossum7bed2132002-08-08 21:57:53 +00004683 if (new_str == NULL) {
4684 new_str = PyString_InternFromString("__new__");
4685 if (new_str == NULL)
4686 return NULL;
4687 }
4688 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004689 if (func == NULL)
4690 return NULL;
4691 assert(PyTuple_Check(args));
4692 n = PyTuple_GET_SIZE(args);
4693 newargs = PyTuple_New(n+1);
4694 if (newargs == NULL)
4695 return NULL;
4696 Py_INCREF(type);
4697 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4698 for (i = 0; i < n; i++) {
4699 x = PyTuple_GET_ITEM(args, i);
4700 Py_INCREF(x);
4701 PyTuple_SET_ITEM(newargs, i+1, x);
4702 }
4703 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004704 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004705 Py_DECREF(func);
4706 return x;
4707}
4708
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004709static void
4710slot_tp_del(PyObject *self)
4711{
4712 static PyObject *del_str = NULL;
4713 PyObject *del, *res;
4714 PyObject *error_type, *error_value, *error_traceback;
4715
4716 /* Temporarily resurrect the object. */
4717 assert(self->ob_refcnt == 0);
4718 self->ob_refcnt = 1;
4719
4720 /* Save the current exception, if any. */
4721 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4722
4723 /* Execute __del__ method, if any. */
4724 del = lookup_maybe(self, "__del__", &del_str);
4725 if (del != NULL) {
4726 res = PyEval_CallObject(del, NULL);
4727 if (res == NULL)
4728 PyErr_WriteUnraisable(del);
4729 else
4730 Py_DECREF(res);
4731 Py_DECREF(del);
4732 }
4733
4734 /* Restore the saved exception. */
4735 PyErr_Restore(error_type, error_value, error_traceback);
4736
4737 /* Undo the temporary resurrection; can't use DECREF here, it would
4738 * cause a recursive call.
4739 */
4740 assert(self->ob_refcnt > 0);
4741 if (--self->ob_refcnt == 0)
4742 return; /* this is the normal path out */
4743
4744 /* __del__ resurrected it! Make it look like the original Py_DECREF
4745 * never happened.
4746 */
4747 {
4748 int refcnt = self->ob_refcnt;
4749 _Py_NewReference(self);
4750 self->ob_refcnt = refcnt;
4751 }
4752 assert(!PyType_IS_GC(self->ob_type) ||
4753 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4754 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4755 * _Py_NewReference bumped it again, so that's a wash.
4756 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4757 * chain, so no more to do there either.
4758 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4759 * _Py_NewReference bumped tp_allocs: both of those need to be
4760 * undone.
4761 */
4762#ifdef COUNT_ALLOCS
4763 --self->ob_type->tp_frees;
4764 --self->ob_type->tp_allocs;
4765#endif
4766}
4767
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004768
4769/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004770 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004771 structure, which incorporates the additional structures used for numbers,
4772 sequences and mappings.
4773 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004774 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004775 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4776 terminated with an all-zero entry. (This table is further initialized and
4777 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004778
Guido van Rossum6d204072001-10-21 00:44:31 +00004779typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004780
4781#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004782#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004783#undef ETSLOT
4784#undef SQSLOT
4785#undef MPSLOT
4786#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004787#undef UNSLOT
4788#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004789#undef BINSLOT
4790#undef RBINSLOT
4791
Guido van Rossum6d204072001-10-21 00:44:31 +00004792#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004793 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4794 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004795#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4796 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004797 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004798#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004799 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004800 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004801#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4802 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4803#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4804 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4805#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4806 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4807#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4808 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4809 "x." NAME "() <==> " DOC)
4810#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4811 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4812 "x." NAME "(y) <==> x" DOC "y")
4813#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4814 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4815 "x." NAME "(y) <==> x" DOC "y")
4816#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4817 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4818 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004819
4820static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004821 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4822 "x.__len__() <==> len(x)"),
4823 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4824 "x.__add__(y) <==> x+y"),
4825 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4826 "x.__mul__(n) <==> x*n"),
4827 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4828 "x.__rmul__(n) <==> n*x"),
4829 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4830 "x.__getitem__(y) <==> x[y]"),
4831 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00004832 "x.__getslice__(i, j) <==> x[i:j]\n\
4833 \n\
4834 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004835 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004836 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004837 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004838 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004839 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004840 wrap_intintobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00004841 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
4842 \n\
4843 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004844 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00004845 "x.__delslice__(i, j) <==> del x[i:j]\n\
4846 \n\
4847 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004848 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4849 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004850 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004851 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004852 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004853 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004854
Guido van Rossum6d204072001-10-21 00:44:31 +00004855 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4856 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004857 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004858 wrap_binaryfunc,
4859 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004860 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004861 wrap_objobjargproc,
4862 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004863 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004864 wrap_delitem,
4865 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004866
Guido van Rossum6d204072001-10-21 00:44:31 +00004867 BINSLOT("__add__", nb_add, slot_nb_add,
4868 "+"),
4869 RBINSLOT("__radd__", nb_add, slot_nb_add,
4870 "+"),
4871 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4872 "-"),
4873 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4874 "-"),
4875 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4876 "*"),
4877 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4878 "*"),
4879 BINSLOT("__div__", nb_divide, slot_nb_divide,
4880 "/"),
4881 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4882 "/"),
4883 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4884 "%"),
4885 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4886 "%"),
4887 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4888 "divmod(x, y)"),
4889 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4890 "divmod(y, x)"),
4891 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4892 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4893 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4894 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4895 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4896 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4897 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4898 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004899 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004900 "x != 0"),
4901 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4902 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4903 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4904 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4905 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4906 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4907 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4908 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4909 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4910 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4911 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4912 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4913 "x.__coerce__(y) <==> coerce(x, y)"),
4914 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4915 "int(x)"),
4916 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4917 "long(x)"),
4918 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4919 "float(x)"),
4920 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4921 "oct(x)"),
4922 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4923 "hex(x)"),
4924 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4925 wrap_binaryfunc, "+"),
4926 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4927 wrap_binaryfunc, "-"),
4928 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4929 wrap_binaryfunc, "*"),
4930 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4931 wrap_binaryfunc, "/"),
4932 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4933 wrap_binaryfunc, "%"),
4934 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004935 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004936 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4937 wrap_binaryfunc, "<<"),
4938 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4939 wrap_binaryfunc, ">>"),
4940 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4941 wrap_binaryfunc, "&"),
4942 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4943 wrap_binaryfunc, "^"),
4944 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4945 wrap_binaryfunc, "|"),
4946 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4947 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4948 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4949 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4950 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4951 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4952 IBSLOT("__itruediv__", nb_inplace_true_divide,
4953 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004954
Guido van Rossum6d204072001-10-21 00:44:31 +00004955 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4956 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004957 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004958 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4959 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004960 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004961 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4962 "x.__cmp__(y) <==> cmp(x,y)"),
4963 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4964 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004965 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4966 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004967 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004968 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4969 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4970 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4971 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4972 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4973 "x.__setattr__('name', value) <==> x.name = value"),
4974 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4975 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4976 "x.__delattr__('name') <==> del x.name"),
4977 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4978 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4979 "x.__lt__(y) <==> x<y"),
4980 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4981 "x.__le__(y) <==> x<=y"),
4982 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4983 "x.__eq__(y) <==> x==y"),
4984 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4985 "x.__ne__(y) <==> x!=y"),
4986 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4987 "x.__gt__(y) <==> x>y"),
4988 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4989 "x.__ge__(y) <==> x>=y"),
4990 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4991 "x.__iter__() <==> iter(x)"),
4992 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4993 "x.next() -> the next value, or raise StopIteration"),
4994 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4995 "descr.__get__(obj[, type]) -> value"),
4996 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4997 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004998 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4999 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005000 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005001 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005002 "see x.__class__.__doc__ for signature",
5003 PyWrapperFlag_KEYWORDS),
5004 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005005 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005006 {NULL}
5007};
5008
Guido van Rossumc334df52002-04-04 23:44:47 +00005009/* Given a type pointer and an offset gotten from a slotdef entry, return a
5010 pointer to the actual slot. This is not quite the same as simply adding
5011 the offset to the type pointer, since it takes care to indirect through the
5012 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5013 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005014static void **
5015slotptr(PyTypeObject *type, int offset)
5016{
5017 char *ptr;
5018
Guido van Rossume5c691a2003-03-07 15:13:17 +00005019 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005020 assert(offset >= 0);
Guido van Rossume5c691a2003-03-07 15:13:17 +00005021 assert(offset < offsetof(PyHeapTypeObject, as_buffer));
5022 if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005023 ptr = (void *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005024 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005025 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005026 else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Guido van Rossum09638c12002-06-13 19:17:46 +00005027 ptr = (void *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005028 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005029 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005030 else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005031 ptr = (void *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005032 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005033 }
5034 else {
5035 ptr = (void *)type;
5036 }
5037 if (ptr != NULL)
5038 ptr += offset;
5039 return (void **)ptr;
5040}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005041
Guido van Rossumc334df52002-04-04 23:44:47 +00005042/* Length of array of slotdef pointers used to store slots with the
5043 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5044 the same __name__, for any __name__. Since that's a static property, it is
5045 appropriate to declare fixed-size arrays for this. */
5046#define MAX_EQUIV 10
5047
5048/* Return a slot pointer for a given name, but ONLY if the attribute has
5049 exactly one slot function. The name must be an interned string. */
5050static void **
5051resolve_slotdups(PyTypeObject *type, PyObject *name)
5052{
5053 /* XXX Maybe this could be optimized more -- but is it worth it? */
5054
5055 /* pname and ptrs act as a little cache */
5056 static PyObject *pname;
5057 static slotdef *ptrs[MAX_EQUIV];
5058 slotdef *p, **pp;
5059 void **res, **ptr;
5060
5061 if (pname != name) {
5062 /* Collect all slotdefs that match name into ptrs. */
5063 pname = name;
5064 pp = ptrs;
5065 for (p = slotdefs; p->name_strobj; p++) {
5066 if (p->name_strobj == name)
5067 *pp++ = p;
5068 }
5069 *pp = NULL;
5070 }
5071
5072 /* Look in all matching slots of the type; if exactly one of these has
5073 a filled-in slot, return its value. Otherwise return NULL. */
5074 res = NULL;
5075 for (pp = ptrs; *pp; pp++) {
5076 ptr = slotptr(type, (*pp)->offset);
5077 if (ptr == NULL || *ptr == NULL)
5078 continue;
5079 if (res != NULL)
5080 return NULL;
5081 res = ptr;
5082 }
5083 return res;
5084}
5085
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005086/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005087 does some incredibly complex thinking and then sticks something into the
5088 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5089 interests, and then stores a generic wrapper or a specific function into
5090 the slot.) Return a pointer to the next slotdef with a different offset,
5091 because that's convenient for fixup_slot_dispatchers(). */
5092static slotdef *
5093update_one_slot(PyTypeObject *type, slotdef *p)
5094{
5095 PyObject *descr;
5096 PyWrapperDescrObject *d;
5097 void *generic = NULL, *specific = NULL;
5098 int use_generic = 0;
5099 int offset = p->offset;
5100 void **ptr = slotptr(type, offset);
5101
5102 if (ptr == NULL) {
5103 do {
5104 ++p;
5105 } while (p->offset == offset);
5106 return p;
5107 }
5108 do {
5109 descr = _PyType_Lookup(type, p->name_strobj);
5110 if (descr == NULL)
5111 continue;
5112 if (descr->ob_type == &PyWrapperDescr_Type) {
5113 void **tptr = resolve_slotdups(type, p->name_strobj);
5114 if (tptr == NULL || tptr == ptr)
5115 generic = p->function;
5116 d = (PyWrapperDescrObject *)descr;
5117 if (d->d_base->wrapper == p->wrapper &&
5118 PyType_IsSubtype(type, d->d_type))
5119 {
5120 if (specific == NULL ||
5121 specific == d->d_wrapped)
5122 specific = d->d_wrapped;
5123 else
5124 use_generic = 1;
5125 }
5126 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005127 else if (descr->ob_type == &PyCFunction_Type &&
5128 PyCFunction_GET_FUNCTION(descr) ==
5129 (PyCFunction)tp_new_wrapper &&
5130 strcmp(p->name, "__new__") == 0)
5131 {
5132 /* The __new__ wrapper is not a wrapper descriptor,
5133 so must be special-cased differently.
5134 If we don't do this, creating an instance will
5135 always use slot_tp_new which will look up
5136 __new__ in the MRO which will call tp_new_wrapper
5137 which will look through the base classes looking
5138 for a static base and call its tp_new (usually
5139 PyType_GenericNew), after performing various
5140 sanity checks and constructing a new argument
5141 list. Cut all that nonsense short -- this speeds
5142 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005143 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005144 /* XXX I'm not 100% sure that there isn't a hole
5145 in this reasoning that requires additional
5146 sanity checks. I'll buy the first person to
5147 point out a bug in this reasoning a beer. */
5148 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005149 else {
5150 use_generic = 1;
5151 generic = p->function;
5152 }
5153 } while ((++p)->offset == offset);
5154 if (specific && !use_generic)
5155 *ptr = specific;
5156 else
5157 *ptr = generic;
5158 return p;
5159}
5160
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005161/* In the type, update the slots whose slotdefs are gathered in the pp array.
5162 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005163static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005164update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005165{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005166 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005167
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005168 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005169 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005170 return 0;
5171}
5172
Guido van Rossumc334df52002-04-04 23:44:47 +00005173/* Comparison function for qsort() to compare slotdefs by their offset, and
5174 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005175static int
5176slotdef_cmp(const void *aa, const void *bb)
5177{
5178 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5179 int c = a->offset - b->offset;
5180 if (c != 0)
5181 return c;
5182 else
5183 return a - b;
5184}
5185
Guido van Rossumc334df52002-04-04 23:44:47 +00005186/* Initialize the slotdefs table by adding interned string objects for the
5187 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005188static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005189init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005190{
5191 slotdef *p;
5192 static int initialized = 0;
5193
5194 if (initialized)
5195 return;
5196 for (p = slotdefs; p->name; p++) {
5197 p->name_strobj = PyString_InternFromString(p->name);
5198 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005199 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005200 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005201 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5202 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005203 initialized = 1;
5204}
5205
Guido van Rossumc334df52002-04-04 23:44:47 +00005206/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005207static int
5208update_slot(PyTypeObject *type, PyObject *name)
5209{
Guido van Rossumc334df52002-04-04 23:44:47 +00005210 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005211 slotdef *p;
5212 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005213 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005214
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005215 init_slotdefs();
5216 pp = ptrs;
5217 for (p = slotdefs; p->name; p++) {
5218 /* XXX assume name is interned! */
5219 if (p->name_strobj == name)
5220 *pp++ = p;
5221 }
5222 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005223 for (pp = ptrs; *pp; pp++) {
5224 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005225 offset = p->offset;
5226 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005227 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005228 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005229 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005230 if (ptrs[0] == NULL)
5231 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005232 return update_subclasses(type, name,
5233 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005234}
5235
Guido van Rossumc334df52002-04-04 23:44:47 +00005236/* Store the proper functions in the slot dispatches at class (type)
5237 definition time, based upon which operations the class overrides in its
5238 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005239static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005240fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005241{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005242 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005243
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005244 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005245 for (p = slotdefs; p->name; )
5246 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005247}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005248
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005249static void
5250update_all_slots(PyTypeObject* type)
5251{
5252 slotdef *p;
5253
5254 init_slotdefs();
5255 for (p = slotdefs; p->name; p++) {
5256 /* update_slot returns int but can't actually fail */
5257 update_slot(type, p->name_strobj);
5258 }
5259}
5260
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005261/* recurse_down_subclasses() and update_subclasses() are mutually
5262 recursive functions to call a callback for all subclasses,
5263 but refraining from recursing into subclasses that define 'name'. */
5264
5265static int
5266update_subclasses(PyTypeObject *type, PyObject *name,
5267 update_callback callback, void *data)
5268{
5269 if (callback(type, data) < 0)
5270 return -1;
5271 return recurse_down_subclasses(type, name, callback, data);
5272}
5273
5274static int
5275recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5276 update_callback callback, void *data)
5277{
5278 PyTypeObject *subclass;
5279 PyObject *ref, *subclasses, *dict;
5280 int i, n;
5281
5282 subclasses = type->tp_subclasses;
5283 if (subclasses == NULL)
5284 return 0;
5285 assert(PyList_Check(subclasses));
5286 n = PyList_GET_SIZE(subclasses);
5287 for (i = 0; i < n; i++) {
5288 ref = PyList_GET_ITEM(subclasses, i);
5289 assert(PyWeakref_CheckRef(ref));
5290 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5291 assert(subclass != NULL);
5292 if ((PyObject *)subclass == Py_None)
5293 continue;
5294 assert(PyType_Check(subclass));
5295 /* Avoid recursing down into unaffected classes */
5296 dict = subclass->tp_dict;
5297 if (dict != NULL && PyDict_Check(dict) &&
5298 PyDict_GetItem(dict, name) != NULL)
5299 continue;
5300 if (update_subclasses(subclass, name, callback, data) < 0)
5301 return -1;
5302 }
5303 return 0;
5304}
5305
Guido van Rossum6d204072001-10-21 00:44:31 +00005306/* This function is called by PyType_Ready() to populate the type's
5307 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005308 function slot (like tp_repr) that's defined in the type, one or more
5309 corresponding descriptors are added in the type's tp_dict dictionary
5310 under the appropriate name (like __repr__). Some function slots
5311 cause more than one descriptor to be added (for example, the nb_add
5312 slot adds both __add__ and __radd__ descriptors) and some function
5313 slots compete for the same descriptor (for example both sq_item and
5314 mp_subscript generate a __getitem__ descriptor).
5315
5316 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005317 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005318 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005319 between competing slots: the members of PyHeapTypeObject are listed
5320 from most general to least general, so the most general slot is
5321 preferred. In particular, because as_mapping comes before as_sequence,
5322 for a type that defines both mp_subscript and sq_item, mp_subscript
5323 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005324
5325 This only adds new descriptors and doesn't overwrite entries in
5326 tp_dict that were previously defined. The descriptors contain a
5327 reference to the C function they must call, so that it's safe if they
5328 are copied into a subtype's __dict__ and the subtype has a different
5329 C function in its slot -- calling the method defined by the
5330 descriptor will call the C function that was used to create it,
5331 rather than the C function present in the slot when it is called.
5332 (This is important because a subtype may have a C function in the
5333 slot that calls the method from the dictionary, and we want to avoid
5334 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005335
5336static int
5337add_operators(PyTypeObject *type)
5338{
5339 PyObject *dict = type->tp_dict;
5340 slotdef *p;
5341 PyObject *descr;
5342 void **ptr;
5343
5344 init_slotdefs();
5345 for (p = slotdefs; p->name; p++) {
5346 if (p->wrapper == NULL)
5347 continue;
5348 ptr = slotptr(type, p->offset);
5349 if (!ptr || !*ptr)
5350 continue;
5351 if (PyDict_GetItem(dict, p->name_strobj))
5352 continue;
5353 descr = PyDescr_NewWrapper(type, p, *ptr);
5354 if (descr == NULL)
5355 return -1;
5356 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5357 return -1;
5358 Py_DECREF(descr);
5359 }
5360 if (type->tp_new != NULL) {
5361 if (add_tp_new_wrapper(type) < 0)
5362 return -1;
5363 }
5364 return 0;
5365}
5366
Guido van Rossum705f0f52001-08-24 16:47:00 +00005367
5368/* Cooperative 'super' */
5369
5370typedef struct {
5371 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005372 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005373 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005374 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005375} superobject;
5376
Guido van Rossum6f799372001-09-20 20:46:19 +00005377static PyMemberDef super_members[] = {
5378 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5379 "the class invoking super()"},
5380 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5381 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005382 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
5383 "the type of the the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005384 {0}
5385};
5386
Guido van Rossum705f0f52001-08-24 16:47:00 +00005387static void
5388super_dealloc(PyObject *self)
5389{
5390 superobject *su = (superobject *)self;
5391
Guido van Rossum048eb752001-10-02 21:24:57 +00005392 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005393 Py_XDECREF(su->obj);
5394 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005395 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005396 self->ob_type->tp_free(self);
5397}
5398
5399static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005400super_repr(PyObject *self)
5401{
5402 superobject *su = (superobject *)self;
5403
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005404 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005405 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005406 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005407 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005408 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005409 else
5410 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005411 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005412 su->type ? su->type->tp_name : "NULL");
5413}
5414
5415static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005416super_getattro(PyObject *self, PyObject *name)
5417{
5418 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005419 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005420
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005421 if (!skip) {
5422 /* We want __class__ to return the class of the super object
5423 (i.e. super, or a subclass), not the class of su->obj. */
5424 skip = (PyString_Check(name) &&
5425 PyString_GET_SIZE(name) == 9 &&
5426 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5427 }
5428
5429 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005430 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005431 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005432 descrgetfunc f;
5433 int i, n;
5434
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005435 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005436 mro = starttype->tp_mro;
5437
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005438 if (mro == NULL)
5439 n = 0;
5440 else {
5441 assert(PyTuple_Check(mro));
5442 n = PyTuple_GET_SIZE(mro);
5443 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005444 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005445 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005446 break;
5447 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005448 i++;
5449 res = NULL;
5450 for (; i < n; i++) {
5451 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005452 if (PyType_Check(tmp))
5453 dict = ((PyTypeObject *)tmp)->tp_dict;
5454 else if (PyClass_Check(tmp))
5455 dict = ((PyClassObject *)tmp)->cl_dict;
5456 else
5457 continue;
5458 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005459 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005460 Py_INCREF(res);
5461 f = res->ob_type->tp_descr_get;
5462 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00005463 tmp = f(res, su->obj,
5464 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005465 Py_DECREF(res);
5466 res = tmp;
5467 }
5468 return res;
5469 }
5470 }
5471 }
5472 return PyObject_GenericGetAttr(self, name);
5473}
5474
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005475static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005476supercheck(PyTypeObject *type, PyObject *obj)
5477{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005478 /* Check that a super() call makes sense. Return a type object.
5479
5480 obj can be a new-style class, or an instance of one:
5481
5482 - If it is a class, it must be a subclass of 'type'. This case is
5483 used for class methods; the return value is obj.
5484
5485 - If it is an instance, it must be an instance of 'type'. This is
5486 the normal case; the return value is obj.__class__.
5487
5488 But... when obj is an instance, we want to allow for the case where
5489 obj->ob_type is not a subclass of type, but obj.__class__ is!
5490 This will allow using super() with a proxy for obj.
5491 */
5492
Guido van Rossum8e80a722003-02-18 19:22:22 +00005493 /* Check for first bullet above (special case) */
5494 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5495 Py_INCREF(obj);
5496 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005497 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005498
5499 /* Normal case */
5500 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005501 Py_INCREF(obj->ob_type);
5502 return obj->ob_type;
5503 }
5504 else {
5505 /* Try the slow way */
5506 static PyObject *class_str = NULL;
5507 PyObject *class_attr;
5508
5509 if (class_str == NULL) {
5510 class_str = PyString_FromString("__class__");
5511 if (class_str == NULL)
5512 return NULL;
5513 }
5514
5515 class_attr = PyObject_GetAttr(obj, class_str);
5516
5517 if (class_attr != NULL &&
5518 PyType_Check(class_attr) &&
5519 (PyTypeObject *)class_attr != obj->ob_type)
5520 {
5521 int ok = PyType_IsSubtype(
5522 (PyTypeObject *)class_attr, type);
5523 if (ok)
5524 return (PyTypeObject *)class_attr;
5525 }
5526
5527 if (class_attr == NULL)
5528 PyErr_Clear();
5529 else
5530 Py_DECREF(class_attr);
5531 }
5532
Tim Peters97e5ff52003-02-18 19:32:50 +00005533 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005534 "super(type, obj): "
5535 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005536 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005537}
5538
Guido van Rossum705f0f52001-08-24 16:47:00 +00005539static PyObject *
5540super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5541{
5542 superobject *su = (superobject *)self;
5543 superobject *new;
5544
5545 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5546 /* Not binding to an object, or already bound */
5547 Py_INCREF(self);
5548 return self;
5549 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005550 if (su->ob_type != &PySuper_Type)
Brett Cannon10147f72003-06-11 20:50:33 +00005551 /* If su is not an instance of a subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005552 call its type */
5553 return PyObject_CallFunction((PyObject *)su->ob_type,
5554 "OO", su->type, obj);
5555 else {
5556 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005557 PyTypeObject *obj_type = supercheck(su->type, obj);
5558 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005559 return NULL;
5560 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5561 NULL, NULL);
5562 if (new == NULL)
5563 return NULL;
5564 Py_INCREF(su->type);
5565 Py_INCREF(obj);
5566 new->type = su->type;
5567 new->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005568 new->obj_type = obj_type;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005569 return (PyObject *)new;
5570 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005571}
5572
5573static int
5574super_init(PyObject *self, PyObject *args, PyObject *kwds)
5575{
5576 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005577 PyTypeObject *type;
5578 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005579 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005580
5581 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5582 return -1;
5583 if (obj == Py_None)
5584 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005585 if (obj != NULL) {
5586 obj_type = supercheck(type, obj);
5587 if (obj_type == NULL)
5588 return -1;
5589 Py_INCREF(obj);
5590 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005591 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005592 su->type = type;
5593 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005594 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005595 return 0;
5596}
5597
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005598PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005599"super(type) -> unbound super object\n"
5600"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005601"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005602"Typical use to call a cooperative superclass method:\n"
5603"class C(B):\n"
5604" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005605" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005606
Guido van Rossum048eb752001-10-02 21:24:57 +00005607static int
5608super_traverse(PyObject *self, visitproc visit, void *arg)
5609{
5610 superobject *su = (superobject *)self;
5611 int err;
5612
5613#define VISIT(SLOT) \
5614 if (SLOT) { \
5615 err = visit((PyObject *)(SLOT), arg); \
5616 if (err) \
5617 return err; \
5618 }
5619
5620 VISIT(su->obj);
5621 VISIT(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005622 VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005623
5624#undef VISIT
5625
5626 return 0;
5627}
5628
Guido van Rossum705f0f52001-08-24 16:47:00 +00005629PyTypeObject PySuper_Type = {
5630 PyObject_HEAD_INIT(&PyType_Type)
5631 0, /* ob_size */
5632 "super", /* tp_name */
5633 sizeof(superobject), /* tp_basicsize */
5634 0, /* tp_itemsize */
5635 /* methods */
5636 super_dealloc, /* tp_dealloc */
5637 0, /* tp_print */
5638 0, /* tp_getattr */
5639 0, /* tp_setattr */
5640 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005641 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005642 0, /* tp_as_number */
5643 0, /* tp_as_sequence */
5644 0, /* tp_as_mapping */
5645 0, /* tp_hash */
5646 0, /* tp_call */
5647 0, /* tp_str */
5648 super_getattro, /* tp_getattro */
5649 0, /* tp_setattro */
5650 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005651 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5652 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005653 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005654 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005655 0, /* tp_clear */
5656 0, /* tp_richcompare */
5657 0, /* tp_weaklistoffset */
5658 0, /* tp_iter */
5659 0, /* tp_iternext */
5660 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005661 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005662 0, /* tp_getset */
5663 0, /* tp_base */
5664 0, /* tp_dict */
5665 super_descr_get, /* tp_descr_get */
5666 0, /* tp_descr_set */
5667 0, /* tp_dictoffset */
5668 super_init, /* tp_init */
5669 PyType_GenericAlloc, /* tp_alloc */
5670 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005671 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005672};