blob: 6ea489af2cca75b3cbd4e17edc2d464024ab1ca0 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
Guido van Rossum6f799372001-09-20 20:46:19 +00008static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00009 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
10 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
11 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000017 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
18 {0}
19};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000020
Guido van Rossumc0b618a1997-05-02 03:12:38 +000021static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000022type_name(PyTypeObject *type, void *context)
23{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +000024 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +000025
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000026 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +000027 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +000028
Georg Brandlc255c7b2006-02-20 22:27:28 +000029 Py_INCREF(et->ht_name);
30 return et->ht_name;
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000031 }
32 else {
33 s = strrchr(type->tp_name, '.');
34 if (s == NULL)
35 s = type->tp_name;
36 else
37 s++;
38 return PyString_FromString(s);
39 }
Guido van Rossumc3542212001-08-16 09:18:56 +000040}
41
Michael W. Hudson98bbc492002-11-26 14:47:27 +000042static int
43type_set_name(PyTypeObject *type, PyObject *value, void *context)
44{
Guido van Rossume5c691a2003-03-07 15:13:17 +000045 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000046
47 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
48 PyErr_Format(PyExc_TypeError,
49 "can't set %s.__name__", type->tp_name);
50 return -1;
51 }
52 if (!value) {
53 PyErr_Format(PyExc_TypeError,
54 "can't delete %s.__name__", type->tp_name);
55 return -1;
56 }
57 if (!PyString_Check(value)) {
58 PyErr_Format(PyExc_TypeError,
59 "can only assign string to %s.__name__, not '%s'",
60 type->tp_name, value->ob_type->tp_name);
61 return -1;
62 }
Tim Petersea7f75d2002-12-07 21:39:16 +000063 if (strlen(PyString_AS_STRING(value))
Michael W. Hudson98bbc492002-11-26 14:47:27 +000064 != (size_t)PyString_GET_SIZE(value)) {
65 PyErr_Format(PyExc_ValueError,
66 "__name__ must not contain null bytes");
67 return -1;
68 }
69
Guido van Rossume5c691a2003-03-07 15:13:17 +000070 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000071
72 Py_INCREF(value);
73
Georg Brandlc255c7b2006-02-20 22:27:28 +000074 Py_DECREF(et->ht_name);
75 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000076
77 type->tp_name = PyString_AS_STRING(value);
78
79 return 0;
80}
81
Guido van Rossumc3542212001-08-16 09:18:56 +000082static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000083type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000084{
Guido van Rossumc3542212001-08-16 09:18:56 +000085 PyObject *mod;
86 char *s;
87
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000088 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
89 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Anthony Baxter3ecdb252004-06-11 14:41:18 +000090 if (!mod) {
91 PyErr_Format(PyExc_AttributeError, "__module__");
92 return 0;
93 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000094 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +000095 return mod;
96 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000097 else {
98 s = strrchr(type->tp_name, '.');
99 if (s != NULL)
100 return PyString_FromStringAndSize(
Armin Rigo7ccbca92006-10-04 12:17:45 +0000101 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000102 return PyString_FromString("__builtin__");
103 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000104}
105
Guido van Rossum3926a632001-09-25 16:25:58 +0000106static int
107type_set_module(PyTypeObject *type, PyObject *value, void *context)
108{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000109 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000110 PyErr_Format(PyExc_TypeError,
111 "can't set %s.__module__", type->tp_name);
112 return -1;
113 }
114 if (!value) {
115 PyErr_Format(PyExc_TypeError,
116 "can't delete %s.__module__", type->tp_name);
117 return -1;
118 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000119
Guido van Rossum3926a632001-09-25 16:25:58 +0000120 return PyDict_SetItemString(type->tp_dict, "__module__", value);
121}
122
Tim Peters6d6c1a32001-08-02 04:15:00 +0000123static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000124type_get_bases(PyTypeObject *type, void *context)
125{
126 Py_INCREF(type->tp_bases);
127 return type->tp_bases;
128}
129
130static PyTypeObject *best_base(PyObject *);
131static int mro_internal(PyTypeObject *);
132static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
133static int add_subclass(PyTypeObject*, PyTypeObject*);
134static void remove_subclass(PyTypeObject *, PyTypeObject *);
135static void update_all_slots(PyTypeObject *);
136
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000137typedef int (*update_callback)(PyTypeObject *, void *);
138static int update_subclasses(PyTypeObject *type, PyObject *name,
139 update_callback callback, void *data);
140static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
141 update_callback callback, void *data);
142
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000143static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000144mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000145{
146 PyTypeObject *subclass;
147 PyObject *ref, *subclasses, *old_mro;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000148 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000149
150 subclasses = type->tp_subclasses;
151 if (subclasses == NULL)
152 return 0;
153 assert(PyList_Check(subclasses));
154 n = PyList_GET_SIZE(subclasses);
155 for (i = 0; i < n; i++) {
156 ref = PyList_GET_ITEM(subclasses, i);
157 assert(PyWeakref_CheckRef(ref));
158 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
159 assert(subclass != NULL);
160 if ((PyObject *)subclass == Py_None)
161 continue;
162 assert(PyType_Check(subclass));
163 old_mro = subclass->tp_mro;
164 if (mro_internal(subclass) < 0) {
165 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000166 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000167 }
168 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000169 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000170 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000171 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000172 if (!tuple)
173 return -1;
174 if (PyList_Append(temp, tuple) < 0)
175 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000176 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000177 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000178 if (mro_subclasses(subclass, temp) < 0)
179 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000180 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000181 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000182}
183
184static int
185type_set_bases(PyTypeObject *type, PyObject *value, void *context)
186{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000187 Py_ssize_t i;
188 int r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000189 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000190 PyTypeObject *new_base, *old_base;
191 PyObject *old_bases, *old_mro;
192
193 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
194 PyErr_Format(PyExc_TypeError,
195 "can't set %s.__bases__", type->tp_name);
196 return -1;
197 }
198 if (!value) {
199 PyErr_Format(PyExc_TypeError,
200 "can't delete %s.__bases__", type->tp_name);
201 return -1;
202 }
203 if (!PyTuple_Check(value)) {
204 PyErr_Format(PyExc_TypeError,
205 "can only assign tuple to %s.__bases__, not %s",
206 type->tp_name, value->ob_type->tp_name);
207 return -1;
208 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000209 if (PyTuple_GET_SIZE(value) == 0) {
210 PyErr_Format(PyExc_TypeError,
211 "can only assign non-empty tuple to %s.__bases__, not ()",
212 type->tp_name);
213 return -1;
214 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000215 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
216 ob = PyTuple_GET_ITEM(value, i);
217 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
218 PyErr_Format(
219 PyExc_TypeError,
220 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
221 type->tp_name, ob->ob_type->tp_name);
222 return -1;
223 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000224 if (PyType_Check(ob)) {
225 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
226 PyErr_SetString(PyExc_TypeError,
227 "a __bases__ item causes an inheritance cycle");
228 return -1;
229 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000230 }
231 }
232
233 new_base = best_base(value);
234
235 if (!new_base) {
236 return -1;
237 }
238
239 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
240 return -1;
241
242 Py_INCREF(new_base);
243 Py_INCREF(value);
244
245 old_bases = type->tp_bases;
246 old_base = type->tp_base;
247 old_mro = type->tp_mro;
248
249 type->tp_bases = value;
250 type->tp_base = new_base;
251
252 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000253 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000254 }
255
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000256 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000257 if (!temp)
258 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000259
260 r = mro_subclasses(type, temp);
261
262 if (r < 0) {
263 for (i = 0; i < PyList_Size(temp); i++) {
264 PyTypeObject* cls;
265 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000266 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
267 "", 2, 2, &cls, &mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000268 Py_DECREF(cls->tp_mro);
269 cls->tp_mro = mro;
270 Py_INCREF(cls->tp_mro);
271 }
272 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000273 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000274 }
275
276 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000277
278 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000279 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000280 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000281 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000282
283 /* for now, sod that: just remove from all old_bases,
284 add to all new_bases */
285
286 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
287 ob = PyTuple_GET_ITEM(old_bases, i);
288 if (PyType_Check(ob)) {
289 remove_subclass(
290 (PyTypeObject*)ob, type);
291 }
292 }
293
294 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
295 ob = PyTuple_GET_ITEM(value, i);
296 if (PyType_Check(ob)) {
297 if (add_subclass((PyTypeObject*)ob, type) < 0)
298 r = -1;
299 }
300 }
301
302 update_all_slots(type);
303
304 Py_DECREF(old_bases);
305 Py_DECREF(old_base);
306 Py_DECREF(old_mro);
307
308 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000309
310 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000311 Py_DECREF(type->tp_bases);
312 Py_DECREF(type->tp_base);
313 if (type->tp_mro != old_mro) {
314 Py_DECREF(type->tp_mro);
315 }
316
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000317 type->tp_bases = old_bases;
318 type->tp_base = old_base;
319 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000320
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000321 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000322}
323
324static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000325type_dict(PyTypeObject *type, void *context)
326{
327 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000328 Py_INCREF(Py_None);
329 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000330 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000331 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000332}
333
Tim Peters24008312002-03-17 18:56:20 +0000334static PyObject *
335type_get_doc(PyTypeObject *type, void *context)
336{
337 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000338 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000339 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000340 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000341 if (result == NULL) {
342 result = Py_None;
343 Py_INCREF(result);
344 }
345 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000346 result = result->ob_type->tp_descr_get(result, NULL,
347 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000348 }
349 else {
350 Py_INCREF(result);
351 }
Tim Peters24008312002-03-17 18:56:20 +0000352 return result;
353}
354
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000355static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000356 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
357 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000358 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000359 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000360 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000361 {0}
362};
363
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000364static int
365type_compare(PyObject *v, PyObject *w)
366{
367 /* This is called with type objects only. So we
368 can just compare the addresses. */
369 Py_uintptr_t vv = (Py_uintptr_t)v;
370 Py_uintptr_t ww = (Py_uintptr_t)w;
371 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
372}
373
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000374static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000375type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000376{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000377 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000378 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000379
380 mod = type_module(type, NULL);
381 if (mod == NULL)
382 PyErr_Clear();
383 else if (!PyString_Check(mod)) {
384 Py_DECREF(mod);
385 mod = NULL;
386 }
387 name = type_name(type, NULL);
388 if (name == NULL)
389 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000390
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000391 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
392 kind = "class";
393 else
394 kind = "type";
395
Barry Warsaw7ce36942001-08-24 18:34:26 +0000396 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000397 rtn = PyString_FromFormat("<%s '%s.%s'>",
398 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000399 PyString_AS_STRING(mod),
400 PyString_AS_STRING(name));
401 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000402 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000403 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000404
Guido van Rossumc3542212001-08-16 09:18:56 +0000405 Py_XDECREF(mod);
406 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000407 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000408}
409
Tim Peters6d6c1a32001-08-02 04:15:00 +0000410static PyObject *
411type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
412{
413 PyObject *obj;
414
415 if (type->tp_new == NULL) {
416 PyErr_Format(PyExc_TypeError,
417 "cannot create '%.100s' instances",
418 type->tp_name);
419 return NULL;
420 }
421
Tim Peters3f996e72001-09-13 19:18:27 +0000422 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000423 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000424 /* Ugly exception: when the call was type(something),
425 don't call tp_init on the result. */
426 if (type == &PyType_Type &&
427 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
428 (kwds == NULL ||
429 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
430 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000431 /* If the returned object is not an instance of type,
432 it won't be initialized. */
433 if (!PyType_IsSubtype(obj->ob_type, type))
434 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000435 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000436 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
437 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000438 type->tp_init(obj, args, kwds) < 0) {
439 Py_DECREF(obj);
440 obj = NULL;
441 }
442 }
443 return obj;
444}
445
446PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000447PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000448{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000449 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000450 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
451 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000452
453 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000454 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000455 else
Anthony Baxtera6286212006-04-11 07:42:36 +0000456 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000457
Neil Schemenauerc806c882001-08-29 23:54:54 +0000458 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000459 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000460
Neil Schemenauerc806c882001-08-29 23:54:54 +0000461 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000462
Tim Peters6d6c1a32001-08-02 04:15:00 +0000463 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
464 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000465
Tim Peters6d6c1a32001-08-02 04:15:00 +0000466 if (type->tp_itemsize == 0)
467 PyObject_INIT(obj, type);
468 else
469 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000470
Tim Peters6d6c1a32001-08-02 04:15:00 +0000471 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000472 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000473 return obj;
474}
475
476PyObject *
477PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
478{
479 return type->tp_alloc(type, 0);
480}
481
Guido van Rossum9475a232001-10-05 20:51:39 +0000482/* Helpers for subtyping */
483
484static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000485traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
486{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000487 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000488 PyMemberDef *mp;
489
490 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000491 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000492 for (i = 0; i < n; i++, mp++) {
493 if (mp->type == T_OBJECT_EX) {
494 char *addr = (char *)self + mp->offset;
495 PyObject *obj = *(PyObject **)addr;
496 if (obj != NULL) {
497 int err = visit(obj, arg);
498 if (err)
499 return err;
500 }
501 }
502 }
503 return 0;
504}
505
506static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000507subtype_traverse(PyObject *self, visitproc visit, void *arg)
508{
509 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000510 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000511
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000512 /* Find the nearest base with a different tp_traverse,
513 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000514 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000515 base = type;
516 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
517 if (base->ob_size) {
518 int err = traverse_slots(base, self, visit, arg);
519 if (err)
520 return err;
521 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000522 base = base->tp_base;
523 assert(base);
524 }
525
526 if (type->tp_dictoffset != base->tp_dictoffset) {
527 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Woutersc6e55062006-04-15 21:47:09 +0000528 if (dictptr && *dictptr)
529 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000530 }
531
Thomas Woutersc6e55062006-04-15 21:47:09 +0000532 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000533 /* For a heaptype, the instances count as references
534 to the type. Traverse the type so the collector
535 can find cycles involving this link. */
Thomas Woutersc6e55062006-04-15 21:47:09 +0000536 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000537
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000538 if (basetraverse)
539 return basetraverse(self, visit, arg);
540 return 0;
541}
542
543static void
544clear_slots(PyTypeObject *type, PyObject *self)
545{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000546 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000547 PyMemberDef *mp;
548
549 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000550 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000551 for (i = 0; i < n; i++, mp++) {
552 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
553 char *addr = (char *)self + mp->offset;
554 PyObject *obj = *(PyObject **)addr;
555 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000556 *(PyObject **)addr = NULL;
Thomas Woutersedf17d82006-04-15 17:28:34 +0000557 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000558 }
559 }
560 }
561}
562
563static int
564subtype_clear(PyObject *self)
565{
566 PyTypeObject *type, *base;
567 inquiry baseclear;
568
569 /* Find the nearest base with a different tp_clear
570 and clear slots while we're at it */
571 type = self->ob_type;
572 base = type;
573 while ((baseclear = base->tp_clear) == subtype_clear) {
574 if (base->ob_size)
575 clear_slots(base, self);
576 base = base->tp_base;
577 assert(base);
578 }
579
Guido van Rossuma3862092002-06-10 15:24:42 +0000580 /* There's no need to clear the instance dict (if any);
581 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000582
583 if (baseclear)
584 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000585 return 0;
586}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000587
588static void
589subtype_dealloc(PyObject *self)
590{
Guido van Rossum14227b42001-12-06 02:35:58 +0000591 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000592 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000593
Guido van Rossum22b13872002-08-06 21:41:44 +0000594 /* Extract the type; we expect it to be a heap type */
595 type = self->ob_type;
596 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000597
Guido van Rossum22b13872002-08-06 21:41:44 +0000598 /* Test whether the type has GC exactly once */
599
600 if (!PyType_IS_GC(type)) {
601 /* It's really rare to find a dynamic type that doesn't have
602 GC; it can only happen when deriving from 'object' and not
603 adding any slots or instance variables. This allows
604 certain simplifications: there's no need to call
605 clear_slots(), or DECREF the dict, or clear weakrefs. */
606
607 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000608 if (type->tp_del) {
609 type->tp_del(self);
610 if (self->ob_refcnt > 0)
611 return;
612 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000613
614 /* Find the nearest base with a different tp_dealloc */
615 base = type;
616 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
617 assert(base->ob_size == 0);
618 base = base->tp_base;
619 assert(base);
620 }
621
622 /* Call the base tp_dealloc() */
623 assert(basedealloc);
624 basedealloc(self);
625
626 /* Can't reference self beyond this point */
627 Py_DECREF(type);
628
629 /* Done */
630 return;
631 }
632
633 /* We get here only if the type has GC */
634
635 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000636 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000637 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000638 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000639 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000640 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000641 /* DO NOT restore GC tracking at this point. weakref callbacks
642 * (if any, and whether directly here or indirectly in something we
643 * call) may trigger GC, and if self is tracked at that point, it
644 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000645 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000646
Guido van Rossum59195fd2003-06-13 20:54:40 +0000647 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000648 base = type;
649 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000650 base = base->tp_base;
651 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000652 }
653
Guido van Rossum1987c662003-05-29 14:29:23 +0000654 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000655 the finalizer (__del__), clearing slots, or clearing the instance
656 dict. */
657
Guido van Rossum1987c662003-05-29 14:29:23 +0000658 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
659 PyObject_ClearWeakRefs(self);
660
661 /* Maybe call finalizer; exit early if resurrected */
662 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000663 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000664 type->tp_del(self);
665 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000666 goto endlabel; /* resurrected */
667 else
668 _PyObject_GC_UNTRACK(self);
Brett Cannonf5bee302007-01-23 23:21:22 +0000669 /* New weakrefs could be created during the finalizer call.
670 If this occurs, clear them out without calling their
671 finalizers since they might rely on part of the object
672 being finalized that has already been destroyed. */
673 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
674 /* Modeled after GET_WEAKREFS_LISTPTR() */
675 PyWeakReference **list = (PyWeakReference **) \
676 PyObject_GET_WEAKREFS_LISTPTR(self);
677 while (*list)
678 _PyWeakref_ClearRef(*list);
679 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000680 }
681
Guido van Rossum59195fd2003-06-13 20:54:40 +0000682 /* Clear slots up to the nearest base with a different tp_dealloc */
683 base = type;
684 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
685 if (base->ob_size)
686 clear_slots(base, self);
687 base = base->tp_base;
688 assert(base);
689 }
690
Tim Peters6d6c1a32001-08-02 04:15:00 +0000691 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000692 if (type->tp_dictoffset && !base->tp_dictoffset) {
693 PyObject **dictptr = _PyObject_GetDictPtr(self);
694 if (dictptr != NULL) {
695 PyObject *dict = *dictptr;
696 if (dict != NULL) {
697 Py_DECREF(dict);
698 *dictptr = NULL;
699 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000700 }
701 }
702
Tim Peters0bd743c2003-11-13 22:50:00 +0000703 /* Call the base tp_dealloc(); first retrack self if
704 * basedealloc knows about gc.
705 */
706 if (PyType_IS_GC(base))
707 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000708 assert(basedealloc);
709 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000710
711 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000712 Py_DECREF(type);
713
Guido van Rossum0906e072002-08-07 20:42:09 +0000714 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000715 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000716 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000717 --_PyTrash_delete_nesting;
718
719 /* Explanation of the weirdness around the trashcan macros:
720
721 Q. What do the trashcan macros do?
722
723 A. Read the comment titled "Trashcan mechanism" in object.h.
724 For one, this explains why there must be a call to GC-untrack
725 before the trashcan begin macro. Without understanding the
726 trashcan code, the answers to the following questions don't make
727 sense.
728
729 Q. Why do we GC-untrack before the trashcan and then immediately
730 GC-track again afterward?
731
732 A. In the case that the base class is GC-aware, the base class
733 probably GC-untracks the object. If it does that using the
734 UNTRACK macro, this will crash when the object is already
735 untracked. Because we don't know what the base class does, the
736 only safe thing is to make sure the object is tracked when we
737 call the base class dealloc. But... The trashcan begin macro
738 requires that the object is *untracked* before it is called. So
739 the dance becomes:
740
741 GC untrack
742 trashcan begin
743 GC track
744
Tim Petersf7f9e992003-11-13 21:59:32 +0000745 Q. Why did the last question say "immediately GC-track again"?
746 It's nowhere near immediately.
747
748 A. Because the code *used* to re-track immediately. Bad Idea.
749 self has a refcount of 0, and if gc ever gets its hands on it
750 (which can happen if any weakref callback gets invoked), it
751 looks like trash to gc too, and gc also tries to delete self
752 then. But we're already deleting self. Double dealloction is
753 a subtle disaster.
754
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000755 Q. Why the bizarre (net-zero) manipulation of
756 _PyTrash_delete_nesting around the trashcan macros?
757
758 A. Some base classes (e.g. list) also use the trashcan mechanism.
759 The following scenario used to be possible:
760
761 - suppose the trashcan level is one below the trashcan limit
762
763 - subtype_dealloc() is called
764
765 - the trashcan limit is not yet reached, so the trashcan level
766 is incremented and the code between trashcan begin and end is
767 executed
768
769 - this destroys much of the object's contents, including its
770 slots and __dict__
771
772 - basedealloc() is called; this is really list_dealloc(), or
773 some other type which also uses the trashcan macros
774
775 - the trashcan limit is now reached, so the object is put on the
776 trashcan's to-be-deleted-later list
777
778 - basedealloc() returns
779
780 - subtype_dealloc() decrefs the object's type
781
782 - subtype_dealloc() returns
783
784 - later, the trashcan code starts deleting the objects from its
785 to-be-deleted-later list
786
787 - subtype_dealloc() is called *AGAIN* for the same object
788
789 - at the very least (if the destroyed slots and __dict__ don't
790 cause problems) the object's type gets decref'ed a second
791 time, which is *BAD*!!!
792
793 The remedy is to make sure that if the code between trashcan
794 begin and end in subtype_dealloc() is called, the code between
795 trashcan begin and end in basedealloc() will also be called.
796 This is done by decrementing the level after passing into the
797 trashcan block, and incrementing it just before leaving the
798 block.
799
800 But now it's possible that a chain of objects consisting solely
801 of objects whose deallocator is subtype_dealloc() will defeat
802 the trashcan mechanism completely: the decremented level means
803 that the effective level never reaches the limit. Therefore, we
804 *increment* the level *before* entering the trashcan block, and
805 matchingly decrement it after leaving. This means the trashcan
806 code will trigger a little early, but that's no big deal.
807
808 Q. Are there any live examples of code in need of all this
809 complexity?
810
811 A. Yes. See SF bug 668433 for code that crashed (when Python was
812 compiled in debug mode) before the trashcan level manipulations
813 were added. For more discussion, see SF patches 581742, 575073
814 and bug 574207.
815 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000816}
817
Jeremy Hylton938ace62002-07-17 16:30:39 +0000818static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000819
Tim Peters6d6c1a32001-08-02 04:15:00 +0000820/* type test with subclassing support */
821
822int
823PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
824{
825 PyObject *mro;
826
Guido van Rossum9478d072001-09-07 18:52:13 +0000827 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
828 return b == a || b == &PyBaseObject_Type;
829
Tim Peters6d6c1a32001-08-02 04:15:00 +0000830 mro = a->tp_mro;
831 if (mro != NULL) {
832 /* Deal with multiple inheritance without recursion
833 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000834 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000835 assert(PyTuple_Check(mro));
836 n = PyTuple_GET_SIZE(mro);
837 for (i = 0; i < n; i++) {
838 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
839 return 1;
840 }
841 return 0;
842 }
843 else {
844 /* a is not completely initilized yet; follow tp_base */
845 do {
846 if (a == b)
847 return 1;
848 a = a->tp_base;
849 } while (a != NULL);
850 return b == &PyBaseObject_Type;
851 }
852}
853
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000854/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000855 without looking in the instance dictionary
856 (so we can't use PyObject_GetAttr) but still binding
857 it to the instance. The arguments are the object,
858 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000859 static variable used to cache the interned Python string.
860
861 Two variants:
862
863 - lookup_maybe() returns NULL without raising an exception
864 when the _PyType_Lookup() call fails;
865
866 - lookup_method() always raises an exception upon errors.
867*/
Guido van Rossum60718732001-08-28 17:47:51 +0000868
869static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000870lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000871{
872 PyObject *res;
873
874 if (*attrobj == NULL) {
875 *attrobj = PyString_InternFromString(attrstr);
876 if (*attrobj == NULL)
877 return NULL;
878 }
879 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000880 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000881 descrgetfunc f;
882 if ((f = res->ob_type->tp_descr_get) == NULL)
883 Py_INCREF(res);
884 else
885 res = f(res, self, (PyObject *)(self->ob_type));
886 }
887 return res;
888}
889
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000890static PyObject *
891lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
892{
893 PyObject *res = lookup_maybe(self, attrstr, attrobj);
894 if (res == NULL && !PyErr_Occurred())
895 PyErr_SetObject(PyExc_AttributeError, *attrobj);
896 return res;
897}
898
Guido van Rossum2730b132001-08-28 18:22:14 +0000899/* A variation of PyObject_CallMethod that uses lookup_method()
900 instead of PyObject_GetAttrString(). This uses the same convention
901 as lookup_method to cache the interned name string object. */
902
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000903static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000904call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
905{
906 va_list va;
907 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000908 va_start(va, format);
909
Guido van Rossumda21c012001-10-03 00:50:18 +0000910 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000911 if (func == NULL) {
912 va_end(va);
913 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000914 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000915 return NULL;
916 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000917
918 if (format && *format)
919 args = Py_VaBuildValue(format, va);
920 else
921 args = PyTuple_New(0);
922
923 va_end(va);
924
925 if (args == NULL)
926 return NULL;
927
928 assert(PyTuple_Check(args));
929 retval = PyObject_Call(func, args, NULL);
930
931 Py_DECREF(args);
932 Py_DECREF(func);
933
934 return retval;
935}
936
937/* Clone of call_method() that returns NotImplemented when the lookup fails. */
938
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000939static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000940call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
941{
942 va_list va;
943 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000944 va_start(va, format);
945
Guido van Rossumda21c012001-10-03 00:50:18 +0000946 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000947 if (func == NULL) {
948 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000949 if (!PyErr_Occurred()) {
950 Py_INCREF(Py_NotImplemented);
951 return Py_NotImplemented;
952 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000953 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000954 }
955
956 if (format && *format)
957 args = Py_VaBuildValue(format, va);
958 else
959 args = PyTuple_New(0);
960
961 va_end(va);
962
Guido van Rossum717ce002001-09-14 16:58:08 +0000963 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000964 return NULL;
965
Guido van Rossum717ce002001-09-14 16:58:08 +0000966 assert(PyTuple_Check(args));
967 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000968
969 Py_DECREF(args);
970 Py_DECREF(func);
971
972 return retval;
973}
974
Tim Petersa91e9642001-11-14 23:32:33 +0000975static int
976fill_classic_mro(PyObject *mro, PyObject *cls)
977{
978 PyObject *bases, *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000979 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +0000980
981 assert(PyList_Check(mro));
982 assert(PyClass_Check(cls));
983 i = PySequence_Contains(mro, cls);
984 if (i < 0)
985 return -1;
986 if (!i) {
987 if (PyList_Append(mro, cls) < 0)
988 return -1;
989 }
990 bases = ((PyClassObject *)cls)->cl_bases;
991 assert(bases && PyTuple_Check(bases));
992 n = PyTuple_GET_SIZE(bases);
993 for (i = 0; i < n; i++) {
994 base = PyTuple_GET_ITEM(bases, i);
995 if (fill_classic_mro(mro, base) < 0)
996 return -1;
997 }
998 return 0;
999}
1000
1001static PyObject *
1002classic_mro(PyObject *cls)
1003{
1004 PyObject *mro;
1005
1006 assert(PyClass_Check(cls));
1007 mro = PyList_New(0);
1008 if (mro != NULL) {
1009 if (fill_classic_mro(mro, cls) == 0)
1010 return mro;
1011 Py_DECREF(mro);
1012 }
1013 return NULL;
1014}
1015
Tim Petersea7f75d2002-12-07 21:39:16 +00001016/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001017 Method resolution order algorithm C3 described in
1018 "A Monotonic Superclass Linearization for Dylan",
1019 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001020 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001021 (OOPSLA 1996)
1022
Guido van Rossum98f33732002-11-25 21:36:54 +00001023 Some notes about the rules implied by C3:
1024
Tim Petersea7f75d2002-12-07 21:39:16 +00001025 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001026 It isn't legal to repeat a class in a list of base classes.
1027
1028 The next three properties are the 3 constraints in "C3".
1029
Tim Petersea7f75d2002-12-07 21:39:16 +00001030 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001031 If A precedes B in C's MRO, then A will precede B in the MRO of all
1032 subclasses of C.
1033
1034 Monotonicity.
1035 The MRO of a class must be an extension without reordering of the
1036 MRO of each of its superclasses.
1037
1038 Extended Precedence Graph (EPG).
1039 Linearization is consistent if there is a path in the EPG from
1040 each class to all its successors in the linearization. See
1041 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001042 */
1043
Tim Petersea7f75d2002-12-07 21:39:16 +00001044static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001045tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001046 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +00001047 size = PyList_GET_SIZE(list);
1048
1049 for (j = whence+1; j < size; j++) {
1050 if (PyList_GET_ITEM(list, j) == o)
1051 return 1;
1052 }
1053 return 0;
1054}
1055
Guido van Rossum98f33732002-11-25 21:36:54 +00001056static PyObject *
1057class_name(PyObject *cls)
1058{
1059 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1060 if (name == NULL) {
1061 PyErr_Clear();
1062 Py_XDECREF(name);
1063 name = PyObject_Repr(cls);
1064 }
1065 if (name == NULL)
1066 return NULL;
1067 if (!PyString_Check(name)) {
1068 Py_DECREF(name);
1069 return NULL;
1070 }
1071 return name;
1072}
1073
1074static int
1075check_duplicates(PyObject *list)
1076{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001077 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001078 /* Let's use a quadratic time algorithm,
1079 assuming that the bases lists is short.
1080 */
1081 n = PyList_GET_SIZE(list);
1082 for (i = 0; i < n; i++) {
1083 PyObject *o = PyList_GET_ITEM(list, i);
1084 for (j = i + 1; j < n; j++) {
1085 if (PyList_GET_ITEM(list, j) == o) {
1086 o = class_name(o);
1087 PyErr_Format(PyExc_TypeError,
1088 "duplicate base class %s",
1089 o ? PyString_AS_STRING(o) : "?");
1090 Py_XDECREF(o);
1091 return -1;
1092 }
1093 }
1094 }
1095 return 0;
1096}
1097
1098/* Raise a TypeError for an MRO order disagreement.
1099
1100 It's hard to produce a good error message. In the absence of better
1101 insight into error reporting, report the classes that were candidates
1102 to be put next into the MRO. There is some conflict between the
1103 order in which they should be put in the MRO, but it's hard to
1104 diagnose what constraint can't be satisfied.
1105*/
1106
1107static void
1108set_mro_error(PyObject *to_merge, int *remain)
1109{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001110 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001111 char buf[1000];
1112 PyObject *k, *v;
1113 PyObject *set = PyDict_New();
Georg Brandl5c170fd2006-03-17 19:03:25 +00001114 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001115
1116 to_merge_size = PyList_GET_SIZE(to_merge);
1117 for (i = 0; i < to_merge_size; i++) {
1118 PyObject *L = PyList_GET_ITEM(to_merge, i);
1119 if (remain[i] < PyList_GET_SIZE(L)) {
1120 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Georg Brandl5c170fd2006-03-17 19:03:25 +00001121 if (PyDict_SetItem(set, c, Py_None) < 0) {
1122 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001123 return;
Georg Brandl5c170fd2006-03-17 19:03:25 +00001124 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001125 }
1126 }
1127 n = PyDict_Size(set);
1128
Raymond Hettingerf394df42003-04-06 19:13:41 +00001129 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1130consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001131 i = 0;
Skip Montanaro429433b2006-04-18 00:35:43 +00001132 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001133 PyObject *name = class_name(k);
1134 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1135 name ? PyString_AS_STRING(name) : "?");
1136 Py_XDECREF(name);
Skip Montanaro429433b2006-04-18 00:35:43 +00001137 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001138 buf[off++] = ',';
1139 buf[off] = '\0';
1140 }
1141 }
1142 PyErr_SetString(PyExc_TypeError, buf);
1143 Py_DECREF(set);
1144}
1145
Tim Petersea7f75d2002-12-07 21:39:16 +00001146static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001147pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001148 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001149 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001150 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001151
Guido van Rossum1f121312002-11-14 19:49:16 +00001152 to_merge_size = PyList_GET_SIZE(to_merge);
1153
Guido van Rossum98f33732002-11-25 21:36:54 +00001154 /* remain stores an index into each sublist of to_merge.
1155 remain[i] is the index of the next base in to_merge[i]
1156 that is not included in acc.
1157 */
Anthony Baxtera6286212006-04-11 07:42:36 +00001158 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001159 if (remain == NULL)
1160 return -1;
1161 for (i = 0; i < to_merge_size; i++)
1162 remain[i] = 0;
1163
1164 again:
1165 empty_cnt = 0;
1166 for (i = 0; i < to_merge_size; i++) {
1167 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001168
Guido van Rossum1f121312002-11-14 19:49:16 +00001169 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1170
1171 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1172 empty_cnt++;
1173 continue;
1174 }
1175
Guido van Rossum98f33732002-11-25 21:36:54 +00001176 /* Choose next candidate for MRO.
1177
1178 The input sequences alone can determine the choice.
1179 If not, choose the class which appears in the MRO
1180 of the earliest direct superclass of the new class.
1181 */
1182
Guido van Rossum1f121312002-11-14 19:49:16 +00001183 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1184 for (j = 0; j < to_merge_size; j++) {
1185 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001186 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001187 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001188 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001189 }
1190 ok = PyList_Append(acc, candidate);
1191 if (ok < 0) {
1192 PyMem_Free(remain);
1193 return -1;
1194 }
1195 for (j = 0; j < to_merge_size; j++) {
1196 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001197 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1198 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001199 remain[j]++;
1200 }
1201 }
1202 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001203 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001204 }
1205
Guido van Rossum98f33732002-11-25 21:36:54 +00001206 if (empty_cnt == to_merge_size) {
1207 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001208 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001209 }
1210 set_mro_error(to_merge, remain);
1211 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001212 return -1;
1213}
1214
Tim Peters6d6c1a32001-08-02 04:15:00 +00001215static PyObject *
1216mro_implementation(PyTypeObject *type)
1217{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001218 Py_ssize_t i, n;
1219 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001220 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001221 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001222
Guido van Rossum63517572002-06-18 16:44:57 +00001223 if(type->tp_dict == NULL) {
1224 if(PyType_Ready(type) < 0)
1225 return NULL;
1226 }
1227
Guido van Rossum98f33732002-11-25 21:36:54 +00001228 /* Find a superclass linearization that honors the constraints
1229 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001230 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001231
1232 to_merge is a list of lists, where each list is a superclass
1233 linearization implied by a base class. The last element of
1234 to_merge is the declared list of bases.
1235 */
1236
Tim Peters6d6c1a32001-08-02 04:15:00 +00001237 bases = type->tp_bases;
1238 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001239
1240 to_merge = PyList_New(n+1);
1241 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001242 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001243
Tim Peters6d6c1a32001-08-02 04:15:00 +00001244 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001245 PyObject *base = PyTuple_GET_ITEM(bases, i);
1246 PyObject *parentMRO;
1247 if (PyType_Check(base))
1248 parentMRO = PySequence_List(
1249 ((PyTypeObject*)base)->tp_mro);
1250 else
1251 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001252 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001253 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001254 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001255 }
1256
1257 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001258 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001259
1260 bases_aslist = PySequence_List(bases);
1261 if (bases_aslist == NULL) {
1262 Py_DECREF(to_merge);
1263 return NULL;
1264 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001265 /* This is just a basic sanity check. */
1266 if (check_duplicates(bases_aslist) < 0) {
1267 Py_DECREF(to_merge);
1268 Py_DECREF(bases_aslist);
1269 return NULL;
1270 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001271 PyList_SET_ITEM(to_merge, n, bases_aslist);
1272
1273 result = Py_BuildValue("[O]", (PyObject *)type);
1274 if (result == NULL) {
1275 Py_DECREF(to_merge);
1276 return NULL;
1277 }
1278
1279 ok = pmerge(result, to_merge);
1280 Py_DECREF(to_merge);
1281 if (ok < 0) {
1282 Py_DECREF(result);
1283 return NULL;
1284 }
1285
Tim Peters6d6c1a32001-08-02 04:15:00 +00001286 return result;
1287}
1288
1289static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001290mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001291{
1292 PyTypeObject *type = (PyTypeObject *)self;
1293
Tim Peters6d6c1a32001-08-02 04:15:00 +00001294 return mro_implementation(type);
1295}
1296
1297static int
1298mro_internal(PyTypeObject *type)
1299{
1300 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001301 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001302
1303 if (type->ob_type == &PyType_Type) {
1304 result = mro_implementation(type);
1305 }
1306 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001307 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001308 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001309 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001310 if (mro == NULL)
1311 return -1;
1312 result = PyObject_CallObject(mro, NULL);
1313 Py_DECREF(mro);
1314 }
1315 if (result == NULL)
1316 return -1;
1317 tuple = PySequence_Tuple(result);
1318 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001319 if (tuple == NULL)
1320 return -1;
1321 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001322 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001323 PyObject *cls;
1324 PyTypeObject *solid;
1325
1326 solid = solid_base(type);
1327
1328 len = PyTuple_GET_SIZE(tuple);
1329
1330 for (i = 0; i < len; i++) {
1331 PyTypeObject *t;
1332 cls = PyTuple_GET_ITEM(tuple, i);
1333 if (PyClass_Check(cls))
1334 continue;
1335 else if (!PyType_Check(cls)) {
1336 PyErr_Format(PyExc_TypeError,
1337 "mro() returned a non-class ('%.500s')",
1338 cls->ob_type->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001339 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001340 return -1;
1341 }
1342 t = (PyTypeObject*)cls;
1343 if (!PyType_IsSubtype(solid, solid_base(t))) {
1344 PyErr_Format(PyExc_TypeError,
1345 "mro() returned base with unsuitable layout ('%.500s')",
1346 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001347 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001348 return -1;
1349 }
1350 }
1351 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001352 type->tp_mro = tuple;
1353 return 0;
1354}
1355
1356
1357/* Calculate the best base amongst multiple base classes.
1358 This is the first one that's on the path to the "solid base". */
1359
1360static PyTypeObject *
1361best_base(PyObject *bases)
1362{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001363 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001364 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001365 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001366
1367 assert(PyTuple_Check(bases));
1368 n = PyTuple_GET_SIZE(bases);
1369 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001370 base = NULL;
1371 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001372 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001373 base_proto = PyTuple_GET_ITEM(bases, i);
1374 if (PyClass_Check(base_proto))
1375 continue;
1376 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001377 PyErr_SetString(
1378 PyExc_TypeError,
1379 "bases must be types");
1380 return NULL;
1381 }
Tim Petersa91e9642001-11-14 23:32:33 +00001382 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001383 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001384 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001385 return NULL;
1386 }
1387 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001388 if (winner == NULL) {
1389 winner = candidate;
1390 base = base_i;
1391 }
1392 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001393 ;
1394 else if (PyType_IsSubtype(candidate, winner)) {
1395 winner = candidate;
1396 base = base_i;
1397 }
1398 else {
1399 PyErr_SetString(
1400 PyExc_TypeError,
1401 "multiple bases have "
1402 "instance lay-out conflict");
1403 return NULL;
1404 }
1405 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001406 if (base == NULL)
1407 PyErr_SetString(PyExc_TypeError,
1408 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001409 return base;
1410}
1411
1412static int
1413extra_ivars(PyTypeObject *type, PyTypeObject *base)
1414{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001415 size_t t_size = type->tp_basicsize;
1416 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001417
Guido van Rossum9676b222001-08-17 20:32:36 +00001418 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001419 if (type->tp_itemsize || base->tp_itemsize) {
1420 /* If itemsize is involved, stricter rules */
1421 return t_size != b_size ||
1422 type->tp_itemsize != base->tp_itemsize;
1423 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001424 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1425 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1426 t_size -= sizeof(PyObject *);
1427 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1428 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1429 t_size -= sizeof(PyObject *);
1430
1431 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001432}
1433
1434static PyTypeObject *
1435solid_base(PyTypeObject *type)
1436{
1437 PyTypeObject *base;
1438
1439 if (type->tp_base)
1440 base = solid_base(type->tp_base);
1441 else
1442 base = &PyBaseObject_Type;
1443 if (extra_ivars(type, base))
1444 return type;
1445 else
1446 return base;
1447}
1448
Jeremy Hylton938ace62002-07-17 16:30:39 +00001449static void object_dealloc(PyObject *);
1450static int object_init(PyObject *, PyObject *, PyObject *);
1451static int update_slot(PyTypeObject *, PyObject *);
1452static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001453
1454static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001455subtype_dict(PyObject *obj, void *context)
1456{
1457 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1458 PyObject *dict;
1459
1460 if (dictptr == NULL) {
1461 PyErr_SetString(PyExc_AttributeError,
1462 "This object has no __dict__");
1463 return NULL;
1464 }
1465 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001466 if (dict == NULL)
1467 *dictptr = dict = PyDict_New();
1468 Py_XINCREF(dict);
1469 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001470}
1471
Guido van Rossum6661be32001-10-26 04:26:12 +00001472static int
1473subtype_setdict(PyObject *obj, PyObject *value, void *context)
1474{
1475 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1476 PyObject *dict;
1477
1478 if (dictptr == NULL) {
1479 PyErr_SetString(PyExc_AttributeError,
1480 "This object has no __dict__");
1481 return -1;
1482 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001483 if (value != NULL && !PyDict_Check(value)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001484 PyErr_Format(PyExc_TypeError,
1485 "__dict__ must be set to a dictionary, "
1486 "not a '%.200s'", value->ob_type->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001487 return -1;
1488 }
1489 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001490 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001491 *dictptr = value;
1492 Py_XDECREF(dict);
1493 return 0;
1494}
1495
Guido van Rossumad47da02002-08-12 19:05:44 +00001496static PyObject *
1497subtype_getweakref(PyObject *obj, void *context)
1498{
1499 PyObject **weaklistptr;
1500 PyObject *result;
1501
1502 if (obj->ob_type->tp_weaklistoffset == 0) {
1503 PyErr_SetString(PyExc_AttributeError,
Fred Drake7a36f5f2006-08-04 05:17:21 +00001504 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001505 return NULL;
1506 }
1507 assert(obj->ob_type->tp_weaklistoffset > 0);
1508 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001509 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001510 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001511 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001512 if (*weaklistptr == NULL)
1513 result = Py_None;
1514 else
1515 result = *weaklistptr;
1516 Py_INCREF(result);
1517 return result;
1518}
1519
Guido van Rossum373c7412003-01-07 13:41:37 +00001520/* Three variants on the subtype_getsets list. */
1521
1522static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001523 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001524 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001525 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001526 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001527 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001528};
1529
Guido van Rossum373c7412003-01-07 13:41:37 +00001530static PyGetSetDef subtype_getsets_dict_only[] = {
1531 {"__dict__", subtype_dict, subtype_setdict,
1532 PyDoc_STR("dictionary for instance variables (if defined)")},
1533 {0}
1534};
1535
1536static PyGetSetDef subtype_getsets_weakref_only[] = {
1537 {"__weakref__", subtype_getweakref, NULL,
1538 PyDoc_STR("list of weak references to the object (if defined)")},
1539 {0}
1540};
1541
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001542static int
1543valid_identifier(PyObject *s)
1544{
Guido van Rossum03013a02002-07-16 14:30:28 +00001545 unsigned char *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001546 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001547
1548 if (!PyString_Check(s)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001549 PyErr_Format(PyExc_TypeError,
1550 "__slots__ items must be strings, not '%.200s'",
1551 s->ob_type->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001552 return 0;
1553 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001554 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001555 n = PyString_GET_SIZE(s);
1556 /* We must reject an empty name. As a hack, we bump the
1557 length to 1 so that the loop will balk on the trailing \0. */
1558 if (n == 0)
1559 n = 1;
1560 for (i = 0; i < n; i++, p++) {
1561 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1562 PyErr_SetString(PyExc_TypeError,
1563 "__slots__ must be identifiers");
1564 return 0;
1565 }
1566 }
1567 return 1;
1568}
1569
Martin v. Löwisd919a592002-10-14 21:07:28 +00001570#ifdef Py_USING_UNICODE
1571/* Replace Unicode objects in slots. */
1572
1573static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001574_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001575{
1576 PyObject *tmp = slots;
1577 PyObject *o, *o1;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001578 Py_ssize_t i;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001579 ssizessizeargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001580 for (i = 0; i < nslots; i++) {
1581 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1582 if (tmp == slots) {
1583 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1584 if (tmp == NULL)
1585 return NULL;
1586 }
1587 o1 = _PyUnicode_AsDefaultEncodedString
1588 (o, NULL);
1589 if (o1 == NULL) {
1590 Py_DECREF(tmp);
1591 return 0;
1592 }
1593 Py_INCREF(o1);
1594 Py_DECREF(o);
1595 PyTuple_SET_ITEM(tmp, i, o1);
1596 }
1597 }
1598 return tmp;
1599}
1600#endif
1601
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001602static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001603type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1604{
1605 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001606 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001607 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001608 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001609 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001610 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001611 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001612 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001613
Tim Peters3abca122001-10-27 19:37:48 +00001614 assert(args != NULL && PyTuple_Check(args));
1615 assert(kwds == NULL || PyDict_Check(kwds));
1616
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001617 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001618 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001619 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1620 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001621
1622 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1623 PyObject *x = PyTuple_GET_ITEM(args, 0);
1624 Py_INCREF(x->ob_type);
1625 return (PyObject *) x->ob_type;
1626 }
1627
1628 /* SF bug 475327 -- if that didn't trigger, we need 3
1629 arguments. but PyArg_ParseTupleAndKeywords below may give
1630 a msg saying type() needs exactly 3. */
1631 if (nargs + nkwds != 3) {
1632 PyErr_SetString(PyExc_TypeError,
1633 "type() takes 1 or 3 arguments");
1634 return NULL;
1635 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001636 }
1637
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001638 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001639 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1640 &name,
1641 &PyTuple_Type, &bases,
1642 &PyDict_Type, &dict))
1643 return NULL;
1644
1645 /* Determine the proper metatype to deal with this,
1646 and check for metatype conflicts while we're at it.
1647 Note that if some other metatype wins to contract,
1648 it's possible that its instances are not types. */
1649 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001650 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001651 for (i = 0; i < nbases; i++) {
1652 tmp = PyTuple_GET_ITEM(bases, i);
1653 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001654 if (tmptype == &PyClass_Type)
1655 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001656 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001657 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001658 if (PyType_IsSubtype(tmptype, winner)) {
1659 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001660 continue;
1661 }
1662 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001663 "metaclass conflict: "
1664 "the metaclass of a derived class "
1665 "must be a (non-strict) subclass "
1666 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001667 return NULL;
1668 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001669 if (winner != metatype) {
1670 if (winner->tp_new != type_new) /* Pass it to the winner */
1671 return winner->tp_new(winner, args, kwds);
1672 metatype = winner;
1673 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001674
1675 /* Adjust for empty tuple bases */
1676 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001677 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001678 if (bases == NULL)
1679 return NULL;
1680 nbases = 1;
1681 }
1682 else
1683 Py_INCREF(bases);
1684
1685 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1686
1687 /* Calculate best base, and check that all bases are type objects */
1688 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001689 if (base == NULL) {
1690 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001691 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001692 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001693 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1694 PyErr_Format(PyExc_TypeError,
1695 "type '%.100s' is not an acceptable base type",
1696 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001697 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001698 return NULL;
1699 }
1700
Tim Peters6d6c1a32001-08-02 04:15:00 +00001701 /* Check for a __slots__ sequence variable in dict, and count it */
1702 slots = PyDict_GetItemString(dict, "__slots__");
1703 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001704 add_dict = 0;
1705 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001706 may_add_dict = base->tp_dictoffset == 0;
1707 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1708 if (slots == NULL) {
1709 if (may_add_dict) {
1710 add_dict++;
1711 }
1712 if (may_add_weak) {
1713 add_weak++;
1714 }
1715 }
1716 else {
1717 /* Have slots */
1718
Tim Peters6d6c1a32001-08-02 04:15:00 +00001719 /* Make it into a tuple */
1720 if (PyString_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001721 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001722 else
1723 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001724 if (slots == NULL) {
1725 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001726 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001727 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001728 assert(PyTuple_Check(slots));
1729
1730 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001731 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001732 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001733 PyErr_Format(PyExc_TypeError,
1734 "nonempty __slots__ "
1735 "not supported for subtype of '%s'",
1736 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001737 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001738 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001739 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001740 return NULL;
1741 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001742
Martin v. Löwisd919a592002-10-14 21:07:28 +00001743#ifdef Py_USING_UNICODE
1744 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001745 if (tmp != slots) {
1746 Py_DECREF(slots);
1747 slots = tmp;
1748 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001749 if (!tmp)
1750 return NULL;
1751#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001752 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001753 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001754 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1755 char *s;
1756 if (!valid_identifier(tmp))
1757 goto bad_slots;
1758 assert(PyString_Check(tmp));
1759 s = PyString_AS_STRING(tmp);
1760 if (strcmp(s, "__dict__") == 0) {
1761 if (!may_add_dict || add_dict) {
1762 PyErr_SetString(PyExc_TypeError,
1763 "__dict__ slot disallowed: "
1764 "we already got one");
1765 goto bad_slots;
1766 }
1767 add_dict++;
1768 }
1769 if (strcmp(s, "__weakref__") == 0) {
1770 if (!may_add_weak || add_weak) {
1771 PyErr_SetString(PyExc_TypeError,
1772 "__weakref__ slot disallowed: "
1773 "either we already got one, "
1774 "or __itemsize__ != 0");
1775 goto bad_slots;
1776 }
1777 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001778 }
1779 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001780
Guido van Rossumad47da02002-08-12 19:05:44 +00001781 /* Copy slots into yet another tuple, demangling names */
1782 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001783 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001784 goto bad_slots;
1785 for (i = j = 0; i < nslots; i++) {
1786 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001787 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001788 s = PyString_AS_STRING(tmp);
1789 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1790 (add_weak && strcmp(s, "__weakref__") == 0))
1791 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001792 tmp =_Py_Mangle(name, tmp);
1793 if (!tmp)
1794 goto bad_slots;
Guido van Rossumad47da02002-08-12 19:05:44 +00001795 PyTuple_SET_ITEM(newslots, j, tmp);
1796 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001797 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001798 assert(j == nslots - add_dict - add_weak);
1799 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001800 Py_DECREF(slots);
1801 slots = newslots;
1802
Guido van Rossumad47da02002-08-12 19:05:44 +00001803 /* Secondary bases may provide weakrefs or dict */
1804 if (nbases > 1 &&
1805 ((may_add_dict && !add_dict) ||
1806 (may_add_weak && !add_weak))) {
1807 for (i = 0; i < nbases; i++) {
1808 tmp = PyTuple_GET_ITEM(bases, i);
1809 if (tmp == (PyObject *)base)
1810 continue; /* Skip primary base */
1811 if (PyClass_Check(tmp)) {
1812 /* Classic base class provides both */
1813 if (may_add_dict && !add_dict)
1814 add_dict++;
1815 if (may_add_weak && !add_weak)
1816 add_weak++;
1817 break;
1818 }
1819 assert(PyType_Check(tmp));
1820 tmptype = (PyTypeObject *)tmp;
1821 if (may_add_dict && !add_dict &&
1822 tmptype->tp_dictoffset != 0)
1823 add_dict++;
1824 if (may_add_weak && !add_weak &&
1825 tmptype->tp_weaklistoffset != 0)
1826 add_weak++;
1827 if (may_add_dict && !add_dict)
1828 continue;
1829 if (may_add_weak && !add_weak)
1830 continue;
1831 /* Nothing more to check */
1832 break;
1833 }
1834 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001835 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001836
1837 /* XXX From here until type is safely allocated,
1838 "return NULL" may leak slots! */
1839
1840 /* Allocate the type object */
1841 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001842 if (type == NULL) {
1843 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001844 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001845 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001846 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001847
1848 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001849 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001850 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00001851 et->ht_name = name;
1852 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001853
Guido van Rossumdc91b992001-08-08 22:26:22 +00001854 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001855 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1856 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001857 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1858 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001859
1860 /* It's a new-style number unless it specifically inherits any
1861 old-style numeric behavior */
1862 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1863 (base->tp_as_number == NULL))
1864 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1865
1866 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001867 type->tp_as_number = &et->as_number;
1868 type->tp_as_sequence = &et->as_sequence;
1869 type->tp_as_mapping = &et->as_mapping;
1870 type->tp_as_buffer = &et->as_buffer;
1871 type->tp_name = PyString_AS_STRING(name);
1872
1873 /* Set tp_base and tp_bases */
1874 type->tp_bases = bases;
1875 Py_INCREF(base);
1876 type->tp_base = base;
1877
Guido van Rossum687ae002001-10-15 22:03:32 +00001878 /* Initialize tp_dict from passed-in dict */
1879 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001880 if (dict == NULL) {
1881 Py_DECREF(type);
1882 return NULL;
1883 }
1884
Guido van Rossumc3542212001-08-16 09:18:56 +00001885 /* Set __module__ in the dict */
1886 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1887 tmp = PyEval_GetGlobals();
1888 if (tmp != NULL) {
1889 tmp = PyDict_GetItemString(tmp, "__name__");
1890 if (tmp != NULL) {
1891 if (PyDict_SetItemString(dict, "__module__",
1892 tmp) < 0)
1893 return NULL;
1894 }
1895 }
1896 }
1897
Tim Peters2f93e282001-10-04 05:27:00 +00001898 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001899 and is a string. The __doc__ accessor will first look for tp_doc;
1900 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001901 */
1902 {
1903 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1904 if (doc != NULL && PyString_Check(doc)) {
1905 const size_t n = (size_t)PyString_GET_SIZE(doc);
Anthony Baxtera6286212006-04-11 07:42:36 +00001906 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001907 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00001908 Py_DECREF(type);
1909 return NULL;
1910 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001911 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
1912 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00001913 }
1914 }
1915
Tim Peters6d6c1a32001-08-02 04:15:00 +00001916 /* Special-case __new__: if it's a plain function,
1917 make it a static function */
1918 tmp = PyDict_GetItemString(dict, "__new__");
1919 if (tmp != NULL && PyFunction_Check(tmp)) {
1920 tmp = PyStaticMethod_New(tmp);
1921 if (tmp == NULL) {
1922 Py_DECREF(type);
1923 return NULL;
1924 }
1925 PyDict_SetItemString(dict, "__new__", tmp);
1926 Py_DECREF(tmp);
1927 }
1928
1929 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001930 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001931 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001932 if (slots != NULL) {
1933 for (i = 0; i < nslots; i++, mp++) {
1934 mp->name = PyString_AS_STRING(
1935 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001936 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001937 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001938 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001939 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001940 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001941 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001942 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001943 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001944 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001945 slotoffset += sizeof(PyObject *);
1946 }
1947 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001948 if (add_dict) {
1949 if (base->tp_itemsize)
1950 type->tp_dictoffset = -(long)sizeof(PyObject *);
1951 else
1952 type->tp_dictoffset = slotoffset;
1953 slotoffset += sizeof(PyObject *);
1954 }
1955 if (add_weak) {
1956 assert(!base->tp_itemsize);
1957 type->tp_weaklistoffset = slotoffset;
1958 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001959 }
1960 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001961 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001962 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001963
1964 if (type->tp_weaklistoffset && type->tp_dictoffset)
1965 type->tp_getset = subtype_getsets_full;
1966 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1967 type->tp_getset = subtype_getsets_weakref_only;
1968 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1969 type->tp_getset = subtype_getsets_dict_only;
1970 else
1971 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001972
1973 /* Special case some slots */
1974 if (type->tp_dictoffset != 0 || nslots > 0) {
1975 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1976 type->tp_getattro = PyObject_GenericGetAttr;
1977 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1978 type->tp_setattro = PyObject_GenericSetAttr;
1979 }
1980 type->tp_dealloc = subtype_dealloc;
1981
Guido van Rossum9475a232001-10-05 20:51:39 +00001982 /* Enable GC unless there are really no instance variables possible */
1983 if (!(type->tp_basicsize == sizeof(PyObject) &&
1984 type->tp_itemsize == 0))
1985 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1986
Tim Peters6d6c1a32001-08-02 04:15:00 +00001987 /* Always override allocation strategy to use regular heap */
1988 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001989 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001990 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001991 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001992 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001993 }
1994 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001995 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001996
1997 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001998 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001999 Py_DECREF(type);
2000 return NULL;
2001 }
2002
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002003 /* Put the proper slots in place */
2004 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002005
Tim Peters6d6c1a32001-08-02 04:15:00 +00002006 return (PyObject *)type;
2007}
2008
2009/* Internal API to look for a name through the MRO.
2010 This returns a borrowed reference, and doesn't set an exception! */
2011PyObject *
2012_PyType_Lookup(PyTypeObject *type, PyObject *name)
2013{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002014 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002015 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002016
Guido van Rossum687ae002001-10-15 22:03:32 +00002017 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002018 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002019
2020 /* If mro is NULL, the type is either not yet initialized
2021 by PyType_Ready(), or already cleared by type_clear().
2022 Either way the safest thing to do is to return NULL. */
2023 if (mro == NULL)
2024 return NULL;
2025
Tim Peters6d6c1a32001-08-02 04:15:00 +00002026 assert(PyTuple_Check(mro));
2027 n = PyTuple_GET_SIZE(mro);
2028 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002029 base = PyTuple_GET_ITEM(mro, i);
2030 if (PyClass_Check(base))
2031 dict = ((PyClassObject *)base)->cl_dict;
2032 else {
2033 assert(PyType_Check(base));
2034 dict = ((PyTypeObject *)base)->tp_dict;
2035 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002036 assert(dict && PyDict_Check(dict));
2037 res = PyDict_GetItem(dict, name);
2038 if (res != NULL)
2039 return res;
2040 }
2041 return NULL;
2042}
2043
2044/* This is similar to PyObject_GenericGetAttr(),
2045 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2046static PyObject *
2047type_getattro(PyTypeObject *type, PyObject *name)
2048{
2049 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002050 PyObject *meta_attribute, *attribute;
2051 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002052
2053 /* Initialize this type (we'll assume the metatype is initialized) */
2054 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002055 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002056 return NULL;
2057 }
2058
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002059 /* No readable descriptor found yet */
2060 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002061
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002062 /* Look for the attribute in the metatype */
2063 meta_attribute = _PyType_Lookup(metatype, name);
2064
2065 if (meta_attribute != NULL) {
2066 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002067
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002068 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2069 /* Data descriptors implement tp_descr_set to intercept
2070 * writes. Assume the attribute is not overridden in
2071 * type's tp_dict (and bases): call the descriptor now.
2072 */
2073 return meta_get(meta_attribute, (PyObject *)type,
2074 (PyObject *)metatype);
2075 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002076 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002077 }
2078
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002079 /* No data descriptor found on metatype. Look in tp_dict of this
2080 * type and its bases */
2081 attribute = _PyType_Lookup(type, name);
2082 if (attribute != NULL) {
2083 /* Implement descriptor functionality, if any */
2084 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002085
2086 Py_XDECREF(meta_attribute);
2087
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002088 if (local_get != NULL) {
2089 /* NULL 2nd argument indicates the descriptor was
2090 * found on the target object itself (or a base) */
2091 return local_get(attribute, (PyObject *)NULL,
2092 (PyObject *)type);
2093 }
Tim Peters34592512002-07-11 06:23:50 +00002094
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002095 Py_INCREF(attribute);
2096 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002097 }
2098
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002099 /* No attribute found in local __dict__ (or bases): use the
2100 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002101 if (meta_get != NULL) {
2102 PyObject *res;
2103 res = meta_get(meta_attribute, (PyObject *)type,
2104 (PyObject *)metatype);
2105 Py_DECREF(meta_attribute);
2106 return res;
2107 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002108
2109 /* If an ordinary attribute was found on the metatype, return it now */
2110 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002111 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002112 }
2113
2114 /* Give up */
2115 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002116 "type object '%.50s' has no attribute '%.400s'",
2117 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002118 return NULL;
2119}
2120
2121static int
2122type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2123{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002124 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2125 PyErr_Format(
2126 PyExc_TypeError,
2127 "can't set attributes of built-in/extension type '%s'",
2128 type->tp_name);
2129 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002130 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002131 /* XXX Example of how I expect this to be used...
2132 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2133 return -1;
2134 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002135 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2136 return -1;
2137 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002138}
2139
2140static void
2141type_dealloc(PyTypeObject *type)
2142{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002143 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002144
2145 /* Assert this is a heap-allocated type object */
2146 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002147 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002148 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002149 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002150 Py_XDECREF(type->tp_base);
2151 Py_XDECREF(type->tp_dict);
2152 Py_XDECREF(type->tp_bases);
2153 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002154 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002155 Py_XDECREF(type->tp_subclasses);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002156 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2157 * of most other objects. It's okay to cast it to char *.
2158 */
2159 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002160 Py_XDECREF(et->ht_name);
2161 Py_XDECREF(et->ht_slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002162 type->ob_type->tp_free((PyObject *)type);
2163}
2164
Guido van Rossum1c450732001-10-08 15:18:27 +00002165static PyObject *
2166type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2167{
2168 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002169 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002170
2171 list = PyList_New(0);
2172 if (list == NULL)
2173 return NULL;
2174 raw = type->tp_subclasses;
2175 if (raw == NULL)
2176 return list;
2177 assert(PyList_Check(raw));
2178 n = PyList_GET_SIZE(raw);
2179 for (i = 0; i < n; i++) {
2180 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002181 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002182 ref = PyWeakref_GET_OBJECT(ref);
2183 if (ref != Py_None) {
2184 if (PyList_Append(list, ref) < 0) {
2185 Py_DECREF(list);
2186 return NULL;
2187 }
2188 }
2189 }
2190 return list;
2191}
2192
Tim Peters6d6c1a32001-08-02 04:15:00 +00002193static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002194 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002195 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002196 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002197 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002198 {0}
2199};
2200
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002201PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002202"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002203"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002204
Guido van Rossum048eb752001-10-02 21:24:57 +00002205static int
2206type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2207{
Guido van Rossuma3862092002-06-10 15:24:42 +00002208 /* Because of type_is_gc(), the collector only calls this
2209 for heaptypes. */
2210 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002211
Thomas Woutersc6e55062006-04-15 21:47:09 +00002212 Py_VISIT(type->tp_dict);
2213 Py_VISIT(type->tp_cache);
2214 Py_VISIT(type->tp_mro);
2215 Py_VISIT(type->tp_bases);
2216 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002217
2218 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002219 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002220 in cycles; tp_subclasses is a list of weak references,
2221 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002222
Guido van Rossum048eb752001-10-02 21:24:57 +00002223 return 0;
2224}
2225
2226static int
2227type_clear(PyTypeObject *type)
2228{
Guido van Rossuma3862092002-06-10 15:24:42 +00002229 /* Because of type_is_gc(), the collector only calls this
2230 for heaptypes. */
2231 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002232
Guido van Rossuma3862092002-06-10 15:24:42 +00002233 /* The only field we need to clear is tp_mro, which is part of a
2234 hard cycle (its first element is the class itself) that won't
2235 be broken otherwise (it's a tuple and tuples don't have a
2236 tp_clear handler). None of the other fields need to be
2237 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002238
Guido van Rossuma3862092002-06-10 15:24:42 +00002239 tp_dict:
2240 It is a dict, so the collector will call its tp_clear.
2241
2242 tp_cache:
2243 Not used; if it were, it would be a dict.
2244
2245 tp_bases, tp_base:
2246 If these are involved in a cycle, there must be at least
2247 one other, mutable object in the cycle, e.g. a base
2248 class's dict; the cycle will be broken that way.
2249
2250 tp_subclasses:
2251 A list of weak references can't be part of a cycle; and
2252 lists have their own tp_clear.
2253
Guido van Rossume5c691a2003-03-07 15:13:17 +00002254 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002255 A tuple of strings can't be part of a cycle.
2256 */
2257
Thomas Woutersedf17d82006-04-15 17:28:34 +00002258 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002259
2260 return 0;
2261}
2262
2263static int
2264type_is_gc(PyTypeObject *type)
2265{
2266 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2267}
2268
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002269PyTypeObject PyType_Type = {
2270 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002271 0, /* ob_size */
2272 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002273 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002274 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002275 (destructor)type_dealloc, /* tp_dealloc */
2276 0, /* tp_print */
2277 0, /* tp_getattr */
2278 0, /* tp_setattr */
2279 type_compare, /* tp_compare */
2280 (reprfunc)type_repr, /* tp_repr */
2281 0, /* tp_as_number */
2282 0, /* tp_as_sequence */
2283 0, /* tp_as_mapping */
2284 (hashfunc)_Py_HashPointer, /* tp_hash */
2285 (ternaryfunc)type_call, /* tp_call */
2286 0, /* tp_str */
2287 (getattrofunc)type_getattro, /* tp_getattro */
2288 (setattrofunc)type_setattro, /* tp_setattro */
2289 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002290 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2291 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002292 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002293 (traverseproc)type_traverse, /* tp_traverse */
2294 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002295 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002296 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002297 0, /* tp_iter */
2298 0, /* tp_iternext */
2299 type_methods, /* tp_methods */
2300 type_members, /* tp_members */
2301 type_getsets, /* tp_getset */
2302 0, /* tp_base */
2303 0, /* tp_dict */
2304 0, /* tp_descr_get */
2305 0, /* tp_descr_set */
2306 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2307 0, /* tp_init */
2308 0, /* tp_alloc */
2309 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002310 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002311 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002312};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002313
2314
2315/* The base type of all types (eventually)... except itself. */
2316
2317static int
2318object_init(PyObject *self, PyObject *args, PyObject *kwds)
2319{
2320 return 0;
2321}
2322
Guido van Rossum298e4212003-02-13 16:30:16 +00002323/* If we don't have a tp_new for a new-style class, new will use this one.
2324 Therefore this should take no arguments/keywords. However, this new may
2325 also be inherited by objects that define a tp_init but no tp_new. These
2326 objects WILL pass argumets to tp_new, because it gets the same args as
2327 tp_init. So only allow arguments if we aren't using the default init, in
2328 which case we expect init to handle argument parsing. */
2329static PyObject *
2330object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2331{
2332 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2333 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2334 PyErr_SetString(PyExc_TypeError,
2335 "default __new__ takes no parameters");
2336 return NULL;
2337 }
2338 return type->tp_alloc(type, 0);
2339}
2340
Tim Peters6d6c1a32001-08-02 04:15:00 +00002341static void
2342object_dealloc(PyObject *self)
2343{
2344 self->ob_type->tp_free(self);
2345}
2346
Guido van Rossum8e248182001-08-12 05:17:56 +00002347static PyObject *
2348object_repr(PyObject *self)
2349{
Guido van Rossum76e69632001-08-16 18:52:43 +00002350 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002351 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002352
Guido van Rossum76e69632001-08-16 18:52:43 +00002353 type = self->ob_type;
2354 mod = type_module(type, NULL);
2355 if (mod == NULL)
2356 PyErr_Clear();
2357 else if (!PyString_Check(mod)) {
2358 Py_DECREF(mod);
2359 mod = NULL;
2360 }
2361 name = type_name(type, NULL);
2362 if (name == NULL)
2363 return NULL;
2364 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002365 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002366 PyString_AS_STRING(mod),
2367 PyString_AS_STRING(name),
2368 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002369 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002370 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002371 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002372 Py_XDECREF(mod);
2373 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002374 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002375}
2376
Guido van Rossumb8f63662001-08-15 23:57:02 +00002377static PyObject *
2378object_str(PyObject *self)
2379{
2380 unaryfunc f;
2381
2382 f = self->ob_type->tp_repr;
2383 if (f == NULL)
2384 f = object_repr;
2385 return f(self);
2386}
2387
Guido van Rossum8e248182001-08-12 05:17:56 +00002388static long
2389object_hash(PyObject *self)
2390{
2391 return _Py_HashPointer(self);
2392}
Guido van Rossum8e248182001-08-12 05:17:56 +00002393
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002394static PyObject *
2395object_get_class(PyObject *self, void *closure)
2396{
2397 Py_INCREF(self->ob_type);
2398 return (PyObject *)(self->ob_type);
2399}
2400
2401static int
2402equiv_structs(PyTypeObject *a, PyTypeObject *b)
2403{
2404 return a == b ||
2405 (a != NULL &&
2406 b != NULL &&
2407 a->tp_basicsize == b->tp_basicsize &&
2408 a->tp_itemsize == b->tp_itemsize &&
2409 a->tp_dictoffset == b->tp_dictoffset &&
2410 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2411 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2412 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2413}
2414
2415static int
2416same_slots_added(PyTypeObject *a, PyTypeObject *b)
2417{
2418 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002419 Py_ssize_t size;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002420
2421 if (base != b->tp_base)
2422 return 0;
2423 if (equiv_structs(a, base) && equiv_structs(b, base))
2424 return 1;
2425 size = base->tp_basicsize;
2426 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2427 size += sizeof(PyObject *);
2428 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2429 size += sizeof(PyObject *);
2430 return size == a->tp_basicsize && size == b->tp_basicsize;
2431}
2432
2433static int
Anthony Baxtera6286212006-04-11 07:42:36 +00002434compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002435{
2436 PyTypeObject *newbase, *oldbase;
2437
Anthony Baxtera6286212006-04-11 07:42:36 +00002438 if (newto->tp_dealloc != oldto->tp_dealloc ||
2439 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002440 {
2441 PyErr_Format(PyExc_TypeError,
2442 "%s assignment: "
2443 "'%s' deallocator differs from '%s'",
2444 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002445 newto->tp_name,
2446 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002447 return 0;
2448 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002449 newbase = newto;
2450 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002451 while (equiv_structs(newbase, newbase->tp_base))
2452 newbase = newbase->tp_base;
2453 while (equiv_structs(oldbase, oldbase->tp_base))
2454 oldbase = oldbase->tp_base;
2455 if (newbase != oldbase &&
2456 (newbase->tp_base != oldbase->tp_base ||
2457 !same_slots_added(newbase, oldbase))) {
2458 PyErr_Format(PyExc_TypeError,
2459 "%s assignment: "
2460 "'%s' object layout differs from '%s'",
2461 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002462 newto->tp_name,
2463 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002464 return 0;
2465 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002466
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002467 return 1;
2468}
2469
2470static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002471object_set_class(PyObject *self, PyObject *value, void *closure)
2472{
Anthony Baxtera6286212006-04-11 07:42:36 +00002473 PyTypeObject *oldto = self->ob_type;
2474 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002475
Guido van Rossumb6b89422002-04-15 01:03:30 +00002476 if (value == NULL) {
2477 PyErr_SetString(PyExc_TypeError,
2478 "can't delete __class__ attribute");
2479 return -1;
2480 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002481 if (!PyType_Check(value)) {
2482 PyErr_Format(PyExc_TypeError,
2483 "__class__ must be set to new-style class, not '%s' object",
2484 value->ob_type->tp_name);
2485 return -1;
2486 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002487 newto = (PyTypeObject *)value;
2488 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2489 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002490 {
2491 PyErr_Format(PyExc_TypeError,
2492 "__class__ assignment: only for heap types");
2493 return -1;
2494 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002495 if (compatible_for_assignment(newto, oldto, "__class__")) {
2496 Py_INCREF(newto);
2497 self->ob_type = newto;
2498 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002499 return 0;
2500 }
2501 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002502 return -1;
2503 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002504}
2505
2506static PyGetSetDef object_getsets[] = {
2507 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002508 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002509 {0}
2510};
2511
Guido van Rossumc53f0092003-02-18 22:05:12 +00002512
Guido van Rossum036f9992003-02-21 22:02:54 +00002513/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2514 We fall back to helpers in copy_reg for:
2515 - pickle protocols < 2
2516 - calculating the list of slot names (done only once per class)
2517 - the __newobj__ function (which is used as a token but never called)
2518*/
2519
2520static PyObject *
2521import_copy_reg(void)
2522{
2523 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002524
2525 if (!copy_reg_str) {
2526 copy_reg_str = PyString_InternFromString("copy_reg");
2527 if (copy_reg_str == NULL)
2528 return NULL;
2529 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002530
2531 return PyImport_Import(copy_reg_str);
2532}
2533
2534static PyObject *
2535slotnames(PyObject *cls)
2536{
2537 PyObject *clsdict;
2538 PyObject *copy_reg;
2539 PyObject *slotnames;
2540
2541 if (!PyType_Check(cls)) {
2542 Py_INCREF(Py_None);
2543 return Py_None;
2544 }
2545
2546 clsdict = ((PyTypeObject *)cls)->tp_dict;
2547 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002548 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002549 Py_INCREF(slotnames);
2550 return slotnames;
2551 }
2552
2553 copy_reg = import_copy_reg();
2554 if (copy_reg == NULL)
2555 return NULL;
2556
2557 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2558 Py_DECREF(copy_reg);
2559 if (slotnames != NULL &&
2560 slotnames != Py_None &&
2561 !PyList_Check(slotnames))
2562 {
2563 PyErr_SetString(PyExc_TypeError,
2564 "copy_reg._slotnames didn't return a list or None");
2565 Py_DECREF(slotnames);
2566 slotnames = NULL;
2567 }
2568
2569 return slotnames;
2570}
2571
2572static PyObject *
2573reduce_2(PyObject *obj)
2574{
2575 PyObject *cls, *getnewargs;
2576 PyObject *args = NULL, *args2 = NULL;
2577 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2578 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2579 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002580 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00002581
2582 cls = PyObject_GetAttrString(obj, "__class__");
2583 if (cls == NULL)
2584 return NULL;
2585
2586 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2587 if (getnewargs != NULL) {
2588 args = PyObject_CallObject(getnewargs, NULL);
2589 Py_DECREF(getnewargs);
2590 if (args != NULL && !PyTuple_Check(args)) {
Georg Brandlccff7852006-06-18 22:17:29 +00002591 PyErr_Format(PyExc_TypeError,
2592 "__getnewargs__ should return a tuple, "
2593 "not '%.200s'", args->ob_type->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00002594 goto end;
2595 }
2596 }
2597 else {
2598 PyErr_Clear();
2599 args = PyTuple_New(0);
2600 }
2601 if (args == NULL)
2602 goto end;
2603
2604 getstate = PyObject_GetAttrString(obj, "__getstate__");
2605 if (getstate != NULL) {
2606 state = PyObject_CallObject(getstate, NULL);
2607 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002608 if (state == NULL)
2609 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002610 }
2611 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002612 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002613 state = PyObject_GetAttrString(obj, "__dict__");
2614 if (state == NULL) {
2615 PyErr_Clear();
2616 state = Py_None;
2617 Py_INCREF(state);
2618 }
2619 names = slotnames(cls);
2620 if (names == NULL)
2621 goto end;
2622 if (names != Py_None) {
2623 assert(PyList_Check(names));
2624 slots = PyDict_New();
2625 if (slots == NULL)
2626 goto end;
2627 n = 0;
2628 /* Can't pre-compute the list size; the list
2629 is stored on the class so accessible to other
2630 threads, which may be run by DECREF */
2631 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2632 PyObject *name, *value;
2633 name = PyList_GET_ITEM(names, i);
2634 value = PyObject_GetAttr(obj, name);
2635 if (value == NULL)
2636 PyErr_Clear();
2637 else {
2638 int err = PyDict_SetItem(slots, name,
2639 value);
2640 Py_DECREF(value);
2641 if (err)
2642 goto end;
2643 n++;
2644 }
2645 }
2646 if (n) {
2647 state = Py_BuildValue("(NO)", state, slots);
2648 if (state == NULL)
2649 goto end;
2650 }
2651 }
2652 }
2653
2654 if (!PyList_Check(obj)) {
2655 listitems = Py_None;
2656 Py_INCREF(listitems);
2657 }
2658 else {
2659 listitems = PyObject_GetIter(obj);
2660 if (listitems == NULL)
2661 goto end;
2662 }
2663
2664 if (!PyDict_Check(obj)) {
2665 dictitems = Py_None;
2666 Py_INCREF(dictitems);
2667 }
2668 else {
2669 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2670 if (dictitems == NULL)
2671 goto end;
2672 }
2673
2674 copy_reg = import_copy_reg();
2675 if (copy_reg == NULL)
2676 goto end;
2677 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2678 if (newobj == NULL)
2679 goto end;
2680
2681 n = PyTuple_GET_SIZE(args);
2682 args2 = PyTuple_New(n+1);
2683 if (args2 == NULL)
2684 goto end;
2685 PyTuple_SET_ITEM(args2, 0, cls);
2686 cls = NULL;
2687 for (i = 0; i < n; i++) {
2688 PyObject *v = PyTuple_GET_ITEM(args, i);
2689 Py_INCREF(v);
2690 PyTuple_SET_ITEM(args2, i+1, v);
2691 }
2692
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002693 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002694
2695 end:
2696 Py_XDECREF(cls);
2697 Py_XDECREF(args);
2698 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002699 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002700 Py_XDECREF(state);
2701 Py_XDECREF(names);
2702 Py_XDECREF(listitems);
2703 Py_XDECREF(dictitems);
2704 Py_XDECREF(copy_reg);
2705 Py_XDECREF(newobj);
2706 return res;
2707}
2708
2709static PyObject *
2710object_reduce_ex(PyObject *self, PyObject *args)
2711{
2712 /* Call copy_reg._reduce_ex(self, proto) */
2713 PyObject *reduce, *copy_reg, *res;
2714 int proto = 0;
2715
2716 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2717 return NULL;
2718
2719 reduce = PyObject_GetAttrString(self, "__reduce__");
2720 if (reduce == NULL)
2721 PyErr_Clear();
2722 else {
2723 PyObject *cls, *clsreduce, *objreduce;
2724 int override;
2725 cls = PyObject_GetAttrString(self, "__class__");
2726 if (cls == NULL) {
2727 Py_DECREF(reduce);
2728 return NULL;
2729 }
2730 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2731 Py_DECREF(cls);
2732 if (clsreduce == NULL) {
2733 Py_DECREF(reduce);
2734 return NULL;
2735 }
2736 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2737 "__reduce__");
2738 override = (clsreduce != objreduce);
2739 Py_DECREF(clsreduce);
2740 if (override) {
2741 res = PyObject_CallObject(reduce, NULL);
2742 Py_DECREF(reduce);
2743 return res;
2744 }
2745 else
2746 Py_DECREF(reduce);
2747 }
2748
2749 if (proto >= 2)
2750 return reduce_2(self);
2751
2752 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002753 if (!copy_reg)
2754 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002755
Guido van Rossumc53f0092003-02-18 22:05:12 +00002756 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002757 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002758
Guido van Rossum3926a632001-09-25 16:25:58 +00002759 return res;
2760}
2761
2762static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002763 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2764 PyDoc_STR("helper for pickle")},
2765 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002766 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002767 {0}
2768};
2769
Guido van Rossum036f9992003-02-21 22:02:54 +00002770
Tim Peters6d6c1a32001-08-02 04:15:00 +00002771PyTypeObject PyBaseObject_Type = {
2772 PyObject_HEAD_INIT(&PyType_Type)
2773 0, /* ob_size */
2774 "object", /* tp_name */
2775 sizeof(PyObject), /* tp_basicsize */
2776 0, /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00002777 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002778 0, /* tp_print */
2779 0, /* tp_getattr */
2780 0, /* tp_setattr */
2781 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002782 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002783 0, /* tp_as_number */
2784 0, /* tp_as_sequence */
2785 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002786 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002787 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002788 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002789 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002790 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002791 0, /* tp_as_buffer */
2792 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002793 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002794 0, /* tp_traverse */
2795 0, /* tp_clear */
2796 0, /* tp_richcompare */
2797 0, /* tp_weaklistoffset */
2798 0, /* tp_iter */
2799 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002800 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002801 0, /* tp_members */
2802 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002803 0, /* tp_base */
2804 0, /* tp_dict */
2805 0, /* tp_descr_get */
2806 0, /* tp_descr_set */
2807 0, /* tp_dictoffset */
2808 object_init, /* tp_init */
2809 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002810 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002811 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002812};
2813
2814
2815/* Initialize the __dict__ in a type object */
2816
2817static int
2818add_methods(PyTypeObject *type, PyMethodDef *meth)
2819{
Guido van Rossum687ae002001-10-15 22:03:32 +00002820 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002821
2822 for (; meth->ml_name != NULL; meth++) {
2823 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002824 if (PyDict_GetItemString(dict, meth->ml_name) &&
2825 !(meth->ml_flags & METH_COEXIST))
2826 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002827 if (meth->ml_flags & METH_CLASS) {
2828 if (meth->ml_flags & METH_STATIC) {
2829 PyErr_SetString(PyExc_ValueError,
2830 "method cannot be both class and static");
2831 return -1;
2832 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002833 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002834 }
2835 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002836 PyObject *cfunc = PyCFunction_New(meth, NULL);
2837 if (cfunc == NULL)
2838 return -1;
2839 descr = PyStaticMethod_New(cfunc);
2840 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002841 }
2842 else {
2843 descr = PyDescr_NewMethod(type, meth);
2844 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002845 if (descr == NULL)
2846 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002847 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002848 return -1;
2849 Py_DECREF(descr);
2850 }
2851 return 0;
2852}
2853
2854static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002855add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002856{
Guido van Rossum687ae002001-10-15 22:03:32 +00002857 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002858
2859 for (; memb->name != NULL; memb++) {
2860 PyObject *descr;
2861 if (PyDict_GetItemString(dict, memb->name))
2862 continue;
2863 descr = PyDescr_NewMember(type, memb);
2864 if (descr == NULL)
2865 return -1;
2866 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2867 return -1;
2868 Py_DECREF(descr);
2869 }
2870 return 0;
2871}
2872
2873static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002874add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002875{
Guido van Rossum687ae002001-10-15 22:03:32 +00002876 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002877
2878 for (; gsp->name != NULL; gsp++) {
2879 PyObject *descr;
2880 if (PyDict_GetItemString(dict, gsp->name))
2881 continue;
2882 descr = PyDescr_NewGetSet(type, gsp);
2883
2884 if (descr == NULL)
2885 return -1;
2886 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2887 return -1;
2888 Py_DECREF(descr);
2889 }
2890 return 0;
2891}
2892
Guido van Rossum13d52f02001-08-10 21:24:08 +00002893static void
2894inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002895{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002896 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002897
Guido van Rossum13d52f02001-08-10 21:24:08 +00002898 /* Special flag magic */
2899 if (!type->tp_as_buffer && base->tp_as_buffer) {
2900 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2901 type->tp_flags |=
2902 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2903 }
2904 if (!type->tp_as_sequence && base->tp_as_sequence) {
2905 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2906 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2907 }
2908 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2909 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2910 if ((!type->tp_as_number && base->tp_as_number) ||
2911 (!type->tp_as_sequence && base->tp_as_sequence)) {
2912 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2913 if (!type->tp_as_number && !type->tp_as_sequence) {
2914 type->tp_flags |= base->tp_flags &
2915 Py_TPFLAGS_HAVE_INPLACEOPS;
2916 }
2917 }
2918 /* Wow */
2919 }
2920 if (!type->tp_as_number && base->tp_as_number) {
2921 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2922 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2923 }
2924
2925 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002926 oldsize = base->tp_basicsize;
2927 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2928 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2929 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002930 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2931 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002932 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002933 if (type->tp_traverse == NULL)
2934 type->tp_traverse = base->tp_traverse;
2935 if (type->tp_clear == NULL)
2936 type->tp_clear = base->tp_clear;
2937 }
2938 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002939 /* The condition below could use some explanation.
2940 It appears that tp_new is not inherited for static types
2941 whose base class is 'object'; this seems to be a precaution
2942 so that old extension types don't suddenly become
2943 callable (object.__new__ wouldn't insure the invariants
2944 that the extension type's own factory function ensures).
2945 Heap types, of course, are under our control, so they do
2946 inherit tp_new; static extension types that specify some
2947 other built-in type as the default are considered
2948 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002949 if (base != &PyBaseObject_Type ||
2950 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2951 if (type->tp_new == NULL)
2952 type->tp_new = base->tp_new;
2953 }
2954 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002955 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002956
2957 /* Copy other non-function slots */
2958
2959#undef COPYVAL
2960#define COPYVAL(SLOT) \
2961 if (type->SLOT == 0) type->SLOT = base->SLOT
2962
2963 COPYVAL(tp_itemsize);
2964 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2965 COPYVAL(tp_weaklistoffset);
2966 }
2967 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2968 COPYVAL(tp_dictoffset);
2969 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002970}
2971
2972static void
2973inherit_slots(PyTypeObject *type, PyTypeObject *base)
2974{
2975 PyTypeObject *basebase;
2976
2977#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002978#undef COPYSLOT
2979#undef COPYNUM
2980#undef COPYSEQ
2981#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002982#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002983
2984#define SLOTDEFINED(SLOT) \
2985 (base->SLOT != 0 && \
2986 (basebase == NULL || base->SLOT != basebase->SLOT))
2987
Tim Peters6d6c1a32001-08-02 04:15:00 +00002988#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002989 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002990
2991#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2992#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2993#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002994#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002995
Guido van Rossum13d52f02001-08-10 21:24:08 +00002996 /* This won't inherit indirect slots (from tp_as_number etc.)
2997 if type doesn't provide the space. */
2998
2999 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3000 basebase = base->tp_base;
3001 if (basebase->tp_as_number == NULL)
3002 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003003 COPYNUM(nb_add);
3004 COPYNUM(nb_subtract);
3005 COPYNUM(nb_multiply);
3006 COPYNUM(nb_divide);
3007 COPYNUM(nb_remainder);
3008 COPYNUM(nb_divmod);
3009 COPYNUM(nb_power);
3010 COPYNUM(nb_negative);
3011 COPYNUM(nb_positive);
3012 COPYNUM(nb_absolute);
3013 COPYNUM(nb_nonzero);
3014 COPYNUM(nb_invert);
3015 COPYNUM(nb_lshift);
3016 COPYNUM(nb_rshift);
3017 COPYNUM(nb_and);
3018 COPYNUM(nb_xor);
3019 COPYNUM(nb_or);
3020 COPYNUM(nb_coerce);
3021 COPYNUM(nb_int);
3022 COPYNUM(nb_long);
3023 COPYNUM(nb_float);
3024 COPYNUM(nb_oct);
3025 COPYNUM(nb_hex);
3026 COPYNUM(nb_inplace_add);
3027 COPYNUM(nb_inplace_subtract);
3028 COPYNUM(nb_inplace_multiply);
3029 COPYNUM(nb_inplace_divide);
3030 COPYNUM(nb_inplace_remainder);
3031 COPYNUM(nb_inplace_power);
3032 COPYNUM(nb_inplace_lshift);
3033 COPYNUM(nb_inplace_rshift);
3034 COPYNUM(nb_inplace_and);
3035 COPYNUM(nb_inplace_xor);
3036 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003037 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3038 COPYNUM(nb_true_divide);
3039 COPYNUM(nb_floor_divide);
3040 COPYNUM(nb_inplace_true_divide);
3041 COPYNUM(nb_inplace_floor_divide);
3042 }
Guido van Rossum38fff8c2006-03-07 18:50:55 +00003043 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3044 COPYNUM(nb_index);
3045 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003046 }
3047
Guido van Rossum13d52f02001-08-10 21:24:08 +00003048 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3049 basebase = base->tp_base;
3050 if (basebase->tp_as_sequence == NULL)
3051 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003052 COPYSEQ(sq_length);
3053 COPYSEQ(sq_concat);
3054 COPYSEQ(sq_repeat);
3055 COPYSEQ(sq_item);
3056 COPYSEQ(sq_slice);
3057 COPYSEQ(sq_ass_item);
3058 COPYSEQ(sq_ass_slice);
3059 COPYSEQ(sq_contains);
3060 COPYSEQ(sq_inplace_concat);
3061 COPYSEQ(sq_inplace_repeat);
3062 }
3063
Guido van Rossum13d52f02001-08-10 21:24:08 +00003064 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3065 basebase = base->tp_base;
3066 if (basebase->tp_as_mapping == NULL)
3067 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003068 COPYMAP(mp_length);
3069 COPYMAP(mp_subscript);
3070 COPYMAP(mp_ass_subscript);
3071 }
3072
Tim Petersfc57ccb2001-10-12 02:38:24 +00003073 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3074 basebase = base->tp_base;
3075 if (basebase->tp_as_buffer == NULL)
3076 basebase = NULL;
3077 COPYBUF(bf_getreadbuffer);
3078 COPYBUF(bf_getwritebuffer);
3079 COPYBUF(bf_getsegcount);
3080 COPYBUF(bf_getcharbuffer);
3081 }
3082
Guido van Rossum13d52f02001-08-10 21:24:08 +00003083 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003084
Tim Peters6d6c1a32001-08-02 04:15:00 +00003085 COPYSLOT(tp_dealloc);
3086 COPYSLOT(tp_print);
3087 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3088 type->tp_getattr = base->tp_getattr;
3089 type->tp_getattro = base->tp_getattro;
3090 }
3091 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3092 type->tp_setattr = base->tp_setattr;
3093 type->tp_setattro = base->tp_setattro;
3094 }
3095 /* tp_compare see tp_richcompare */
3096 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003097 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003098 COPYSLOT(tp_call);
3099 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003100 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003101 if (type->tp_compare == NULL &&
3102 type->tp_richcompare == NULL &&
3103 type->tp_hash == NULL)
3104 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003105 type->tp_compare = base->tp_compare;
3106 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003107 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003108 }
3109 }
3110 else {
3111 COPYSLOT(tp_compare);
3112 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003113 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3114 COPYSLOT(tp_iter);
3115 COPYSLOT(tp_iternext);
3116 }
3117 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3118 COPYSLOT(tp_descr_get);
3119 COPYSLOT(tp_descr_set);
3120 COPYSLOT(tp_dictoffset);
3121 COPYSLOT(tp_init);
3122 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003123 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003124 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3125 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3126 /* They agree about gc. */
3127 COPYSLOT(tp_free);
3128 }
3129 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3130 type->tp_free == NULL &&
3131 base->tp_free == _PyObject_Del) {
3132 /* A bit of magic to plug in the correct default
3133 * tp_free function when a derived class adds gc,
3134 * didn't define tp_free, and the base uses the
3135 * default non-gc tp_free.
3136 */
3137 type->tp_free = PyObject_GC_Del;
3138 }
3139 /* else they didn't agree about gc, and there isn't something
3140 * obvious to be done -- the type is on its own.
3141 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003142 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003143}
3144
Jeremy Hylton938ace62002-07-17 16:30:39 +00003145static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003146
Tim Peters6d6c1a32001-08-02 04:15:00 +00003147int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003148PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003149{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003150 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003151 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003152 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003153
Guido van Rossumcab05802002-06-10 15:29:03 +00003154 if (type->tp_flags & Py_TPFLAGS_READY) {
3155 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003156 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003157 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003158 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003159
3160 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003161
Tim Peters36eb4df2003-03-23 03:33:13 +00003162#ifdef Py_TRACE_REFS
3163 /* PyType_Ready is the closest thing we have to a choke point
3164 * for type objects, so is the best place I can think of to try
3165 * to get type objects into the doubly-linked list of all objects.
3166 * Still, not all type objects go thru PyType_Ready.
3167 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003168 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003169#endif
3170
Tim Peters6d6c1a32001-08-02 04:15:00 +00003171 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3172 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003173 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003174 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003175 Py_INCREF(base);
3176 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003177
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003178 /* Now the only way base can still be NULL is if type is
3179 * &PyBaseObject_Type.
3180 */
3181
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003182 /* Initialize the base class */
3183 if (base && base->tp_dict == NULL) {
3184 if (PyType_Ready(base) < 0)
3185 goto error;
3186 }
3187
Guido van Rossum0986d822002-04-08 01:38:42 +00003188 /* Initialize ob_type if NULL. This means extensions that want to be
3189 compilable separately on Windows can call PyType_Ready() instead of
3190 initializing the ob_type field of their type objects. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003191 /* The test for base != NULL is really unnecessary, since base is only
3192 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3193 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3194 know that. */
3195 if (type->ob_type == NULL && base != NULL)
Guido van Rossum0986d822002-04-08 01:38:42 +00003196 type->ob_type = base->ob_type;
3197
Tim Peters6d6c1a32001-08-02 04:15:00 +00003198 /* Initialize tp_bases */
3199 bases = type->tp_bases;
3200 if (bases == NULL) {
3201 if (base == NULL)
3202 bases = PyTuple_New(0);
3203 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003204 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003205 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003206 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003207 type->tp_bases = bases;
3208 }
3209
Guido van Rossum687ae002001-10-15 22:03:32 +00003210 /* Initialize tp_dict */
3211 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003212 if (dict == NULL) {
3213 dict = PyDict_New();
3214 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003215 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003216 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003217 }
3218
Guido van Rossum687ae002001-10-15 22:03:32 +00003219 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003220 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003221 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003222 if (type->tp_methods != NULL) {
3223 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003224 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003225 }
3226 if (type->tp_members != NULL) {
3227 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003228 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003229 }
3230 if (type->tp_getset != NULL) {
3231 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003232 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003233 }
3234
Tim Peters6d6c1a32001-08-02 04:15:00 +00003235 /* Calculate method resolution order */
3236 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003237 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003238 }
3239
Guido van Rossum13d52f02001-08-10 21:24:08 +00003240 /* Inherit special flags from dominant base */
3241 if (type->tp_base != NULL)
3242 inherit_special(type, type->tp_base);
3243
Tim Peters6d6c1a32001-08-02 04:15:00 +00003244 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003245 bases = type->tp_mro;
3246 assert(bases != NULL);
3247 assert(PyTuple_Check(bases));
3248 n = PyTuple_GET_SIZE(bases);
3249 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003250 PyObject *b = PyTuple_GET_ITEM(bases, i);
3251 if (PyType_Check(b))
3252 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003253 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003254
Tim Peters3cfe7542003-05-21 21:29:48 +00003255 /* Sanity check for tp_free. */
3256 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3257 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3258 /* This base class needs to call tp_free, but doesn't have
3259 * one, or its tp_free is for non-gc'ed objects.
3260 */
3261 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3262 "gc and is a base type but has inappropriate "
3263 "tp_free slot",
3264 type->tp_name);
3265 goto error;
3266 }
3267
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003268 /* if the type dictionary doesn't contain a __doc__, set it from
3269 the tp_doc slot.
3270 */
3271 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3272 if (type->tp_doc != NULL) {
3273 PyObject *doc = PyString_FromString(type->tp_doc);
Neal Norwitze1fdb322006-07-21 05:32:28 +00003274 if (doc == NULL)
3275 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003276 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3277 Py_DECREF(doc);
3278 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003279 PyDict_SetItemString(type->tp_dict,
3280 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003281 }
3282 }
3283
Guido van Rossum13d52f02001-08-10 21:24:08 +00003284 /* Some more special stuff */
3285 base = type->tp_base;
3286 if (base != NULL) {
3287 if (type->tp_as_number == NULL)
3288 type->tp_as_number = base->tp_as_number;
3289 if (type->tp_as_sequence == NULL)
3290 type->tp_as_sequence = base->tp_as_sequence;
3291 if (type->tp_as_mapping == NULL)
3292 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003293 if (type->tp_as_buffer == NULL)
3294 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003295 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003296
Guido van Rossum1c450732001-10-08 15:18:27 +00003297 /* Link into each base class's list of subclasses */
3298 bases = type->tp_bases;
3299 n = PyTuple_GET_SIZE(bases);
3300 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003301 PyObject *b = PyTuple_GET_ITEM(bases, i);
3302 if (PyType_Check(b) &&
3303 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003304 goto error;
3305 }
3306
Guido van Rossum13d52f02001-08-10 21:24:08 +00003307 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003308 assert(type->tp_dict != NULL);
3309 type->tp_flags =
3310 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003311 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003312
3313 error:
3314 type->tp_flags &= ~Py_TPFLAGS_READYING;
3315 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003316}
3317
Guido van Rossum1c450732001-10-08 15:18:27 +00003318static int
3319add_subclass(PyTypeObject *base, PyTypeObject *type)
3320{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003321 Py_ssize_t i;
3322 int result;
Anthony Baxtera6286212006-04-11 07:42:36 +00003323 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003324
3325 list = base->tp_subclasses;
3326 if (list == NULL) {
3327 base->tp_subclasses = list = PyList_New(0);
3328 if (list == NULL)
3329 return -1;
3330 }
3331 assert(PyList_Check(list));
Anthony Baxtera6286212006-04-11 07:42:36 +00003332 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003333 i = PyList_GET_SIZE(list);
3334 while (--i >= 0) {
3335 ref = PyList_GET_ITEM(list, i);
3336 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003337 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Anthony Baxtera6286212006-04-11 07:42:36 +00003338 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003339 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003340 result = PyList_Append(list, newobj);
3341 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003342 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003343}
3344
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003345static void
3346remove_subclass(PyTypeObject *base, PyTypeObject *type)
3347{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003348 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003349 PyObject *list, *ref;
3350
3351 list = base->tp_subclasses;
3352 if (list == NULL) {
3353 return;
3354 }
3355 assert(PyList_Check(list));
3356 i = PyList_GET_SIZE(list);
3357 while (--i >= 0) {
3358 ref = PyList_GET_ITEM(list, i);
3359 assert(PyWeakref_CheckRef(ref));
3360 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3361 /* this can't fail, right? */
3362 PySequence_DelItem(list, i);
3363 return;
3364 }
3365 }
3366}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003367
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003368static int
3369check_num_args(PyObject *ob, int n)
3370{
3371 if (!PyTuple_CheckExact(ob)) {
3372 PyErr_SetString(PyExc_SystemError,
3373 "PyArg_UnpackTuple() argument list is not a tuple");
3374 return 0;
3375 }
3376 if (n == PyTuple_GET_SIZE(ob))
3377 return 1;
3378 PyErr_Format(
3379 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003380 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003381 return 0;
3382}
3383
Tim Peters6d6c1a32001-08-02 04:15:00 +00003384/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3385
3386/* There's a wrapper *function* for each distinct function typedef used
3387 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3388 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3389 Most tables have only one entry; the tables for binary operators have two
3390 entries, one regular and one with reversed arguments. */
3391
3392static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003393wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003394{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003395 lenfunc func = (lenfunc)wrapped;
3396 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003397
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003398 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003399 return NULL;
3400 res = (*func)(self);
3401 if (res == -1 && PyErr_Occurred())
3402 return NULL;
3403 return PyInt_FromLong((long)res);
3404}
3405
Tim Peters6d6c1a32001-08-02 04:15:00 +00003406static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003407wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3408{
3409 inquiry func = (inquiry)wrapped;
3410 int res;
3411
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003412 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003413 return NULL;
3414 res = (*func)(self);
3415 if (res == -1 && PyErr_Occurred())
3416 return NULL;
3417 return PyBool_FromLong((long)res);
3418}
3419
3420static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003421wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3422{
3423 binaryfunc func = (binaryfunc)wrapped;
3424 PyObject *other;
3425
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003426 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003427 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003428 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003429 return (*func)(self, other);
3430}
3431
3432static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003433wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3434{
3435 binaryfunc func = (binaryfunc)wrapped;
3436 PyObject *other;
3437
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003438 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003439 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003440 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003441 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003442 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003443 Py_INCREF(Py_NotImplemented);
3444 return Py_NotImplemented;
3445 }
3446 return (*func)(self, other);
3447}
3448
3449static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003450wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3451{
3452 binaryfunc func = (binaryfunc)wrapped;
3453 PyObject *other;
3454
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003455 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003456 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003457 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003458 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003459 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003460 Py_INCREF(Py_NotImplemented);
3461 return Py_NotImplemented;
3462 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003463 return (*func)(other, self);
3464}
3465
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003466static PyObject *
3467wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3468{
3469 coercion func = (coercion)wrapped;
3470 PyObject *other, *res;
3471 int ok;
3472
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003473 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003474 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003475 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003476 ok = func(&self, &other);
3477 if (ok < 0)
3478 return NULL;
3479 if (ok > 0) {
3480 Py_INCREF(Py_NotImplemented);
3481 return Py_NotImplemented;
3482 }
3483 res = PyTuple_New(2);
3484 if (res == NULL) {
3485 Py_DECREF(self);
3486 Py_DECREF(other);
3487 return NULL;
3488 }
3489 PyTuple_SET_ITEM(res, 0, self);
3490 PyTuple_SET_ITEM(res, 1, other);
3491 return res;
3492}
3493
Tim Peters6d6c1a32001-08-02 04:15:00 +00003494static PyObject *
3495wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3496{
3497 ternaryfunc func = (ternaryfunc)wrapped;
3498 PyObject *other;
3499 PyObject *third = Py_None;
3500
3501 /* Note: This wrapper only works for __pow__() */
3502
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003503 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003504 return NULL;
3505 return (*func)(self, other, third);
3506}
3507
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003508static PyObject *
3509wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3510{
3511 ternaryfunc func = (ternaryfunc)wrapped;
3512 PyObject *other;
3513 PyObject *third = Py_None;
3514
3515 /* Note: This wrapper only works for __pow__() */
3516
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003517 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003518 return NULL;
3519 return (*func)(other, self, third);
3520}
3521
Tim Peters6d6c1a32001-08-02 04:15:00 +00003522static PyObject *
3523wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3524{
3525 unaryfunc func = (unaryfunc)wrapped;
3526
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003527 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003528 return NULL;
3529 return (*func)(self);
3530}
3531
Tim Peters6d6c1a32001-08-02 04:15:00 +00003532static PyObject *
Armin Rigo314861c2006-03-30 14:04:02 +00003533wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003534{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003535 ssizeargfunc func = (ssizeargfunc)wrapped;
Armin Rigo314861c2006-03-30 14:04:02 +00003536 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003537 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003538
Armin Rigo314861c2006-03-30 14:04:02 +00003539 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
3540 return NULL;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00003541 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Armin Rigo314861c2006-03-30 14:04:02 +00003542 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003543 return NULL;
3544 return (*func)(self, i);
3545}
3546
Martin v. Löwis18e16552006-02-15 17:27:45 +00003547static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00003548getindex(PyObject *self, PyObject *arg)
3549{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003550 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003551
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00003552 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003553 if (i == -1 && PyErr_Occurred())
3554 return -1;
3555 if (i < 0) {
3556 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3557 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003558 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003559 if (n < 0)
3560 return -1;
3561 i += n;
3562 }
3563 }
3564 return i;
3565}
3566
3567static PyObject *
3568wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3569{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003570 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003571 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003572 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003573
Guido van Rossumf4593e02001-10-03 12:09:30 +00003574 if (PyTuple_GET_SIZE(args) == 1) {
3575 arg = PyTuple_GET_ITEM(args, 0);
3576 i = getindex(self, arg);
3577 if (i == -1 && PyErr_Occurred())
3578 return NULL;
3579 return (*func)(self, i);
3580 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003581 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003582 assert(PyErr_Occurred());
3583 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003584}
3585
Tim Peters6d6c1a32001-08-02 04:15:00 +00003586static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003587wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003588{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003589 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
3590 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003591
Martin v. Löwis18e16552006-02-15 17:27:45 +00003592 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003593 return NULL;
3594 return (*func)(self, i, j);
3595}
3596
Tim Peters6d6c1a32001-08-02 04:15:00 +00003597static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003598wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003599{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003600 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3601 Py_ssize_t i;
3602 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003603 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003604
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003605 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003606 return NULL;
3607 i = getindex(self, arg);
3608 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003609 return NULL;
3610 res = (*func)(self, i, value);
3611 if (res == -1 && PyErr_Occurred())
3612 return NULL;
3613 Py_INCREF(Py_None);
3614 return Py_None;
3615}
3616
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003617static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003618wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003619{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003620 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3621 Py_ssize_t i;
3622 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003623 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003624
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003625 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003626 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003627 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003628 i = getindex(self, arg);
3629 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003630 return NULL;
3631 res = (*func)(self, i, NULL);
3632 if (res == -1 && PyErr_Occurred())
3633 return NULL;
3634 Py_INCREF(Py_None);
3635 return Py_None;
3636}
3637
Tim Peters6d6c1a32001-08-02 04:15:00 +00003638static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003639wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003640{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003641 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3642 Py_ssize_t i, j;
3643 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003644 PyObject *value;
3645
Martin v. Löwis18e16552006-02-15 17:27:45 +00003646 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003647 return NULL;
3648 res = (*func)(self, i, j, value);
3649 if (res == -1 && PyErr_Occurred())
3650 return NULL;
3651 Py_INCREF(Py_None);
3652 return Py_None;
3653}
3654
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003655static PyObject *
3656wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3657{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003658 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3659 Py_ssize_t i, j;
3660 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003661
Martin v. Löwis18e16552006-02-15 17:27:45 +00003662 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003663 return NULL;
3664 res = (*func)(self, i, j, NULL);
3665 if (res == -1 && PyErr_Occurred())
3666 return NULL;
3667 Py_INCREF(Py_None);
3668 return Py_None;
3669}
3670
Tim Peters6d6c1a32001-08-02 04:15:00 +00003671/* XXX objobjproc is a misnomer; should be objargpred */
3672static PyObject *
3673wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3674{
3675 objobjproc func = (objobjproc)wrapped;
3676 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003677 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003678
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003679 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003680 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003681 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003682 res = (*func)(self, value);
3683 if (res == -1 && PyErr_Occurred())
3684 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003685 else
3686 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003687}
3688
Tim Peters6d6c1a32001-08-02 04:15:00 +00003689static PyObject *
3690wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3691{
3692 objobjargproc func = (objobjargproc)wrapped;
3693 int res;
3694 PyObject *key, *value;
3695
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003696 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003697 return NULL;
3698 res = (*func)(self, key, value);
3699 if (res == -1 && PyErr_Occurred())
3700 return NULL;
3701 Py_INCREF(Py_None);
3702 return Py_None;
3703}
3704
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003705static PyObject *
3706wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3707{
3708 objobjargproc func = (objobjargproc)wrapped;
3709 int res;
3710 PyObject *key;
3711
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003712 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003713 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003714 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003715 res = (*func)(self, key, NULL);
3716 if (res == -1 && PyErr_Occurred())
3717 return NULL;
3718 Py_INCREF(Py_None);
3719 return Py_None;
3720}
3721
Tim Peters6d6c1a32001-08-02 04:15:00 +00003722static PyObject *
3723wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3724{
3725 cmpfunc func = (cmpfunc)wrapped;
3726 int res;
3727 PyObject *other;
3728
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003729 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003730 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003731 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003732 if (other->ob_type->tp_compare != func &&
3733 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003734 PyErr_Format(
3735 PyExc_TypeError,
3736 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3737 self->ob_type->tp_name,
3738 self->ob_type->tp_name,
3739 other->ob_type->tp_name);
3740 return NULL;
3741 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003742 res = (*func)(self, other);
3743 if (PyErr_Occurred())
3744 return NULL;
3745 return PyInt_FromLong((long)res);
3746}
3747
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003748/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003749 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003750static int
3751hackcheck(PyObject *self, setattrofunc func, char *what)
3752{
3753 PyTypeObject *type = self->ob_type;
3754 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3755 type = type->tp_base;
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003756 /* If type is NULL now, this is a really weird type.
Andrew M. Kuchlingb3f37552006-10-09 18:05:19 +00003757 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003758 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003759 PyErr_Format(PyExc_TypeError,
3760 "can't apply this %s to %s object",
3761 what,
3762 type->tp_name);
3763 return 0;
3764 }
3765 return 1;
3766}
3767
Tim Peters6d6c1a32001-08-02 04:15:00 +00003768static PyObject *
3769wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3770{
3771 setattrofunc func = (setattrofunc)wrapped;
3772 int res;
3773 PyObject *name, *value;
3774
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003775 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003776 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003777 if (!hackcheck(self, func, "__setattr__"))
3778 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003779 res = (*func)(self, name, value);
3780 if (res < 0)
3781 return NULL;
3782 Py_INCREF(Py_None);
3783 return Py_None;
3784}
3785
3786static PyObject *
3787wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3788{
3789 setattrofunc func = (setattrofunc)wrapped;
3790 int res;
3791 PyObject *name;
3792
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003793 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003794 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003795 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003796 if (!hackcheck(self, func, "__delattr__"))
3797 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003798 res = (*func)(self, name, NULL);
3799 if (res < 0)
3800 return NULL;
3801 Py_INCREF(Py_None);
3802 return Py_None;
3803}
3804
Tim Peters6d6c1a32001-08-02 04:15:00 +00003805static PyObject *
3806wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3807{
3808 hashfunc func = (hashfunc)wrapped;
3809 long res;
3810
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003811 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003812 return NULL;
3813 res = (*func)(self);
3814 if (res == -1 && PyErr_Occurred())
3815 return NULL;
3816 return PyInt_FromLong(res);
3817}
3818
Tim Peters6d6c1a32001-08-02 04:15:00 +00003819static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003820wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003821{
3822 ternaryfunc func = (ternaryfunc)wrapped;
3823
Guido van Rossumc8e56452001-10-22 00:43:43 +00003824 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003825}
3826
Tim Peters6d6c1a32001-08-02 04:15:00 +00003827static PyObject *
3828wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3829{
3830 richcmpfunc func = (richcmpfunc)wrapped;
3831 PyObject *other;
3832
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003833 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003834 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003835 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003836 return (*func)(self, other, op);
3837}
3838
3839#undef RICHCMP_WRAPPER
3840#define RICHCMP_WRAPPER(NAME, OP) \
3841static PyObject * \
3842richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3843{ \
3844 return wrap_richcmpfunc(self, args, wrapped, OP); \
3845}
3846
Jack Jansen8e938b42001-08-08 15:29:49 +00003847RICHCMP_WRAPPER(lt, Py_LT)
3848RICHCMP_WRAPPER(le, Py_LE)
3849RICHCMP_WRAPPER(eq, Py_EQ)
3850RICHCMP_WRAPPER(ne, Py_NE)
3851RICHCMP_WRAPPER(gt, Py_GT)
3852RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003853
Tim Peters6d6c1a32001-08-02 04:15:00 +00003854static PyObject *
3855wrap_next(PyObject *self, PyObject *args, void *wrapped)
3856{
3857 unaryfunc func = (unaryfunc)wrapped;
3858 PyObject *res;
3859
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003860 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003861 return NULL;
3862 res = (*func)(self);
3863 if (res == NULL && !PyErr_Occurred())
3864 PyErr_SetNone(PyExc_StopIteration);
3865 return res;
3866}
3867
Tim Peters6d6c1a32001-08-02 04:15:00 +00003868static PyObject *
3869wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3870{
3871 descrgetfunc func = (descrgetfunc)wrapped;
3872 PyObject *obj;
3873 PyObject *type = NULL;
3874
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003875 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003876 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003877 if (obj == Py_None)
3878 obj = NULL;
3879 if (type == Py_None)
3880 type = NULL;
3881 if (type == NULL &&obj == NULL) {
3882 PyErr_SetString(PyExc_TypeError,
3883 "__get__(None, None) is invalid");
3884 return NULL;
3885 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003886 return (*func)(self, obj, type);
3887}
3888
Tim Peters6d6c1a32001-08-02 04:15:00 +00003889static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003890wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003891{
3892 descrsetfunc func = (descrsetfunc)wrapped;
3893 PyObject *obj, *value;
3894 int ret;
3895
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003896 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003897 return NULL;
3898 ret = (*func)(self, obj, value);
3899 if (ret < 0)
3900 return NULL;
3901 Py_INCREF(Py_None);
3902 return Py_None;
3903}
Guido van Rossum22b13872002-08-06 21:41:44 +00003904
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003905static PyObject *
3906wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3907{
3908 descrsetfunc func = (descrsetfunc)wrapped;
3909 PyObject *obj;
3910 int ret;
3911
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003912 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003913 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003914 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003915 ret = (*func)(self, obj, NULL);
3916 if (ret < 0)
3917 return NULL;
3918 Py_INCREF(Py_None);
3919 return Py_None;
3920}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003921
Tim Peters6d6c1a32001-08-02 04:15:00 +00003922static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003923wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003924{
3925 initproc func = (initproc)wrapped;
3926
Guido van Rossumc8e56452001-10-22 00:43:43 +00003927 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003928 return NULL;
3929 Py_INCREF(Py_None);
3930 return Py_None;
3931}
3932
Tim Peters6d6c1a32001-08-02 04:15:00 +00003933static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003934tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003935{
Barry Warsaw60f01882001-08-22 19:24:42 +00003936 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003937 PyObject *arg0, *res;
3938
3939 if (self == NULL || !PyType_Check(self))
3940 Py_FatalError("__new__() called with non-type 'self'");
3941 type = (PyTypeObject *)self;
3942 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003943 PyErr_Format(PyExc_TypeError,
3944 "%s.__new__(): not enough arguments",
3945 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003946 return NULL;
3947 }
3948 arg0 = PyTuple_GET_ITEM(args, 0);
3949 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003950 PyErr_Format(PyExc_TypeError,
3951 "%s.__new__(X): X is not a type object (%s)",
3952 type->tp_name,
3953 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003954 return NULL;
3955 }
3956 subtype = (PyTypeObject *)arg0;
3957 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003958 PyErr_Format(PyExc_TypeError,
3959 "%s.__new__(%s): %s is not a subtype of %s",
3960 type->tp_name,
3961 subtype->tp_name,
3962 subtype->tp_name,
3963 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003964 return NULL;
3965 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003966
3967 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003968 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003969 most derived base that's not a heap type is this type. */
3970 staticbase = subtype;
3971 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3972 staticbase = staticbase->tp_base;
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003973 /* If staticbase is NULL now, it is a really weird type.
Andrew M. Kuchlingb3f37552006-10-09 18:05:19 +00003974 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003975 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003976 PyErr_Format(PyExc_TypeError,
3977 "%s.__new__(%s) is not safe, use %s.__new__()",
3978 type->tp_name,
3979 subtype->tp_name,
3980 staticbase == NULL ? "?" : staticbase->tp_name);
3981 return NULL;
3982 }
3983
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003984 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3985 if (args == NULL)
3986 return NULL;
3987 res = type->tp_new(subtype, args, kwds);
3988 Py_DECREF(args);
3989 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003990}
3991
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003992static struct PyMethodDef tp_new_methoddef[] = {
3993 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003994 PyDoc_STR("T.__new__(S, ...) -> "
3995 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003996 {0}
3997};
3998
3999static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004000add_tp_new_wrapper(PyTypeObject *type)
4001{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004002 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004003
Guido van Rossum687ae002001-10-15 22:03:32 +00004004 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004005 return 0;
4006 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004007 if (func == NULL)
4008 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004009 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004010 Py_DECREF(func);
4011 return -1;
4012 }
4013 Py_DECREF(func);
4014 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004015}
4016
Guido van Rossumf040ede2001-08-07 16:40:56 +00004017/* Slot wrappers that call the corresponding __foo__ slot. See comments
4018 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004019
Guido van Rossumdc91b992001-08-08 22:26:22 +00004020#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004021static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004022FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004023{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004024 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004025 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004026}
4027
Guido van Rossumdc91b992001-08-08 22:26:22 +00004028#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004029static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004030FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004031{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004032 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004033 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004034}
4035
Guido van Rossumcd118802003-01-06 22:57:47 +00004036/* Boolean helper for SLOT1BINFULL().
4037 right.__class__ is a nontrivial subclass of left.__class__. */
4038static int
4039method_is_overloaded(PyObject *left, PyObject *right, char *name)
4040{
4041 PyObject *a, *b;
4042 int ok;
4043
4044 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
4045 if (b == NULL) {
4046 PyErr_Clear();
4047 /* If right doesn't have it, it's not overloaded */
4048 return 0;
4049 }
4050
4051 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
4052 if (a == NULL) {
4053 PyErr_Clear();
4054 Py_DECREF(b);
4055 /* If right has it but left doesn't, it's overloaded */
4056 return 1;
4057 }
4058
4059 ok = PyObject_RichCompareBool(a, b, Py_NE);
4060 Py_DECREF(a);
4061 Py_DECREF(b);
4062 if (ok < 0) {
4063 PyErr_Clear();
4064 return 0;
4065 }
4066
4067 return ok;
4068}
4069
Guido van Rossumdc91b992001-08-08 22:26:22 +00004070
4071#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004072static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004073FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004074{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004075 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004076 int do_other = self->ob_type != other->ob_type && \
4077 other->ob_type->tp_as_number != NULL && \
4078 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004079 if (self->ob_type->tp_as_number != NULL && \
4080 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
4081 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004082 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004083 PyType_IsSubtype(other->ob_type, self->ob_type) && \
4084 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004085 r = call_maybe( \
4086 other, ROPSTR, &rcache_str, "(O)", self); \
4087 if (r != Py_NotImplemented) \
4088 return r; \
4089 Py_DECREF(r); \
4090 do_other = 0; \
4091 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004092 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004093 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004094 if (r != Py_NotImplemented || \
4095 other->ob_type == self->ob_type) \
4096 return r; \
4097 Py_DECREF(r); \
4098 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004099 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004100 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004101 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004102 } \
4103 Py_INCREF(Py_NotImplemented); \
4104 return Py_NotImplemented; \
4105}
4106
4107#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4108 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4109
4110#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4111static PyObject * \
4112FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4113{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004114 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004115 return call_method(self, OPSTR, &cache_str, \
4116 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004117}
4118
Martin v. Löwis18e16552006-02-15 17:27:45 +00004119static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004120slot_sq_length(PyObject *self)
4121{
Guido van Rossum2730b132001-08-28 18:22:14 +00004122 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004123 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004124 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004125
4126 if (res == NULL)
4127 return -1;
Neal Norwitz1872b1c2006-08-12 18:44:06 +00004128 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004129 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004130 if (len < 0) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00004131 if (!PyErr_Occurred())
4132 PyErr_SetString(PyExc_ValueError,
4133 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004134 return -1;
4135 }
Guido van Rossum26111622001-10-01 16:42:49 +00004136 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004137}
4138
Guido van Rossumf4593e02001-10-03 12:09:30 +00004139/* Super-optimized version of slot_sq_item.
4140 Other slots could do the same... */
4141static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004142slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004143{
4144 static PyObject *getitem_str;
4145 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4146 descrgetfunc f;
4147
4148 if (getitem_str == NULL) {
4149 getitem_str = PyString_InternFromString("__getitem__");
4150 if (getitem_str == NULL)
4151 return NULL;
4152 }
4153 func = _PyType_Lookup(self->ob_type, getitem_str);
4154 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004155 if ((f = func->ob_type->tp_descr_get) == NULL)
4156 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004157 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004158 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004159 if (func == NULL) {
4160 return NULL;
4161 }
4162 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004163 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004164 if (ival != NULL) {
4165 args = PyTuple_New(1);
4166 if (args != NULL) {
4167 PyTuple_SET_ITEM(args, 0, ival);
4168 retval = PyObject_Call(func, args, NULL);
4169 Py_XDECREF(args);
4170 Py_XDECREF(func);
4171 return retval;
4172 }
4173 }
4174 }
4175 else {
4176 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4177 }
4178 Py_XDECREF(args);
4179 Py_XDECREF(ival);
4180 Py_XDECREF(func);
4181 return NULL;
4182}
4183
Martin v. Löwis18e16552006-02-15 17:27:45 +00004184SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004185
4186static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004187slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004188{
4189 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004190 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004191
4192 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004193 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004194 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004195 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004196 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004197 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004198 if (res == NULL)
4199 return -1;
4200 Py_DECREF(res);
4201 return 0;
4202}
4203
4204static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004205slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004206{
4207 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004208 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004209
4210 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004211 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004212 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004213 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004214 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004215 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004216 if (res == NULL)
4217 return -1;
4218 Py_DECREF(res);
4219 return 0;
4220}
4221
4222static int
4223slot_sq_contains(PyObject *self, PyObject *value)
4224{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004225 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004226 int result = -1;
4227
Guido van Rossum60718732001-08-28 17:47:51 +00004228 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004229
Guido van Rossum55f20992001-10-01 17:18:22 +00004230 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004231 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004232 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004233 if (args == NULL)
4234 res = NULL;
4235 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004236 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004237 Py_DECREF(args);
4238 }
4239 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004240 if (res != NULL) {
4241 result = PyObject_IsTrue(res);
4242 Py_DECREF(res);
4243 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004244 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004245 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004246 /* Possible results: -1 and 1 */
4247 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004248 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004249 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004250 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004251}
4252
Tim Peters6d6c1a32001-08-02 04:15:00 +00004253#define slot_mp_length slot_sq_length
4254
Guido van Rossumdc91b992001-08-08 22:26:22 +00004255SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004256
4257static int
4258slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4259{
4260 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004261 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004262
4263 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004264 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004265 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004266 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004267 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004268 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004269 if (res == NULL)
4270 return -1;
4271 Py_DECREF(res);
4272 return 0;
4273}
4274
Guido van Rossumdc91b992001-08-08 22:26:22 +00004275SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4276SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4277SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4278SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4279SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4280SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4281
Jeremy Hylton938ace62002-07-17 16:30:39 +00004282static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004283
4284SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4285 nb_power, "__pow__", "__rpow__")
4286
4287static PyObject *
4288slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4289{
Guido van Rossum2730b132001-08-28 18:22:14 +00004290 static PyObject *pow_str;
4291
Guido van Rossumdc91b992001-08-08 22:26:22 +00004292 if (modulus == Py_None)
4293 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004294 /* Three-arg power doesn't use __rpow__. But ternary_op
4295 can call this when the second argument's type uses
4296 slot_nb_power, so check before calling self.__pow__. */
4297 if (self->ob_type->tp_as_number != NULL &&
4298 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4299 return call_method(self, "__pow__", &pow_str,
4300 "(OO)", other, modulus);
4301 }
4302 Py_INCREF(Py_NotImplemented);
4303 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004304}
4305
4306SLOT0(slot_nb_negative, "__neg__")
4307SLOT0(slot_nb_positive, "__pos__")
4308SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004309
4310static int
4311slot_nb_nonzero(PyObject *self)
4312{
Tim Petersea7f75d2002-12-07 21:39:16 +00004313 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004314 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004315 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004316
Guido van Rossum55f20992001-10-01 17:18:22 +00004317 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004318 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004319 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004320 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004321 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004322 if (func == NULL)
4323 return PyErr_Occurred() ? -1 : 1;
4324 }
4325 args = PyTuple_New(0);
4326 if (args != NULL) {
4327 PyObject *temp = PyObject_Call(func, args, NULL);
4328 Py_DECREF(args);
4329 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004330 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004331 result = PyObject_IsTrue(temp);
4332 else {
4333 PyErr_Format(PyExc_TypeError,
4334 "__nonzero__ should return "
4335 "bool or int, returned %s",
4336 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004337 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004338 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004339 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004340 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004341 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004342 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004343 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004344}
4345
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004346
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004347static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004348slot_nb_index(PyObject *self)
4349{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004350 static PyObject *index_str;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004351 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004352}
4353
4354
Guido van Rossumdc91b992001-08-08 22:26:22 +00004355SLOT0(slot_nb_invert, "__invert__")
4356SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4357SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4358SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4359SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4360SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004361
4362static int
4363slot_nb_coerce(PyObject **a, PyObject **b)
4364{
4365 static PyObject *coerce_str;
4366 PyObject *self = *a, *other = *b;
4367
4368 if (self->ob_type->tp_as_number != NULL &&
4369 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4370 PyObject *r;
4371 r = call_maybe(
4372 self, "__coerce__", &coerce_str, "(O)", other);
4373 if (r == NULL)
4374 return -1;
4375 if (r == Py_NotImplemented) {
4376 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004377 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004378 else {
4379 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4380 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004381 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004382 Py_DECREF(r);
4383 return -1;
4384 }
4385 *a = PyTuple_GET_ITEM(r, 0);
4386 Py_INCREF(*a);
4387 *b = PyTuple_GET_ITEM(r, 1);
4388 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004389 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004390 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004391 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004392 }
4393 if (other->ob_type->tp_as_number != NULL &&
4394 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4395 PyObject *r;
4396 r = call_maybe(
4397 other, "__coerce__", &coerce_str, "(O)", self);
4398 if (r == NULL)
4399 return -1;
4400 if (r == Py_NotImplemented) {
4401 Py_DECREF(r);
4402 return 1;
4403 }
4404 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4405 PyErr_SetString(PyExc_TypeError,
4406 "__coerce__ didn't return a 2-tuple");
4407 Py_DECREF(r);
4408 return -1;
4409 }
4410 *a = PyTuple_GET_ITEM(r, 1);
4411 Py_INCREF(*a);
4412 *b = PyTuple_GET_ITEM(r, 0);
4413 Py_INCREF(*b);
4414 Py_DECREF(r);
4415 return 0;
4416 }
4417 return 1;
4418}
4419
Guido van Rossumdc91b992001-08-08 22:26:22 +00004420SLOT0(slot_nb_int, "__int__")
4421SLOT0(slot_nb_long, "__long__")
4422SLOT0(slot_nb_float, "__float__")
4423SLOT0(slot_nb_oct, "__oct__")
4424SLOT0(slot_nb_hex, "__hex__")
4425SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4426SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4427SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4428SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4429SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004430SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004431SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4432SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4433SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4434SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4435SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4436SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4437 "__floordiv__", "__rfloordiv__")
4438SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4439SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4440SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004441
4442static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004443half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004444{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004445 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004446 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004447 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004448
Guido van Rossum60718732001-08-28 17:47:51 +00004449 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004450 if (func == NULL) {
4451 PyErr_Clear();
4452 }
4453 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004454 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004455 if (args == NULL)
4456 res = NULL;
4457 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004458 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004459 Py_DECREF(args);
4460 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004461 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004462 if (res != Py_NotImplemented) {
4463 if (res == NULL)
4464 return -2;
4465 c = PyInt_AsLong(res);
4466 Py_DECREF(res);
4467 if (c == -1 && PyErr_Occurred())
4468 return -2;
4469 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4470 }
4471 Py_DECREF(res);
4472 }
4473 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004474}
4475
Guido van Rossumab3b0342001-09-18 20:38:53 +00004476/* This slot is published for the benefit of try_3way_compare in object.c */
4477int
4478_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004479{
4480 int c;
4481
Guido van Rossumab3b0342001-09-18 20:38:53 +00004482 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004483 c = half_compare(self, other);
4484 if (c <= 1)
4485 return c;
4486 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004487 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004488 c = half_compare(other, self);
4489 if (c < -1)
4490 return -2;
4491 if (c <= 1)
4492 return -c;
4493 }
4494 return (void *)self < (void *)other ? -1 :
4495 (void *)self > (void *)other ? 1 : 0;
4496}
4497
4498static PyObject *
4499slot_tp_repr(PyObject *self)
4500{
4501 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004502 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004503
Guido van Rossum60718732001-08-28 17:47:51 +00004504 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004505 if (func != NULL) {
4506 res = PyEval_CallObject(func, NULL);
4507 Py_DECREF(func);
4508 return res;
4509 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004510 PyErr_Clear();
4511 return PyString_FromFormat("<%s object at %p>",
4512 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004513}
4514
4515static PyObject *
4516slot_tp_str(PyObject *self)
4517{
4518 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004519 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004520
Guido van Rossum60718732001-08-28 17:47:51 +00004521 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004522 if (func != NULL) {
4523 res = PyEval_CallObject(func, NULL);
4524 Py_DECREF(func);
4525 return res;
4526 }
4527 else {
4528 PyErr_Clear();
4529 return slot_tp_repr(self);
4530 }
4531}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004532
4533static long
4534slot_tp_hash(PyObject *self)
4535{
Tim Peters61ce0a92002-12-06 23:38:02 +00004536 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004537 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004538 long h;
4539
Guido van Rossum60718732001-08-28 17:47:51 +00004540 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004541
4542 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004543 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004544 Py_DECREF(func);
4545 if (res == NULL)
4546 return -1;
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00004547 if (PyLong_Check(res))
Armin Rigo51fc8c42006-08-09 14:55:26 +00004548 h = PyLong_Type.tp_hash(res);
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00004549 else
4550 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004551 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004552 }
4553 else {
4554 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004555 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004556 if (func == NULL) {
4557 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004558 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004559 }
4560 if (func != NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00004561 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
4562 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004563 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004564 return -1;
4565 }
4566 PyErr_Clear();
4567 h = _Py_HashPointer((void *)self);
4568 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004569 if (h == -1 && !PyErr_Occurred())
4570 h = -2;
4571 return h;
4572}
4573
4574static PyObject *
4575slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4576{
Guido van Rossum60718732001-08-28 17:47:51 +00004577 static PyObject *call_str;
4578 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004579 PyObject *res;
4580
4581 if (meth == NULL)
4582 return NULL;
Armin Rigo53c1692f2006-06-21 21:58:50 +00004583
4584 /* PyObject_Call() will end up calling slot_tp_call() again if
4585 the object returned for __call__ has __call__ itself defined
4586 upon it. This can be an infinite recursion if you set
4587 __call__ in a class to an instance of it. */
Neal Norwitzb1149842006-06-23 03:32:44 +00004588 if (Py_EnterRecursiveCall(" in __call__")) {
4589 Py_DECREF(meth);
Armin Rigo53c1692f2006-06-21 21:58:50 +00004590 return NULL;
Neal Norwitzb1149842006-06-23 03:32:44 +00004591 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004592 res = PyObject_Call(meth, args, kwds);
Armin Rigo53c1692f2006-06-21 21:58:50 +00004593 Py_LeaveRecursiveCall();
4594
Tim Peters6d6c1a32001-08-02 04:15:00 +00004595 Py_DECREF(meth);
4596 return res;
4597}
4598
Guido van Rossum14a6f832001-10-17 13:59:09 +00004599/* There are two slot dispatch functions for tp_getattro.
4600
4601 - slot_tp_getattro() is used when __getattribute__ is overridden
4602 but no __getattr__ hook is present;
4603
4604 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4605
Guido van Rossumc334df52002-04-04 23:44:47 +00004606 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4607 detects the absence of __getattr__ and then installs the simpler slot if
4608 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004609
Tim Peters6d6c1a32001-08-02 04:15:00 +00004610static PyObject *
4611slot_tp_getattro(PyObject *self, PyObject *name)
4612{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004613 static PyObject *getattribute_str = NULL;
4614 return call_method(self, "__getattribute__", &getattribute_str,
4615 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004616}
4617
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004618static PyObject *
4619slot_tp_getattr_hook(PyObject *self, PyObject *name)
4620{
4621 PyTypeObject *tp = self->ob_type;
4622 PyObject *getattr, *getattribute, *res;
4623 static PyObject *getattribute_str = NULL;
4624 static PyObject *getattr_str = NULL;
4625
4626 if (getattr_str == NULL) {
4627 getattr_str = PyString_InternFromString("__getattr__");
4628 if (getattr_str == NULL)
4629 return NULL;
4630 }
4631 if (getattribute_str == NULL) {
4632 getattribute_str =
4633 PyString_InternFromString("__getattribute__");
4634 if (getattribute_str == NULL)
4635 return NULL;
4636 }
4637 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004638 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004639 /* No __getattr__ hook: use a simpler dispatcher */
4640 tp->tp_getattro = slot_tp_getattro;
4641 return slot_tp_getattro(self, name);
4642 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004643 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004644 if (getattribute == NULL ||
4645 (getattribute->ob_type == &PyWrapperDescr_Type &&
4646 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4647 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004648 res = PyObject_GenericGetAttr(self, name);
4649 else
Georg Brandl684fd0c2006-05-25 19:15:31 +00004650 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004651 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004652 PyErr_Clear();
Georg Brandl684fd0c2006-05-25 19:15:31 +00004653 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004654 }
4655 return res;
4656}
4657
Tim Peters6d6c1a32001-08-02 04:15:00 +00004658static int
4659slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4660{
4661 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004662 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004663
4664 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004665 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004666 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004667 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004668 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004669 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004670 if (res == NULL)
4671 return -1;
4672 Py_DECREF(res);
4673 return 0;
4674}
4675
4676/* Map rich comparison operators to their __xx__ namesakes */
4677static char *name_op[] = {
4678 "__lt__",
4679 "__le__",
4680 "__eq__",
4681 "__ne__",
4682 "__gt__",
4683 "__ge__",
4684};
4685
4686static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004687half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004688{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004689 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004690 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004691
Guido van Rossum60718732001-08-28 17:47:51 +00004692 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004693 if (func == NULL) {
4694 PyErr_Clear();
4695 Py_INCREF(Py_NotImplemented);
4696 return Py_NotImplemented;
4697 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004698 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004699 if (args == NULL)
4700 res = NULL;
4701 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004702 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004703 Py_DECREF(args);
4704 }
4705 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004706 return res;
4707}
4708
Guido van Rossumb8f63662001-08-15 23:57:02 +00004709static PyObject *
4710slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4711{
4712 PyObject *res;
4713
4714 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4715 res = half_richcompare(self, other, op);
4716 if (res != Py_NotImplemented)
4717 return res;
4718 Py_DECREF(res);
4719 }
4720 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004721 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004722 if (res != Py_NotImplemented) {
4723 return res;
4724 }
4725 Py_DECREF(res);
4726 }
4727 Py_INCREF(Py_NotImplemented);
4728 return Py_NotImplemented;
4729}
4730
4731static PyObject *
4732slot_tp_iter(PyObject *self)
4733{
4734 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004735 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004736
Guido van Rossum60718732001-08-28 17:47:51 +00004737 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004738 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004739 PyObject *args;
4740 args = res = PyTuple_New(0);
4741 if (args != NULL) {
4742 res = PyObject_Call(func, args, NULL);
4743 Py_DECREF(args);
4744 }
4745 Py_DECREF(func);
4746 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004747 }
4748 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004749 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004750 if (func == NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00004751 PyErr_Format(PyExc_TypeError,
4752 "'%.200s' object is not iterable",
4753 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004754 return NULL;
4755 }
4756 Py_DECREF(func);
4757 return PySeqIter_New(self);
4758}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004759
4760static PyObject *
4761slot_tp_iternext(PyObject *self)
4762{
Guido van Rossum2730b132001-08-28 18:22:14 +00004763 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004764 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004765}
4766
Guido van Rossum1a493502001-08-17 16:47:50 +00004767static PyObject *
4768slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4769{
4770 PyTypeObject *tp = self->ob_type;
4771 PyObject *get;
4772 static PyObject *get_str = NULL;
4773
4774 if (get_str == NULL) {
4775 get_str = PyString_InternFromString("__get__");
4776 if (get_str == NULL)
4777 return NULL;
4778 }
4779 get = _PyType_Lookup(tp, get_str);
4780 if (get == NULL) {
4781 /* Avoid further slowdowns */
4782 if (tp->tp_descr_get == slot_tp_descr_get)
4783 tp->tp_descr_get = NULL;
4784 Py_INCREF(self);
4785 return self;
4786 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004787 if (obj == NULL)
4788 obj = Py_None;
4789 if (type == NULL)
4790 type = Py_None;
Georg Brandl684fd0c2006-05-25 19:15:31 +00004791 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00004792}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004793
4794static int
4795slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4796{
Guido van Rossum2c252392001-08-24 10:13:31 +00004797 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004798 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004799
4800 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004801 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004802 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004803 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004804 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004805 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004806 if (res == NULL)
4807 return -1;
4808 Py_DECREF(res);
4809 return 0;
4810}
4811
4812static int
4813slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4814{
Guido van Rossum60718732001-08-28 17:47:51 +00004815 static PyObject *init_str;
4816 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004817 PyObject *res;
4818
4819 if (meth == NULL)
4820 return -1;
4821 res = PyObject_Call(meth, args, kwds);
4822 Py_DECREF(meth);
4823 if (res == NULL)
4824 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004825 if (res != Py_None) {
Georg Brandlccff7852006-06-18 22:17:29 +00004826 PyErr_Format(PyExc_TypeError,
4827 "__init__() should return None, not '%.200s'",
4828 res->ob_type->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004829 Py_DECREF(res);
4830 return -1;
4831 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004832 Py_DECREF(res);
4833 return 0;
4834}
4835
4836static PyObject *
4837slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4838{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004839 static PyObject *new_str;
4840 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004841 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004842 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004843
Guido van Rossum7bed2132002-08-08 21:57:53 +00004844 if (new_str == NULL) {
4845 new_str = PyString_InternFromString("__new__");
4846 if (new_str == NULL)
4847 return NULL;
4848 }
4849 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004850 if (func == NULL)
4851 return NULL;
4852 assert(PyTuple_Check(args));
4853 n = PyTuple_GET_SIZE(args);
4854 newargs = PyTuple_New(n+1);
4855 if (newargs == NULL)
4856 return NULL;
4857 Py_INCREF(type);
4858 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4859 for (i = 0; i < n; i++) {
4860 x = PyTuple_GET_ITEM(args, i);
4861 Py_INCREF(x);
4862 PyTuple_SET_ITEM(newargs, i+1, x);
4863 }
4864 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004865 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004866 Py_DECREF(func);
4867 return x;
4868}
4869
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004870static void
4871slot_tp_del(PyObject *self)
4872{
4873 static PyObject *del_str = NULL;
4874 PyObject *del, *res;
4875 PyObject *error_type, *error_value, *error_traceback;
4876
4877 /* Temporarily resurrect the object. */
4878 assert(self->ob_refcnt == 0);
4879 self->ob_refcnt = 1;
4880
4881 /* Save the current exception, if any. */
4882 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4883
4884 /* Execute __del__ method, if any. */
4885 del = lookup_maybe(self, "__del__", &del_str);
4886 if (del != NULL) {
4887 res = PyEval_CallObject(del, NULL);
4888 if (res == NULL)
4889 PyErr_WriteUnraisable(del);
4890 else
4891 Py_DECREF(res);
4892 Py_DECREF(del);
4893 }
4894
4895 /* Restore the saved exception. */
4896 PyErr_Restore(error_type, error_value, error_traceback);
4897
4898 /* Undo the temporary resurrection; can't use DECREF here, it would
4899 * cause a recursive call.
4900 */
4901 assert(self->ob_refcnt > 0);
4902 if (--self->ob_refcnt == 0)
4903 return; /* this is the normal path out */
4904
4905 /* __del__ resurrected it! Make it look like the original Py_DECREF
4906 * never happened.
4907 */
4908 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004909 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004910 _Py_NewReference(self);
4911 self->ob_refcnt = refcnt;
4912 }
4913 assert(!PyType_IS_GC(self->ob_type) ||
4914 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00004915 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
4916 * we need to undo that. */
4917 _Py_DEC_REFTOTAL;
4918 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4919 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004920 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4921 * _Py_NewReference bumped tp_allocs: both of those need to be
4922 * undone.
4923 */
4924#ifdef COUNT_ALLOCS
4925 --self->ob_type->tp_frees;
4926 --self->ob_type->tp_allocs;
4927#endif
4928}
4929
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004930
4931/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004932 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004933 structure, which incorporates the additional structures used for numbers,
4934 sequences and mappings.
4935 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004936 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004937 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4938 terminated with an all-zero entry. (This table is further initialized and
4939 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004940
Guido van Rossum6d204072001-10-21 00:44:31 +00004941typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004942
4943#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004944#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004945#undef ETSLOT
4946#undef SQSLOT
4947#undef MPSLOT
4948#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004949#undef UNSLOT
4950#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004951#undef BINSLOT
4952#undef RBINSLOT
4953
Guido van Rossum6d204072001-10-21 00:44:31 +00004954#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004955 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4956 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004957#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4958 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004959 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004960#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004961 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004962 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004963#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4964 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4965#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4966 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4967#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4968 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4969#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4970 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4971 "x." NAME "() <==> " DOC)
4972#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4973 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4974 "x." NAME "(y) <==> x" DOC "y")
4975#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4976 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4977 "x." NAME "(y) <==> x" DOC "y")
4978#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4979 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4980 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00004981#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
4982 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4983 "x." NAME "(y) <==> " DOC)
4984#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
4985 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4986 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004987
4988static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00004989 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00004990 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00004991 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
4992 The logic in abstract.c always falls back to nb_add/nb_multiply in
4993 this case. Defining both the nb_* and the sq_* slots to call the
4994 user-defined methods has unexpected side-effects, as shown by
4995 test_descr.notimplemented() */
4996 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
4997 "x.__add__(y) <==> x+y"),
Armin Rigo314861c2006-03-30 14:04:02 +00004998 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Armin Rigofd163f92005-12-29 15:59:19 +00004999 "x.__mul__(n) <==> x*n"),
Armin Rigo314861c2006-03-30 14:04:02 +00005000 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Armin Rigofd163f92005-12-29 15:59:19 +00005001 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005002 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5003 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005004 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005005 "x.__getslice__(i, j) <==> x[i:j]\n\
5006 \n\
5007 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005008 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005009 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005010 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005011 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005012 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005013 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005014 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
5015 \n\
5016 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005017 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005018 "x.__delslice__(i, j) <==> del x[i:j]\n\
5019 \n\
5020 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005021 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5022 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005023 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5024 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5025 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Armin Rigo314861c2006-03-30 14:04:02 +00005026 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005027
Martin v. Löwis18e16552006-02-15 17:27:45 +00005028 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005029 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005030 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005031 wrap_binaryfunc,
5032 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005033 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005034 wrap_objobjargproc,
5035 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005036 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005037 wrap_delitem,
5038 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005039
Guido van Rossum6d204072001-10-21 00:44:31 +00005040 BINSLOT("__add__", nb_add, slot_nb_add,
5041 "+"),
5042 RBINSLOT("__radd__", nb_add, slot_nb_add,
5043 "+"),
5044 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5045 "-"),
5046 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5047 "-"),
5048 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5049 "*"),
5050 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5051 "*"),
5052 BINSLOT("__div__", nb_divide, slot_nb_divide,
5053 "/"),
5054 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5055 "/"),
5056 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5057 "%"),
5058 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5059 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005060 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005061 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005062 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005063 "divmod(y, x)"),
5064 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5065 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5066 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5067 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5068 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5069 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5070 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5071 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005072 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005073 "x != 0"),
5074 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5075 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5076 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5077 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5078 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5079 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5080 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5081 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5082 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5083 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5084 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5085 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5086 "x.__coerce__(y) <==> coerce(x, y)"),
5087 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5088 "int(x)"),
5089 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5090 "long(x)"),
5091 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5092 "float(x)"),
5093 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5094 "oct(x)"),
5095 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5096 "hex(x)"),
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005097 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005098 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005099 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5100 wrap_binaryfunc, "+"),
5101 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5102 wrap_binaryfunc, "-"),
5103 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5104 wrap_binaryfunc, "*"),
5105 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5106 wrap_binaryfunc, "/"),
5107 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5108 wrap_binaryfunc, "%"),
5109 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005110 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005111 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5112 wrap_binaryfunc, "<<"),
5113 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5114 wrap_binaryfunc, ">>"),
5115 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5116 wrap_binaryfunc, "&"),
5117 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5118 wrap_binaryfunc, "^"),
5119 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5120 wrap_binaryfunc, "|"),
5121 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5122 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5123 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5124 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5125 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5126 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5127 IBSLOT("__itruediv__", nb_inplace_true_divide,
5128 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005129
Guido van Rossum6d204072001-10-21 00:44:31 +00005130 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5131 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005132 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005133 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5134 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005135 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005136 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5137 "x.__cmp__(y) <==> cmp(x,y)"),
5138 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5139 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005140 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5141 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005142 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005143 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5144 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5145 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5146 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5147 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5148 "x.__setattr__('name', value) <==> x.name = value"),
5149 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5150 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5151 "x.__delattr__('name') <==> del x.name"),
5152 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5153 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5154 "x.__lt__(y) <==> x<y"),
5155 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5156 "x.__le__(y) <==> x<=y"),
5157 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5158 "x.__eq__(y) <==> x==y"),
5159 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5160 "x.__ne__(y) <==> x!=y"),
5161 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5162 "x.__gt__(y) <==> x>y"),
5163 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5164 "x.__ge__(y) <==> x>=y"),
5165 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5166 "x.__iter__() <==> iter(x)"),
5167 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5168 "x.next() -> the next value, or raise StopIteration"),
5169 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5170 "descr.__get__(obj[, type]) -> value"),
5171 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5172 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005173 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5174 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005175 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005176 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005177 "see x.__class__.__doc__ for signature",
5178 PyWrapperFlag_KEYWORDS),
5179 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005180 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005181 {NULL}
5182};
5183
Guido van Rossumc334df52002-04-04 23:44:47 +00005184/* Given a type pointer and an offset gotten from a slotdef entry, return a
5185 pointer to the actual slot. This is not quite the same as simply adding
5186 the offset to the type pointer, since it takes care to indirect through the
5187 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5188 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005189static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005190slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005191{
5192 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005193 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005194
Guido van Rossume5c691a2003-03-07 15:13:17 +00005195 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005196 assert(offset >= 0);
Skip Montanaro429433b2006-04-18 00:35:43 +00005197 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5198 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005199 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005200 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005201 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005202 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005203 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005204 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005205 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005206 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005207 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005208 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005209 }
5210 else {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005211 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005212 }
5213 if (ptr != NULL)
5214 ptr += offset;
5215 return (void **)ptr;
5216}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005217
Guido van Rossumc334df52002-04-04 23:44:47 +00005218/* Length of array of slotdef pointers used to store slots with the
5219 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5220 the same __name__, for any __name__. Since that's a static property, it is
5221 appropriate to declare fixed-size arrays for this. */
5222#define MAX_EQUIV 10
5223
5224/* Return a slot pointer for a given name, but ONLY if the attribute has
5225 exactly one slot function. The name must be an interned string. */
5226static void **
5227resolve_slotdups(PyTypeObject *type, PyObject *name)
5228{
5229 /* XXX Maybe this could be optimized more -- but is it worth it? */
5230
5231 /* pname and ptrs act as a little cache */
5232 static PyObject *pname;
5233 static slotdef *ptrs[MAX_EQUIV];
5234 slotdef *p, **pp;
5235 void **res, **ptr;
5236
5237 if (pname != name) {
5238 /* Collect all slotdefs that match name into ptrs. */
5239 pname = name;
5240 pp = ptrs;
5241 for (p = slotdefs; p->name_strobj; p++) {
5242 if (p->name_strobj == name)
5243 *pp++ = p;
5244 }
5245 *pp = NULL;
5246 }
5247
5248 /* Look in all matching slots of the type; if exactly one of these has
5249 a filled-in slot, return its value. Otherwise return NULL. */
5250 res = NULL;
5251 for (pp = ptrs; *pp; pp++) {
5252 ptr = slotptr(type, (*pp)->offset);
5253 if (ptr == NULL || *ptr == NULL)
5254 continue;
5255 if (res != NULL)
5256 return NULL;
5257 res = ptr;
5258 }
5259 return res;
5260}
5261
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005262/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005263 does some incredibly complex thinking and then sticks something into the
5264 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5265 interests, and then stores a generic wrapper or a specific function into
5266 the slot.) Return a pointer to the next slotdef with a different offset,
5267 because that's convenient for fixup_slot_dispatchers(). */
5268static slotdef *
5269update_one_slot(PyTypeObject *type, slotdef *p)
5270{
5271 PyObject *descr;
5272 PyWrapperDescrObject *d;
5273 void *generic = NULL, *specific = NULL;
5274 int use_generic = 0;
5275 int offset = p->offset;
5276 void **ptr = slotptr(type, offset);
5277
5278 if (ptr == NULL) {
5279 do {
5280 ++p;
5281 } while (p->offset == offset);
5282 return p;
5283 }
5284 do {
5285 descr = _PyType_Lookup(type, p->name_strobj);
5286 if (descr == NULL)
5287 continue;
5288 if (descr->ob_type == &PyWrapperDescr_Type) {
5289 void **tptr = resolve_slotdups(type, p->name_strobj);
5290 if (tptr == NULL || tptr == ptr)
5291 generic = p->function;
5292 d = (PyWrapperDescrObject *)descr;
5293 if (d->d_base->wrapper == p->wrapper &&
5294 PyType_IsSubtype(type, d->d_type))
5295 {
5296 if (specific == NULL ||
5297 specific == d->d_wrapped)
5298 specific = d->d_wrapped;
5299 else
5300 use_generic = 1;
5301 }
5302 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005303 else if (descr->ob_type == &PyCFunction_Type &&
5304 PyCFunction_GET_FUNCTION(descr) ==
5305 (PyCFunction)tp_new_wrapper &&
5306 strcmp(p->name, "__new__") == 0)
5307 {
5308 /* The __new__ wrapper is not a wrapper descriptor,
5309 so must be special-cased differently.
5310 If we don't do this, creating an instance will
5311 always use slot_tp_new which will look up
5312 __new__ in the MRO which will call tp_new_wrapper
5313 which will look through the base classes looking
5314 for a static base and call its tp_new (usually
5315 PyType_GenericNew), after performing various
5316 sanity checks and constructing a new argument
5317 list. Cut all that nonsense short -- this speeds
5318 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005319 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005320 /* XXX I'm not 100% sure that there isn't a hole
5321 in this reasoning that requires additional
5322 sanity checks. I'll buy the first person to
5323 point out a bug in this reasoning a beer. */
5324 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005325 else {
5326 use_generic = 1;
5327 generic = p->function;
5328 }
5329 } while ((++p)->offset == offset);
5330 if (specific && !use_generic)
5331 *ptr = specific;
5332 else
5333 *ptr = generic;
5334 return p;
5335}
5336
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005337/* In the type, update the slots whose slotdefs are gathered in the pp array.
5338 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005339static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005340update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005341{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005342 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005343
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005344 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005345 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005346 return 0;
5347}
5348
Guido van Rossumc334df52002-04-04 23:44:47 +00005349/* Comparison function for qsort() to compare slotdefs by their offset, and
5350 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005351static int
5352slotdef_cmp(const void *aa, const void *bb)
5353{
5354 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5355 int c = a->offset - b->offset;
5356 if (c != 0)
5357 return c;
5358 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005359 /* Cannot use a-b, as this gives off_t,
5360 which may lose precision when converted to int. */
5361 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005362}
5363
Guido van Rossumc334df52002-04-04 23:44:47 +00005364/* Initialize the slotdefs table by adding interned string objects for the
5365 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005366static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005367init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005368{
5369 slotdef *p;
5370 static int initialized = 0;
5371
5372 if (initialized)
5373 return;
5374 for (p = slotdefs; p->name; p++) {
5375 p->name_strobj = PyString_InternFromString(p->name);
5376 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005377 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005378 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005379 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5380 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005381 initialized = 1;
5382}
5383
Guido van Rossumc334df52002-04-04 23:44:47 +00005384/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005385static int
5386update_slot(PyTypeObject *type, PyObject *name)
5387{
Guido van Rossumc334df52002-04-04 23:44:47 +00005388 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005389 slotdef *p;
5390 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005391 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005392
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005393 init_slotdefs();
5394 pp = ptrs;
5395 for (p = slotdefs; p->name; p++) {
5396 /* XXX assume name is interned! */
5397 if (p->name_strobj == name)
5398 *pp++ = p;
5399 }
5400 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005401 for (pp = ptrs; *pp; pp++) {
5402 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005403 offset = p->offset;
5404 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005405 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005406 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005407 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005408 if (ptrs[0] == NULL)
5409 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005410 return update_subclasses(type, name,
5411 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005412}
5413
Guido van Rossumc334df52002-04-04 23:44:47 +00005414/* Store the proper functions in the slot dispatches at class (type)
5415 definition time, based upon which operations the class overrides in its
5416 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005417static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005418fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005419{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005420 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005421
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005422 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005423 for (p = slotdefs; p->name; )
5424 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005425}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005426
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005427static void
5428update_all_slots(PyTypeObject* type)
5429{
5430 slotdef *p;
5431
5432 init_slotdefs();
5433 for (p = slotdefs; p->name; p++) {
5434 /* update_slot returns int but can't actually fail */
5435 update_slot(type, p->name_strobj);
5436 }
5437}
5438
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005439/* recurse_down_subclasses() and update_subclasses() are mutually
5440 recursive functions to call a callback for all subclasses,
5441 but refraining from recursing into subclasses that define 'name'. */
5442
5443static int
5444update_subclasses(PyTypeObject *type, PyObject *name,
5445 update_callback callback, void *data)
5446{
5447 if (callback(type, data) < 0)
5448 return -1;
5449 return recurse_down_subclasses(type, name, callback, data);
5450}
5451
5452static int
5453recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5454 update_callback callback, void *data)
5455{
5456 PyTypeObject *subclass;
5457 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005458 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005459
5460 subclasses = type->tp_subclasses;
5461 if (subclasses == NULL)
5462 return 0;
5463 assert(PyList_Check(subclasses));
5464 n = PyList_GET_SIZE(subclasses);
5465 for (i = 0; i < n; i++) {
5466 ref = PyList_GET_ITEM(subclasses, i);
5467 assert(PyWeakref_CheckRef(ref));
5468 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5469 assert(subclass != NULL);
5470 if ((PyObject *)subclass == Py_None)
5471 continue;
5472 assert(PyType_Check(subclass));
5473 /* Avoid recursing down into unaffected classes */
5474 dict = subclass->tp_dict;
5475 if (dict != NULL && PyDict_Check(dict) &&
5476 PyDict_GetItem(dict, name) != NULL)
5477 continue;
5478 if (update_subclasses(subclass, name, callback, data) < 0)
5479 return -1;
5480 }
5481 return 0;
5482}
5483
Guido van Rossum6d204072001-10-21 00:44:31 +00005484/* This function is called by PyType_Ready() to populate the type's
5485 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005486 function slot (like tp_repr) that's defined in the type, one or more
5487 corresponding descriptors are added in the type's tp_dict dictionary
5488 under the appropriate name (like __repr__). Some function slots
5489 cause more than one descriptor to be added (for example, the nb_add
5490 slot adds both __add__ and __radd__ descriptors) and some function
5491 slots compete for the same descriptor (for example both sq_item and
5492 mp_subscript generate a __getitem__ descriptor).
5493
5494 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005495 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005496 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005497 between competing slots: the members of PyHeapTypeObject are listed
5498 from most general to least general, so the most general slot is
5499 preferred. In particular, because as_mapping comes before as_sequence,
5500 for a type that defines both mp_subscript and sq_item, mp_subscript
5501 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005502
5503 This only adds new descriptors and doesn't overwrite entries in
5504 tp_dict that were previously defined. The descriptors contain a
5505 reference to the C function they must call, so that it's safe if they
5506 are copied into a subtype's __dict__ and the subtype has a different
5507 C function in its slot -- calling the method defined by the
5508 descriptor will call the C function that was used to create it,
5509 rather than the C function present in the slot when it is called.
5510 (This is important because a subtype may have a C function in the
5511 slot that calls the method from the dictionary, and we want to avoid
5512 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005513
5514static int
5515add_operators(PyTypeObject *type)
5516{
5517 PyObject *dict = type->tp_dict;
5518 slotdef *p;
5519 PyObject *descr;
5520 void **ptr;
5521
5522 init_slotdefs();
5523 for (p = slotdefs; p->name; p++) {
5524 if (p->wrapper == NULL)
5525 continue;
5526 ptr = slotptr(type, p->offset);
5527 if (!ptr || !*ptr)
5528 continue;
5529 if (PyDict_GetItem(dict, p->name_strobj))
5530 continue;
5531 descr = PyDescr_NewWrapper(type, p, *ptr);
5532 if (descr == NULL)
5533 return -1;
5534 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5535 return -1;
5536 Py_DECREF(descr);
5537 }
5538 if (type->tp_new != NULL) {
5539 if (add_tp_new_wrapper(type) < 0)
5540 return -1;
5541 }
5542 return 0;
5543}
5544
Guido van Rossum705f0f52001-08-24 16:47:00 +00005545
5546/* Cooperative 'super' */
5547
5548typedef struct {
5549 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005550 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005551 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005552 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005553} superobject;
5554
Guido van Rossum6f799372001-09-20 20:46:19 +00005555static PyMemberDef super_members[] = {
5556 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5557 "the class invoking super()"},
5558 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5559 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005560 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005561 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005562 {0}
5563};
5564
Guido van Rossum705f0f52001-08-24 16:47:00 +00005565static void
5566super_dealloc(PyObject *self)
5567{
5568 superobject *su = (superobject *)self;
5569
Guido van Rossum048eb752001-10-02 21:24:57 +00005570 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005571 Py_XDECREF(su->obj);
5572 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005573 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005574 self->ob_type->tp_free(self);
5575}
5576
5577static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005578super_repr(PyObject *self)
5579{
5580 superobject *su = (superobject *)self;
5581
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005582 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005583 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005584 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005585 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005586 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005587 else
5588 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005589 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005590 su->type ? su->type->tp_name : "NULL");
5591}
5592
5593static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005594super_getattro(PyObject *self, PyObject *name)
5595{
5596 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005597 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005598
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005599 if (!skip) {
5600 /* We want __class__ to return the class of the super object
5601 (i.e. super, or a subclass), not the class of su->obj. */
5602 skip = (PyString_Check(name) &&
5603 PyString_GET_SIZE(name) == 9 &&
5604 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5605 }
5606
5607 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005608 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005609 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005610 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005611 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005612
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005613 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005614 mro = starttype->tp_mro;
5615
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005616 if (mro == NULL)
5617 n = 0;
5618 else {
5619 assert(PyTuple_Check(mro));
5620 n = PyTuple_GET_SIZE(mro);
5621 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005622 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005623 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005624 break;
5625 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005626 i++;
5627 res = NULL;
5628 for (; i < n; i++) {
5629 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005630 if (PyType_Check(tmp))
5631 dict = ((PyTypeObject *)tmp)->tp_dict;
5632 else if (PyClass_Check(tmp))
5633 dict = ((PyClassObject *)tmp)->cl_dict;
5634 else
5635 continue;
5636 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005637 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005638 Py_INCREF(res);
5639 f = res->ob_type->tp_descr_get;
5640 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005641 tmp = f(res,
5642 /* Only pass 'obj' param if
5643 this is instance-mode super
5644 (See SF ID #743627)
5645 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005646 (su->obj == (PyObject *)
5647 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005648 ? (PyObject *)NULL
5649 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005650 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005651 Py_DECREF(res);
5652 res = tmp;
5653 }
5654 return res;
5655 }
5656 }
5657 }
5658 return PyObject_GenericGetAttr(self, name);
5659}
5660
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005661static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005662supercheck(PyTypeObject *type, PyObject *obj)
5663{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005664 /* Check that a super() call makes sense. Return a type object.
5665
5666 obj can be a new-style class, or an instance of one:
5667
5668 - If it is a class, it must be a subclass of 'type'. This case is
5669 used for class methods; the return value is obj.
5670
5671 - If it is an instance, it must be an instance of 'type'. This is
5672 the normal case; the return value is obj.__class__.
5673
5674 But... when obj is an instance, we want to allow for the case where
5675 obj->ob_type is not a subclass of type, but obj.__class__ is!
5676 This will allow using super() with a proxy for obj.
5677 */
5678
Guido van Rossum8e80a722003-02-18 19:22:22 +00005679 /* Check for first bullet above (special case) */
5680 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5681 Py_INCREF(obj);
5682 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005683 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005684
5685 /* Normal case */
5686 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005687 Py_INCREF(obj->ob_type);
5688 return obj->ob_type;
5689 }
5690 else {
5691 /* Try the slow way */
5692 static PyObject *class_str = NULL;
5693 PyObject *class_attr;
5694
5695 if (class_str == NULL) {
5696 class_str = PyString_FromString("__class__");
5697 if (class_str == NULL)
5698 return NULL;
5699 }
5700
5701 class_attr = PyObject_GetAttr(obj, class_str);
5702
5703 if (class_attr != NULL &&
5704 PyType_Check(class_attr) &&
5705 (PyTypeObject *)class_attr != obj->ob_type)
5706 {
5707 int ok = PyType_IsSubtype(
5708 (PyTypeObject *)class_attr, type);
5709 if (ok)
5710 return (PyTypeObject *)class_attr;
5711 }
5712
5713 if (class_attr == NULL)
5714 PyErr_Clear();
5715 else
5716 Py_DECREF(class_attr);
5717 }
5718
Tim Peters97e5ff52003-02-18 19:32:50 +00005719 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005720 "super(type, obj): "
5721 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005722 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005723}
5724
Guido van Rossum705f0f52001-08-24 16:47:00 +00005725static PyObject *
5726super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5727{
5728 superobject *su = (superobject *)self;
Anthony Baxtera6286212006-04-11 07:42:36 +00005729 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005730
5731 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5732 /* Not binding to an object, or already bound */
5733 Py_INCREF(self);
5734 return self;
5735 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005736 if (su->ob_type != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005737 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005738 call its type */
Georg Brandl684fd0c2006-05-25 19:15:31 +00005739 return PyObject_CallFunctionObjArgs((PyObject *)su->ob_type,
5740 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005741 else {
5742 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005743 PyTypeObject *obj_type = supercheck(su->type, obj);
5744 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005745 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00005746 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005747 NULL, NULL);
Anthony Baxtera6286212006-04-11 07:42:36 +00005748 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005749 return NULL;
5750 Py_INCREF(su->type);
5751 Py_INCREF(obj);
Anthony Baxtera6286212006-04-11 07:42:36 +00005752 newobj->type = su->type;
5753 newobj->obj = obj;
5754 newobj->obj_type = obj_type;
5755 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005756 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005757}
5758
5759static int
5760super_init(PyObject *self, PyObject *args, PyObject *kwds)
5761{
5762 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005763 PyTypeObject *type;
5764 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005765 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005766
Georg Brandl5d59c092006-09-30 08:43:30 +00005767 if (!_PyArg_NoKeywords("super", kwds))
5768 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005769 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5770 return -1;
5771 if (obj == Py_None)
5772 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005773 if (obj != NULL) {
5774 obj_type = supercheck(type, obj);
5775 if (obj_type == NULL)
5776 return -1;
5777 Py_INCREF(obj);
5778 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005779 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005780 su->type = type;
5781 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005782 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005783 return 0;
5784}
5785
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005786PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005787"super(type) -> unbound super object\n"
5788"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005789"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005790"Typical use to call a cooperative superclass method:\n"
5791"class C(B):\n"
5792" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005793" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005794
Guido van Rossum048eb752001-10-02 21:24:57 +00005795static int
5796super_traverse(PyObject *self, visitproc visit, void *arg)
5797{
5798 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00005799
Thomas Woutersc6e55062006-04-15 21:47:09 +00005800 Py_VISIT(su->obj);
5801 Py_VISIT(su->type);
5802 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005803
5804 return 0;
5805}
5806
Guido van Rossum705f0f52001-08-24 16:47:00 +00005807PyTypeObject PySuper_Type = {
5808 PyObject_HEAD_INIT(&PyType_Type)
5809 0, /* ob_size */
5810 "super", /* tp_name */
5811 sizeof(superobject), /* tp_basicsize */
5812 0, /* tp_itemsize */
5813 /* methods */
5814 super_dealloc, /* tp_dealloc */
5815 0, /* tp_print */
5816 0, /* tp_getattr */
5817 0, /* tp_setattr */
5818 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005819 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005820 0, /* tp_as_number */
5821 0, /* tp_as_sequence */
5822 0, /* tp_as_mapping */
5823 0, /* tp_hash */
5824 0, /* tp_call */
5825 0, /* tp_str */
5826 super_getattro, /* tp_getattro */
5827 0, /* tp_setattro */
5828 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005829 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5830 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005831 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005832 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005833 0, /* tp_clear */
5834 0, /* tp_richcompare */
5835 0, /* tp_weaklistoffset */
5836 0, /* tp_iter */
5837 0, /* tp_iternext */
5838 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005839 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005840 0, /* tp_getset */
5841 0, /* tp_base */
5842 0, /* tp_dict */
5843 super_descr_get, /* tp_descr_get */
5844 0, /* tp_descr_set */
5845 0, /* tp_dictoffset */
5846 super_init, /* tp_init */
5847 PyType_GenericAlloc, /* tp_alloc */
5848 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005849 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005850};